rpc.rs

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