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::{tests::TestDb, UserId},
 923        github, AppState, Config,
 924    };
 925    use async_std::{sync::RwLockReadGuard, task};
 926    use gpui::TestAppContext;
 927    use postage::mpsc;
 928    use serde_json::json;
 929    use sqlx::types::time::OffsetDateTime;
 930    use std::{path::Path, sync::Arc, time::Duration};
 931    use zed::{
 932        channel::{Channel, ChannelDetails, ChannelList},
 933        editor::{Editor, Insert},
 934        fs::{FakeFs, Fs as _},
 935        language::LanguageRegistry,
 936        rpc::Client,
 937        settings, test,
 938        user::UserStore,
 939        worktree::Worktree,
 940    };
 941    use zrpc::Peer;
 942
 943    #[gpui::test]
 944    async fn test_share_worktree(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
 945        let (window_b, _) = cx_b.add_window(|_| EmptyView);
 946        let settings = cx_b.read(settings::test).1;
 947        let lang_registry = Arc::new(LanguageRegistry::new());
 948
 949        // Connect to a server as 2 clients.
 950        let mut server = TestServer::start().await;
 951        let (_, client_a) = server.create_client(&mut cx_a, "user_a").await;
 952        let (_, client_b) = server.create_client(&mut cx_b, "user_b").await;
 953
 954        cx_a.foreground().forbid_parking();
 955
 956        // Share a local worktree as client A
 957        let fs = Arc::new(FakeFs::new());
 958        fs.insert_tree(
 959            "/a",
 960            json!({
 961                "a.txt": "a-contents",
 962                "b.txt": "b-contents",
 963            }),
 964        )
 965        .await;
 966        let worktree_a = Worktree::open_local(
 967            "/a".as_ref(),
 968            lang_registry.clone(),
 969            fs,
 970            &mut cx_a.to_async(),
 971        )
 972        .await
 973        .unwrap();
 974        worktree_a
 975            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
 976            .await;
 977        let (worktree_id, worktree_token) = worktree_a
 978            .update(&mut cx_a, |tree, cx| {
 979                tree.as_local_mut().unwrap().share(client_a.clone(), cx)
 980            })
 981            .await
 982            .unwrap();
 983
 984        // Join that worktree as client B, and see that a guest has joined as client A.
 985        let worktree_b = Worktree::open_remote(
 986            client_b.clone(),
 987            worktree_id,
 988            worktree_token,
 989            lang_registry.clone(),
 990            &mut cx_b.to_async(),
 991        )
 992        .await
 993        .unwrap();
 994        let replica_id_b = worktree_b.read_with(&cx_b, |tree, _| tree.replica_id());
 995        worktree_a
 996            .condition(&cx_a, |tree, _| {
 997                tree.peers()
 998                    .values()
 999                    .any(|replica_id| *replica_id == replica_id_b)
1000            })
1001            .await;
1002
1003        // Open the same file as client B and client A.
1004        let buffer_b = worktree_b
1005            .update(&mut cx_b, |worktree, cx| worktree.open_buffer("b.txt", cx))
1006            .await
1007            .unwrap();
1008        buffer_b.read_with(&cx_b, |buf, _| assert_eq!(buf.text(), "b-contents"));
1009        worktree_a.read_with(&cx_a, |tree, cx| assert!(tree.has_open_buffer("b.txt", cx)));
1010        let buffer_a = worktree_a
1011            .update(&mut cx_a, |tree, cx| tree.open_buffer("b.txt", cx))
1012            .await
1013            .unwrap();
1014
1015        // Create a selection set as client B and see that selection set as client A.
1016        let editor_b = cx_b.add_view(window_b, |cx| Editor::for_buffer(buffer_b, settings, cx));
1017        buffer_a
1018            .condition(&cx_a, |buffer, _| buffer.selection_sets().count() == 1)
1019            .await;
1020
1021        // Edit the buffer as client B and see that edit as client A.
1022        editor_b.update(&mut cx_b, |editor, cx| {
1023            editor.insert(&Insert("ok, ".into()), cx)
1024        });
1025        buffer_a
1026            .condition(&cx_a, |buffer, _| buffer.text() == "ok, b-contents")
1027            .await;
1028
1029        // Remove the selection set as client B, see those selections disappear as client A.
1030        cx_b.update(move |_| drop(editor_b));
1031        buffer_a
1032            .condition(&cx_a, |buffer, _| buffer.selection_sets().count() == 0)
1033            .await;
1034
1035        // Close the buffer as client A, see that the buffer is closed.
1036        drop(buffer_a);
1037        worktree_a
1038            .condition(&cx_a, |tree, cx| !tree.has_open_buffer("b.txt", cx))
1039            .await;
1040
1041        // Dropping the worktree removes client B from client A's peers.
1042        cx_b.update(move |_| drop(worktree_b));
1043        worktree_a
1044            .condition(&cx_a, |tree, _| tree.peers().is_empty())
1045            .await;
1046    }
1047
1048    #[gpui::test]
1049    async fn test_propagate_saves_and_fs_changes_in_shared_worktree(
1050        mut cx_a: TestAppContext,
1051        mut cx_b: TestAppContext,
1052        mut cx_c: TestAppContext,
1053    ) {
1054        cx_a.foreground().forbid_parking();
1055        let lang_registry = Arc::new(LanguageRegistry::new());
1056
1057        // Connect to a server as 3 clients.
1058        let mut server = TestServer::start().await;
1059        let (_, client_a) = server.create_client(&mut cx_a, "user_a").await;
1060        let (_, client_b) = server.create_client(&mut cx_b, "user_b").await;
1061        let (_, client_c) = server.create_client(&mut cx_c, "user_c").await;
1062
1063        let fs = Arc::new(FakeFs::new());
1064
1065        // Share a worktree as client A.
1066        fs.insert_tree(
1067            "/a",
1068            json!({
1069                "file1": "",
1070                "file2": ""
1071            }),
1072        )
1073        .await;
1074
1075        let worktree_a = Worktree::open_local(
1076            "/a".as_ref(),
1077            lang_registry.clone(),
1078            fs.clone(),
1079            &mut cx_a.to_async(),
1080        )
1081        .await
1082        .unwrap();
1083        worktree_a
1084            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1085            .await;
1086        let (worktree_id, worktree_token) = worktree_a
1087            .update(&mut cx_a, |tree, cx| {
1088                tree.as_local_mut().unwrap().share(client_a.clone(), cx)
1089            })
1090            .await
1091            .unwrap();
1092
1093        // Join that worktree as clients B and C.
1094        let worktree_b = Worktree::open_remote(
1095            client_b.clone(),
1096            worktree_id,
1097            worktree_token.clone(),
1098            lang_registry.clone(),
1099            &mut cx_b.to_async(),
1100        )
1101        .await
1102        .unwrap();
1103        let worktree_c = Worktree::open_remote(
1104            client_c.clone(),
1105            worktree_id,
1106            worktree_token,
1107            lang_registry.clone(),
1108            &mut cx_c.to_async(),
1109        )
1110        .await
1111        .unwrap();
1112
1113        // Open and edit a buffer as both guests B and C.
1114        let buffer_b = worktree_b
1115            .update(&mut cx_b, |tree, cx| tree.open_buffer("file1", cx))
1116            .await
1117            .unwrap();
1118        let buffer_c = worktree_c
1119            .update(&mut cx_c, |tree, cx| tree.open_buffer("file1", cx))
1120            .await
1121            .unwrap();
1122        buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "i-am-b, ", cx));
1123        buffer_c.update(&mut cx_c, |buf, cx| buf.edit([0..0], "i-am-c, ", cx));
1124
1125        // Open and edit that buffer as the host.
1126        let buffer_a = worktree_a
1127            .update(&mut cx_a, |tree, cx| tree.open_buffer("file1", cx))
1128            .await
1129            .unwrap();
1130
1131        buffer_a
1132            .condition(&mut cx_a, |buf, _| buf.text() == "i-am-c, i-am-b, ")
1133            .await;
1134        buffer_a.update(&mut cx_a, |buf, cx| {
1135            buf.edit([buf.len()..buf.len()], "i-am-a", cx)
1136        });
1137
1138        // Wait for edits to propagate
1139        buffer_a
1140            .condition(&mut cx_a, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1141            .await;
1142        buffer_b
1143            .condition(&mut cx_b, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1144            .await;
1145        buffer_c
1146            .condition(&mut cx_c, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1147            .await;
1148
1149        // Edit the buffer as the host and concurrently save as guest B.
1150        let save_b = buffer_b.update(&mut cx_b, |buf, cx| buf.save(cx).unwrap());
1151        buffer_a.update(&mut cx_a, |buf, cx| buf.edit([0..0], "hi-a, ", cx));
1152        save_b.await.unwrap();
1153        assert_eq!(
1154            fs.load("/a/file1".as_ref()).await.unwrap(),
1155            "hi-a, i-am-c, i-am-b, i-am-a"
1156        );
1157        buffer_a.read_with(&cx_a, |buf, _| assert!(!buf.is_dirty()));
1158        buffer_b.read_with(&cx_b, |buf, _| assert!(!buf.is_dirty()));
1159        buffer_c.condition(&cx_c, |buf, _| !buf.is_dirty()).await;
1160
1161        // Make changes on host's file system, see those changes on the guests.
1162        fs.rename("/a/file2".as_ref(), "/a/file3".as_ref())
1163            .await
1164            .unwrap();
1165        fs.insert_file(Path::new("/a/file4"), "4".into())
1166            .await
1167            .unwrap();
1168
1169        worktree_b
1170            .condition(&cx_b, |tree, _| tree.file_count() == 3)
1171            .await;
1172        worktree_c
1173            .condition(&cx_c, |tree, _| tree.file_count() == 3)
1174            .await;
1175        worktree_b.read_with(&cx_b, |tree, _| {
1176            assert_eq!(
1177                tree.paths()
1178                    .map(|p| p.to_string_lossy())
1179                    .collect::<Vec<_>>(),
1180                &["file1", "file3", "file4"]
1181            )
1182        });
1183        worktree_c.read_with(&cx_c, |tree, _| {
1184            assert_eq!(
1185                tree.paths()
1186                    .map(|p| p.to_string_lossy())
1187                    .collect::<Vec<_>>(),
1188                &["file1", "file3", "file4"]
1189            )
1190        });
1191    }
1192
1193    #[gpui::test]
1194    async fn test_buffer_conflict_after_save(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1195        cx_a.foreground().forbid_parking();
1196        let lang_registry = Arc::new(LanguageRegistry::new());
1197
1198        // Connect to a server as 2 clients.
1199        let mut server = TestServer::start().await;
1200        let (_, client_a) = server.create_client(&mut cx_a, "user_a").await;
1201        let (_, client_b) = server.create_client(&mut cx_b, "user_b").await;
1202
1203        // Share a local worktree as client A
1204        let fs = Arc::new(FakeFs::new());
1205        fs.save(Path::new("/a.txt"), &"a-contents".into())
1206            .await
1207            .unwrap();
1208        let worktree_a = Worktree::open_local(
1209            "/".as_ref(),
1210            lang_registry.clone(),
1211            fs,
1212            &mut cx_a.to_async(),
1213        )
1214        .await
1215        .unwrap();
1216        worktree_a
1217            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1218            .await;
1219        let (worktree_id, worktree_token) = worktree_a
1220            .update(&mut cx_a, |tree, cx| {
1221                tree.as_local_mut().unwrap().share(client_a.clone(), cx)
1222            })
1223            .await
1224            .unwrap();
1225
1226        // Join that worktree as client B, and see that a guest has joined as client A.
1227        let worktree_b = Worktree::open_remote(
1228            client_b.clone(),
1229            worktree_id,
1230            worktree_token,
1231            lang_registry.clone(),
1232            &mut cx_b.to_async(),
1233        )
1234        .await
1235        .unwrap();
1236
1237        let buffer_b = worktree_b
1238            .update(&mut cx_b, |worktree, cx| worktree.open_buffer("a.txt", cx))
1239            .await
1240            .unwrap();
1241        let mtime = buffer_b.read_with(&cx_b, |buf, _| buf.file().unwrap().mtime);
1242
1243        buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "world ", cx));
1244        buffer_b.read_with(&cx_b, |buf, _| {
1245            assert!(buf.is_dirty());
1246            assert!(!buf.has_conflict());
1247        });
1248
1249        buffer_b
1250            .update(&mut cx_b, |buf, cx| buf.save(cx))
1251            .unwrap()
1252            .await
1253            .unwrap();
1254        worktree_b
1255            .condition(&cx_b, |_, cx| {
1256                buffer_b.read(cx).file().unwrap().mtime != mtime
1257            })
1258            .await;
1259        buffer_b.read_with(&cx_b, |buf, _| {
1260            assert!(!buf.is_dirty());
1261            assert!(!buf.has_conflict());
1262        });
1263
1264        buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "hello ", cx));
1265        buffer_b.read_with(&cx_b, |buf, _| {
1266            assert!(buf.is_dirty());
1267            assert!(!buf.has_conflict());
1268        });
1269    }
1270
1271    #[gpui::test]
1272    async fn test_editing_while_guest_opens_buffer(
1273        mut cx_a: TestAppContext,
1274        mut cx_b: TestAppContext,
1275    ) {
1276        cx_a.foreground().forbid_parking();
1277        let lang_registry = Arc::new(LanguageRegistry::new());
1278
1279        // Connect to a server as 2 clients.
1280        let mut server = TestServer::start().await;
1281        let (_, client_a) = server.create_client(&mut cx_a, "user_a").await;
1282        let (_, client_b) = server.create_client(&mut cx_b, "user_b").await;
1283
1284        // Share a local worktree as client A
1285        let fs = Arc::new(FakeFs::new());
1286        fs.save(Path::new("/a.txt"), &"a-contents".into())
1287            .await
1288            .unwrap();
1289        let worktree_a = Worktree::open_local(
1290            "/".as_ref(),
1291            lang_registry.clone(),
1292            fs,
1293            &mut cx_a.to_async(),
1294        )
1295        .await
1296        .unwrap();
1297        worktree_a
1298            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1299            .await;
1300        let (worktree_id, worktree_token) = worktree_a
1301            .update(&mut cx_a, |tree, cx| {
1302                tree.as_local_mut().unwrap().share(client_a.clone(), cx)
1303            })
1304            .await
1305            .unwrap();
1306
1307        // Join that worktree as client B, and see that a guest has joined as client A.
1308        let worktree_b = Worktree::open_remote(
1309            client_b.clone(),
1310            worktree_id,
1311            worktree_token,
1312            lang_registry.clone(),
1313            &mut cx_b.to_async(),
1314        )
1315        .await
1316        .unwrap();
1317
1318        let buffer_a = worktree_a
1319            .update(&mut cx_a, |tree, cx| tree.open_buffer("a.txt", cx))
1320            .await
1321            .unwrap();
1322        let buffer_b = cx_b
1323            .background()
1324            .spawn(worktree_b.update(&mut cx_b, |worktree, cx| worktree.open_buffer("a.txt", cx)));
1325
1326        task::yield_now().await;
1327        buffer_a.update(&mut cx_a, |buf, cx| buf.edit([0..0], "z", cx));
1328
1329        let text = buffer_a.read_with(&cx_a, |buf, _| buf.text());
1330        let buffer_b = buffer_b.await.unwrap();
1331        buffer_b.condition(&cx_b, |buf, _| buf.text() == text).await;
1332    }
1333
1334    #[gpui::test]
1335    async fn test_peer_disconnection(mut cx_a: TestAppContext, cx_b: TestAppContext) {
1336        cx_a.foreground().forbid_parking();
1337        let lang_registry = Arc::new(LanguageRegistry::new());
1338
1339        // Connect to a server as 2 clients.
1340        let mut server = TestServer::start().await;
1341        let (_, client_a) = server.create_client(&mut cx_a, "user_a").await;
1342        let (_, client_b) = server.create_client(&mut cx_a, "user_b").await;
1343
1344        // Share a local worktree as client A
1345        let fs = Arc::new(FakeFs::new());
1346        fs.insert_tree(
1347            "/a",
1348            json!({
1349                "a.txt": "a-contents",
1350                "b.txt": "b-contents",
1351            }),
1352        )
1353        .await;
1354        let worktree_a = Worktree::open_local(
1355            "/a".as_ref(),
1356            lang_registry.clone(),
1357            fs,
1358            &mut cx_a.to_async(),
1359        )
1360        .await
1361        .unwrap();
1362        worktree_a
1363            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1364            .await;
1365        let (worktree_id, worktree_token) = worktree_a
1366            .update(&mut cx_a, |tree, cx| {
1367                tree.as_local_mut().unwrap().share(client_a.clone(), cx)
1368            })
1369            .await
1370            .unwrap();
1371
1372        // Join that worktree as client B, and see that a guest has joined as client A.
1373        let _worktree_b = Worktree::open_remote(
1374            client_b.clone(),
1375            worktree_id,
1376            worktree_token,
1377            lang_registry.clone(),
1378            &mut cx_b.to_async(),
1379        )
1380        .await
1381        .unwrap();
1382        worktree_a
1383            .condition(&cx_a, |tree, _| tree.peers().len() == 1)
1384            .await;
1385
1386        // Drop client B's connection and ensure client A observes client B leaving the worktree.
1387        client_b.disconnect().await.unwrap();
1388        worktree_a
1389            .condition(&cx_a, |tree, _| tree.peers().len() == 0)
1390            .await;
1391    }
1392
1393    #[gpui::test]
1394    async fn test_basic_chat(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1395        cx_a.foreground().forbid_parking();
1396
1397        // Connect to a server as 2 clients.
1398        let mut server = TestServer::start().await;
1399        let (user_id_a, client_a) = server.create_client(&mut cx_a, "user_a").await;
1400        let (user_id_b, client_b) = server.create_client(&mut cx_b, "user_b").await;
1401
1402        // Create an org that includes these 2 users.
1403        let db = &server.app_state.db;
1404        let org_id = db.create_org("Test Org", "test-org").await.unwrap();
1405        db.add_org_member(org_id, user_id_a, false).await.unwrap();
1406        db.add_org_member(org_id, user_id_b, false).await.unwrap();
1407
1408        // Create a channel that includes all the users.
1409        let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
1410        db.add_channel_member(channel_id, user_id_a, false)
1411            .await
1412            .unwrap();
1413        db.add_channel_member(channel_id, user_id_b, false)
1414            .await
1415            .unwrap();
1416        db.create_channel_message(
1417            channel_id,
1418            user_id_b,
1419            "hello A, it's B.",
1420            OffsetDateTime::now_utc(),
1421        )
1422        .await
1423        .unwrap();
1424
1425        let user_store_a = Arc::new(UserStore::new(client_a.clone()));
1426        let channels_a = cx_a.add_model(|cx| ChannelList::new(user_store_a, client_a, cx));
1427        channels_a
1428            .condition(&mut cx_a, |list, _| list.available_channels().is_some())
1429            .await;
1430        channels_a.read_with(&cx_a, |list, _| {
1431            assert_eq!(
1432                list.available_channels().unwrap(),
1433                &[ChannelDetails {
1434                    id: channel_id.to_proto(),
1435                    name: "test-channel".to_string()
1436                }]
1437            )
1438        });
1439        let channel_a = channels_a.update(&mut cx_a, |this, cx| {
1440            this.get_channel(channel_id.to_proto(), cx).unwrap()
1441        });
1442        channel_a.read_with(&cx_a, |channel, _| assert!(channel.messages().is_empty()));
1443        channel_a
1444            .condition(&cx_a, |channel, _| {
1445                channel_messages(channel)
1446                    == [("user_b".to_string(), "hello A, it's B.".to_string())]
1447            })
1448            .await;
1449
1450        let user_store_b = Arc::new(UserStore::new(client_b.clone()));
1451        let channels_b = cx_b.add_model(|cx| ChannelList::new(user_store_b, client_b, cx));
1452        channels_b
1453            .condition(&mut cx_b, |list, _| list.available_channels().is_some())
1454            .await;
1455        channels_b.read_with(&cx_b, |list, _| {
1456            assert_eq!(
1457                list.available_channels().unwrap(),
1458                &[ChannelDetails {
1459                    id: channel_id.to_proto(),
1460                    name: "test-channel".to_string()
1461                }]
1462            )
1463        });
1464
1465        let channel_b = channels_b.update(&mut cx_b, |this, cx| {
1466            this.get_channel(channel_id.to_proto(), cx).unwrap()
1467        });
1468        channel_b.read_with(&cx_b, |channel, _| assert!(channel.messages().is_empty()));
1469        channel_b
1470            .condition(&cx_b, |channel, _| {
1471                channel_messages(channel)
1472                    == [("user_b".to_string(), "hello A, it's B.".to_string())]
1473            })
1474            .await;
1475
1476        channel_a.update(&mut cx_a, |channel, cx| {
1477            channel.send_message("oh, hi B.".to_string(), cx).unwrap();
1478            channel.send_message("sup".to_string(), cx).unwrap();
1479            assert_eq!(
1480                channel
1481                    .pending_messages()
1482                    .iter()
1483                    .map(|m| &m.body)
1484                    .collect::<Vec<_>>(),
1485                &["oh, hi B.", "sup"]
1486            )
1487        });
1488
1489        channel_a
1490            .condition(&cx_a, |channel, _| channel.pending_messages().is_empty())
1491            .await;
1492        channel_b
1493            .condition(&cx_b, |channel, _| {
1494                channel_messages(channel)
1495                    == [
1496                        ("user_b".to_string(), "hello A, it's B.".to_string()),
1497                        ("user_a".to_string(), "oh, hi B.".to_string()),
1498                        ("user_a".to_string(), "sup".to_string()),
1499                    ]
1500            })
1501            .await;
1502
1503        assert_eq!(
1504            server.state().await.channels[&channel_id]
1505                .connection_ids
1506                .len(),
1507            2
1508        );
1509        cx_b.update(|_| drop(channel_b));
1510        server
1511            .condition(|state| state.channels[&channel_id].connection_ids.len() == 1)
1512            .await;
1513
1514        cx_a.update(|_| drop(channel_a));
1515        server
1516            .condition(|state| !state.channels.contains_key(&channel_id))
1517            .await;
1518
1519        fn channel_messages(channel: &Channel) -> Vec<(String, String)> {
1520            channel
1521                .messages()
1522                .cursor::<(), ()>()
1523                .map(|m| (m.sender.github_login.clone(), m.body.clone()))
1524                .collect()
1525        }
1526    }
1527
1528    struct TestServer {
1529        peer: Arc<Peer>,
1530        app_state: Arc<AppState>,
1531        server: Arc<Server>,
1532        notifications: mpsc::Receiver<()>,
1533        _test_db: TestDb,
1534    }
1535
1536    impl TestServer {
1537        async fn start() -> Self {
1538            let test_db = TestDb::new();
1539            let app_state = Self::build_app_state(&test_db).await;
1540            let peer = Peer::new();
1541            let notifications = mpsc::channel(128);
1542            let server = Server::new(app_state.clone(), peer.clone(), Some(notifications.0));
1543            Self {
1544                peer,
1545                app_state,
1546                server,
1547                notifications: notifications.1,
1548                _test_db: test_db,
1549            }
1550        }
1551
1552        async fn create_client(
1553            &mut self,
1554            cx: &mut TestAppContext,
1555            name: &str,
1556        ) -> (UserId, Arc<Client>) {
1557            let user_id = self.app_state.db.create_user(name, false).await.unwrap();
1558            let client = Client::new();
1559            let (client_conn, server_conn) = test::Channel::bidirectional();
1560            cx.background()
1561                .spawn(
1562                    self.server
1563                        .handle_connection(server_conn, name.to_string(), user_id),
1564                )
1565                .detach();
1566            client
1567                .add_connection(user_id.to_proto(), client_conn, cx.to_async())
1568                .await
1569                .unwrap();
1570            (user_id, client)
1571        }
1572
1573        async fn build_app_state(test_db: &TestDb) -> Arc<AppState> {
1574            let mut config = Config::default();
1575            config.session_secret = "a".repeat(32);
1576            config.database_url = test_db.url.clone();
1577            let github_client = github::AppClient::test();
1578            Arc::new(AppState {
1579                db: test_db.db().clone(),
1580                handlebars: Default::default(),
1581                auth_client: auth::build_client("", ""),
1582                repo_client: github::RepoClient::test(&github_client),
1583                github_client,
1584                config,
1585            })
1586        }
1587
1588        async fn state<'a>(&'a self) -> RwLockReadGuard<'a, ServerState> {
1589            self.server.state.read().await
1590        }
1591
1592        async fn condition<F>(&mut self, mut predicate: F)
1593        where
1594            F: FnMut(&ServerState) -> bool,
1595        {
1596            async_std::future::timeout(Duration::from_millis(500), async {
1597                while !(predicate)(&*self.server.state.read().await) {
1598                    self.notifications.recv().await;
1599                }
1600            })
1601            .await
1602            .expect("condition timed out");
1603        }
1604    }
1605
1606    impl Drop for TestServer {
1607        fn drop(&mut self) {
1608            task::block_on(self.peer.reset());
1609        }
1610    }
1611
1612    struct EmptyView;
1613
1614    impl gpui::Entity for EmptyView {
1615        type Event = ();
1616    }
1617
1618    impl gpui::View for EmptyView {
1619        fn ui_name() -> &'static str {
1620            "empty view"
1621        }
1622
1623        fn render(&self, _: &mut gpui::RenderContext<Self>) -> gpui::ElementBox {
1624            gpui::Element::boxed(gpui::elements::Empty)
1625        }
1626    }
1627}