rpc.rs

   1use super::{
   2    auth,
   3    db::{ChannelId, UserId},
   4    AppState,
   5};
   6use anyhow::anyhow;
   7use async_std::{sync::RwLock, task};
   8use async_tungstenite::{
   9    tungstenite::{protocol::Role, Error as WebSocketError, Message as WebSocketMessage},
  10    WebSocketStream,
  11};
  12use futures::{future::BoxFuture, FutureExt};
  13use postage::{mpsc, prelude::Sink as _, prelude::Stream as _};
  14use sha1::{Digest as _, Sha1};
  15use std::{
  16    any::TypeId,
  17    collections::{hash_map, HashMap, HashSet},
  18    future::Future,
  19    mem,
  20    sync::Arc,
  21    time::Instant,
  22};
  23use surf::StatusCode;
  24use tide::log;
  25use tide::{
  26    http::headers::{HeaderName, CONNECTION, UPGRADE},
  27    Request, Response,
  28};
  29use time::OffsetDateTime;
  30use zrpc::{
  31    auth::random_token,
  32    proto::{self, AnyTypedEnvelope, EnvelopedMessage},
  33    ConnectionId, Peer, TypedEnvelope,
  34};
  35
  36type ReplicaId = u16;
  37
  38type MessageHandler = Box<
  39    dyn Send
  40        + Sync
  41        + Fn(Arc<Server>, Box<dyn AnyTypedEnvelope>) -> BoxFuture<'static, tide::Result<()>>,
  42>;
  43
  44pub struct Server {
  45    peer: Arc<Peer>,
  46    state: RwLock<ServerState>,
  47    app_state: Arc<AppState>,
  48    handlers: HashMap<TypeId, MessageHandler>,
  49    notifications: Option<mpsc::Sender<()>>,
  50}
  51
  52#[derive(Default)]
  53struct ServerState {
  54    connections: HashMap<ConnectionId, Connection>,
  55    pub worktrees: HashMap<u64, Worktree>,
  56    channels: HashMap<ChannelId, Channel>,
  57    next_worktree_id: u64,
  58}
  59
  60struct Connection {
  61    user_id: UserId,
  62    worktrees: HashSet<u64>,
  63    channels: HashSet<ChannelId>,
  64}
  65
  66struct Worktree {
  67    host_connection_id: Option<ConnectionId>,
  68    guest_connection_ids: HashMap<ConnectionId, ReplicaId>,
  69    active_replica_ids: HashSet<ReplicaId>,
  70    access_token: String,
  71    root_name: String,
  72    entries: HashMap<u64, proto::Entry>,
  73}
  74
  75#[derive(Default)]
  76struct Channel {
  77    connection_ids: HashSet<ConnectionId>,
  78}
  79
  80impl Server {
  81    pub fn new(
  82        app_state: Arc<AppState>,
  83        peer: Arc<Peer>,
  84        notifications: Option<mpsc::Sender<()>>,
  85    ) -> Arc<Self> {
  86        let mut server = Self {
  87            peer,
  88            app_state,
  89            state: Default::default(),
  90            handlers: Default::default(),
  91            notifications,
  92        };
  93
  94        server
  95            .add_handler(Server::share_worktree)
  96            .add_handler(Server::join_worktree)
  97            .add_handler(Server::update_worktree)
  98            .add_handler(Server::close_worktree)
  99            .add_handler(Server::open_buffer)
 100            .add_handler(Server::close_buffer)
 101            .add_handler(Server::update_buffer)
 102            .add_handler(Server::buffer_saved)
 103            .add_handler(Server::save_buffer)
 104            .add_handler(Server::get_channels)
 105            .add_handler(Server::get_users)
 106            .add_handler(Server::join_channel)
 107            .add_handler(Server::leave_channel)
 108            .add_handler(Server::send_channel_message);
 109
 110        Arc::new(server)
 111    }
 112
 113    fn add_handler<F, Fut, M>(&mut self, handler: F) -> &mut Self
 114    where
 115        F: 'static + Send + Sync + Fn(Arc<Self>, TypedEnvelope<M>) -> Fut,
 116        Fut: 'static + Send + Future<Output = tide::Result<()>>,
 117        M: EnvelopedMessage,
 118    {
 119        let prev_handler = self.handlers.insert(
 120            TypeId::of::<M>(),
 121            Box::new(move |server, envelope| {
 122                let envelope = envelope.into_any().downcast::<TypedEnvelope<M>>().unwrap();
 123                (handler)(server, *envelope).boxed()
 124            }),
 125        );
 126        if prev_handler.is_some() {
 127            panic!("registered a handler for the same message twice");
 128        }
 129        self
 130    }
 131
 132    pub fn handle_connection<Conn>(
 133        self: &Arc<Self>,
 134        connection: Conn,
 135        addr: String,
 136        user_id: UserId,
 137    ) -> impl Future<Output = ()>
 138    where
 139        Conn: 'static
 140            + futures::Sink<WebSocketMessage, Error = WebSocketError>
 141            + futures::Stream<Item = Result<WebSocketMessage, WebSocketError>>
 142            + Send
 143            + Unpin,
 144    {
 145        let this = self.clone();
 146        async move {
 147            let (connection_id, handle_io, mut incoming_rx) =
 148                this.peer.add_connection(connection).await;
 149            this.add_connection(connection_id, user_id).await;
 150
 151            let handle_io = handle_io.fuse();
 152            futures::pin_mut!(handle_io);
 153            loop {
 154                let next_message = incoming_rx.recv().fuse();
 155                futures::pin_mut!(next_message);
 156                futures::select_biased! {
 157                    message = next_message => {
 158                        if let Some(message) = message {
 159                            let start_time = Instant::now();
 160                            log::info!("RPC message received: {}", message.payload_type_name());
 161                            if let Some(handler) = this.handlers.get(&message.payload_type_id()) {
 162                                if let Err(err) = (handler)(this.clone(), message).await {
 163                                    log::error!("error handling message: {:?}", err);
 164                                } else {
 165                                    log::info!("RPC message handled. duration:{:?}", start_time.elapsed());
 166                                }
 167
 168                                if let Some(mut notifications) = this.notifications.clone() {
 169                                    let _ = notifications.send(()).await;
 170                                }
 171                            } else {
 172                                log::warn!("unhandled message: {}", message.payload_type_name());
 173                            }
 174                        } else {
 175                            log::info!("rpc connection closed {:?}", addr);
 176                            break;
 177                        }
 178                    }
 179                    handle_io = handle_io => {
 180                        if let Err(err) = handle_io {
 181                            log::error!("error handling rpc connection {:?} - {:?}", addr, err);
 182                        }
 183                        break;
 184                    }
 185                }
 186            }
 187
 188            if let Err(err) = this.sign_out(connection_id).await {
 189                log::error!("error signing out connection {:?} - {:?}", addr, err);
 190            }
 191        }
 192    }
 193
 194    async fn sign_out(self: &Arc<Self>, connection_id: zrpc::ConnectionId) -> tide::Result<()> {
 195        self.peer.disconnect(connection_id).await;
 196        let worktree_ids = self.remove_connection(connection_id).await;
 197        for worktree_id in worktree_ids {
 198            let state = self.state.read().await;
 199            if let Some(worktree) = state.worktrees.get(&worktree_id) {
 200                broadcast(connection_id, worktree.connection_ids(), |conn_id| {
 201                    self.peer.send(
 202                        conn_id,
 203                        proto::RemovePeer {
 204                            worktree_id,
 205                            peer_id: connection_id.0,
 206                        },
 207                    )
 208                })
 209                .await?;
 210            }
 211        }
 212        Ok(())
 213    }
 214
 215    // Add a new connection associated with a given user.
 216    async fn add_connection(&self, connection_id: ConnectionId, user_id: UserId) {
 217        self.state.write().await.connections.insert(
 218            connection_id,
 219            Connection {
 220                user_id,
 221                worktrees: Default::default(),
 222                channels: Default::default(),
 223            },
 224        );
 225    }
 226
 227    // Remove the given connection and its association with any worktrees.
 228    async fn remove_connection(&self, connection_id: ConnectionId) -> Vec<u64> {
 229        let mut worktree_ids = Vec::new();
 230        let mut state = self.state.write().await;
 231        if let Some(connection) = state.connections.remove(&connection_id) {
 232            for channel_id in connection.channels {
 233                if let Some(channel) = state.channels.get_mut(&channel_id) {
 234                    channel.connection_ids.remove(&connection_id);
 235                }
 236            }
 237            for worktree_id in connection.worktrees {
 238                if let Some(worktree) = state.worktrees.get_mut(&worktree_id) {
 239                    if worktree.host_connection_id == Some(connection_id) {
 240                        worktree_ids.push(worktree_id);
 241                    } else if let Some(replica_id) =
 242                        worktree.guest_connection_ids.remove(&connection_id)
 243                    {
 244                        worktree.active_replica_ids.remove(&replica_id);
 245                        worktree_ids.push(worktree_id);
 246                    }
 247                }
 248            }
 249        }
 250        worktree_ids
 251    }
 252
 253    async fn share_worktree(
 254        self: Arc<Server>,
 255        mut request: TypedEnvelope<proto::ShareWorktree>,
 256    ) -> tide::Result<()> {
 257        let mut state = self.state.write().await;
 258        let worktree_id = state.next_worktree_id;
 259        state.next_worktree_id += 1;
 260        let access_token = random_token();
 261        let worktree = request
 262            .payload
 263            .worktree
 264            .as_mut()
 265            .ok_or_else(|| anyhow!("missing worktree"))?;
 266        let entries = mem::take(&mut worktree.entries)
 267            .into_iter()
 268            .map(|entry| (entry.id, entry))
 269            .collect();
 270        state.worktrees.insert(
 271            worktree_id,
 272            Worktree {
 273                host_connection_id: Some(request.sender_id),
 274                guest_connection_ids: Default::default(),
 275                active_replica_ids: Default::default(),
 276                access_token: access_token.clone(),
 277                root_name: mem::take(&mut worktree.root_name),
 278                entries,
 279            },
 280        );
 281
 282        self.peer
 283            .respond(
 284                request.receipt(),
 285                proto::ShareWorktreeResponse {
 286                    worktree_id,
 287                    access_token,
 288                },
 289            )
 290            .await?;
 291        Ok(())
 292    }
 293
 294    async fn join_worktree(
 295        self: Arc<Server>,
 296        request: TypedEnvelope<proto::OpenWorktree>,
 297    ) -> tide::Result<()> {
 298        let worktree_id = request.payload.worktree_id;
 299        let access_token = &request.payload.access_token;
 300
 301        let mut state = self.state.write().await;
 302        if let Some((peer_replica_id, worktree)) =
 303            state.join_worktree(request.sender_id, worktree_id, access_token)
 304        {
 305            let mut peers = Vec::new();
 306            if let Some(host_connection_id) = worktree.host_connection_id {
 307                peers.push(proto::Peer {
 308                    peer_id: host_connection_id.0,
 309                    replica_id: 0,
 310                });
 311            }
 312            for (peer_conn_id, peer_replica_id) in &worktree.guest_connection_ids {
 313                if *peer_conn_id != request.sender_id {
 314                    peers.push(proto::Peer {
 315                        peer_id: peer_conn_id.0,
 316                        replica_id: *peer_replica_id as u32,
 317                    });
 318                }
 319            }
 320
 321            broadcast(request.sender_id, worktree.connection_ids(), |conn_id| {
 322                self.peer.send(
 323                    conn_id,
 324                    proto::AddPeer {
 325                        worktree_id,
 326                        peer: Some(proto::Peer {
 327                            peer_id: request.sender_id.0,
 328                            replica_id: peer_replica_id as u32,
 329                        }),
 330                    },
 331                )
 332            })
 333            .await?;
 334            self.peer
 335                .respond(
 336                    request.receipt(),
 337                    proto::OpenWorktreeResponse {
 338                        worktree_id,
 339                        worktree: Some(proto::Worktree {
 340                            root_name: worktree.root_name.clone(),
 341                            entries: worktree.entries.values().cloned().collect(),
 342                        }),
 343                        replica_id: peer_replica_id as u32,
 344                        peers,
 345                    },
 346                )
 347                .await?;
 348        } else {
 349            self.peer
 350                .respond(
 351                    request.receipt(),
 352                    proto::OpenWorktreeResponse {
 353                        worktree_id,
 354                        worktree: None,
 355                        replica_id: 0,
 356                        peers: Vec::new(),
 357                    },
 358                )
 359                .await?;
 360        }
 361
 362        Ok(())
 363    }
 364
 365    async fn update_worktree(
 366        self: Arc<Server>,
 367        request: TypedEnvelope<proto::UpdateWorktree>,
 368    ) -> tide::Result<()> {
 369        {
 370            let mut state = self.state.write().await;
 371            let worktree = state.write_worktree(request.payload.worktree_id, request.sender_id)?;
 372            for entry_id in &request.payload.removed_entries {
 373                worktree.entries.remove(&entry_id);
 374            }
 375
 376            for entry in &request.payload.updated_entries {
 377                worktree.entries.insert(entry.id, entry.clone());
 378            }
 379        }
 380
 381        self.broadcast_in_worktree(request.payload.worktree_id, &request)
 382            .await?;
 383        Ok(())
 384    }
 385
 386    async fn close_worktree(
 387        self: Arc<Server>,
 388        request: TypedEnvelope<proto::CloseWorktree>,
 389    ) -> tide::Result<()> {
 390        let connection_ids;
 391        {
 392            let mut state = self.state.write().await;
 393            let worktree = state.write_worktree(request.payload.worktree_id, request.sender_id)?;
 394            connection_ids = worktree.connection_ids();
 395            if worktree.host_connection_id == Some(request.sender_id) {
 396                worktree.host_connection_id = None;
 397            } else if let Some(replica_id) =
 398                worktree.guest_connection_ids.remove(&request.sender_id)
 399            {
 400                worktree.active_replica_ids.remove(&replica_id);
 401            }
 402        }
 403
 404        broadcast(request.sender_id, connection_ids, |conn_id| {
 405            self.peer.send(
 406                conn_id,
 407                proto::RemovePeer {
 408                    worktree_id: request.payload.worktree_id,
 409                    peer_id: request.sender_id.0,
 410                },
 411            )
 412        })
 413        .await?;
 414
 415        Ok(())
 416    }
 417
 418    async fn open_buffer(
 419        self: Arc<Server>,
 420        request: TypedEnvelope<proto::OpenBuffer>,
 421    ) -> tide::Result<()> {
 422        let receipt = request.receipt();
 423        let worktree_id = request.payload.worktree_id;
 424        let host_connection_id = self
 425            .state
 426            .read()
 427            .await
 428            .read_worktree(worktree_id, request.sender_id)?
 429            .host_connection_id()?;
 430
 431        let response = self
 432            .peer
 433            .forward_request(request.sender_id, host_connection_id, request.payload)
 434            .await?;
 435        self.peer.respond(receipt, response).await?;
 436        Ok(())
 437    }
 438
 439    async fn close_buffer(
 440        self: Arc<Server>,
 441        request: TypedEnvelope<proto::CloseBuffer>,
 442    ) -> tide::Result<()> {
 443        let host_connection_id = self
 444            .state
 445            .read()
 446            .await
 447            .read_worktree(request.payload.worktree_id, request.sender_id)?
 448            .host_connection_id()?;
 449
 450        self.peer
 451            .forward_send(request.sender_id, host_connection_id, request.payload)
 452            .await?;
 453
 454        Ok(())
 455    }
 456
 457    async fn save_buffer(
 458        self: Arc<Server>,
 459        request: TypedEnvelope<proto::SaveBuffer>,
 460    ) -> tide::Result<()> {
 461        let host;
 462        let guests;
 463        {
 464            let state = self.state.read().await;
 465            let worktree = state.read_worktree(request.payload.worktree_id, request.sender_id)?;
 466            host = worktree.host_connection_id()?;
 467            guests = worktree
 468                .guest_connection_ids
 469                .keys()
 470                .copied()
 471                .collect::<Vec<_>>();
 472        }
 473
 474        let sender = request.sender_id;
 475        let receipt = request.receipt();
 476        let response = self
 477            .peer
 478            .forward_request(sender, host, request.payload.clone())
 479            .await?;
 480
 481        broadcast(host, guests, |conn_id| {
 482            let response = response.clone();
 483            let peer = &self.peer;
 484            async move {
 485                if conn_id == sender {
 486                    peer.respond(receipt, response).await
 487                } else {
 488                    peer.forward_send(host, conn_id, response).await
 489                }
 490            }
 491        })
 492        .await?;
 493
 494        Ok(())
 495    }
 496
 497    async fn update_buffer(
 498        self: Arc<Server>,
 499        request: TypedEnvelope<proto::UpdateBuffer>,
 500    ) -> tide::Result<()> {
 501        self.broadcast_in_worktree(request.payload.worktree_id, &request)
 502            .await
 503    }
 504
 505    async fn buffer_saved(
 506        self: Arc<Server>,
 507        request: TypedEnvelope<proto::BufferSaved>,
 508    ) -> tide::Result<()> {
 509        self.broadcast_in_worktree(request.payload.worktree_id, &request)
 510            .await
 511    }
 512
 513    async fn get_channels(
 514        self: Arc<Server>,
 515        request: TypedEnvelope<proto::GetChannels>,
 516    ) -> tide::Result<()> {
 517        let user_id = self
 518            .state
 519            .read()
 520            .await
 521            .user_id_for_connection(request.sender_id)?;
 522        let channels = self.app_state.db.get_channels_for_user(user_id).await?;
 523        self.peer
 524            .respond(
 525                request.receipt(),
 526                proto::GetChannelsResponse {
 527                    channels: channels
 528                        .into_iter()
 529                        .map(|chan| proto::Channel {
 530                            id: chan.id.to_proto(),
 531                            name: chan.name,
 532                        })
 533                        .collect(),
 534                },
 535            )
 536            .await?;
 537        Ok(())
 538    }
 539
 540    async fn get_users(
 541        self: Arc<Server>,
 542        request: TypedEnvelope<proto::GetUsers>,
 543    ) -> tide::Result<()> {
 544        let user_id = self
 545            .state
 546            .read()
 547            .await
 548            .user_id_for_connection(request.sender_id)?;
 549        let receipt = request.receipt();
 550        let user_ids = request.payload.user_ids.into_iter().map(UserId::from_proto);
 551        let users = self
 552            .app_state
 553            .db
 554            .get_users_by_ids(user_id, user_ids)
 555            .await?
 556            .into_iter()
 557            .map(|user| proto::User {
 558                id: user.id.to_proto(),
 559                github_login: user.github_login,
 560                avatar_url: String::new(),
 561            })
 562            .collect();
 563        self.peer
 564            .respond(receipt, proto::GetUsersResponse { users })
 565            .await?;
 566        Ok(())
 567    }
 568
 569    async fn join_channel(
 570        self: Arc<Self>,
 571        request: TypedEnvelope<proto::JoinChannel>,
 572    ) -> tide::Result<()> {
 573        let user_id = self
 574            .state
 575            .read()
 576            .await
 577            .user_id_for_connection(request.sender_id)?;
 578        let channel_id = ChannelId::from_proto(request.payload.channel_id);
 579        if !self
 580            .app_state
 581            .db
 582            .can_user_access_channel(user_id, channel_id)
 583            .await?
 584        {
 585            Err(anyhow!("access denied"))?;
 586        }
 587
 588        self.state
 589            .write()
 590            .await
 591            .join_channel(request.sender_id, channel_id);
 592        let messages = self
 593            .app_state
 594            .db
 595            .get_recent_channel_messages(channel_id, 50)
 596            .await?
 597            .into_iter()
 598            .map(|msg| proto::ChannelMessage {
 599                id: msg.id.to_proto(),
 600                body: msg.body,
 601                timestamp: msg.sent_at.unix_timestamp() as u64,
 602                sender_id: msg.sender_id.to_proto(),
 603            })
 604            .collect();
 605        self.peer
 606            .respond(request.receipt(), proto::JoinChannelResponse { messages })
 607            .await?;
 608        Ok(())
 609    }
 610
 611    async fn leave_channel(
 612        self: Arc<Self>,
 613        request: TypedEnvelope<proto::LeaveChannel>,
 614    ) -> tide::Result<()> {
 615        let user_id = self
 616            .state
 617            .read()
 618            .await
 619            .user_id_for_connection(request.sender_id)?;
 620        let channel_id = ChannelId::from_proto(request.payload.channel_id);
 621        if !self
 622            .app_state
 623            .db
 624            .can_user_access_channel(user_id, channel_id)
 625            .await?
 626        {
 627            Err(anyhow!("access denied"))?;
 628        }
 629
 630        self.state
 631            .write()
 632            .await
 633            .leave_channel(request.sender_id, channel_id);
 634
 635        Ok(())
 636    }
 637
 638    async fn send_channel_message(
 639        self: Arc<Self>,
 640        request: TypedEnvelope<proto::SendChannelMessage>,
 641    ) -> tide::Result<()> {
 642        let channel_id = ChannelId::from_proto(request.payload.channel_id);
 643        let user_id;
 644        let connection_ids;
 645        {
 646            let state = self.state.read().await;
 647            user_id = state.user_id_for_connection(request.sender_id)?;
 648            if let Some(channel) = state.channels.get(&channel_id) {
 649                connection_ids = channel.connection_ids();
 650            } else {
 651                return Ok(());
 652            }
 653        }
 654
 655        let timestamp = OffsetDateTime::now_utc();
 656        let message_id = self
 657            .app_state
 658            .db
 659            .create_channel_message(channel_id, user_id, &request.payload.body, timestamp)
 660            .await?
 661            .to_proto();
 662        let receipt = request.receipt();
 663        let message = proto::ChannelMessageSent {
 664            channel_id: channel_id.to_proto(),
 665            message: Some(proto::ChannelMessage {
 666                sender_id: user_id.to_proto(),
 667                id: message_id,
 668                body: request.payload.body,
 669                timestamp: timestamp.unix_timestamp() as u64,
 670            }),
 671        };
 672        broadcast(request.sender_id, connection_ids, |conn_id| {
 673            self.peer.send(conn_id, message.clone())
 674        })
 675        .await?;
 676        self.peer
 677            .respond(
 678                receipt,
 679                proto::SendChannelMessageResponse {
 680                    message_id,
 681                    timestamp: timestamp.unix_timestamp() as u64,
 682                },
 683            )
 684            .await?;
 685        Ok(())
 686    }
 687
 688    async fn broadcast_in_worktree<T: proto::EnvelopedMessage>(
 689        &self,
 690        worktree_id: u64,
 691        message: &TypedEnvelope<T>,
 692    ) -> tide::Result<()> {
 693        let connection_ids = self
 694            .state
 695            .read()
 696            .await
 697            .read_worktree(worktree_id, message.sender_id)?
 698            .connection_ids();
 699
 700        broadcast(message.sender_id, connection_ids, |conn_id| {
 701            self.peer
 702                .forward_send(message.sender_id, conn_id, message.payload.clone())
 703        })
 704        .await?;
 705
 706        Ok(())
 707    }
 708}
 709
 710pub async fn broadcast<F, T>(
 711    sender_id: ConnectionId,
 712    receiver_ids: Vec<ConnectionId>,
 713    mut f: F,
 714) -> anyhow::Result<()>
 715where
 716    F: FnMut(ConnectionId) -> T,
 717    T: Future<Output = anyhow::Result<()>>,
 718{
 719    let futures = receiver_ids
 720        .into_iter()
 721        .filter(|id| *id != sender_id)
 722        .map(|id| f(id));
 723    futures::future::try_join_all(futures).await?;
 724    Ok(())
 725}
 726
 727impl ServerState {
 728    fn join_channel(&mut self, connection_id: ConnectionId, channel_id: ChannelId) {
 729        if let Some(connection) = self.connections.get_mut(&connection_id) {
 730            connection.channels.insert(channel_id);
 731            self.channels
 732                .entry(channel_id)
 733                .or_default()
 734                .connection_ids
 735                .insert(connection_id);
 736        }
 737    }
 738
 739    fn leave_channel(&mut self, connection_id: ConnectionId, channel_id: ChannelId) {
 740        if let Some(connection) = self.connections.get_mut(&connection_id) {
 741            connection.channels.remove(&channel_id);
 742            if let hash_map::Entry::Occupied(mut entry) = self.channels.entry(channel_id) {
 743                entry.get_mut().connection_ids.remove(&connection_id);
 744                if entry.get_mut().connection_ids.is_empty() {
 745                    entry.remove();
 746                }
 747            }
 748        }
 749    }
 750
 751    fn user_id_for_connection(&self, connection_id: ConnectionId) -> tide::Result<UserId> {
 752        Ok(self
 753            .connections
 754            .get(&connection_id)
 755            .ok_or_else(|| anyhow!("unknown connection"))?
 756            .user_id)
 757    }
 758
 759    // Add the given connection as a guest of the given worktree
 760    fn join_worktree(
 761        &mut self,
 762        connection_id: ConnectionId,
 763        worktree_id: u64,
 764        access_token: &str,
 765    ) -> Option<(ReplicaId, &Worktree)> {
 766        if let Some(worktree) = self.worktrees.get_mut(&worktree_id) {
 767            if access_token == worktree.access_token {
 768                if let Some(connection) = self.connections.get_mut(&connection_id) {
 769                    connection.worktrees.insert(worktree_id);
 770                }
 771
 772                let mut replica_id = 1;
 773                while worktree.active_replica_ids.contains(&replica_id) {
 774                    replica_id += 1;
 775                }
 776                worktree.active_replica_ids.insert(replica_id);
 777                worktree
 778                    .guest_connection_ids
 779                    .insert(connection_id, replica_id);
 780                Some((replica_id, worktree))
 781            } else {
 782                None
 783            }
 784        } else {
 785            None
 786        }
 787    }
 788
 789    fn read_worktree(
 790        &self,
 791        worktree_id: u64,
 792        connection_id: ConnectionId,
 793    ) -> tide::Result<&Worktree> {
 794        let worktree = self
 795            .worktrees
 796            .get(&worktree_id)
 797            .ok_or_else(|| anyhow!("worktree not found"))?;
 798
 799        if worktree.host_connection_id == Some(connection_id)
 800            || worktree.guest_connection_ids.contains_key(&connection_id)
 801        {
 802            Ok(worktree)
 803        } else {
 804            Err(anyhow!(
 805                "{} is not a member of worktree {}",
 806                connection_id,
 807                worktree_id
 808            ))?
 809        }
 810    }
 811
 812    fn write_worktree(
 813        &mut self,
 814        worktree_id: u64,
 815        connection_id: ConnectionId,
 816    ) -> tide::Result<&mut Worktree> {
 817        let worktree = self
 818            .worktrees
 819            .get_mut(&worktree_id)
 820            .ok_or_else(|| anyhow!("worktree not found"))?;
 821
 822        if worktree.host_connection_id == Some(connection_id)
 823            || worktree.guest_connection_ids.contains_key(&connection_id)
 824        {
 825            Ok(worktree)
 826        } else {
 827            Err(anyhow!(
 828                "{} is not a member of worktree {}",
 829                connection_id,
 830                worktree_id
 831            ))?
 832        }
 833    }
 834}
 835
 836impl Worktree {
 837    pub fn connection_ids(&self) -> Vec<ConnectionId> {
 838        self.guest_connection_ids
 839            .keys()
 840            .copied()
 841            .chain(self.host_connection_id)
 842            .collect()
 843    }
 844
 845    fn host_connection_id(&self) -> tide::Result<ConnectionId> {
 846        Ok(self
 847            .host_connection_id
 848            .ok_or_else(|| anyhow!("host disconnected from worktree"))?)
 849    }
 850}
 851
 852impl Channel {
 853    fn connection_ids(&self) -> Vec<ConnectionId> {
 854        self.connection_ids.iter().copied().collect()
 855    }
 856}
 857
 858pub fn add_routes(app: &mut tide::Server<Arc<AppState>>, rpc: &Arc<Peer>) {
 859    let server = Server::new(app.state().clone(), rpc.clone(), None);
 860    app.at("/rpc").with(auth::VerifyToken).get(move |request: Request<Arc<AppState>>| {
 861        let user_id = request.ext::<UserId>().copied();
 862        let server = server.clone();
 863        async move {
 864            const WEBSOCKET_GUID: &str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
 865
 866            let connection_upgrade = header_contains_ignore_case(&request, CONNECTION, "upgrade");
 867            let upgrade_to_websocket = header_contains_ignore_case(&request, UPGRADE, "websocket");
 868            let upgrade_requested = connection_upgrade && upgrade_to_websocket;
 869
 870            if !upgrade_requested {
 871                return Ok(Response::new(StatusCode::UpgradeRequired));
 872            }
 873
 874            let header = match request.header("Sec-Websocket-Key") {
 875                Some(h) => h.as_str(),
 876                None => return Err(anyhow!("expected sec-websocket-key"))?,
 877            };
 878
 879            let mut response = Response::new(StatusCode::SwitchingProtocols);
 880            response.insert_header(UPGRADE, "websocket");
 881            response.insert_header(CONNECTION, "Upgrade");
 882            let hash = Sha1::new().chain(header).chain(WEBSOCKET_GUID).finalize();
 883            response.insert_header("Sec-Websocket-Accept", base64::encode(&hash[..]));
 884            response.insert_header("Sec-Websocket-Version", "13");
 885
 886            let http_res: &mut tide::http::Response = response.as_mut();
 887            let upgrade_receiver = http_res.recv_upgrade().await;
 888            let addr = request.remote().unwrap_or("unknown").to_string();
 889            let user_id = user_id.ok_or_else(|| anyhow!("user_id is not present on request. ensure auth::VerifyToken middleware is present"))?;
 890            task::spawn(async move {
 891                if let Some(stream) = upgrade_receiver.await {
 892                    let stream = WebSocketStream::from_raw_socket(stream, Role::Server, None).await;
 893                    server.handle_connection(stream, addr, user_id).await;
 894                }
 895            });
 896
 897            Ok(response)
 898        }
 899    });
 900}
 901
 902fn header_contains_ignore_case<T>(
 903    request: &tide::Request<T>,
 904    header_name: HeaderName,
 905    value: &str,
 906) -> bool {
 907    request
 908        .header(header_name)
 909        .map(|h| {
 910            h.as_str()
 911                .split(',')
 912                .any(|s| s.trim().eq_ignore_ascii_case(value.trim()))
 913        })
 914        .unwrap_or(false)
 915}
 916
 917#[cfg(test)]
 918mod tests {
 919    use super::*;
 920    use crate::{
 921        auth,
 922        db::{self, UserId},
 923        github, AppState, Config,
 924    };
 925    use async_std::{
 926        sync::RwLockReadGuard,
 927        task::{self, block_on},
 928    };
 929    use gpui::TestAppContext;
 930    use postage::mpsc;
 931    use rand::prelude::*;
 932    use serde_json::json;
 933    use sqlx::{migrate::MigrateDatabase, types::time::OffsetDateTime, Postgres};
 934    use std::{path::Path, sync::Arc, time::Duration};
 935    use zed::{
 936        channel::{Channel, ChannelDetails, ChannelList},
 937        editor::{Editor, Insert},
 938        fs::{FakeFs, Fs as _},
 939        language::LanguageRegistry,
 940        rpc::Client,
 941        settings, test,
 942        worktree::Worktree,
 943    };
 944    use zrpc::Peer;
 945
 946    #[gpui::test]
 947    async fn test_share_worktree(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
 948        let (window_b, _) = cx_b.add_window(|_| EmptyView);
 949        let settings = settings::channel(&cx_b.font_cache()).unwrap().1;
 950        let lang_registry = Arc::new(LanguageRegistry::new());
 951
 952        // Connect to a server as 2 clients.
 953        let mut server = TestServer::start().await;
 954        let (_, client_a) = server.create_client(&mut cx_a, "user_a").await;
 955        let (_, client_b) = server.create_client(&mut cx_b, "user_b").await;
 956
 957        cx_a.foreground().forbid_parking();
 958
 959        // Share a local worktree as client A
 960        let fs = Arc::new(FakeFs::new());
 961        fs.insert_tree(
 962            "/a",
 963            json!({
 964                "a.txt": "a-contents",
 965                "b.txt": "b-contents",
 966            }),
 967        )
 968        .await;
 969        let worktree_a = Worktree::open_local(
 970            "/a".as_ref(),
 971            lang_registry.clone(),
 972            fs,
 973            &mut cx_a.to_async(),
 974        )
 975        .await
 976        .unwrap();
 977        worktree_a
 978            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
 979            .await;
 980        let (worktree_id, worktree_token) = worktree_a
 981            .update(&mut cx_a, |tree, cx| {
 982                tree.as_local_mut().unwrap().share(client_a.clone(), cx)
 983            })
 984            .await
 985            .unwrap();
 986
 987        // Join that worktree as client B, and see that a guest has joined as client A.
 988        let worktree_b = Worktree::open_remote(
 989            client_b.clone(),
 990            worktree_id,
 991            worktree_token,
 992            lang_registry.clone(),
 993            &mut cx_b.to_async(),
 994        )
 995        .await
 996        .unwrap();
 997        let replica_id_b = worktree_b.read_with(&cx_b, |tree, _| tree.replica_id());
 998        worktree_a
 999            .condition(&cx_a, |tree, _| {
1000                tree.peers()
1001                    .values()
1002                    .any(|replica_id| *replica_id == replica_id_b)
1003            })
1004            .await;
1005
1006        // Open the same file as client B and client A.
1007        let buffer_b = worktree_b
1008            .update(&mut cx_b, |worktree, cx| worktree.open_buffer("b.txt", cx))
1009            .await
1010            .unwrap();
1011        buffer_b.read_with(&cx_b, |buf, _| assert_eq!(buf.text(), "b-contents"));
1012        worktree_a.read_with(&cx_a, |tree, cx| assert!(tree.has_open_buffer("b.txt", cx)));
1013        let buffer_a = worktree_a
1014            .update(&mut cx_a, |tree, cx| tree.open_buffer("b.txt", cx))
1015            .await
1016            .unwrap();
1017
1018        // Create a selection set as client B and see that selection set as client A.
1019        let editor_b = cx_b.add_view(window_b, |cx| Editor::for_buffer(buffer_b, settings, cx));
1020        buffer_a
1021            .condition(&cx_a, |buffer, _| buffer.selection_sets().count() == 1)
1022            .await;
1023
1024        // Edit the buffer as client B and see that edit as client A.
1025        editor_b.update(&mut cx_b, |editor, cx| {
1026            editor.insert(&Insert("ok, ".into()), cx)
1027        });
1028        buffer_a
1029            .condition(&cx_a, |buffer, _| buffer.text() == "ok, b-contents")
1030            .await;
1031
1032        // Remove the selection set as client B, see those selections disappear as client A.
1033        cx_b.update(move |_| drop(editor_b));
1034        buffer_a
1035            .condition(&cx_a, |buffer, _| buffer.selection_sets().count() == 0)
1036            .await;
1037
1038        // Close the buffer as client A, see that the buffer is closed.
1039        drop(buffer_a);
1040        worktree_a
1041            .condition(&cx_a, |tree, cx| !tree.has_open_buffer("b.txt", cx))
1042            .await;
1043
1044        // Dropping the worktree removes client B from client A's peers.
1045        cx_b.update(move |_| drop(worktree_b));
1046        worktree_a
1047            .condition(&cx_a, |tree, _| tree.peers().is_empty())
1048            .await;
1049    }
1050
1051    #[gpui::test]
1052    async fn test_propagate_saves_and_fs_changes_in_shared_worktree(
1053        mut cx_a: TestAppContext,
1054        mut cx_b: TestAppContext,
1055        mut cx_c: TestAppContext,
1056    ) {
1057        cx_a.foreground().forbid_parking();
1058        let lang_registry = Arc::new(LanguageRegistry::new());
1059
1060        // Connect to a server as 3 clients.
1061        let mut server = TestServer::start().await;
1062        let (_, client_a) = server.create_client(&mut cx_a, "user_a").await;
1063        let (_, client_b) = server.create_client(&mut cx_b, "user_b").await;
1064        let (_, client_c) = server.create_client(&mut cx_c, "user_c").await;
1065
1066        let fs = Arc::new(FakeFs::new());
1067
1068        // Share a worktree as client A.
1069        fs.insert_tree(
1070            "/a",
1071            json!({
1072                "file1": "",
1073                "file2": ""
1074            }),
1075        )
1076        .await;
1077
1078        let worktree_a = Worktree::open_local(
1079            "/a".as_ref(),
1080            lang_registry.clone(),
1081            fs.clone(),
1082            &mut cx_a.to_async(),
1083        )
1084        .await
1085        .unwrap();
1086        worktree_a
1087            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1088            .await;
1089        let (worktree_id, worktree_token) = worktree_a
1090            .update(&mut cx_a, |tree, cx| {
1091                tree.as_local_mut().unwrap().share(client_a.clone(), cx)
1092            })
1093            .await
1094            .unwrap();
1095
1096        // Join that worktree as clients B and C.
1097        let worktree_b = Worktree::open_remote(
1098            client_b.clone(),
1099            worktree_id,
1100            worktree_token.clone(),
1101            lang_registry.clone(),
1102            &mut cx_b.to_async(),
1103        )
1104        .await
1105        .unwrap();
1106        let worktree_c = Worktree::open_remote(
1107            client_c.clone(),
1108            worktree_id,
1109            worktree_token,
1110            lang_registry.clone(),
1111            &mut cx_c.to_async(),
1112        )
1113        .await
1114        .unwrap();
1115
1116        // Open and edit a buffer as both guests B and C.
1117        let buffer_b = worktree_b
1118            .update(&mut cx_b, |tree, cx| tree.open_buffer("file1", cx))
1119            .await
1120            .unwrap();
1121        let buffer_c = worktree_c
1122            .update(&mut cx_c, |tree, cx| tree.open_buffer("file1", cx))
1123            .await
1124            .unwrap();
1125        buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "i-am-b, ", cx));
1126        buffer_c.update(&mut cx_c, |buf, cx| buf.edit([0..0], "i-am-c, ", cx));
1127
1128        // Open and edit that buffer as the host.
1129        let buffer_a = worktree_a
1130            .update(&mut cx_a, |tree, cx| tree.open_buffer("file1", cx))
1131            .await
1132            .unwrap();
1133
1134        buffer_a
1135            .condition(&mut cx_a, |buf, _| buf.text() == "i-am-c, i-am-b, ")
1136            .await;
1137        buffer_a.update(&mut cx_a, |buf, cx| {
1138            buf.edit([buf.len()..buf.len()], "i-am-a", cx)
1139        });
1140
1141        // Wait for edits to propagate
1142        buffer_a
1143            .condition(&mut cx_a, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1144            .await;
1145        buffer_b
1146            .condition(&mut cx_b, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1147            .await;
1148        buffer_c
1149            .condition(&mut cx_c, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1150            .await;
1151
1152        // Edit the buffer as the host and concurrently save as guest B.
1153        let save_b = buffer_b.update(&mut cx_b, |buf, cx| buf.save(cx).unwrap());
1154        buffer_a.update(&mut cx_a, |buf, cx| buf.edit([0..0], "hi-a, ", cx));
1155        save_b.await.unwrap();
1156        assert_eq!(
1157            fs.load("/a/file1".as_ref()).await.unwrap(),
1158            "hi-a, i-am-c, i-am-b, i-am-a"
1159        );
1160        buffer_a.read_with(&cx_a, |buf, _| assert!(!buf.is_dirty()));
1161        buffer_b.read_with(&cx_b, |buf, _| assert!(!buf.is_dirty()));
1162        buffer_c.condition(&cx_c, |buf, _| !buf.is_dirty()).await;
1163
1164        // Make changes on host's file system, see those changes on the guests.
1165        fs.rename("/a/file2".as_ref(), "/a/file3".as_ref())
1166            .await
1167            .unwrap();
1168        fs.insert_file(Path::new("/a/file4"), "4".into())
1169            .await
1170            .unwrap();
1171
1172        worktree_b
1173            .condition(&cx_b, |tree, _| tree.file_count() == 3)
1174            .await;
1175        worktree_c
1176            .condition(&cx_c, |tree, _| tree.file_count() == 3)
1177            .await;
1178        worktree_b.read_with(&cx_b, |tree, _| {
1179            assert_eq!(
1180                tree.paths()
1181                    .map(|p| p.to_string_lossy())
1182                    .collect::<Vec<_>>(),
1183                &["file1", "file3", "file4"]
1184            )
1185        });
1186        worktree_c.read_with(&cx_c, |tree, _| {
1187            assert_eq!(
1188                tree.paths()
1189                    .map(|p| p.to_string_lossy())
1190                    .collect::<Vec<_>>(),
1191                &["file1", "file3", "file4"]
1192            )
1193        });
1194    }
1195
1196    #[gpui::test]
1197    async fn test_buffer_conflict_after_save(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1198        cx_a.foreground().forbid_parking();
1199        let lang_registry = Arc::new(LanguageRegistry::new());
1200
1201        // Connect to a server as 2 clients.
1202        let mut server = TestServer::start().await;
1203        let (_, client_a) = server.create_client(&mut cx_a, "user_a").await;
1204        let (_, client_b) = server.create_client(&mut cx_b, "user_b").await;
1205
1206        // Share a local worktree as client A
1207        let fs = Arc::new(FakeFs::new());
1208        fs.save(Path::new("/a.txt"), &"a-contents".into())
1209            .await
1210            .unwrap();
1211        let worktree_a = Worktree::open_local(
1212            "/".as_ref(),
1213            lang_registry.clone(),
1214            fs,
1215            &mut cx_a.to_async(),
1216        )
1217        .await
1218        .unwrap();
1219        worktree_a
1220            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1221            .await;
1222        let (worktree_id, worktree_token) = worktree_a
1223            .update(&mut cx_a, |tree, cx| {
1224                tree.as_local_mut().unwrap().share(client_a.clone(), cx)
1225            })
1226            .await
1227            .unwrap();
1228
1229        // Join that worktree as client B, and see that a guest has joined as client A.
1230        let worktree_b = Worktree::open_remote(
1231            client_b.clone(),
1232            worktree_id,
1233            worktree_token,
1234            lang_registry.clone(),
1235            &mut cx_b.to_async(),
1236        )
1237        .await
1238        .unwrap();
1239
1240        let buffer_b = worktree_b
1241            .update(&mut cx_b, |worktree, cx| worktree.open_buffer("a.txt", cx))
1242            .await
1243            .unwrap();
1244        let mtime = buffer_b.read_with(&cx_b, |buf, _| buf.file().unwrap().mtime);
1245
1246        buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "world ", cx));
1247        buffer_b.read_with(&cx_b, |buf, _| {
1248            assert!(buf.is_dirty());
1249            assert!(!buf.has_conflict());
1250        });
1251
1252        buffer_b
1253            .update(&mut cx_b, |buf, cx| buf.save(cx))
1254            .unwrap()
1255            .await
1256            .unwrap();
1257        worktree_b
1258            .condition(&cx_b, |_, cx| {
1259                buffer_b.read(cx).file().unwrap().mtime != mtime
1260            })
1261            .await;
1262        buffer_b.read_with(&cx_b, |buf, _| {
1263            assert!(!buf.is_dirty());
1264            assert!(!buf.has_conflict());
1265        });
1266
1267        buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "hello ", cx));
1268        buffer_b.read_with(&cx_b, |buf, _| {
1269            assert!(buf.is_dirty());
1270            assert!(!buf.has_conflict());
1271        });
1272    }
1273
1274    #[gpui::test]
1275    async fn test_editing_while_guest_opens_buffer(
1276        mut cx_a: TestAppContext,
1277        mut cx_b: TestAppContext,
1278    ) {
1279        cx_a.foreground().forbid_parking();
1280        let lang_registry = Arc::new(LanguageRegistry::new());
1281
1282        // Connect to a server as 2 clients.
1283        let mut server = TestServer::start().await;
1284        let (_, client_a) = server.create_client(&mut cx_a, "user_a").await;
1285        let (_, client_b) = server.create_client(&mut cx_b, "user_b").await;
1286
1287        // Share a local worktree as client A
1288        let fs = Arc::new(FakeFs::new());
1289        fs.save(Path::new("/a.txt"), &"a-contents".into())
1290            .await
1291            .unwrap();
1292        let worktree_a = Worktree::open_local(
1293            "/".as_ref(),
1294            lang_registry.clone(),
1295            fs,
1296            &mut cx_a.to_async(),
1297        )
1298        .await
1299        .unwrap();
1300        worktree_a
1301            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1302            .await;
1303        let (worktree_id, worktree_token) = worktree_a
1304            .update(&mut cx_a, |tree, cx| {
1305                tree.as_local_mut().unwrap().share(client_a.clone(), cx)
1306            })
1307            .await
1308            .unwrap();
1309
1310        // Join that worktree as client B, and see that a guest has joined as client A.
1311        let worktree_b = Worktree::open_remote(
1312            client_b.clone(),
1313            worktree_id,
1314            worktree_token,
1315            lang_registry.clone(),
1316            &mut cx_b.to_async(),
1317        )
1318        .await
1319        .unwrap();
1320
1321        let buffer_a = worktree_a
1322            .update(&mut cx_a, |tree, cx| tree.open_buffer("a.txt", cx))
1323            .await
1324            .unwrap();
1325        let buffer_b = cx_b
1326            .background()
1327            .spawn(worktree_b.update(&mut cx_b, |worktree, cx| worktree.open_buffer("a.txt", cx)));
1328
1329        task::yield_now().await;
1330        buffer_a.update(&mut cx_a, |buf, cx| buf.edit([0..0], "z", cx));
1331
1332        let text = buffer_a.read_with(&cx_a, |buf, _| buf.text());
1333        let buffer_b = buffer_b.await.unwrap();
1334        buffer_b.condition(&cx_b, |buf, _| buf.text() == text).await;
1335    }
1336
1337    #[gpui::test]
1338    async fn test_peer_disconnection(mut cx_a: TestAppContext, cx_b: TestAppContext) {
1339        cx_a.foreground().forbid_parking();
1340        let lang_registry = Arc::new(LanguageRegistry::new());
1341
1342        // Connect to a server as 2 clients.
1343        let mut server = TestServer::start().await;
1344        let (_, client_a) = server.create_client(&mut cx_a, "user_a").await;
1345        let (_, client_b) = server.create_client(&mut cx_a, "user_b").await;
1346
1347        // Share a local worktree as client A
1348        let fs = Arc::new(FakeFs::new());
1349        fs.insert_tree(
1350            "/a",
1351            json!({
1352                "a.txt": "a-contents",
1353                "b.txt": "b-contents",
1354            }),
1355        )
1356        .await;
1357        let worktree_a = Worktree::open_local(
1358            "/a".as_ref(),
1359            lang_registry.clone(),
1360            fs,
1361            &mut cx_a.to_async(),
1362        )
1363        .await
1364        .unwrap();
1365        worktree_a
1366            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1367            .await;
1368        let (worktree_id, worktree_token) = worktree_a
1369            .update(&mut cx_a, |tree, cx| {
1370                tree.as_local_mut().unwrap().share(client_a.clone(), cx)
1371            })
1372            .await
1373            .unwrap();
1374
1375        // Join that worktree as client B, and see that a guest has joined as client A.
1376        let _worktree_b = Worktree::open_remote(
1377            client_b.clone(),
1378            worktree_id,
1379            worktree_token,
1380            lang_registry.clone(),
1381            &mut cx_b.to_async(),
1382        )
1383        .await
1384        .unwrap();
1385        worktree_a
1386            .condition(&cx_a, |tree, _| tree.peers().len() == 1)
1387            .await;
1388
1389        // Drop client B's connection and ensure client A observes client B leaving the worktree.
1390        client_b.disconnect().await.unwrap();
1391        worktree_a
1392            .condition(&cx_a, |tree, _| tree.peers().len() == 0)
1393            .await;
1394    }
1395
1396    #[gpui::test]
1397    async fn test_basic_chat(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1398        cx_a.foreground().forbid_parking();
1399
1400        // Connect to a server as 2 clients.
1401        let mut server = TestServer::start().await;
1402        let (user_id_a, client_a) = server.create_client(&mut cx_a, "user_a").await;
1403        let (user_id_b, client_b) = server.create_client(&mut cx_b, "user_b").await;
1404
1405        // Create an org that includes these 2 users.
1406        let db = &server.app_state.db;
1407        let org_id = db.create_org("Test Org", "test-org").await.unwrap();
1408        db.add_org_member(org_id, user_id_a, false).await.unwrap();
1409        db.add_org_member(org_id, user_id_b, false).await.unwrap();
1410
1411        // Create a channel that includes all the users.
1412        let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
1413        db.add_channel_member(channel_id, user_id_a, false)
1414            .await
1415            .unwrap();
1416        db.add_channel_member(channel_id, user_id_b, false)
1417            .await
1418            .unwrap();
1419        db.create_channel_message(
1420            channel_id,
1421            user_id_b,
1422            "hello A, it's B.",
1423            OffsetDateTime::now_utc(),
1424        )
1425        .await
1426        .unwrap();
1427
1428        let channels_a = cx_a.add_model(|cx| ChannelList::new(client_a, cx));
1429        channels_a
1430            .condition(&mut cx_a, |list, _| list.available_channels().is_some())
1431            .await;
1432        channels_a.read_with(&cx_a, |list, _| {
1433            assert_eq!(
1434                list.available_channels().unwrap(),
1435                &[ChannelDetails {
1436                    id: channel_id.to_proto(),
1437                    name: "test-channel".to_string()
1438                }]
1439            )
1440        });
1441        let channel_a = channels_a.update(&mut cx_a, |this, cx| {
1442            this.get_channel(channel_id.to_proto(), cx).unwrap()
1443        });
1444        channel_a.read_with(&cx_a, |channel, _| assert!(channel.messages().is_empty()));
1445        channel_a
1446            .condition(&cx_a, |channel, _| {
1447                channel_messages(channel)
1448                    == [(user_id_b.to_proto(), "hello A, it's B.".to_string())]
1449            })
1450            .await;
1451
1452        let channels_b = cx_b.add_model(|cx| ChannelList::new(client_b, cx));
1453        channels_b
1454            .condition(&mut cx_b, |list, _| list.available_channels().is_some())
1455            .await;
1456        channels_b.read_with(&cx_b, |list, _| {
1457            assert_eq!(
1458                list.available_channels().unwrap(),
1459                &[ChannelDetails {
1460                    id: channel_id.to_proto(),
1461                    name: "test-channel".to_string()
1462                }]
1463            )
1464        });
1465
1466        let channel_b = channels_b.update(&mut cx_b, |this, cx| {
1467            this.get_channel(channel_id.to_proto(), cx).unwrap()
1468        });
1469        channel_b.read_with(&cx_b, |channel, _| assert!(channel.messages().is_empty()));
1470        channel_b
1471            .condition(&cx_b, |channel, _| {
1472                channel_messages(channel)
1473                    == [(user_id_b.to_proto(), "hello A, it's B.".to_string())]
1474            })
1475            .await;
1476
1477        channel_a.update(&mut cx_a, |channel, cx| {
1478            channel.send_message("oh, hi B.".to_string(), cx).unwrap();
1479            channel.send_message("sup".to_string(), cx).unwrap();
1480            assert_eq!(
1481                channel
1482                    .pending_messages()
1483                    .iter()
1484                    .map(|m| &m.body)
1485                    .collect::<Vec<_>>(),
1486                &["oh, hi B.", "sup"]
1487            )
1488        });
1489
1490        channel_a
1491            .condition(&cx_a, |channel, _| channel.pending_messages().is_empty())
1492            .await;
1493        channel_b
1494            .condition(&cx_b, |channel, _| {
1495                channel_messages(channel)
1496                    == [
1497                        (user_id_b.to_proto(), "hello A, it's B.".to_string()),
1498                        (user_id_a.to_proto(), "oh, hi B.".to_string()),
1499                        (user_id_a.to_proto(), "sup".to_string()),
1500                    ]
1501            })
1502            .await;
1503
1504        assert_eq!(
1505            server.state().await.channels[&channel_id]
1506                .connection_ids
1507                .len(),
1508            2
1509        );
1510        cx_b.update(|_| drop(channel_b));
1511        server
1512            .condition(|state| state.channels[&channel_id].connection_ids.len() == 1)
1513            .await;
1514
1515        cx_a.update(|_| drop(channel_a));
1516        server
1517            .condition(|state| !state.channels.contains_key(&channel_id))
1518            .await;
1519
1520        fn channel_messages(channel: &Channel) -> Vec<(u64, String)> {
1521            channel
1522                .messages()
1523                .cursor::<(), ()>()
1524                .map(|m| (m.sender_id, m.body.clone()))
1525                .collect()
1526        }
1527    }
1528
1529    struct TestServer {
1530        peer: Arc<Peer>,
1531        app_state: Arc<AppState>,
1532        server: Arc<Server>,
1533        db_name: String,
1534        notifications: mpsc::Receiver<()>,
1535    }
1536
1537    impl TestServer {
1538        async fn start() -> Self {
1539            let mut rng = StdRng::from_entropy();
1540            let db_name = format!("zed-test-{}", rng.gen::<u128>());
1541            let app_state = Self::build_app_state(&db_name).await;
1542            let peer = Peer::new();
1543            let notifications = mpsc::channel(128);
1544            let server = Server::new(app_state.clone(), peer.clone(), Some(notifications.0));
1545            Self {
1546                peer,
1547                app_state,
1548                server,
1549                db_name,
1550                notifications: notifications.1,
1551            }
1552        }
1553
1554        async fn create_client(
1555            &mut self,
1556            cx: &mut TestAppContext,
1557            name: &str,
1558        ) -> (UserId, Arc<Client>) {
1559            let user_id = self.app_state.db.create_user(name, false).await.unwrap();
1560            let client = Client::new();
1561            let (client_conn, server_conn) = test::Channel::bidirectional();
1562            cx.background()
1563                .spawn(
1564                    self.server
1565                        .handle_connection(server_conn, name.to_string(), user_id),
1566                )
1567                .detach();
1568            client
1569                .add_connection(user_id.to_proto(), client_conn, cx.to_async())
1570                .await
1571                .unwrap();
1572            (user_id, client)
1573        }
1574
1575        async fn build_app_state(db_name: &str) -> Arc<AppState> {
1576            let mut config = Config::default();
1577            config.session_secret = "a".repeat(32);
1578            config.database_url = format!("postgres://postgres@localhost/{}", db_name);
1579
1580            Self::create_db(&config.database_url);
1581            let db = db::Db::test(&config.database_url, 5);
1582            db.migrate(Path::new(concat!(
1583                env!("CARGO_MANIFEST_DIR"),
1584                "/migrations"
1585            )));
1586
1587            let github_client = github::AppClient::test();
1588            Arc::new(AppState {
1589                db,
1590                handlebars: Default::default(),
1591                auth_client: auth::build_client("", ""),
1592                repo_client: github::RepoClient::test(&github_client),
1593                github_client,
1594                config,
1595            })
1596        }
1597
1598        fn create_db(url: &str) {
1599            // Enable tests to run in parallel by serializing the creation of each test database.
1600            lazy_static::lazy_static! {
1601                static ref DB_CREATION: std::sync::Mutex<()> = std::sync::Mutex::new(());
1602            }
1603
1604            let _lock = DB_CREATION.lock();
1605            block_on(Postgres::create_database(url)).expect("failed to create test database");
1606        }
1607
1608        async fn state<'a>(&'a self) -> RwLockReadGuard<'a, ServerState> {
1609            self.server.state.read().await
1610        }
1611
1612        async fn condition<F>(&mut self, mut predicate: F)
1613        where
1614            F: FnMut(&ServerState) -> bool,
1615        {
1616            async_std::future::timeout(Duration::from_millis(500), async {
1617                while !(predicate)(&*self.server.state.read().await) {
1618                    self.notifications.recv().await;
1619                }
1620            })
1621            .await
1622            .expect("condition timed out");
1623        }
1624    }
1625
1626    impl Drop for TestServer {
1627        fn drop(&mut self) {
1628            task::block_on(async {
1629                self.peer.reset().await;
1630                self.app_state.db.close(&self.db_name).await;
1631                Postgres::drop_database(&self.app_state.config.database_url)
1632                    .await
1633                    .unwrap();
1634            });
1635        }
1636    }
1637
1638    struct EmptyView;
1639
1640    impl gpui::Entity for EmptyView {
1641        type Event = ();
1642    }
1643
1644    impl gpui::View for EmptyView {
1645        fn ui_name() -> &'static str {
1646            "empty view"
1647        }
1648
1649        fn render<'a>(&self, _: &gpui::RenderContext<Self>) -> gpui::ElementBox {
1650            gpui::Element::boxed(gpui::elements::Empty)
1651        }
1652    }
1653}