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