rpc.rs

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