rpc.rs

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