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::{tungstenite::protocol::Role, WebSocketStream};
   9use futures::{future::BoxFuture, FutureExt};
  10use postage::{mpsc, prelude::Sink as _, prelude::Stream as _};
  11use sha1::{Digest as _, Sha1};
  12use std::{
  13    any::TypeId,
  14    collections::{hash_map, HashMap, HashSet},
  15    future::Future,
  16    mem,
  17    sync::Arc,
  18    time::Instant,
  19};
  20use surf::StatusCode;
  21use tide::log;
  22use tide::{
  23    http::headers::{HeaderName, CONNECTION, UPGRADE},
  24    Request, Response,
  25};
  26use time::OffsetDateTime;
  27use zrpc::{
  28    auth::random_token,
  29    proto::{self, AnyTypedEnvelope, EnvelopedMessage},
  30    Conn, ConnectionId, Peer, TypedEnvelope,
  31};
  32
  33type ReplicaId = u16;
  34
  35type MessageHandler = Box<
  36    dyn Send
  37        + Sync
  38        + Fn(Arc<Server>, Box<dyn AnyTypedEnvelope>) -> BoxFuture<'static, tide::Result<()>>,
  39>;
  40
  41pub struct Server {
  42    peer: Arc<Peer>,
  43    state: RwLock<ServerState>,
  44    app_state: Arc<AppState>,
  45    handlers: HashMap<TypeId, MessageHandler>,
  46    notifications: Option<mpsc::Sender<()>>,
  47}
  48
  49#[derive(Default)]
  50struct ServerState {
  51    connections: HashMap<ConnectionId, Connection>,
  52    pub worktrees: HashMap<u64, Worktree>,
  53    channels: HashMap<ChannelId, Channel>,
  54    next_worktree_id: u64,
  55}
  56
  57struct Connection {
  58    user_id: UserId,
  59    worktrees: HashSet<u64>,
  60    channels: HashSet<ChannelId>,
  61}
  62
  63struct Worktree {
  64    host_connection_id: Option<ConnectionId>,
  65    guest_connection_ids: HashMap<ConnectionId, ReplicaId>,
  66    active_replica_ids: HashSet<ReplicaId>,
  67    access_token: String,
  68    root_name: String,
  69    entries: HashMap<u64, proto::Entry>,
  70}
  71
  72#[derive(Default)]
  73struct Channel {
  74    connection_ids: HashSet<ConnectionId>,
  75}
  76
  77const MESSAGE_COUNT_PER_PAGE: usize = 100;
  78const MAX_MESSAGE_LEN: usize = 1024;
  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::ping)
  96            .add_handler(Server::share_worktree)
  97            .add_handler(Server::join_worktree)
  98            .add_handler(Server::update_worktree)
  99            .add_handler(Server::close_worktree)
 100            .add_handler(Server::open_buffer)
 101            .add_handler(Server::close_buffer)
 102            .add_handler(Server::update_buffer)
 103            .add_handler(Server::buffer_saved)
 104            .add_handler(Server::save_buffer)
 105            .add_handler(Server::get_channels)
 106            .add_handler(Server::get_users)
 107            .add_handler(Server::join_channel)
 108            .add_handler(Server::leave_channel)
 109            .add_handler(Server::send_channel_message)
 110            .add_handler(Server::get_channel_messages);
 111
 112        Arc::new(server)
 113    }
 114
 115    fn add_handler<F, Fut, M>(&mut self, handler: F) -> &mut Self
 116    where
 117        F: 'static + Send + Sync + Fn(Arc<Self>, TypedEnvelope<M>) -> Fut,
 118        Fut: 'static + Send + Future<Output = tide::Result<()>>,
 119        M: EnvelopedMessage,
 120    {
 121        let prev_handler = self.handlers.insert(
 122            TypeId::of::<M>(),
 123            Box::new(move |server, envelope| {
 124                let envelope = envelope.into_any().downcast::<TypedEnvelope<M>>().unwrap();
 125                (handler)(server, *envelope).boxed()
 126            }),
 127        );
 128        if prev_handler.is_some() {
 129            panic!("registered a handler for the same message twice");
 130        }
 131        self
 132    }
 133
 134    pub fn handle_connection(
 135        self: &Arc<Self>,
 136        connection: Conn,
 137        addr: String,
 138        user_id: UserId,
 139    ) -> impl Future<Output = ()> {
 140        let this = self.clone();
 141        async move {
 142            let (connection_id, handle_io, mut incoming_rx) =
 143                this.peer.add_connection(connection).await;
 144            this.add_connection(connection_id, user_id).await;
 145
 146            let handle_io = handle_io.fuse();
 147            futures::pin_mut!(handle_io);
 148            loop {
 149                let next_message = incoming_rx.recv().fuse();
 150                futures::pin_mut!(next_message);
 151                futures::select_biased! {
 152                    message = next_message => {
 153                        if let Some(message) = message {
 154                            let start_time = Instant::now();
 155                            log::info!("RPC message received: {}", message.payload_type_name());
 156                            if let Some(handler) = this.handlers.get(&message.payload_type_id()) {
 157                                if let Err(err) = (handler)(this.clone(), message).await {
 158                                    log::error!("error handling message: {:?}", err);
 159                                } else {
 160                                    log::info!("RPC message handled. duration:{:?}", start_time.elapsed());
 161                                }
 162
 163                                if let Some(mut notifications) = this.notifications.clone() {
 164                                    let _ = notifications.send(()).await;
 165                                }
 166                            } else {
 167                                log::warn!("unhandled message: {}", message.payload_type_name());
 168                            }
 169                        } else {
 170                            log::info!("rpc connection closed {:?}", addr);
 171                            break;
 172                        }
 173                    }
 174                    handle_io = handle_io => {
 175                        if let Err(err) = handle_io {
 176                            log::error!("error handling rpc connection {:?} - {:?}", addr, err);
 177                        }
 178                        break;
 179                    }
 180                }
 181            }
 182
 183            if let Err(err) = this.sign_out(connection_id).await {
 184                log::error!("error signing out connection {:?} - {:?}", addr, err);
 185            }
 186        }
 187    }
 188
 189    async fn sign_out(self: &Arc<Self>, connection_id: zrpc::ConnectionId) -> tide::Result<()> {
 190        self.peer.disconnect(connection_id).await;
 191        let worktree_ids = self.remove_connection(connection_id).await;
 192        for worktree_id in worktree_ids {
 193            let state = self.state.read().await;
 194            if let Some(worktree) = state.worktrees.get(&worktree_id) {
 195                broadcast(connection_id, worktree.connection_ids(), |conn_id| {
 196                    self.peer.send(
 197                        conn_id,
 198                        proto::RemovePeer {
 199                            worktree_id,
 200                            peer_id: connection_id.0,
 201                        },
 202                    )
 203                })
 204                .await?;
 205            }
 206        }
 207        Ok(())
 208    }
 209
 210    // Add a new connection associated with a given user.
 211    async fn add_connection(&self, connection_id: ConnectionId, user_id: UserId) {
 212        self.state.write().await.connections.insert(
 213            connection_id,
 214            Connection {
 215                user_id,
 216                worktrees: Default::default(),
 217                channels: Default::default(),
 218            },
 219        );
 220    }
 221
 222    // Remove the given connection and its association with any worktrees.
 223    async fn remove_connection(&self, connection_id: ConnectionId) -> Vec<u64> {
 224        let mut worktree_ids = Vec::new();
 225        let mut state = self.state.write().await;
 226        if let Some(connection) = state.connections.remove(&connection_id) {
 227            for channel_id in connection.channels {
 228                if let Some(channel) = state.channels.get_mut(&channel_id) {
 229                    channel.connection_ids.remove(&connection_id);
 230                }
 231            }
 232            for worktree_id in connection.worktrees {
 233                if let Some(worktree) = state.worktrees.get_mut(&worktree_id) {
 234                    if worktree.host_connection_id == Some(connection_id) {
 235                        worktree_ids.push(worktree_id);
 236                    } else if let Some(replica_id) =
 237                        worktree.guest_connection_ids.remove(&connection_id)
 238                    {
 239                        worktree.active_replica_ids.remove(&replica_id);
 240                        worktree_ids.push(worktree_id);
 241                    }
 242                }
 243            }
 244        }
 245        worktree_ids
 246    }
 247
 248    async fn ping(self: Arc<Server>, request: TypedEnvelope<proto::Ping>) -> tide::Result<()> {
 249        self.peer.respond(request.receipt(), proto::Ack {}).await?;
 250        Ok(())
 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        self.peer.respond(request.receipt(), proto::Ack {}).await?;
 504        Ok(())
 505    }
 506
 507    async fn buffer_saved(
 508        self: Arc<Server>,
 509        request: TypedEnvelope<proto::BufferSaved>,
 510    ) -> tide::Result<()> {
 511        self.broadcast_in_worktree(request.payload.worktree_id, &request)
 512            .await
 513    }
 514
 515    async fn get_channels(
 516        self: Arc<Server>,
 517        request: TypedEnvelope<proto::GetChannels>,
 518    ) -> tide::Result<()> {
 519        let user_id = self
 520            .state
 521            .read()
 522            .await
 523            .user_id_for_connection(request.sender_id)?;
 524        let channels = self.app_state.db.get_accessible_channels(user_id).await?;
 525        self.peer
 526            .respond(
 527                request.receipt(),
 528                proto::GetChannelsResponse {
 529                    channels: channels
 530                        .into_iter()
 531                        .map(|chan| proto::Channel {
 532                            id: chan.id.to_proto(),
 533                            name: chan.name,
 534                        })
 535                        .collect(),
 536                },
 537            )
 538            .await?;
 539        Ok(())
 540    }
 541
 542    async fn get_users(
 543        self: Arc<Server>,
 544        request: TypedEnvelope<proto::GetUsers>,
 545    ) -> tide::Result<()> {
 546        let user_id = self
 547            .state
 548            .read()
 549            .await
 550            .user_id_for_connection(request.sender_id)?;
 551        let receipt = request.receipt();
 552        let user_ids = request.payload.user_ids.into_iter().map(UserId::from_proto);
 553        let users = self
 554            .app_state
 555            .db
 556            .get_users_by_ids(user_id, user_ids)
 557            .await?
 558            .into_iter()
 559            .map(|user| proto::User {
 560                id: user.id.to_proto(),
 561                github_login: user.github_login,
 562                avatar_url: String::new(),
 563            })
 564            .collect();
 565        self.peer
 566            .respond(receipt, proto::GetUsersResponse { users })
 567            .await?;
 568        Ok(())
 569    }
 570
 571    async fn join_channel(
 572        self: Arc<Self>,
 573        request: TypedEnvelope<proto::JoinChannel>,
 574    ) -> tide::Result<()> {
 575        let user_id = self
 576            .state
 577            .read()
 578            .await
 579            .user_id_for_connection(request.sender_id)?;
 580        let channel_id = ChannelId::from_proto(request.payload.channel_id);
 581        if !self
 582            .app_state
 583            .db
 584            .can_user_access_channel(user_id, channel_id)
 585            .await?
 586        {
 587            Err(anyhow!("access denied"))?;
 588        }
 589
 590        self.state
 591            .write()
 592            .await
 593            .join_channel(request.sender_id, channel_id);
 594        let messages = self
 595            .app_state
 596            .db
 597            .get_channel_messages(channel_id, MESSAGE_COUNT_PER_PAGE, None)
 598            .await?
 599            .into_iter()
 600            .map(|msg| proto::ChannelMessage {
 601                id: msg.id.to_proto(),
 602                body: msg.body,
 603                timestamp: msg.sent_at.unix_timestamp() as u64,
 604                sender_id: msg.sender_id.to_proto(),
 605            })
 606            .collect::<Vec<_>>();
 607        self.peer
 608            .respond(
 609                request.receipt(),
 610                proto::JoinChannelResponse {
 611                    done: messages.len() < MESSAGE_COUNT_PER_PAGE,
 612                    messages,
 613                },
 614            )
 615            .await?;
 616        Ok(())
 617    }
 618
 619    async fn leave_channel(
 620        self: Arc<Self>,
 621        request: TypedEnvelope<proto::LeaveChannel>,
 622    ) -> tide::Result<()> {
 623        let user_id = self
 624            .state
 625            .read()
 626            .await
 627            .user_id_for_connection(request.sender_id)?;
 628        let channel_id = ChannelId::from_proto(request.payload.channel_id);
 629        if !self
 630            .app_state
 631            .db
 632            .can_user_access_channel(user_id, channel_id)
 633            .await?
 634        {
 635            Err(anyhow!("access denied"))?;
 636        }
 637
 638        self.state
 639            .write()
 640            .await
 641            .leave_channel(request.sender_id, channel_id);
 642
 643        Ok(())
 644    }
 645
 646    async fn send_channel_message(
 647        self: Arc<Self>,
 648        request: TypedEnvelope<proto::SendChannelMessage>,
 649    ) -> tide::Result<()> {
 650        let receipt = request.receipt();
 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        // Validate the message body.
 665        let body = request.payload.body.trim().to_string();
 666        if body.len() > MAX_MESSAGE_LEN {
 667            self.peer
 668                .respond_with_error(
 669                    receipt,
 670                    proto::Error {
 671                        message: "message is too long".to_string(),
 672                    },
 673                )
 674                .await?;
 675            return Ok(());
 676        }
 677        if body.is_empty() {
 678            self.peer
 679                .respond_with_error(
 680                    receipt,
 681                    proto::Error {
 682                        message: "message can't be blank".to_string(),
 683                    },
 684                )
 685                .await?;
 686            return Ok(());
 687        }
 688
 689        let timestamp = OffsetDateTime::now_utc();
 690        let message_id = self
 691            .app_state
 692            .db
 693            .create_channel_message(channel_id, user_id, &body, timestamp)
 694            .await?
 695            .to_proto();
 696        let message = proto::ChannelMessage {
 697            sender_id: user_id.to_proto(),
 698            id: message_id,
 699            body,
 700            timestamp: timestamp.unix_timestamp() as u64,
 701        };
 702        broadcast(request.sender_id, connection_ids, |conn_id| {
 703            self.peer.send(
 704                conn_id,
 705                proto::ChannelMessageSent {
 706                    channel_id: channel_id.to_proto(),
 707                    message: Some(message.clone()),
 708                },
 709            )
 710        })
 711        .await?;
 712        self.peer
 713            .respond(
 714                receipt,
 715                proto::SendChannelMessageResponse {
 716                    message: Some(message),
 717                },
 718            )
 719            .await?;
 720        Ok(())
 721    }
 722
 723    async fn get_channel_messages(
 724        self: Arc<Self>,
 725        request: TypedEnvelope<proto::GetChannelMessages>,
 726    ) -> tide::Result<()> {
 727        let user_id = self
 728            .state
 729            .read()
 730            .await
 731            .user_id_for_connection(request.sender_id)?;
 732        let channel_id = ChannelId::from_proto(request.payload.channel_id);
 733        if !self
 734            .app_state
 735            .db
 736            .can_user_access_channel(user_id, channel_id)
 737            .await?
 738        {
 739            Err(anyhow!("access denied"))?;
 740        }
 741
 742        let messages = self
 743            .app_state
 744            .db
 745            .get_channel_messages(
 746                channel_id,
 747                MESSAGE_COUNT_PER_PAGE,
 748                Some(MessageId::from_proto(request.payload.before_message_id)),
 749            )
 750            .await?
 751            .into_iter()
 752            .map(|msg| proto::ChannelMessage {
 753                id: msg.id.to_proto(),
 754                body: msg.body,
 755                timestamp: msg.sent_at.unix_timestamp() as u64,
 756                sender_id: msg.sender_id.to_proto(),
 757            })
 758            .collect::<Vec<_>>();
 759        self.peer
 760            .respond(
 761                request.receipt(),
 762                proto::GetChannelMessagesResponse {
 763                    done: messages.len() < MESSAGE_COUNT_PER_PAGE,
 764                    messages,
 765                },
 766            )
 767            .await?;
 768        Ok(())
 769    }
 770
 771    async fn broadcast_in_worktree<T: proto::EnvelopedMessage>(
 772        &self,
 773        worktree_id: u64,
 774        message: &TypedEnvelope<T>,
 775    ) -> tide::Result<()> {
 776        let connection_ids = self
 777            .state
 778            .read()
 779            .await
 780            .read_worktree(worktree_id, message.sender_id)?
 781            .connection_ids();
 782
 783        broadcast(message.sender_id, connection_ids, |conn_id| {
 784            self.peer
 785                .forward_send(message.sender_id, conn_id, message.payload.clone())
 786        })
 787        .await?;
 788
 789        Ok(())
 790    }
 791}
 792
 793pub async fn broadcast<F, T>(
 794    sender_id: ConnectionId,
 795    receiver_ids: Vec<ConnectionId>,
 796    mut f: F,
 797) -> anyhow::Result<()>
 798where
 799    F: FnMut(ConnectionId) -> T,
 800    T: Future<Output = anyhow::Result<()>>,
 801{
 802    let futures = receiver_ids
 803        .into_iter()
 804        .filter(|id| *id != sender_id)
 805        .map(|id| f(id));
 806    futures::future::try_join_all(futures).await?;
 807    Ok(())
 808}
 809
 810impl ServerState {
 811    fn join_channel(&mut self, connection_id: ConnectionId, channel_id: ChannelId) {
 812        if let Some(connection) = self.connections.get_mut(&connection_id) {
 813            connection.channels.insert(channel_id);
 814            self.channels
 815                .entry(channel_id)
 816                .or_default()
 817                .connection_ids
 818                .insert(connection_id);
 819        }
 820    }
 821
 822    fn leave_channel(&mut self, connection_id: ConnectionId, channel_id: ChannelId) {
 823        if let Some(connection) = self.connections.get_mut(&connection_id) {
 824            connection.channels.remove(&channel_id);
 825            if let hash_map::Entry::Occupied(mut entry) = self.channels.entry(channel_id) {
 826                entry.get_mut().connection_ids.remove(&connection_id);
 827                if entry.get_mut().connection_ids.is_empty() {
 828                    entry.remove();
 829                }
 830            }
 831        }
 832    }
 833
 834    fn user_id_for_connection(&self, connection_id: ConnectionId) -> tide::Result<UserId> {
 835        Ok(self
 836            .connections
 837            .get(&connection_id)
 838            .ok_or_else(|| anyhow!("unknown connection"))?
 839            .user_id)
 840    }
 841
 842    // Add the given connection as a guest of the given worktree
 843    fn join_worktree(
 844        &mut self,
 845        connection_id: ConnectionId,
 846        worktree_id: u64,
 847        access_token: &str,
 848    ) -> Option<(ReplicaId, &Worktree)> {
 849        if let Some(worktree) = self.worktrees.get_mut(&worktree_id) {
 850            if access_token == worktree.access_token {
 851                if let Some(connection) = self.connections.get_mut(&connection_id) {
 852                    connection.worktrees.insert(worktree_id);
 853                }
 854
 855                let mut replica_id = 1;
 856                while worktree.active_replica_ids.contains(&replica_id) {
 857                    replica_id += 1;
 858                }
 859                worktree.active_replica_ids.insert(replica_id);
 860                worktree
 861                    .guest_connection_ids
 862                    .insert(connection_id, replica_id);
 863                Some((replica_id, worktree))
 864            } else {
 865                None
 866            }
 867        } else {
 868            None
 869        }
 870    }
 871
 872    fn read_worktree(
 873        &self,
 874        worktree_id: u64,
 875        connection_id: ConnectionId,
 876    ) -> tide::Result<&Worktree> {
 877        let worktree = self
 878            .worktrees
 879            .get(&worktree_id)
 880            .ok_or_else(|| anyhow!("worktree not found"))?;
 881
 882        if worktree.host_connection_id == Some(connection_id)
 883            || worktree.guest_connection_ids.contains_key(&connection_id)
 884        {
 885            Ok(worktree)
 886        } else {
 887            Err(anyhow!(
 888                "{} is not a member of worktree {}",
 889                connection_id,
 890                worktree_id
 891            ))?
 892        }
 893    }
 894
 895    fn write_worktree(
 896        &mut self,
 897        worktree_id: u64,
 898        connection_id: ConnectionId,
 899    ) -> tide::Result<&mut Worktree> {
 900        let worktree = self
 901            .worktrees
 902            .get_mut(&worktree_id)
 903            .ok_or_else(|| anyhow!("worktree not found"))?;
 904
 905        if worktree.host_connection_id == Some(connection_id)
 906            || worktree.guest_connection_ids.contains_key(&connection_id)
 907        {
 908            Ok(worktree)
 909        } else {
 910            Err(anyhow!(
 911                "{} is not a member of worktree {}",
 912                connection_id,
 913                worktree_id
 914            ))?
 915        }
 916    }
 917}
 918
 919impl Worktree {
 920    pub fn connection_ids(&self) -> Vec<ConnectionId> {
 921        self.guest_connection_ids
 922            .keys()
 923            .copied()
 924            .chain(self.host_connection_id)
 925            .collect()
 926    }
 927
 928    fn host_connection_id(&self) -> tide::Result<ConnectionId> {
 929        Ok(self
 930            .host_connection_id
 931            .ok_or_else(|| anyhow!("host disconnected from worktree"))?)
 932    }
 933}
 934
 935impl Channel {
 936    fn connection_ids(&self) -> Vec<ConnectionId> {
 937        self.connection_ids.iter().copied().collect()
 938    }
 939}
 940
 941pub fn add_routes(app: &mut tide::Server<Arc<AppState>>, rpc: &Arc<Peer>) {
 942    let server = Server::new(app.state().clone(), rpc.clone(), None);
 943    app.at("/rpc").with(auth::VerifyToken).get(move |request: Request<Arc<AppState>>| {
 944        let user_id = request.ext::<UserId>().copied();
 945        let server = server.clone();
 946        async move {
 947            const WEBSOCKET_GUID: &str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
 948
 949            let connection_upgrade = header_contains_ignore_case(&request, CONNECTION, "upgrade");
 950            let upgrade_to_websocket = header_contains_ignore_case(&request, UPGRADE, "websocket");
 951            let upgrade_requested = connection_upgrade && upgrade_to_websocket;
 952
 953            if !upgrade_requested {
 954                return Ok(Response::new(StatusCode::UpgradeRequired));
 955            }
 956
 957            let header = match request.header("Sec-Websocket-Key") {
 958                Some(h) => h.as_str(),
 959                None => return Err(anyhow!("expected sec-websocket-key"))?,
 960            };
 961
 962            let mut response = Response::new(StatusCode::SwitchingProtocols);
 963            response.insert_header(UPGRADE, "websocket");
 964            response.insert_header(CONNECTION, "Upgrade");
 965            let hash = Sha1::new().chain(header).chain(WEBSOCKET_GUID).finalize();
 966            response.insert_header("Sec-Websocket-Accept", base64::encode(&hash[..]));
 967            response.insert_header("Sec-Websocket-Version", "13");
 968
 969            let http_res: &mut tide::http::Response = response.as_mut();
 970            let upgrade_receiver = http_res.recv_upgrade().await;
 971            let addr = request.remote().unwrap_or("unknown").to_string();
 972            let user_id = user_id.ok_or_else(|| anyhow!("user_id is not present on request. ensure auth::VerifyToken middleware is present"))?;
 973            task::spawn(async move {
 974                if let Some(stream) = upgrade_receiver.await {
 975                    server.handle_connection(Conn::new(WebSocketStream::from_raw_socket(stream, Role::Server, None).await), addr, user_id).await;
 976                }
 977            });
 978
 979            Ok(response)
 980        }
 981    });
 982}
 983
 984fn header_contains_ignore_case<T>(
 985    request: &tide::Request<T>,
 986    header_name: HeaderName,
 987    value: &str,
 988) -> bool {
 989    request
 990        .header(header_name)
 991        .map(|h| {
 992            h.as_str()
 993                .split(',')
 994                .any(|s| s.trim().eq_ignore_ascii_case(value.trim()))
 995        })
 996        .unwrap_or(false)
 997}
 998
 999#[cfg(test)]
1000mod tests {
1001    use super::*;
1002    use crate::{
1003        auth,
1004        db::{tests::TestDb, UserId},
1005        github, AppState, Config,
1006    };
1007    use async_std::{sync::RwLockReadGuard, task};
1008    use gpui::TestAppContext;
1009    use parking_lot::Mutex;
1010    use postage::{mpsc, watch};
1011    use serde_json::json;
1012    use sqlx::types::time::OffsetDateTime;
1013    use std::{
1014        path::Path,
1015        sync::{
1016            atomic::{AtomicBool, Ordering::SeqCst},
1017            Arc,
1018        },
1019        time::Duration,
1020    };
1021    use zed::{
1022        channel::{Channel, ChannelDetails, ChannelList},
1023        editor::{Editor, Insert},
1024        fs::{FakeFs, Fs as _},
1025        language::LanguageRegistry,
1026        rpc::{self, Client},
1027        settings,
1028        user::UserStore,
1029        worktree::Worktree,
1030    };
1031    use zrpc::Peer;
1032
1033    #[gpui::test]
1034    async fn test_share_worktree(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1035        let (window_b, _) = cx_b.add_window(|_| EmptyView);
1036        let settings = cx_b.read(settings::test).1;
1037        let lang_registry = Arc::new(LanguageRegistry::new());
1038
1039        // Connect to a server as 2 clients.
1040        let mut server = TestServer::start().await;
1041        let (_, client_a) = server.create_client(&mut cx_a, "user_a").await;
1042        let (_, client_b) = server.create_client(&mut cx_b, "user_b").await;
1043
1044        cx_a.foreground().forbid_parking();
1045
1046        // Share a local worktree as client A
1047        let fs = Arc::new(FakeFs::new());
1048        fs.insert_tree(
1049            "/a",
1050            json!({
1051                "a.txt": "a-contents",
1052                "b.txt": "b-contents",
1053            }),
1054        )
1055        .await;
1056        let worktree_a = Worktree::open_local(
1057            "/a".as_ref(),
1058            lang_registry.clone(),
1059            fs,
1060            &mut cx_a.to_async(),
1061        )
1062        .await
1063        .unwrap();
1064        worktree_a
1065            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1066            .await;
1067        let (worktree_id, worktree_token) = worktree_a
1068            .update(&mut cx_a, |tree, cx| {
1069                tree.as_local_mut().unwrap().share(client_a.clone(), cx)
1070            })
1071            .await
1072            .unwrap();
1073
1074        // Join that worktree as client B, and see that a guest has joined as client A.
1075        let worktree_b = Worktree::open_remote(
1076            client_b.clone(),
1077            worktree_id,
1078            worktree_token,
1079            lang_registry.clone(),
1080            &mut cx_b.to_async(),
1081        )
1082        .await
1083        .unwrap();
1084        let replica_id_b = worktree_b.read_with(&cx_b, |tree, _| tree.replica_id());
1085        worktree_a
1086            .condition(&cx_a, |tree, _| {
1087                tree.peers()
1088                    .values()
1089                    .any(|replica_id| *replica_id == replica_id_b)
1090            })
1091            .await;
1092
1093        // Open the same file as client B and client A.
1094        let buffer_b = worktree_b
1095            .update(&mut cx_b, |worktree, cx| worktree.open_buffer("b.txt", cx))
1096            .await
1097            .unwrap();
1098        buffer_b.read_with(&cx_b, |buf, _| assert_eq!(buf.text(), "b-contents"));
1099        worktree_a.read_with(&cx_a, |tree, cx| assert!(tree.has_open_buffer("b.txt", cx)));
1100        let buffer_a = worktree_a
1101            .update(&mut cx_a, |tree, cx| tree.open_buffer("b.txt", cx))
1102            .await
1103            .unwrap();
1104
1105        // Create a selection set as client B and see that selection set as client A.
1106        let editor_b = cx_b.add_view(window_b, |cx| Editor::for_buffer(buffer_b, settings, cx));
1107        buffer_a
1108            .condition(&cx_a, |buffer, _| buffer.selection_sets().count() == 1)
1109            .await;
1110
1111        // Edit the buffer as client B and see that edit as client A.
1112        editor_b.update(&mut cx_b, |editor, cx| {
1113            editor.insert(&Insert("ok, ".into()), cx)
1114        });
1115        buffer_a
1116            .condition(&cx_a, |buffer, _| buffer.text() == "ok, b-contents")
1117            .await;
1118
1119        // Remove the selection set as client B, see those selections disappear as client A.
1120        cx_b.update(move |_| drop(editor_b));
1121        buffer_a
1122            .condition(&cx_a, |buffer, _| buffer.selection_sets().count() == 0)
1123            .await;
1124
1125        // Close the buffer as client A, see that the buffer is closed.
1126        drop(buffer_a);
1127        worktree_a
1128            .condition(&cx_a, |tree, cx| !tree.has_open_buffer("b.txt", cx))
1129            .await;
1130
1131        // Dropping the worktree removes client B from client A's peers.
1132        cx_b.update(move |_| drop(worktree_b));
1133        worktree_a
1134            .condition(&cx_a, |tree, _| tree.peers().is_empty())
1135            .await;
1136    }
1137
1138    #[gpui::test]
1139    async fn test_propagate_saves_and_fs_changes_in_shared_worktree(
1140        mut cx_a: TestAppContext,
1141        mut cx_b: TestAppContext,
1142        mut cx_c: TestAppContext,
1143    ) {
1144        cx_a.foreground().forbid_parking();
1145        let lang_registry = Arc::new(LanguageRegistry::new());
1146
1147        // Connect to a server as 3 clients.
1148        let mut server = TestServer::start().await;
1149        let (_, client_a) = server.create_client(&mut cx_a, "user_a").await;
1150        let (_, client_b) = server.create_client(&mut cx_b, "user_b").await;
1151        let (_, client_c) = server.create_client(&mut cx_c, "user_c").await;
1152
1153        let fs = Arc::new(FakeFs::new());
1154
1155        // Share a worktree as client A.
1156        fs.insert_tree(
1157            "/a",
1158            json!({
1159                "file1": "",
1160                "file2": ""
1161            }),
1162        )
1163        .await;
1164
1165        let worktree_a = Worktree::open_local(
1166            "/a".as_ref(),
1167            lang_registry.clone(),
1168            fs.clone(),
1169            &mut cx_a.to_async(),
1170        )
1171        .await
1172        .unwrap();
1173        worktree_a
1174            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1175            .await;
1176        let (worktree_id, worktree_token) = worktree_a
1177            .update(&mut cx_a, |tree, cx| {
1178                tree.as_local_mut().unwrap().share(client_a.clone(), cx)
1179            })
1180            .await
1181            .unwrap();
1182
1183        // Join that worktree as clients B and C.
1184        let worktree_b = Worktree::open_remote(
1185            client_b.clone(),
1186            worktree_id,
1187            worktree_token.clone(),
1188            lang_registry.clone(),
1189            &mut cx_b.to_async(),
1190        )
1191        .await
1192        .unwrap();
1193        let worktree_c = Worktree::open_remote(
1194            client_c.clone(),
1195            worktree_id,
1196            worktree_token,
1197            lang_registry.clone(),
1198            &mut cx_c.to_async(),
1199        )
1200        .await
1201        .unwrap();
1202
1203        // Open and edit a buffer as both guests B and C.
1204        let buffer_b = worktree_b
1205            .update(&mut cx_b, |tree, cx| tree.open_buffer("file1", cx))
1206            .await
1207            .unwrap();
1208        let buffer_c = worktree_c
1209            .update(&mut cx_c, |tree, cx| tree.open_buffer("file1", cx))
1210            .await
1211            .unwrap();
1212        buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "i-am-b, ", cx));
1213        buffer_c.update(&mut cx_c, |buf, cx| buf.edit([0..0], "i-am-c, ", cx));
1214
1215        // Open and edit that buffer as the host.
1216        let buffer_a = worktree_a
1217            .update(&mut cx_a, |tree, cx| tree.open_buffer("file1", cx))
1218            .await
1219            .unwrap();
1220
1221        buffer_a
1222            .condition(&mut cx_a, |buf, _| buf.text() == "i-am-c, i-am-b, ")
1223            .await;
1224        buffer_a.update(&mut cx_a, |buf, cx| {
1225            buf.edit([buf.len()..buf.len()], "i-am-a", cx)
1226        });
1227
1228        // Wait for edits to propagate
1229        buffer_a
1230            .condition(&mut cx_a, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1231            .await;
1232        buffer_b
1233            .condition(&mut cx_b, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1234            .await;
1235        buffer_c
1236            .condition(&mut cx_c, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1237            .await;
1238
1239        // Edit the buffer as the host and concurrently save as guest B.
1240        let save_b = buffer_b.update(&mut cx_b, |buf, cx| buf.save(cx).unwrap());
1241        buffer_a.update(&mut cx_a, |buf, cx| buf.edit([0..0], "hi-a, ", cx));
1242        save_b.await.unwrap();
1243        assert_eq!(
1244            fs.load("/a/file1".as_ref()).await.unwrap(),
1245            "hi-a, i-am-c, i-am-b, i-am-a"
1246        );
1247        buffer_a.read_with(&cx_a, |buf, _| assert!(!buf.is_dirty()));
1248        buffer_b.read_with(&cx_b, |buf, _| assert!(!buf.is_dirty()));
1249        buffer_c.condition(&cx_c, |buf, _| !buf.is_dirty()).await;
1250
1251        // Make changes on host's file system, see those changes on the guests.
1252        fs.rename("/a/file2".as_ref(), "/a/file3".as_ref())
1253            .await
1254            .unwrap();
1255        fs.insert_file(Path::new("/a/file4"), "4".into())
1256            .await
1257            .unwrap();
1258
1259        worktree_b
1260            .condition(&cx_b, |tree, _| tree.file_count() == 3)
1261            .await;
1262        worktree_c
1263            .condition(&cx_c, |tree, _| tree.file_count() == 3)
1264            .await;
1265        worktree_b.read_with(&cx_b, |tree, _| {
1266            assert_eq!(
1267                tree.paths()
1268                    .map(|p| p.to_string_lossy())
1269                    .collect::<Vec<_>>(),
1270                &["file1", "file3", "file4"]
1271            )
1272        });
1273        worktree_c.read_with(&cx_c, |tree, _| {
1274            assert_eq!(
1275                tree.paths()
1276                    .map(|p| p.to_string_lossy())
1277                    .collect::<Vec<_>>(),
1278                &["file1", "file3", "file4"]
1279            )
1280        });
1281    }
1282
1283    #[gpui::test]
1284    async fn test_buffer_conflict_after_save(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1285        cx_a.foreground().forbid_parking();
1286        let lang_registry = Arc::new(LanguageRegistry::new());
1287
1288        // Connect to a server as 2 clients.
1289        let mut server = TestServer::start().await;
1290        let (_, client_a) = server.create_client(&mut cx_a, "user_a").await;
1291        let (_, client_b) = server.create_client(&mut cx_b, "user_b").await;
1292
1293        // Share a local worktree as client A
1294        let fs = Arc::new(FakeFs::new());
1295        fs.save(Path::new("/a.txt"), &"a-contents".into())
1296            .await
1297            .unwrap();
1298        let worktree_a = Worktree::open_local(
1299            "/".as_ref(),
1300            lang_registry.clone(),
1301            fs,
1302            &mut cx_a.to_async(),
1303        )
1304        .await
1305        .unwrap();
1306        worktree_a
1307            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1308            .await;
1309        let (worktree_id, worktree_token) = worktree_a
1310            .update(&mut cx_a, |tree, cx| {
1311                tree.as_local_mut().unwrap().share(client_a.clone(), cx)
1312            })
1313            .await
1314            .unwrap();
1315
1316        // Join that worktree as client B, and see that a guest has joined as client A.
1317        let worktree_b = Worktree::open_remote(
1318            client_b.clone(),
1319            worktree_id,
1320            worktree_token,
1321            lang_registry.clone(),
1322            &mut cx_b.to_async(),
1323        )
1324        .await
1325        .unwrap();
1326
1327        let buffer_b = worktree_b
1328            .update(&mut cx_b, |worktree, cx| worktree.open_buffer("a.txt", cx))
1329            .await
1330            .unwrap();
1331        let mtime = buffer_b.read_with(&cx_b, |buf, _| buf.file().unwrap().mtime);
1332
1333        buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "world ", cx));
1334        buffer_b.read_with(&cx_b, |buf, _| {
1335            assert!(buf.is_dirty());
1336            assert!(!buf.has_conflict());
1337        });
1338
1339        buffer_b
1340            .update(&mut cx_b, |buf, cx| buf.save(cx))
1341            .unwrap()
1342            .await
1343            .unwrap();
1344        worktree_b
1345            .condition(&cx_b, |_, cx| {
1346                buffer_b.read(cx).file().unwrap().mtime != mtime
1347            })
1348            .await;
1349        buffer_b.read_with(&cx_b, |buf, _| {
1350            assert!(!buf.is_dirty());
1351            assert!(!buf.has_conflict());
1352        });
1353
1354        buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "hello ", cx));
1355        buffer_b.read_with(&cx_b, |buf, _| {
1356            assert!(buf.is_dirty());
1357            assert!(!buf.has_conflict());
1358        });
1359    }
1360
1361    #[gpui::test]
1362    async fn test_editing_while_guest_opens_buffer(
1363        mut cx_a: TestAppContext,
1364        mut cx_b: TestAppContext,
1365    ) {
1366        cx_a.foreground().forbid_parking();
1367        let lang_registry = Arc::new(LanguageRegistry::new());
1368
1369        // Connect to a server as 2 clients.
1370        let mut server = TestServer::start().await;
1371        let (_, client_a) = server.create_client(&mut cx_a, "user_a").await;
1372        let (_, client_b) = server.create_client(&mut cx_b, "user_b").await;
1373
1374        // Share a local worktree as client A
1375        let fs = Arc::new(FakeFs::new());
1376        fs.save(Path::new("/a.txt"), &"a-contents".into())
1377            .await
1378            .unwrap();
1379        let worktree_a = Worktree::open_local(
1380            "/".as_ref(),
1381            lang_registry.clone(),
1382            fs,
1383            &mut cx_a.to_async(),
1384        )
1385        .await
1386        .unwrap();
1387        worktree_a
1388            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1389            .await;
1390        let (worktree_id, worktree_token) = worktree_a
1391            .update(&mut cx_a, |tree, cx| {
1392                tree.as_local_mut().unwrap().share(client_a.clone(), cx)
1393            })
1394            .await
1395            .unwrap();
1396
1397        // Join that worktree as client B, and see that a guest has joined as client A.
1398        let worktree_b = Worktree::open_remote(
1399            client_b.clone(),
1400            worktree_id,
1401            worktree_token,
1402            lang_registry.clone(),
1403            &mut cx_b.to_async(),
1404        )
1405        .await
1406        .unwrap();
1407
1408        let buffer_a = worktree_a
1409            .update(&mut cx_a, |tree, cx| tree.open_buffer("a.txt", cx))
1410            .await
1411            .unwrap();
1412        let buffer_b = cx_b
1413            .background()
1414            .spawn(worktree_b.update(&mut cx_b, |worktree, cx| worktree.open_buffer("a.txt", cx)));
1415
1416        task::yield_now().await;
1417        buffer_a.update(&mut cx_a, |buf, cx| buf.edit([0..0], "z", cx));
1418
1419        let text = buffer_a.read_with(&cx_a, |buf, _| buf.text());
1420        let buffer_b = buffer_b.await.unwrap();
1421        buffer_b.condition(&cx_b, |buf, _| buf.text() == text).await;
1422    }
1423
1424    #[gpui::test]
1425    async fn test_peer_disconnection(mut cx_a: TestAppContext, cx_b: TestAppContext) {
1426        cx_a.foreground().forbid_parking();
1427        let lang_registry = Arc::new(LanguageRegistry::new());
1428
1429        // Connect to a server as 2 clients.
1430        let mut server = TestServer::start().await;
1431        let (_, client_a) = server.create_client(&mut cx_a, "user_a").await;
1432        let (_, client_b) = server.create_client(&mut cx_a, "user_b").await;
1433
1434        // Share a local worktree as client A
1435        let fs = Arc::new(FakeFs::new());
1436        fs.insert_tree(
1437            "/a",
1438            json!({
1439                "a.txt": "a-contents",
1440                "b.txt": "b-contents",
1441            }),
1442        )
1443        .await;
1444        let worktree_a = Worktree::open_local(
1445            "/a".as_ref(),
1446            lang_registry.clone(),
1447            fs,
1448            &mut cx_a.to_async(),
1449        )
1450        .await
1451        .unwrap();
1452        worktree_a
1453            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1454            .await;
1455        let (worktree_id, worktree_token) = worktree_a
1456            .update(&mut cx_a, |tree, cx| {
1457                tree.as_local_mut().unwrap().share(client_a.clone(), cx)
1458            })
1459            .await
1460            .unwrap();
1461
1462        // Join that worktree as client B, and see that a guest has joined as client A.
1463        let _worktree_b = Worktree::open_remote(
1464            client_b.clone(),
1465            worktree_id,
1466            worktree_token,
1467            lang_registry.clone(),
1468            &mut cx_b.to_async(),
1469        )
1470        .await
1471        .unwrap();
1472        worktree_a
1473            .condition(&cx_a, |tree, _| tree.peers().len() == 1)
1474            .await;
1475
1476        // Drop client B's connection and ensure client A observes client B leaving the worktree.
1477        client_b.disconnect(&cx_b.to_async()).await.unwrap();
1478        worktree_a
1479            .condition(&cx_a, |tree, _| tree.peers().len() == 0)
1480            .await;
1481    }
1482
1483    #[gpui::test]
1484    async fn test_basic_chat(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1485        cx_a.foreground().forbid_parking();
1486
1487        // Connect to a server as 2 clients.
1488        let mut server = TestServer::start().await;
1489        let (user_id_a, client_a) = server.create_client(&mut cx_a, "user_a").await;
1490        let (user_id_b, client_b) = server.create_client(&mut cx_b, "user_b").await;
1491
1492        // Create an org that includes these 2 users.
1493        let db = &server.app_state.db;
1494        let org_id = db.create_org("Test Org", "test-org").await.unwrap();
1495        db.add_org_member(org_id, user_id_a, false).await.unwrap();
1496        db.add_org_member(org_id, user_id_b, false).await.unwrap();
1497
1498        // Create a channel that includes all the users.
1499        let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
1500        db.add_channel_member(channel_id, user_id_a, false)
1501            .await
1502            .unwrap();
1503        db.add_channel_member(channel_id, user_id_b, false)
1504            .await
1505            .unwrap();
1506        db.create_channel_message(
1507            channel_id,
1508            user_id_b,
1509            "hello A, it's B.",
1510            OffsetDateTime::now_utc(),
1511        )
1512        .await
1513        .unwrap();
1514
1515        let user_store_a = Arc::new(UserStore::new(client_a.clone()));
1516        let channels_a = cx_a.add_model(|cx| ChannelList::new(user_store_a, client_a, cx));
1517        channels_a
1518            .condition(&mut cx_a, |list, _| list.available_channels().is_some())
1519            .await;
1520        channels_a.read_with(&cx_a, |list, _| {
1521            assert_eq!(
1522                list.available_channels().unwrap(),
1523                &[ChannelDetails {
1524                    id: channel_id.to_proto(),
1525                    name: "test-channel".to_string()
1526                }]
1527            )
1528        });
1529        let channel_a = channels_a.update(&mut cx_a, |this, cx| {
1530            this.get_channel(channel_id.to_proto(), cx).unwrap()
1531        });
1532        channel_a.read_with(&cx_a, |channel, _| assert!(channel.messages().is_empty()));
1533        channel_a
1534            .condition(&cx_a, |channel, _| {
1535                channel_messages(channel)
1536                    == [("user_b".to_string(), "hello A, it's B.".to_string())]
1537            })
1538            .await;
1539
1540        let user_store_b = Arc::new(UserStore::new(client_b.clone()));
1541        let channels_b = cx_b.add_model(|cx| ChannelList::new(user_store_b, client_b, cx));
1542        channels_b
1543            .condition(&mut cx_b, |list, _| list.available_channels().is_some())
1544            .await;
1545        channels_b.read_with(&cx_b, |list, _| {
1546            assert_eq!(
1547                list.available_channels().unwrap(),
1548                &[ChannelDetails {
1549                    id: channel_id.to_proto(),
1550                    name: "test-channel".to_string()
1551                }]
1552            )
1553        });
1554
1555        let channel_b = channels_b.update(&mut cx_b, |this, cx| {
1556            this.get_channel(channel_id.to_proto(), cx).unwrap()
1557        });
1558        channel_b.read_with(&cx_b, |channel, _| assert!(channel.messages().is_empty()));
1559        channel_b
1560            .condition(&cx_b, |channel, _| {
1561                channel_messages(channel)
1562                    == [("user_b".to_string(), "hello A, it's B.".to_string())]
1563            })
1564            .await;
1565
1566        channel_a
1567            .update(&mut cx_a, |channel, cx| {
1568                channel
1569                    .send_message("oh, hi B.".to_string(), cx)
1570                    .unwrap()
1571                    .detach();
1572                let task = channel.send_message("sup".to_string(), cx).unwrap();
1573                assert_eq!(
1574                    channel
1575                        .pending_messages()
1576                        .iter()
1577                        .map(|m| &m.body)
1578                        .collect::<Vec<_>>(),
1579                    &["oh, hi B.", "sup"]
1580                );
1581                task
1582            })
1583            .await
1584            .unwrap();
1585
1586        channel_a
1587            .condition(&cx_a, |channel, _| channel.pending_messages().is_empty())
1588            .await;
1589        channel_b
1590            .condition(&cx_b, |channel, _| {
1591                channel_messages(channel)
1592                    == [
1593                        ("user_b".to_string(), "hello A, it's B.".to_string()),
1594                        ("user_a".to_string(), "oh, hi B.".to_string()),
1595                        ("user_a".to_string(), "sup".to_string()),
1596                    ]
1597            })
1598            .await;
1599
1600        assert_eq!(
1601            server.state().await.channels[&channel_id]
1602                .connection_ids
1603                .len(),
1604            2
1605        );
1606        cx_b.update(|_| drop(channel_b));
1607        server
1608            .condition(|state| state.channels[&channel_id].connection_ids.len() == 1)
1609            .await;
1610
1611        cx_a.update(|_| drop(channel_a));
1612        server
1613            .condition(|state| !state.channels.contains_key(&channel_id))
1614            .await;
1615
1616        fn channel_messages(channel: &Channel) -> Vec<(String, String)> {
1617            channel
1618                .messages()
1619                .cursor::<(), ()>()
1620                .map(|m| (m.sender.github_login.clone(), m.body.clone()))
1621                .collect()
1622        }
1623    }
1624
1625    #[gpui::test]
1626    async fn test_chat_message_validation(mut cx_a: TestAppContext) {
1627        cx_a.foreground().forbid_parking();
1628
1629        let mut server = TestServer::start().await;
1630        let (user_id_a, client_a) = server.create_client(&mut cx_a, "user_a").await;
1631
1632        let db = &server.app_state.db;
1633        let org_id = db.create_org("Test Org", "test-org").await.unwrap();
1634        let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
1635        db.add_org_member(org_id, user_id_a, false).await.unwrap();
1636        db.add_channel_member(channel_id, user_id_a, false)
1637            .await
1638            .unwrap();
1639
1640        let user_store_a = Arc::new(UserStore::new(client_a.clone()));
1641        let channels_a = cx_a.add_model(|cx| ChannelList::new(user_store_a, client_a, cx));
1642        channels_a
1643            .condition(&mut cx_a, |list, _| list.available_channels().is_some())
1644            .await;
1645        let channel_a = channels_a.update(&mut cx_a, |this, cx| {
1646            this.get_channel(channel_id.to_proto(), cx).unwrap()
1647        });
1648
1649        // Messages aren't allowed to be too long.
1650        channel_a
1651            .update(&mut cx_a, |channel, cx| {
1652                let long_body = "this is long.\n".repeat(1024);
1653                channel.send_message(long_body, cx).unwrap()
1654            })
1655            .await
1656            .unwrap_err();
1657
1658        // Messages aren't allowed to be blank.
1659        channel_a.update(&mut cx_a, |channel, cx| {
1660            channel.send_message(String::new(), cx).unwrap_err()
1661        });
1662
1663        // Leading and trailing whitespace are trimmed.
1664        channel_a
1665            .update(&mut cx_a, |channel, cx| {
1666                channel
1667                    .send_message("\n surrounded by whitespace  \n".to_string(), cx)
1668                    .unwrap()
1669            })
1670            .await
1671            .unwrap();
1672        assert_eq!(
1673            db.get_channel_messages(channel_id, 10, None)
1674                .await
1675                .unwrap()
1676                .iter()
1677                .map(|m| &m.body)
1678                .collect::<Vec<_>>(),
1679            &["surrounded by whitespace"]
1680        );
1681    }
1682
1683    #[gpui::test]
1684    async fn test_chat_reconnection(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1685        cx_a.foreground().forbid_parking();
1686
1687        // Connect to a server as 2 clients.
1688        let mut server = TestServer::start().await;
1689        let (user_id_a, client_a) = server.create_client(&mut cx_a, "user_a").await;
1690        let (user_id_b, client_b) = server.create_client(&mut cx_b, "user_b").await;
1691        let mut status_b = client_b.status();
1692
1693        // Create an org that includes these 2 users.
1694        let db = &server.app_state.db;
1695        let org_id = db.create_org("Test Org", "test-org").await.unwrap();
1696        db.add_org_member(org_id, user_id_a, false).await.unwrap();
1697        db.add_org_member(org_id, user_id_b, false).await.unwrap();
1698
1699        // Create a channel that includes all the users.
1700        let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
1701        db.add_channel_member(channel_id, user_id_a, false)
1702            .await
1703            .unwrap();
1704        db.add_channel_member(channel_id, user_id_b, false)
1705            .await
1706            .unwrap();
1707        db.create_channel_message(
1708            channel_id,
1709            user_id_b,
1710            "hello A, it's B.",
1711            OffsetDateTime::now_utc(),
1712        )
1713        .await
1714        .unwrap();
1715
1716        let user_store_a = Arc::new(UserStore::new(client_a.clone()));
1717        let channels_a = cx_a.add_model(|cx| ChannelList::new(user_store_a, client_a, cx));
1718        channels_a
1719            .condition(&mut cx_a, |list, _| list.available_channels().is_some())
1720            .await;
1721
1722        channels_a.read_with(&cx_a, |list, _| {
1723            assert_eq!(
1724                list.available_channels().unwrap(),
1725                &[ChannelDetails {
1726                    id: channel_id.to_proto(),
1727                    name: "test-channel".to_string()
1728                }]
1729            )
1730        });
1731        let channel_a = channels_a.update(&mut cx_a, |this, cx| {
1732            this.get_channel(channel_id.to_proto(), cx).unwrap()
1733        });
1734        channel_a.read_with(&cx_a, |channel, _| assert!(channel.messages().is_empty()));
1735        channel_a
1736            .condition(&cx_a, |channel, _| {
1737                channel_messages(channel)
1738                    == [("user_b".to_string(), "hello A, it's B.".to_string())]
1739            })
1740            .await;
1741
1742        let user_store_b = Arc::new(UserStore::new(client_b.clone()));
1743        let channels_b = cx_b.add_model(|cx| ChannelList::new(user_store_b, client_b, cx));
1744        channels_b
1745            .condition(&mut cx_b, |list, _| list.available_channels().is_some())
1746            .await;
1747        channels_b.read_with(&cx_b, |list, _| {
1748            assert_eq!(
1749                list.available_channels().unwrap(),
1750                &[ChannelDetails {
1751                    id: channel_id.to_proto(),
1752                    name: "test-channel".to_string()
1753                }]
1754            )
1755        });
1756
1757        let channel_b = channels_b.update(&mut cx_b, |this, cx| {
1758            this.get_channel(channel_id.to_proto(), cx).unwrap()
1759        });
1760        channel_b.read_with(&cx_b, |channel, _| assert!(channel.messages().is_empty()));
1761        channel_b
1762            .condition(&cx_b, |channel, _| {
1763                channel_messages(channel)
1764                    == [("user_b".to_string(), "hello A, it's B.".to_string())]
1765            })
1766            .await;
1767
1768        // Disconnect client B, ensuring we can still access its cached channel data.
1769        server.forbid_connections();
1770        server.disconnect_client(user_id_b);
1771        while !matches!(
1772            status_b.recv().await,
1773            Some(rpc::Status::ReconnectionError { .. })
1774        ) {}
1775
1776        channels_b.read_with(&cx_b, |channels, _| {
1777            assert_eq!(
1778                channels.available_channels().unwrap(),
1779                [ChannelDetails {
1780                    id: channel_id.to_proto(),
1781                    name: "test-channel".to_string()
1782                }]
1783            )
1784        });
1785        channel_b.read_with(&cx_b, |channel, _| {
1786            assert_eq!(
1787                channel_messages(channel),
1788                [("user_b".to_string(), "hello A, it's B.".to_string())]
1789            )
1790        });
1791
1792        // Send a message from client A while B is disconnected.
1793        channel_a
1794            .update(&mut cx_a, |channel, cx| {
1795                channel
1796                    .send_message("oh, hi B.".to_string(), cx)
1797                    .unwrap()
1798                    .detach();
1799                let task = channel.send_message("sup".to_string(), cx).unwrap();
1800                assert_eq!(
1801                    channel
1802                        .pending_messages()
1803                        .iter()
1804                        .map(|m| &m.body)
1805                        .collect::<Vec<_>>(),
1806                    &["oh, hi B.", "sup"]
1807                );
1808                task
1809            })
1810            .await
1811            .unwrap();
1812
1813        // Give client B a chance to reconnect.
1814        server.allow_connections();
1815        cx_b.foreground().advance_clock(Duration::from_secs(10));
1816
1817        // Verify that B sees the new messages upon reconnection.
1818        channel_b
1819            .condition(&cx_b, |channel, _| {
1820                channel_messages(channel)
1821                    == [
1822                        ("user_b".to_string(), "hello A, it's B.".to_string()),
1823                        ("user_a".to_string(), "oh, hi B.".to_string()),
1824                        ("user_a".to_string(), "sup".to_string()),
1825                    ]
1826            })
1827            .await;
1828
1829        // Ensure client A and B can communicate normally after reconnection.
1830        channel_a
1831            .update(&mut cx_a, |channel, cx| {
1832                channel.send_message("you online?".to_string(), cx).unwrap()
1833            })
1834            .await
1835            .unwrap();
1836        channel_b
1837            .condition(&cx_b, |channel, _| {
1838                channel_messages(channel)
1839                    == [
1840                        ("user_b".to_string(), "hello A, it's B.".to_string()),
1841                        ("user_a".to_string(), "oh, hi B.".to_string()),
1842                        ("user_a".to_string(), "sup".to_string()),
1843                        ("user_a".to_string(), "you online?".to_string()),
1844                    ]
1845            })
1846            .await;
1847
1848        channel_b
1849            .update(&mut cx_b, |channel, cx| {
1850                channel.send_message("yep".to_string(), cx).unwrap()
1851            })
1852            .await
1853            .unwrap();
1854        channel_a
1855            .condition(&cx_a, |channel, _| {
1856                channel_messages(channel)
1857                    == [
1858                        ("user_b".to_string(), "hello A, it's B.".to_string()),
1859                        ("user_a".to_string(), "oh, hi B.".to_string()),
1860                        ("user_a".to_string(), "sup".to_string()),
1861                        ("user_a".to_string(), "you online?".to_string()),
1862                        ("user_b".to_string(), "yep".to_string()),
1863                    ]
1864            })
1865            .await;
1866
1867        fn channel_messages(channel: &Channel) -> Vec<(String, String)> {
1868            channel
1869                .messages()
1870                .cursor::<(), ()>()
1871                .map(|m| (m.sender.github_login.clone(), m.body.clone()))
1872                .collect()
1873        }
1874    }
1875
1876    struct TestServer {
1877        peer: Arc<Peer>,
1878        app_state: Arc<AppState>,
1879        server: Arc<Server>,
1880        notifications: mpsc::Receiver<()>,
1881        connection_killers: Arc<Mutex<HashMap<UserId, watch::Sender<Option<()>>>>>,
1882        forbid_connections: Arc<AtomicBool>,
1883        _test_db: TestDb,
1884    }
1885
1886    impl TestServer {
1887        async fn start() -> Self {
1888            let test_db = TestDb::new();
1889            let app_state = Self::build_app_state(&test_db).await;
1890            let peer = Peer::new();
1891            let notifications = mpsc::channel(128);
1892            let server = Server::new(app_state.clone(), peer.clone(), Some(notifications.0));
1893            Self {
1894                peer,
1895                app_state,
1896                server,
1897                notifications: notifications.1,
1898                connection_killers: Default::default(),
1899                forbid_connections: Default::default(),
1900                _test_db: test_db,
1901            }
1902        }
1903
1904        async fn create_client(
1905            &mut self,
1906            cx: &mut TestAppContext,
1907            name: &str,
1908        ) -> (UserId, Arc<Client>) {
1909            let client_user_id = self.app_state.db.create_user(name, false).await.unwrap();
1910            let client_name = name.to_string();
1911            let mut client = Client::new();
1912            let server = self.server.clone();
1913            let connection_killers = self.connection_killers.clone();
1914            let forbid_connections = self.forbid_connections.clone();
1915            Arc::get_mut(&mut client)
1916                .unwrap()
1917                .set_login_and_connect_callbacks(
1918                    move |cx| {
1919                        cx.spawn(|_| async move {
1920                            let access_token = "the-token".to_string();
1921                            Ok((client_user_id.0 as u64, access_token))
1922                        })
1923                    },
1924                    move |user_id, access_token, cx| {
1925                        assert_eq!(user_id, client_user_id.0 as u64);
1926                        assert_eq!(access_token, "the-token");
1927
1928                        let server = server.clone();
1929                        let connection_killers = connection_killers.clone();
1930                        let forbid_connections = forbid_connections.clone();
1931                        let client_name = client_name.clone();
1932                        cx.spawn(move |cx| async move {
1933                            if forbid_connections.load(SeqCst) {
1934                                Err(anyhow!("server is forbidding connections"))
1935                            } else {
1936                                let (client_conn, server_conn, kill_conn) = Conn::in_memory();
1937                                connection_killers.lock().insert(client_user_id, kill_conn);
1938                                cx.background()
1939                                    .spawn(server.handle_connection(
1940                                        server_conn,
1941                                        client_name,
1942                                        client_user_id,
1943                                    ))
1944                                    .detach();
1945                                Ok(client_conn)
1946                            }
1947                        })
1948                    },
1949                );
1950
1951            client
1952                .authenticate_and_connect(&cx.to_async())
1953                .await
1954                .unwrap();
1955            (client_user_id, client)
1956        }
1957
1958        fn disconnect_client(&self, user_id: UserId) {
1959            if let Some(mut kill_conn) = self.connection_killers.lock().remove(&user_id) {
1960                let _ = kill_conn.try_send(Some(()));
1961            }
1962        }
1963
1964        fn forbid_connections(&self) {
1965            self.forbid_connections.store(true, SeqCst);
1966        }
1967
1968        fn allow_connections(&self) {
1969            self.forbid_connections.store(false, SeqCst);
1970        }
1971
1972        async fn build_app_state(test_db: &TestDb) -> Arc<AppState> {
1973            let mut config = Config::default();
1974            config.session_secret = "a".repeat(32);
1975            config.database_url = test_db.url.clone();
1976            let github_client = github::AppClient::test();
1977            Arc::new(AppState {
1978                db: test_db.db().clone(),
1979                handlebars: Default::default(),
1980                auth_client: auth::build_client("", ""),
1981                repo_client: github::RepoClient::test(&github_client),
1982                github_client,
1983                config,
1984            })
1985        }
1986
1987        async fn state<'a>(&'a self) -> RwLockReadGuard<'a, ServerState> {
1988            self.server.state.read().await
1989        }
1990
1991        async fn condition<F>(&mut self, mut predicate: F)
1992        where
1993            F: FnMut(&ServerState) -> bool,
1994        {
1995            async_std::future::timeout(Duration::from_millis(500), async {
1996                while !(predicate)(&*self.server.state.read().await) {
1997                    self.notifications.recv().await;
1998                }
1999            })
2000            .await
2001            .expect("condition timed out");
2002        }
2003    }
2004
2005    impl Drop for TestServer {
2006        fn drop(&mut self) {
2007            task::block_on(self.peer.reset());
2008        }
2009    }
2010
2011    struct EmptyView;
2012
2013    impl gpui::Entity for EmptyView {
2014        type Event = ();
2015    }
2016
2017    impl gpui::View for EmptyView {
2018        fn ui_name() -> &'static str {
2019            "empty view"
2020        }
2021
2022        fn render(&mut self, _: &mut gpui::RenderContext<Self>) -> gpui::ElementBox {
2023            gpui::Element::boxed(gpui::elements::Empty)
2024        }
2025    }
2026}