rpc.rs

   1mod store;
   2
   3use super::{
   4    auth::process_auth_header,
   5    db::{ChannelId, MessageId, UserId},
   6    AppState,
   7};
   8use anyhow::anyhow;
   9use async_std::task;
  10use async_tungstenite::{tungstenite::protocol::Role, WebSocketStream};
  11use collections::{HashMap, HashSet};
  12use futures::{future::BoxFuture, FutureExt, StreamExt};
  13use parking_lot::{RwLock, RwLockReadGuard, RwLockWriteGuard};
  14use postage::{mpsc, prelude::Sink as _};
  15use rpc::{
  16    proto::{self, AnyTypedEnvelope, EnvelopedMessage},
  17    Connection, ConnectionId, Peer, TypedEnvelope,
  18};
  19use sha1::{Digest as _, Sha1};
  20use std::{any::TypeId, future::Future, mem, path::PathBuf, sync::Arc, time::Instant};
  21use store::{Store, Worktree};
  22use surf::StatusCode;
  23use tide::log;
  24use tide::{
  25    http::headers::{HeaderName, CONNECTION, UPGRADE},
  26    Request, Response,
  27};
  28use time::OffsetDateTime;
  29
  30type MessageHandler = Box<
  31    dyn Send
  32        + Sync
  33        + Fn(Arc<Server>, Box<dyn AnyTypedEnvelope>) -> BoxFuture<'static, tide::Result<()>>,
  34>;
  35
  36pub struct Server {
  37    peer: Arc<Peer>,
  38    store: RwLock<Store>,
  39    app_state: Arc<AppState>,
  40    handlers: HashMap<TypeId, MessageHandler>,
  41    notifications: Option<mpsc::Sender<()>>,
  42}
  43
  44const MESSAGE_COUNT_PER_PAGE: usize = 100;
  45const MAX_MESSAGE_LEN: usize = 1024;
  46const NO_SUCH_PROJECT: &'static str = "no such project";
  47
  48impl Server {
  49    pub fn new(
  50        app_state: Arc<AppState>,
  51        peer: Arc<Peer>,
  52        notifications: Option<mpsc::Sender<()>>,
  53    ) -> Arc<Self> {
  54        let mut server = Self {
  55            peer,
  56            app_state,
  57            store: Default::default(),
  58            handlers: Default::default(),
  59            notifications,
  60        };
  61
  62        server
  63            .add_handler(Server::ping)
  64            .add_handler(Server::register_project)
  65            .add_handler(Server::unregister_project)
  66            .add_handler(Server::share_project)
  67            .add_handler(Server::unshare_project)
  68            .add_handler(Server::join_project)
  69            .add_handler(Server::leave_project)
  70            .add_handler(Server::register_worktree)
  71            .add_handler(Server::unregister_worktree)
  72            .add_handler(Server::share_worktree)
  73            .add_handler(Server::update_worktree)
  74            .add_handler(Server::update_diagnostic_summary)
  75            .add_handler(Server::disk_based_diagnostics_updating)
  76            .add_handler(Server::disk_based_diagnostics_updated)
  77            .add_handler(Server::open_buffer)
  78            .add_handler(Server::close_buffer)
  79            .add_handler(Server::update_buffer)
  80            .add_handler(Server::buffer_saved)
  81            .add_handler(Server::save_buffer)
  82            .add_handler(Server::format_buffer)
  83            .add_handler(Server::get_channels)
  84            .add_handler(Server::get_users)
  85            .add_handler(Server::join_channel)
  86            .add_handler(Server::leave_channel)
  87            .add_handler(Server::send_channel_message)
  88            .add_handler(Server::get_channel_messages);
  89
  90        Arc::new(server)
  91    }
  92
  93    fn add_handler<F, Fut, M>(&mut self, handler: F) -> &mut Self
  94    where
  95        F: 'static + Send + Sync + Fn(Arc<Self>, TypedEnvelope<M>) -> Fut,
  96        Fut: 'static + Send + Future<Output = tide::Result<()>>,
  97        M: EnvelopedMessage,
  98    {
  99        let prev_handler = self.handlers.insert(
 100            TypeId::of::<M>(),
 101            Box::new(move |server, envelope| {
 102                let envelope = envelope.into_any().downcast::<TypedEnvelope<M>>().unwrap();
 103                (handler)(server, *envelope).boxed()
 104            }),
 105        );
 106        if prev_handler.is_some() {
 107            panic!("registered a handler for the same message twice");
 108        }
 109        self
 110    }
 111
 112    pub fn handle_connection(
 113        self: &Arc<Self>,
 114        connection: Connection,
 115        addr: String,
 116        user_id: UserId,
 117        mut send_connection_id: Option<postage::mpsc::Sender<ConnectionId>>,
 118    ) -> impl Future<Output = ()> {
 119        let mut this = self.clone();
 120        async move {
 121            let (connection_id, handle_io, mut incoming_rx) =
 122                this.peer.add_connection(connection).await;
 123
 124            if let Some(send_connection_id) = send_connection_id.as_mut() {
 125                let _ = send_connection_id.send(connection_id).await;
 126            }
 127
 128            this.state_mut().add_connection(connection_id, user_id);
 129            if let Err(err) = this.update_contacts_for_users(&[user_id]).await {
 130                log::error!("error updating contacts for {:?}: {}", user_id, err);
 131            }
 132
 133            let handle_io = handle_io.fuse();
 134            futures::pin_mut!(handle_io);
 135            loop {
 136                let next_message = incoming_rx.next().fuse();
 137                futures::pin_mut!(next_message);
 138                futures::select_biased! {
 139                    message = next_message => {
 140                        if let Some(message) = message {
 141                            let start_time = Instant::now();
 142                            log::info!("RPC message received: {}", message.payload_type_name());
 143                            if let Some(handler) = this.handlers.get(&message.payload_type_id()) {
 144                                if let Err(err) = (handler)(this.clone(), message).await {
 145                                    log::error!("error handling message: {:?}", err);
 146                                } else {
 147                                    log::info!("RPC message handled. duration:{:?}", start_time.elapsed());
 148                                }
 149
 150                                if let Some(mut notifications) = this.notifications.clone() {
 151                                    let _ = notifications.send(()).await;
 152                                }
 153                            } else {
 154                                log::warn!("unhandled message: {}", message.payload_type_name());
 155                            }
 156                        } else {
 157                            log::info!("rpc connection closed {:?}", addr);
 158                            break;
 159                        }
 160                    }
 161                    handle_io = handle_io => {
 162                        if let Err(err) = handle_io {
 163                            log::error!("error handling rpc connection {:?} - {:?}", addr, err);
 164                        }
 165                        break;
 166                    }
 167                }
 168            }
 169
 170            if let Err(err) = this.sign_out(connection_id).await {
 171                log::error!("error signing out connection {:?} - {:?}", addr, err);
 172            }
 173        }
 174    }
 175
 176    async fn sign_out(self: &mut Arc<Self>, connection_id: ConnectionId) -> tide::Result<()> {
 177        self.peer.disconnect(connection_id);
 178        let removed_connection = self.state_mut().remove_connection(connection_id)?;
 179
 180        for (project_id, project) in removed_connection.hosted_projects {
 181            if let Some(share) = project.share {
 182                broadcast(
 183                    connection_id,
 184                    share.guests.keys().copied().collect(),
 185                    |conn_id| {
 186                        self.peer
 187                            .send(conn_id, proto::UnshareProject { project_id })
 188                    },
 189                )
 190                .await?;
 191            }
 192        }
 193
 194        for (project_id, peer_ids) in removed_connection.guest_project_ids {
 195            broadcast(connection_id, peer_ids, |conn_id| {
 196                self.peer.send(
 197                    conn_id,
 198                    proto::RemoveProjectCollaborator {
 199                        project_id,
 200                        peer_id: connection_id.0,
 201                    },
 202                )
 203            })
 204            .await?;
 205        }
 206
 207        self.update_contacts_for_users(removed_connection.contact_ids.iter())
 208            .await?;
 209
 210        Ok(())
 211    }
 212
 213    async fn ping(self: Arc<Server>, request: TypedEnvelope<proto::Ping>) -> tide::Result<()> {
 214        self.peer.respond(request.receipt(), proto::Ack {}).await?;
 215        Ok(())
 216    }
 217
 218    async fn register_project(
 219        mut self: Arc<Server>,
 220        request: TypedEnvelope<proto::RegisterProject>,
 221    ) -> tide::Result<()> {
 222        let project_id = {
 223            let mut state = self.state_mut();
 224            let user_id = state.user_id_for_connection(request.sender_id)?;
 225            state.register_project(request.sender_id, user_id)
 226        };
 227        self.peer
 228            .respond(
 229                request.receipt(),
 230                proto::RegisterProjectResponse { project_id },
 231            )
 232            .await?;
 233        Ok(())
 234    }
 235
 236    async fn unregister_project(
 237        mut self: Arc<Server>,
 238        request: TypedEnvelope<proto::UnregisterProject>,
 239    ) -> tide::Result<()> {
 240        let project = self
 241            .state_mut()
 242            .unregister_project(request.payload.project_id, request.sender_id)
 243            .ok_or_else(|| anyhow!("no such project"))?;
 244        self.update_contacts_for_users(project.authorized_user_ids().iter())
 245            .await?;
 246        Ok(())
 247    }
 248
 249    async fn share_project(
 250        mut self: Arc<Server>,
 251        request: TypedEnvelope<proto::ShareProject>,
 252    ) -> tide::Result<()> {
 253        self.state_mut()
 254            .share_project(request.payload.project_id, request.sender_id);
 255        self.peer.respond(request.receipt(), proto::Ack {}).await?;
 256        Ok(())
 257    }
 258
 259    async fn unshare_project(
 260        mut self: Arc<Server>,
 261        request: TypedEnvelope<proto::UnshareProject>,
 262    ) -> tide::Result<()> {
 263        let project_id = request.payload.project_id;
 264        let project = self
 265            .state_mut()
 266            .unshare_project(project_id, request.sender_id)?;
 267
 268        broadcast(request.sender_id, project.connection_ids, |conn_id| {
 269            self.peer
 270                .send(conn_id, proto::UnshareProject { project_id })
 271        })
 272        .await?;
 273        self.update_contacts_for_users(&project.authorized_user_ids)
 274            .await?;
 275
 276        Ok(())
 277    }
 278
 279    async fn join_project(
 280        mut self: Arc<Server>,
 281        request: TypedEnvelope<proto::JoinProject>,
 282    ) -> tide::Result<()> {
 283        let project_id = request.payload.project_id;
 284
 285        let user_id = self.state().user_id_for_connection(request.sender_id)?;
 286        let response_data = self
 287            .state_mut()
 288            .join_project(request.sender_id, user_id, project_id)
 289            .and_then(|joined| {
 290                let share = joined.project.share()?;
 291                let peer_count = share.guests.len();
 292                let mut collaborators = Vec::with_capacity(peer_count);
 293                collaborators.push(proto::Collaborator {
 294                    peer_id: joined.project.host_connection_id.0,
 295                    replica_id: 0,
 296                    user_id: joined.project.host_user_id.to_proto(),
 297                });
 298                let worktrees = joined
 299                    .project
 300                    .worktrees
 301                    .iter()
 302                    .filter_map(|(id, worktree)| {
 303                        worktree.share.as_ref().map(|share| proto::Worktree {
 304                            id: *id,
 305                            root_name: worktree.root_name.clone(),
 306                            entries: share.entries.values().cloned().collect(),
 307                            diagnostic_summaries: share
 308                                .diagnostic_summaries
 309                                .values()
 310                                .cloned()
 311                                .collect(),
 312                        })
 313                    })
 314                    .collect();
 315                for (peer_conn_id, (peer_replica_id, peer_user_id)) in &share.guests {
 316                    if *peer_conn_id != request.sender_id {
 317                        collaborators.push(proto::Collaborator {
 318                            peer_id: peer_conn_id.0,
 319                            replica_id: *peer_replica_id as u32,
 320                            user_id: peer_user_id.to_proto(),
 321                        });
 322                    }
 323                }
 324                let response = proto::JoinProjectResponse {
 325                    worktrees,
 326                    replica_id: joined.replica_id as u32,
 327                    collaborators,
 328                };
 329                let connection_ids = joined.project.connection_ids();
 330                let contact_user_ids = joined.project.authorized_user_ids();
 331                Ok((response, connection_ids, contact_user_ids))
 332            });
 333
 334        match response_data {
 335            Ok((response, connection_ids, contact_user_ids)) => {
 336                broadcast(request.sender_id, connection_ids, |conn_id| {
 337                    self.peer.send(
 338                        conn_id,
 339                        proto::AddProjectCollaborator {
 340                            project_id: project_id,
 341                            collaborator: Some(proto::Collaborator {
 342                                peer_id: request.sender_id.0,
 343                                replica_id: response.replica_id,
 344                                user_id: user_id.to_proto(),
 345                            }),
 346                        },
 347                    )
 348                })
 349                .await?;
 350                self.peer.respond(request.receipt(), response).await?;
 351                self.update_contacts_for_users(&contact_user_ids).await?;
 352            }
 353            Err(error) => {
 354                self.peer
 355                    .respond_with_error(
 356                        request.receipt(),
 357                        proto::Error {
 358                            message: error.to_string(),
 359                        },
 360                    )
 361                    .await?;
 362            }
 363        }
 364
 365        Ok(())
 366    }
 367
 368    async fn leave_project(
 369        mut self: Arc<Server>,
 370        request: TypedEnvelope<proto::LeaveProject>,
 371    ) -> tide::Result<()> {
 372        let sender_id = request.sender_id;
 373        let project_id = request.payload.project_id;
 374        let worktree = self.state_mut().leave_project(sender_id, project_id);
 375        if let Some(worktree) = worktree {
 376            broadcast(sender_id, worktree.connection_ids, |conn_id| {
 377                self.peer.send(
 378                    conn_id,
 379                    proto::RemoveProjectCollaborator {
 380                        project_id,
 381                        peer_id: sender_id.0,
 382                    },
 383                )
 384            })
 385            .await?;
 386            self.update_contacts_for_users(&worktree.authorized_user_ids)
 387                .await?;
 388        }
 389        Ok(())
 390    }
 391
 392    async fn register_worktree(
 393        mut self: Arc<Server>,
 394        request: TypedEnvelope<proto::RegisterWorktree>,
 395    ) -> tide::Result<()> {
 396        let receipt = request.receipt();
 397        let host_user_id = self.state().user_id_for_connection(request.sender_id)?;
 398
 399        let mut contact_user_ids = HashSet::default();
 400        contact_user_ids.insert(host_user_id);
 401        for github_login in request.payload.authorized_logins {
 402            match self.app_state.db.create_user(&github_login, false).await {
 403                Ok(contact_user_id) => {
 404                    contact_user_ids.insert(contact_user_id);
 405                }
 406                Err(err) => {
 407                    let message = err.to_string();
 408                    self.peer
 409                        .respond_with_error(receipt, proto::Error { message })
 410                        .await?;
 411                    return Ok(());
 412                }
 413            }
 414        }
 415
 416        let contact_user_ids = contact_user_ids.into_iter().collect::<Vec<_>>();
 417        let ok = self.state_mut().register_worktree(
 418            request.payload.project_id,
 419            request.payload.worktree_id,
 420            Worktree {
 421                authorized_user_ids: contact_user_ids.clone(),
 422                root_name: request.payload.root_name,
 423                share: None,
 424            },
 425        );
 426
 427        if ok {
 428            self.peer.respond(receipt, proto::Ack {}).await?;
 429            self.update_contacts_for_users(&contact_user_ids).await?;
 430        } else {
 431            self.peer
 432                .respond_with_error(
 433                    receipt,
 434                    proto::Error {
 435                        message: NO_SUCH_PROJECT.to_string(),
 436                    },
 437                )
 438                .await?;
 439        }
 440
 441        Ok(())
 442    }
 443
 444    async fn unregister_worktree(
 445        mut self: Arc<Server>,
 446        request: TypedEnvelope<proto::UnregisterWorktree>,
 447    ) -> tide::Result<()> {
 448        let project_id = request.payload.project_id;
 449        let worktree_id = request.payload.worktree_id;
 450        let (worktree, guest_connection_ids) =
 451            self.state_mut()
 452                .unregister_worktree(project_id, worktree_id, request.sender_id)?;
 453
 454        broadcast(request.sender_id, guest_connection_ids, |conn_id| {
 455            self.peer.send(
 456                conn_id,
 457                proto::UnregisterWorktree {
 458                    project_id,
 459                    worktree_id,
 460                },
 461            )
 462        })
 463        .await?;
 464        self.update_contacts_for_users(&worktree.authorized_user_ids)
 465            .await?;
 466        Ok(())
 467    }
 468
 469    async fn share_worktree(
 470        mut self: Arc<Server>,
 471        mut request: TypedEnvelope<proto::ShareWorktree>,
 472    ) -> tide::Result<()> {
 473        let worktree = request
 474            .payload
 475            .worktree
 476            .as_mut()
 477            .ok_or_else(|| anyhow!("missing worktree"))?;
 478        let entries = mem::take(&mut worktree.entries)
 479            .into_iter()
 480            .map(|entry| (entry.id, entry))
 481            .collect();
 482
 483        let diagnostic_summaries = mem::take(&mut worktree.diagnostic_summaries)
 484            .into_iter()
 485            .map(|summary| (PathBuf::from(summary.path.clone()), summary))
 486            .collect();
 487
 488        let contact_user_ids = self.state_mut().share_worktree(
 489            request.payload.project_id,
 490            worktree.id,
 491            request.sender_id,
 492            entries,
 493            diagnostic_summaries,
 494        );
 495        if let Some(contact_user_ids) = contact_user_ids {
 496            self.peer.respond(request.receipt(), proto::Ack {}).await?;
 497            self.update_contacts_for_users(&contact_user_ids).await?;
 498        } else {
 499            self.peer
 500                .respond_with_error(
 501                    request.receipt(),
 502                    proto::Error {
 503                        message: "no such worktree".to_string(),
 504                    },
 505                )
 506                .await?;
 507        }
 508        Ok(())
 509    }
 510
 511    async fn update_worktree(
 512        mut self: Arc<Server>,
 513        request: TypedEnvelope<proto::UpdateWorktree>,
 514    ) -> tide::Result<()> {
 515        let connection_ids = self
 516            .state_mut()
 517            .update_worktree(
 518                request.sender_id,
 519                request.payload.project_id,
 520                request.payload.worktree_id,
 521                &request.payload.removed_entries,
 522                &request.payload.updated_entries,
 523            )
 524            .ok_or_else(|| anyhow!("no such worktree"))?;
 525
 526        broadcast(request.sender_id, connection_ids, |connection_id| {
 527            self.peer
 528                .forward_send(request.sender_id, connection_id, request.payload.clone())
 529        })
 530        .await?;
 531
 532        Ok(())
 533    }
 534
 535    async fn update_diagnostic_summary(
 536        mut self: Arc<Server>,
 537        request: TypedEnvelope<proto::UpdateDiagnosticSummary>,
 538    ) -> tide::Result<()> {
 539        let receiver_ids = request
 540            .payload
 541            .summary
 542            .clone()
 543            .and_then(|summary| {
 544                self.state_mut().update_diagnostic_summary(
 545                    request.payload.project_id,
 546                    request.payload.worktree_id,
 547                    request.sender_id,
 548                    summary,
 549                )
 550            })
 551            .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?;
 552
 553        broadcast(request.sender_id, receiver_ids, |connection_id| {
 554            self.peer
 555                .forward_send(request.sender_id, connection_id, request.payload.clone())
 556        })
 557        .await?;
 558        Ok(())
 559    }
 560
 561    async fn disk_based_diagnostics_updating(
 562        self: Arc<Server>,
 563        request: TypedEnvelope<proto::DiskBasedDiagnosticsUpdating>,
 564    ) -> tide::Result<()> {
 565        let receiver_ids = self
 566            .state()
 567            .project_connection_ids(request.payload.project_id, request.sender_id)
 568            .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?;
 569        broadcast(request.sender_id, receiver_ids, |connection_id| {
 570            self.peer
 571                .forward_send(request.sender_id, connection_id, request.payload.clone())
 572        })
 573        .await?;
 574        Ok(())
 575    }
 576
 577    async fn disk_based_diagnostics_updated(
 578        self: Arc<Server>,
 579        request: TypedEnvelope<proto::DiskBasedDiagnosticsUpdated>,
 580    ) -> tide::Result<()> {
 581        let receiver_ids = self
 582            .state()
 583            .project_connection_ids(request.payload.project_id, request.sender_id)
 584            .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?;
 585        broadcast(request.sender_id, receiver_ids, |connection_id| {
 586            self.peer
 587                .forward_send(request.sender_id, connection_id, request.payload.clone())
 588        })
 589        .await?;
 590        Ok(())
 591    }
 592
 593    async fn open_buffer(
 594        self: Arc<Server>,
 595        request: TypedEnvelope<proto::OpenBuffer>,
 596    ) -> tide::Result<()> {
 597        let receipt = request.receipt();
 598        let host_connection_id = self
 599            .state()
 600            .read_project(request.payload.project_id, request.sender_id)
 601            .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?
 602            .host_connection_id;
 603        let response = self
 604            .peer
 605            .forward_request(request.sender_id, host_connection_id, request.payload)
 606            .await?;
 607        self.peer.respond(receipt, response).await?;
 608        Ok(())
 609    }
 610
 611    async fn close_buffer(
 612        self: Arc<Server>,
 613        request: TypedEnvelope<proto::CloseBuffer>,
 614    ) -> tide::Result<()> {
 615        let host_connection_id = self
 616            .state()
 617            .read_project(request.payload.project_id, request.sender_id)
 618            .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?
 619            .host_connection_id;
 620        self.peer
 621            .forward_send(request.sender_id, host_connection_id, request.payload)
 622            .await?;
 623        Ok(())
 624    }
 625
 626    async fn save_buffer(
 627        self: Arc<Server>,
 628        request: TypedEnvelope<proto::SaveBuffer>,
 629    ) -> tide::Result<()> {
 630        let host;
 631        let guests;
 632        {
 633            let state = self.state();
 634            let project = state
 635                .read_project(request.payload.project_id, request.sender_id)
 636                .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?;
 637            host = project.host_connection_id;
 638            guests = project.guest_connection_ids()
 639        }
 640
 641        let sender = request.sender_id;
 642        let receipt = request.receipt();
 643        let response = self
 644            .peer
 645            .forward_request(sender, host, request.payload.clone())
 646            .await?;
 647
 648        broadcast(host, guests, |conn_id| {
 649            let response = response.clone();
 650            let peer = &self.peer;
 651            async move {
 652                if conn_id == sender {
 653                    peer.respond(receipt, response).await
 654                } else {
 655                    peer.forward_send(host, conn_id, response).await
 656                }
 657            }
 658        })
 659        .await?;
 660
 661        Ok(())
 662    }
 663
 664    async fn format_buffer(
 665        self: Arc<Server>,
 666        request: TypedEnvelope<proto::FormatBuffer>,
 667    ) -> tide::Result<()> {
 668        let host;
 669        {
 670            let state = self.state();
 671            let project = state
 672                .read_project(request.payload.project_id, request.sender_id)
 673                .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?;
 674            host = project.host_connection_id;
 675        }
 676
 677        let sender = request.sender_id;
 678        let receipt = request.receipt();
 679        let response = self
 680            .peer
 681            .forward_request(sender, host, request.payload.clone())
 682            .await?;
 683        self.peer.respond(receipt, response).await?;
 684
 685        Ok(())
 686    }
 687
 688    async fn update_buffer(
 689        self: Arc<Server>,
 690        request: TypedEnvelope<proto::UpdateBuffer>,
 691    ) -> tide::Result<()> {
 692        let receiver_ids = self
 693            .state()
 694            .project_connection_ids(request.payload.project_id, request.sender_id)
 695            .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?;
 696        broadcast(request.sender_id, receiver_ids, |connection_id| {
 697            self.peer
 698                .forward_send(request.sender_id, connection_id, request.payload.clone())
 699        })
 700        .await?;
 701        self.peer.respond(request.receipt(), proto::Ack {}).await?;
 702        Ok(())
 703    }
 704
 705    async fn buffer_saved(
 706        self: Arc<Server>,
 707        request: TypedEnvelope<proto::BufferSaved>,
 708    ) -> tide::Result<()> {
 709        let receiver_ids = self
 710            .state()
 711            .project_connection_ids(request.payload.project_id, request.sender_id)
 712            .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?;
 713        broadcast(request.sender_id, receiver_ids, |connection_id| {
 714            self.peer
 715                .forward_send(request.sender_id, connection_id, request.payload.clone())
 716        })
 717        .await?;
 718        Ok(())
 719    }
 720
 721    async fn get_channels(
 722        self: Arc<Server>,
 723        request: TypedEnvelope<proto::GetChannels>,
 724    ) -> tide::Result<()> {
 725        let user_id = self.state().user_id_for_connection(request.sender_id)?;
 726        let channels = self.app_state.db.get_accessible_channels(user_id).await?;
 727        self.peer
 728            .respond(
 729                request.receipt(),
 730                proto::GetChannelsResponse {
 731                    channels: channels
 732                        .into_iter()
 733                        .map(|chan| proto::Channel {
 734                            id: chan.id.to_proto(),
 735                            name: chan.name,
 736                        })
 737                        .collect(),
 738                },
 739            )
 740            .await?;
 741        Ok(())
 742    }
 743
 744    async fn get_users(
 745        self: Arc<Server>,
 746        request: TypedEnvelope<proto::GetUsers>,
 747    ) -> tide::Result<()> {
 748        let receipt = request.receipt();
 749        let user_ids = request.payload.user_ids.into_iter().map(UserId::from_proto);
 750        let users = self
 751            .app_state
 752            .db
 753            .get_users_by_ids(user_ids)
 754            .await?
 755            .into_iter()
 756            .map(|user| proto::User {
 757                id: user.id.to_proto(),
 758                avatar_url: format!("https://github.com/{}.png?size=128", user.github_login),
 759                github_login: user.github_login,
 760            })
 761            .collect();
 762        self.peer
 763            .respond(receipt, proto::GetUsersResponse { users })
 764            .await?;
 765        Ok(())
 766    }
 767
 768    async fn update_contacts_for_users<'a>(
 769        self: &Arc<Server>,
 770        user_ids: impl IntoIterator<Item = &'a UserId>,
 771    ) -> tide::Result<()> {
 772        let mut send_futures = Vec::new();
 773
 774        {
 775            let state = self.state();
 776            for user_id in user_ids {
 777                let contacts = state.contacts_for_user(*user_id);
 778                for connection_id in state.connection_ids_for_user(*user_id) {
 779                    send_futures.push(self.peer.send(
 780                        connection_id,
 781                        proto::UpdateContacts {
 782                            contacts: contacts.clone(),
 783                        },
 784                    ));
 785                }
 786            }
 787        }
 788        futures::future::try_join_all(send_futures).await?;
 789
 790        Ok(())
 791    }
 792
 793    async fn join_channel(
 794        mut self: Arc<Self>,
 795        request: TypedEnvelope<proto::JoinChannel>,
 796    ) -> tide::Result<()> {
 797        let user_id = self.state().user_id_for_connection(request.sender_id)?;
 798        let channel_id = ChannelId::from_proto(request.payload.channel_id);
 799        if !self
 800            .app_state
 801            .db
 802            .can_user_access_channel(user_id, channel_id)
 803            .await?
 804        {
 805            Err(anyhow!("access denied"))?;
 806        }
 807
 808        self.state_mut().join_channel(request.sender_id, channel_id);
 809        let messages = self
 810            .app_state
 811            .db
 812            .get_channel_messages(channel_id, MESSAGE_COUNT_PER_PAGE, None)
 813            .await?
 814            .into_iter()
 815            .map(|msg| proto::ChannelMessage {
 816                id: msg.id.to_proto(),
 817                body: msg.body,
 818                timestamp: msg.sent_at.unix_timestamp() as u64,
 819                sender_id: msg.sender_id.to_proto(),
 820                nonce: Some(msg.nonce.as_u128().into()),
 821            })
 822            .collect::<Vec<_>>();
 823        self.peer
 824            .respond(
 825                request.receipt(),
 826                proto::JoinChannelResponse {
 827                    done: messages.len() < MESSAGE_COUNT_PER_PAGE,
 828                    messages,
 829                },
 830            )
 831            .await?;
 832        Ok(())
 833    }
 834
 835    async fn leave_channel(
 836        mut self: Arc<Self>,
 837        request: TypedEnvelope<proto::LeaveChannel>,
 838    ) -> tide::Result<()> {
 839        let user_id = self.state().user_id_for_connection(request.sender_id)?;
 840        let channel_id = ChannelId::from_proto(request.payload.channel_id);
 841        if !self
 842            .app_state
 843            .db
 844            .can_user_access_channel(user_id, channel_id)
 845            .await?
 846        {
 847            Err(anyhow!("access denied"))?;
 848        }
 849
 850        self.state_mut()
 851            .leave_channel(request.sender_id, channel_id);
 852
 853        Ok(())
 854    }
 855
 856    async fn send_channel_message(
 857        self: Arc<Self>,
 858        request: TypedEnvelope<proto::SendChannelMessage>,
 859    ) -> tide::Result<()> {
 860        let receipt = request.receipt();
 861        let channel_id = ChannelId::from_proto(request.payload.channel_id);
 862        let user_id;
 863        let connection_ids;
 864        {
 865            let state = self.state();
 866            user_id = state.user_id_for_connection(request.sender_id)?;
 867            if let Some(ids) = state.channel_connection_ids(channel_id) {
 868                connection_ids = ids;
 869            } else {
 870                return Ok(());
 871            }
 872        }
 873
 874        // Validate the message body.
 875        let body = request.payload.body.trim().to_string();
 876        if body.len() > MAX_MESSAGE_LEN {
 877            self.peer
 878                .respond_with_error(
 879                    receipt,
 880                    proto::Error {
 881                        message: "message is too long".to_string(),
 882                    },
 883                )
 884                .await?;
 885            return Ok(());
 886        }
 887        if body.is_empty() {
 888            self.peer
 889                .respond_with_error(
 890                    receipt,
 891                    proto::Error {
 892                        message: "message can't be blank".to_string(),
 893                    },
 894                )
 895                .await?;
 896            return Ok(());
 897        }
 898
 899        let timestamp = OffsetDateTime::now_utc();
 900        let nonce = if let Some(nonce) = request.payload.nonce {
 901            nonce
 902        } else {
 903            self.peer
 904                .respond_with_error(
 905                    receipt,
 906                    proto::Error {
 907                        message: "nonce can't be blank".to_string(),
 908                    },
 909                )
 910                .await?;
 911            return Ok(());
 912        };
 913
 914        let message_id = self
 915            .app_state
 916            .db
 917            .create_channel_message(channel_id, user_id, &body, timestamp, nonce.clone().into())
 918            .await?
 919            .to_proto();
 920        let message = proto::ChannelMessage {
 921            sender_id: user_id.to_proto(),
 922            id: message_id,
 923            body,
 924            timestamp: timestamp.unix_timestamp() as u64,
 925            nonce: Some(nonce),
 926        };
 927        broadcast(request.sender_id, connection_ids, |conn_id| {
 928            self.peer.send(
 929                conn_id,
 930                proto::ChannelMessageSent {
 931                    channel_id: channel_id.to_proto(),
 932                    message: Some(message.clone()),
 933                },
 934            )
 935        })
 936        .await?;
 937        self.peer
 938            .respond(
 939                receipt,
 940                proto::SendChannelMessageResponse {
 941                    message: Some(message),
 942                },
 943            )
 944            .await?;
 945        Ok(())
 946    }
 947
 948    async fn get_channel_messages(
 949        self: Arc<Self>,
 950        request: TypedEnvelope<proto::GetChannelMessages>,
 951    ) -> tide::Result<()> {
 952        let user_id = self.state().user_id_for_connection(request.sender_id)?;
 953        let channel_id = ChannelId::from_proto(request.payload.channel_id);
 954        if !self
 955            .app_state
 956            .db
 957            .can_user_access_channel(user_id, channel_id)
 958            .await?
 959        {
 960            Err(anyhow!("access denied"))?;
 961        }
 962
 963        let messages = self
 964            .app_state
 965            .db
 966            .get_channel_messages(
 967                channel_id,
 968                MESSAGE_COUNT_PER_PAGE,
 969                Some(MessageId::from_proto(request.payload.before_message_id)),
 970            )
 971            .await?
 972            .into_iter()
 973            .map(|msg| proto::ChannelMessage {
 974                id: msg.id.to_proto(),
 975                body: msg.body,
 976                timestamp: msg.sent_at.unix_timestamp() as u64,
 977                sender_id: msg.sender_id.to_proto(),
 978                nonce: Some(msg.nonce.as_u128().into()),
 979            })
 980            .collect::<Vec<_>>();
 981        self.peer
 982            .respond(
 983                request.receipt(),
 984                proto::GetChannelMessagesResponse {
 985                    done: messages.len() < MESSAGE_COUNT_PER_PAGE,
 986                    messages,
 987                },
 988            )
 989            .await?;
 990        Ok(())
 991    }
 992
 993    fn state<'a>(self: &'a Arc<Self>) -> RwLockReadGuard<'a, Store> {
 994        self.store.read()
 995    }
 996
 997    fn state_mut<'a>(self: &'a mut Arc<Self>) -> RwLockWriteGuard<'a, Store> {
 998        self.store.write()
 999    }
1000}
1001
1002pub async fn broadcast<F, T>(
1003    sender_id: ConnectionId,
1004    receiver_ids: Vec<ConnectionId>,
1005    mut f: F,
1006) -> anyhow::Result<()>
1007where
1008    F: FnMut(ConnectionId) -> T,
1009    T: Future<Output = anyhow::Result<()>>,
1010{
1011    let futures = receiver_ids
1012        .into_iter()
1013        .filter(|id| *id != sender_id)
1014        .map(|id| f(id));
1015    futures::future::try_join_all(futures).await?;
1016    Ok(())
1017}
1018
1019pub fn add_routes(app: &mut tide::Server<Arc<AppState>>, rpc: &Arc<Peer>) {
1020    let server = Server::new(app.state().clone(), rpc.clone(), None);
1021    app.at("/rpc").get(move |request: Request<Arc<AppState>>| {
1022        let server = server.clone();
1023        async move {
1024            const WEBSOCKET_GUID: &str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
1025
1026            let connection_upgrade = header_contains_ignore_case(&request, CONNECTION, "upgrade");
1027            let upgrade_to_websocket = header_contains_ignore_case(&request, UPGRADE, "websocket");
1028            let upgrade_requested = connection_upgrade && upgrade_to_websocket;
1029            let client_protocol_version: Option<u32> = request
1030                .header("X-Zed-Protocol-Version")
1031                .and_then(|v| v.as_str().parse().ok());
1032
1033            if !upgrade_requested || client_protocol_version != Some(rpc::PROTOCOL_VERSION) {
1034                return Ok(Response::new(StatusCode::UpgradeRequired));
1035            }
1036
1037            let header = match request.header("Sec-Websocket-Key") {
1038                Some(h) => h.as_str(),
1039                None => return Err(anyhow!("expected sec-websocket-key"))?,
1040            };
1041
1042            let user_id = process_auth_header(&request).await?;
1043
1044            let mut response = Response::new(StatusCode::SwitchingProtocols);
1045            response.insert_header(UPGRADE, "websocket");
1046            response.insert_header(CONNECTION, "Upgrade");
1047            let hash = Sha1::new().chain(header).chain(WEBSOCKET_GUID).finalize();
1048            response.insert_header("Sec-Websocket-Accept", base64::encode(&hash[..]));
1049            response.insert_header("Sec-Websocket-Version", "13");
1050
1051            let http_res: &mut tide::http::Response = response.as_mut();
1052            let upgrade_receiver = http_res.recv_upgrade().await;
1053            let addr = request.remote().unwrap_or("unknown").to_string();
1054            task::spawn(async move {
1055                if let Some(stream) = upgrade_receiver.await {
1056                    server
1057                        .handle_connection(
1058                            Connection::new(
1059                                WebSocketStream::from_raw_socket(stream, Role::Server, None).await,
1060                            ),
1061                            addr,
1062                            user_id,
1063                            None,
1064                        )
1065                        .await;
1066                }
1067            });
1068
1069            Ok(response)
1070        }
1071    });
1072}
1073
1074fn header_contains_ignore_case<T>(
1075    request: &tide::Request<T>,
1076    header_name: HeaderName,
1077    value: &str,
1078) -> bool {
1079    request
1080        .header(header_name)
1081        .map(|h| {
1082            h.as_str()
1083                .split(',')
1084                .any(|s| s.trim().eq_ignore_ascii_case(value.trim()))
1085        })
1086        .unwrap_or(false)
1087}
1088
1089#[cfg(test)]
1090mod tests {
1091    use super::*;
1092    use crate::{
1093        auth,
1094        db::{tests::TestDb, UserId},
1095        github, AppState, Config,
1096    };
1097    use ::rpc::Peer;
1098    use async_std::task;
1099    use gpui::{executor, ModelHandle, TestAppContext};
1100    use parking_lot::Mutex;
1101    use postage::{mpsc, watch};
1102    use rpc::PeerId;
1103    use serde_json::json;
1104    use sqlx::types::time::OffsetDateTime;
1105    use std::{
1106        ops::Deref,
1107        path::Path,
1108        rc::Rc,
1109        sync::{
1110            atomic::{AtomicBool, Ordering::SeqCst},
1111            Arc,
1112        },
1113        time::Duration,
1114    };
1115    use zed::{
1116        client::{
1117            self, test::FakeHttpClient, Channel, ChannelDetails, ChannelList, Client, Credentials,
1118            EstablishConnectionError, UserStore,
1119        },
1120        editor::{Editor, EditorSettings, Input, MultiBuffer},
1121        fs::{FakeFs, Fs as _},
1122        language::{
1123            tree_sitter_rust, Diagnostic, DiagnosticEntry, Language, LanguageConfig,
1124            LanguageRegistry, LanguageServerConfig, Point,
1125        },
1126        lsp,
1127        project::{DiagnosticSummary, Project, ProjectPath},
1128    };
1129
1130    #[gpui::test]
1131    async fn test_share_project(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1132        let (window_b, _) = cx_b.add_window(|_| EmptyView);
1133        let lang_registry = Arc::new(LanguageRegistry::new());
1134        let fs = Arc::new(FakeFs::new());
1135        cx_a.foreground().forbid_parking();
1136
1137        // Connect to a server as 2 clients.
1138        let mut server = TestServer::start(cx_a.foreground()).await;
1139        let client_a = server.create_client(&mut cx_a, "user_a").await;
1140        let client_b = server.create_client(&mut cx_b, "user_b").await;
1141
1142        // Share a project as client A
1143        fs.insert_tree(
1144            "/a",
1145            json!({
1146                ".zed.toml": r#"collaborators = ["user_b"]"#,
1147                "a.txt": "a-contents",
1148                "b.txt": "b-contents",
1149            }),
1150        )
1151        .await;
1152        let project_a = cx_a.update(|cx| {
1153            Project::local(
1154                client_a.clone(),
1155                client_a.user_store.clone(),
1156                lang_registry.clone(),
1157                fs.clone(),
1158                cx,
1159            )
1160        });
1161        let worktree_a = project_a
1162            .update(&mut cx_a, |p, cx| p.add_local_worktree("/a", cx))
1163            .await
1164            .unwrap();
1165        worktree_a
1166            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1167            .await;
1168        let project_id = project_a
1169            .update(&mut cx_a, |project, _| project.next_remote_id())
1170            .await;
1171        project_a
1172            .update(&mut cx_a, |project, cx| project.share(cx))
1173            .await
1174            .unwrap();
1175
1176        // Join that project as client B
1177        let project_b = Project::remote(
1178            project_id,
1179            client_b.clone(),
1180            client_b.user_store.clone(),
1181            lang_registry.clone(),
1182            fs.clone(),
1183            &mut cx_b.to_async(),
1184        )
1185        .await
1186        .unwrap();
1187        let worktree_b = project_b.update(&mut cx_b, |p, _| p.worktrees()[0].clone());
1188
1189        let replica_id_b = project_b.read_with(&cx_b, |project, _| {
1190            assert_eq!(
1191                project
1192                    .collaborators()
1193                    .get(&client_a.peer_id)
1194                    .unwrap()
1195                    .user
1196                    .github_login,
1197                "user_a"
1198            );
1199            project.replica_id()
1200        });
1201        project_a
1202            .condition(&cx_a, |tree, _| {
1203                tree.collaborators()
1204                    .get(&client_b.peer_id)
1205                    .map_or(false, |collaborator| {
1206                        collaborator.replica_id == replica_id_b
1207                            && collaborator.user.github_login == "user_b"
1208                    })
1209            })
1210            .await;
1211
1212        // Open the same file as client B and client A.
1213        let buffer_b = worktree_b
1214            .update(&mut cx_b, |worktree, cx| worktree.open_buffer("b.txt", cx))
1215            .await
1216            .unwrap()
1217            .0;
1218        let buffer_b = cx_b.add_model(|cx| MultiBuffer::singleton(buffer_b, cx));
1219        buffer_b.read_with(&cx_b, |buf, cx| {
1220            assert_eq!(buf.read(cx).text(), "b-contents")
1221        });
1222        worktree_a.read_with(&cx_a, |tree, cx| assert!(tree.has_open_buffer("b.txt", cx)));
1223        let buffer_a = worktree_a
1224            .update(&mut cx_a, |tree, cx| tree.open_buffer("b.txt", cx))
1225            .await
1226            .unwrap()
1227            .0;
1228
1229        let editor_b = cx_b.add_view(window_b, |cx| {
1230            Editor::for_buffer(buffer_b, Arc::new(|cx| EditorSettings::test(cx)), cx)
1231        });
1232        // TODO
1233        // // Create a selection set as client B and see that selection set as client A.
1234        // buffer_a
1235        //     .condition(&cx_a, |buffer, _| buffer.selection_sets().count() == 1)
1236        //     .await;
1237
1238        // Edit the buffer as client B and see that edit as client A.
1239        editor_b.update(&mut cx_b, |editor, cx| {
1240            editor.handle_input(&Input("ok, ".into()), cx)
1241        });
1242        buffer_a
1243            .condition(&cx_a, |buffer, _| buffer.text() == "ok, b-contents")
1244            .await;
1245
1246        // TODO
1247        // // Remove the selection set as client B, see those selections disappear as client A.
1248        cx_b.update(move |_| drop(editor_b));
1249        // buffer_a
1250        //     .condition(&cx_a, |buffer, _| buffer.selection_sets().count() == 0)
1251        //     .await;
1252
1253        // Close the buffer as client A, see that the buffer is closed.
1254        cx_a.update(move |_| drop(buffer_a));
1255        worktree_a
1256            .condition(&cx_a, |tree, cx| !tree.has_open_buffer("b.txt", cx))
1257            .await;
1258
1259        // Dropping the client B's project removes client B from client A's collaborators.
1260        cx_b.update(move |_| drop(project_b));
1261        project_a
1262            .condition(&cx_a, |project, _| project.collaborators().is_empty())
1263            .await;
1264    }
1265
1266    #[gpui::test]
1267    async fn test_unshare_project(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1268        let lang_registry = Arc::new(LanguageRegistry::new());
1269        let fs = Arc::new(FakeFs::new());
1270        cx_a.foreground().forbid_parking();
1271
1272        // Connect to a server as 2 clients.
1273        let mut server = TestServer::start(cx_a.foreground()).await;
1274        let client_a = server.create_client(&mut cx_a, "user_a").await;
1275        let client_b = server.create_client(&mut cx_b, "user_b").await;
1276
1277        // Share a project as client A
1278        fs.insert_tree(
1279            "/a",
1280            json!({
1281                ".zed.toml": r#"collaborators = ["user_b"]"#,
1282                "a.txt": "a-contents",
1283                "b.txt": "b-contents",
1284            }),
1285        )
1286        .await;
1287        let project_a = cx_a.update(|cx| {
1288            Project::local(
1289                client_a.clone(),
1290                client_a.user_store.clone(),
1291                lang_registry.clone(),
1292                fs.clone(),
1293                cx,
1294            )
1295        });
1296        let worktree_a = project_a
1297            .update(&mut cx_a, |p, cx| p.add_local_worktree("/a", cx))
1298            .await
1299            .unwrap();
1300        worktree_a
1301            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1302            .await;
1303        let project_id = project_a
1304            .update(&mut cx_a, |project, _| project.next_remote_id())
1305            .await;
1306        project_a
1307            .update(&mut cx_a, |project, cx| project.share(cx))
1308            .await
1309            .unwrap();
1310        assert!(worktree_a.read_with(&cx_a, |tree, _| tree.as_local().unwrap().is_shared()));
1311
1312        // Join that project as client B
1313        let project_b = Project::remote(
1314            project_id,
1315            client_b.clone(),
1316            client_b.user_store.clone(),
1317            lang_registry.clone(),
1318            fs.clone(),
1319            &mut cx_b.to_async(),
1320        )
1321        .await
1322        .unwrap();
1323
1324        let worktree_b = project_b.read_with(&cx_b, |p, _| p.worktrees()[0].clone());
1325        worktree_b
1326            .update(&mut cx_b, |tree, cx| tree.open_buffer("a.txt", cx))
1327            .await
1328            .unwrap();
1329
1330        project_a
1331            .update(&mut cx_a, |project, cx| project.unshare(cx))
1332            .await
1333            .unwrap();
1334        project_b
1335            .condition(&mut cx_b, |project, _| project.is_read_only())
1336            .await;
1337        assert!(worktree_a.read_with(&cx_a, |tree, _| !tree.as_local().unwrap().is_shared()));
1338        drop(project_b);
1339
1340        // Share the project again and ensure guests can still join.
1341        project_a
1342            .update(&mut cx_a, |project, cx| project.share(cx))
1343            .await
1344            .unwrap();
1345        assert!(worktree_a.read_with(&cx_a, |tree, _| tree.as_local().unwrap().is_shared()));
1346        let project_c = Project::remote(
1347            project_id,
1348            client_b.clone(),
1349            client_b.user_store.clone(),
1350            lang_registry.clone(),
1351            fs.clone(),
1352            &mut cx_b.to_async(),
1353        )
1354        .await
1355        .unwrap();
1356        let worktree_c = project_c.read_with(&cx_b, |p, _| p.worktrees()[0].clone());
1357        worktree_c
1358            .update(&mut cx_b, |tree, cx| tree.open_buffer("a.txt", cx))
1359            .await
1360            .unwrap();
1361    }
1362
1363    #[gpui::test]
1364    async fn test_propagate_saves_and_fs_changes(
1365        mut cx_a: TestAppContext,
1366        mut cx_b: TestAppContext,
1367        mut cx_c: TestAppContext,
1368    ) {
1369        let lang_registry = Arc::new(LanguageRegistry::new());
1370        let fs = Arc::new(FakeFs::new());
1371        cx_a.foreground().forbid_parking();
1372
1373        // Connect to a server as 3 clients.
1374        let mut server = TestServer::start(cx_a.foreground()).await;
1375        let client_a = server.create_client(&mut cx_a, "user_a").await;
1376        let client_b = server.create_client(&mut cx_b, "user_b").await;
1377        let client_c = server.create_client(&mut cx_c, "user_c").await;
1378
1379        // Share a worktree as client A.
1380        fs.insert_tree(
1381            "/a",
1382            json!({
1383                ".zed.toml": r#"collaborators = ["user_b", "user_c"]"#,
1384                "file1": "",
1385                "file2": ""
1386            }),
1387        )
1388        .await;
1389        let project_a = cx_a.update(|cx| {
1390            Project::local(
1391                client_a.clone(),
1392                client_a.user_store.clone(),
1393                lang_registry.clone(),
1394                fs.clone(),
1395                cx,
1396            )
1397        });
1398        let worktree_a = project_a
1399            .update(&mut cx_a, |p, cx| p.add_local_worktree("/a", cx))
1400            .await
1401            .unwrap();
1402        worktree_a
1403            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1404            .await;
1405        let project_id = project_a
1406            .update(&mut cx_a, |project, _| project.next_remote_id())
1407            .await;
1408        project_a
1409            .update(&mut cx_a, |project, cx| project.share(cx))
1410            .await
1411            .unwrap();
1412
1413        // Join that worktree as clients B and C.
1414        let project_b = Project::remote(
1415            project_id,
1416            client_b.clone(),
1417            client_b.user_store.clone(),
1418            lang_registry.clone(),
1419            fs.clone(),
1420            &mut cx_b.to_async(),
1421        )
1422        .await
1423        .unwrap();
1424        let project_c = Project::remote(
1425            project_id,
1426            client_c.clone(),
1427            client_c.user_store.clone(),
1428            lang_registry.clone(),
1429            fs.clone(),
1430            &mut cx_c.to_async(),
1431        )
1432        .await
1433        .unwrap();
1434
1435        // Open and edit a buffer as both guests B and C.
1436        let worktree_b = project_b.read_with(&cx_b, |p, _| p.worktrees()[0].clone());
1437        let worktree_c = project_c.read_with(&cx_c, |p, _| p.worktrees()[0].clone());
1438        let buffer_b = worktree_b
1439            .update(&mut cx_b, |tree, cx| tree.open_buffer("file1", cx))
1440            .await
1441            .unwrap()
1442            .0;
1443        let buffer_c = worktree_c
1444            .update(&mut cx_c, |tree, cx| tree.open_buffer("file1", cx))
1445            .await
1446            .unwrap()
1447            .0;
1448        buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "i-am-b, ", cx));
1449        buffer_c.update(&mut cx_c, |buf, cx| buf.edit([0..0], "i-am-c, ", cx));
1450
1451        // Open and edit that buffer as the host.
1452        let buffer_a = worktree_a
1453            .update(&mut cx_a, |tree, cx| tree.open_buffer("file1", cx))
1454            .await
1455            .unwrap()
1456            .0;
1457
1458        buffer_a
1459            .condition(&mut cx_a, |buf, _| buf.text() == "i-am-c, i-am-b, ")
1460            .await;
1461        buffer_a.update(&mut cx_a, |buf, cx| {
1462            buf.edit([buf.len()..buf.len()], "i-am-a", cx)
1463        });
1464
1465        // Wait for edits to propagate
1466        buffer_a
1467            .condition(&mut cx_a, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1468            .await;
1469        buffer_b
1470            .condition(&mut cx_b, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1471            .await;
1472        buffer_c
1473            .condition(&mut cx_c, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1474            .await;
1475
1476        // Edit the buffer as the host and concurrently save as guest B.
1477        let save_b = buffer_b.update(&mut cx_b, |buf, cx| buf.save(cx).unwrap());
1478        buffer_a.update(&mut cx_a, |buf, cx| buf.edit([0..0], "hi-a, ", cx));
1479        save_b.await.unwrap();
1480        assert_eq!(
1481            fs.load("/a/file1".as_ref()).await.unwrap(),
1482            "hi-a, i-am-c, i-am-b, i-am-a"
1483        );
1484        buffer_a.read_with(&cx_a, |buf, _| assert!(!buf.is_dirty()));
1485        buffer_b.read_with(&cx_b, |buf, _| assert!(!buf.is_dirty()));
1486        buffer_c.condition(&cx_c, |buf, _| !buf.is_dirty()).await;
1487
1488        // Make changes on host's file system, see those changes on the guests.
1489        fs.rename("/a/file2".as_ref(), "/a/file3".as_ref())
1490            .await
1491            .unwrap();
1492        fs.insert_file(Path::new("/a/file4"), "4".into())
1493            .await
1494            .unwrap();
1495
1496        worktree_b
1497            .condition(&cx_b, |tree, _| tree.file_count() == 4)
1498            .await;
1499        worktree_c
1500            .condition(&cx_c, |tree, _| tree.file_count() == 4)
1501            .await;
1502        worktree_b.read_with(&cx_b, |tree, _| {
1503            assert_eq!(
1504                tree.paths()
1505                    .map(|p| p.to_string_lossy())
1506                    .collect::<Vec<_>>(),
1507                &[".zed.toml", "file1", "file3", "file4"]
1508            )
1509        });
1510        worktree_c.read_with(&cx_c, |tree, _| {
1511            assert_eq!(
1512                tree.paths()
1513                    .map(|p| p.to_string_lossy())
1514                    .collect::<Vec<_>>(),
1515                &[".zed.toml", "file1", "file3", "file4"]
1516            )
1517        });
1518    }
1519
1520    #[gpui::test]
1521    async fn test_buffer_conflict_after_save(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1522        cx_a.foreground().forbid_parking();
1523        let lang_registry = Arc::new(LanguageRegistry::new());
1524        let fs = Arc::new(FakeFs::new());
1525
1526        // Connect to a server as 2 clients.
1527        let mut server = TestServer::start(cx_a.foreground()).await;
1528        let client_a = server.create_client(&mut cx_a, "user_a").await;
1529        let client_b = server.create_client(&mut cx_b, "user_b").await;
1530
1531        // Share a project as client A
1532        fs.insert_tree(
1533            "/dir",
1534            json!({
1535                ".zed.toml": r#"collaborators = ["user_b", "user_c"]"#,
1536                "a.txt": "a-contents",
1537            }),
1538        )
1539        .await;
1540
1541        let project_a = cx_a.update(|cx| {
1542            Project::local(
1543                client_a.clone(),
1544                client_a.user_store.clone(),
1545                lang_registry.clone(),
1546                fs.clone(),
1547                cx,
1548            )
1549        });
1550        let worktree_a = project_a
1551            .update(&mut cx_a, |p, cx| p.add_local_worktree("/dir", cx))
1552            .await
1553            .unwrap();
1554        worktree_a
1555            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1556            .await;
1557        let project_id = project_a
1558            .update(&mut cx_a, |project, _| project.next_remote_id())
1559            .await;
1560        project_a
1561            .update(&mut cx_a, |project, cx| project.share(cx))
1562            .await
1563            .unwrap();
1564
1565        // Join that project as client B
1566        let project_b = Project::remote(
1567            project_id,
1568            client_b.clone(),
1569            client_b.user_store.clone(),
1570            lang_registry.clone(),
1571            fs.clone(),
1572            &mut cx_b.to_async(),
1573        )
1574        .await
1575        .unwrap();
1576        let worktree_b = project_b.update(&mut cx_b, |p, _| p.worktrees()[0].clone());
1577
1578        // Open a buffer as client B
1579        let buffer_b = worktree_b
1580            .update(&mut cx_b, |worktree, cx| worktree.open_buffer("a.txt", cx))
1581            .await
1582            .unwrap()
1583            .0;
1584        let mtime = buffer_b.read_with(&cx_b, |buf, _| buf.file().unwrap().mtime());
1585
1586        buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "world ", cx));
1587        buffer_b.read_with(&cx_b, |buf, _| {
1588            assert!(buf.is_dirty());
1589            assert!(!buf.has_conflict());
1590        });
1591
1592        buffer_b
1593            .update(&mut cx_b, |buf, cx| buf.save(cx))
1594            .unwrap()
1595            .await
1596            .unwrap();
1597        worktree_b
1598            .condition(&cx_b, |_, cx| {
1599                buffer_b.read(cx).file().unwrap().mtime() != mtime
1600            })
1601            .await;
1602        buffer_b.read_with(&cx_b, |buf, _| {
1603            assert!(!buf.is_dirty());
1604            assert!(!buf.has_conflict());
1605        });
1606
1607        buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "hello ", cx));
1608        buffer_b.read_with(&cx_b, |buf, _| {
1609            assert!(buf.is_dirty());
1610            assert!(!buf.has_conflict());
1611        });
1612    }
1613
1614    #[gpui::test]
1615    async fn test_editing_while_guest_opens_buffer(
1616        mut cx_a: TestAppContext,
1617        mut cx_b: TestAppContext,
1618    ) {
1619        cx_a.foreground().forbid_parking();
1620        let lang_registry = Arc::new(LanguageRegistry::new());
1621        let fs = Arc::new(FakeFs::new());
1622
1623        // Connect to a server as 2 clients.
1624        let mut server = TestServer::start(cx_a.foreground()).await;
1625        let client_a = server.create_client(&mut cx_a, "user_a").await;
1626        let client_b = server.create_client(&mut cx_b, "user_b").await;
1627
1628        // Share a project as client A
1629        fs.insert_tree(
1630            "/dir",
1631            json!({
1632                ".zed.toml": r#"collaborators = ["user_b"]"#,
1633                "a.txt": "a-contents",
1634            }),
1635        )
1636        .await;
1637        let project_a = cx_a.update(|cx| {
1638            Project::local(
1639                client_a.clone(),
1640                client_a.user_store.clone(),
1641                lang_registry.clone(),
1642                fs.clone(),
1643                cx,
1644            )
1645        });
1646        let worktree_a = project_a
1647            .update(&mut cx_a, |p, cx| p.add_local_worktree("/dir", cx))
1648            .await
1649            .unwrap();
1650        worktree_a
1651            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1652            .await;
1653        let project_id = project_a
1654            .update(&mut cx_a, |project, _| project.next_remote_id())
1655            .await;
1656        project_a
1657            .update(&mut cx_a, |project, cx| project.share(cx))
1658            .await
1659            .unwrap();
1660
1661        // Join that project as client B
1662        let project_b = Project::remote(
1663            project_id,
1664            client_b.clone(),
1665            client_b.user_store.clone(),
1666            lang_registry.clone(),
1667            fs.clone(),
1668            &mut cx_b.to_async(),
1669        )
1670        .await
1671        .unwrap();
1672        let worktree_b = project_b.update(&mut cx_b, |p, _| p.worktrees()[0].clone());
1673
1674        // Open a buffer as client A
1675        let buffer_a = worktree_a
1676            .update(&mut cx_a, |tree, cx| tree.open_buffer("a.txt", cx))
1677            .await
1678            .unwrap()
1679            .0;
1680
1681        // Start opening the same buffer as client B
1682        let buffer_b = cx_b
1683            .background()
1684            .spawn(worktree_b.update(&mut cx_b, |worktree, cx| worktree.open_buffer("a.txt", cx)));
1685        task::yield_now().await;
1686
1687        // Edit the buffer as client A while client B is still opening it.
1688        buffer_a.update(&mut cx_a, |buf, cx| buf.edit([0..0], "z", cx));
1689
1690        let text = buffer_a.read_with(&cx_a, |buf, _| buf.text());
1691        let buffer_b = buffer_b.await.unwrap().0;
1692        buffer_b.condition(&cx_b, |buf, _| buf.text() == text).await;
1693    }
1694
1695    #[gpui::test]
1696    async fn test_leaving_worktree_while_opening_buffer(
1697        mut cx_a: TestAppContext,
1698        mut cx_b: TestAppContext,
1699    ) {
1700        cx_a.foreground().forbid_parking();
1701        let lang_registry = Arc::new(LanguageRegistry::new());
1702        let fs = Arc::new(FakeFs::new());
1703
1704        // Connect to a server as 2 clients.
1705        let mut server = TestServer::start(cx_a.foreground()).await;
1706        let client_a = server.create_client(&mut cx_a, "user_a").await;
1707        let client_b = server.create_client(&mut cx_b, "user_b").await;
1708
1709        // Share a project as client A
1710        fs.insert_tree(
1711            "/dir",
1712            json!({
1713                ".zed.toml": r#"collaborators = ["user_b"]"#,
1714                "a.txt": "a-contents",
1715            }),
1716        )
1717        .await;
1718        let project_a = cx_a.update(|cx| {
1719            Project::local(
1720                client_a.clone(),
1721                client_a.user_store.clone(),
1722                lang_registry.clone(),
1723                fs.clone(),
1724                cx,
1725            )
1726        });
1727        let worktree_a = project_a
1728            .update(&mut cx_a, |p, cx| p.add_local_worktree("/dir", cx))
1729            .await
1730            .unwrap();
1731        worktree_a
1732            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1733            .await;
1734        let project_id = project_a
1735            .update(&mut cx_a, |project, _| project.next_remote_id())
1736            .await;
1737        project_a
1738            .update(&mut cx_a, |project, cx| project.share(cx))
1739            .await
1740            .unwrap();
1741
1742        // Join that project as client B
1743        let project_b = Project::remote(
1744            project_id,
1745            client_b.clone(),
1746            client_b.user_store.clone(),
1747            lang_registry.clone(),
1748            fs.clone(),
1749            &mut cx_b.to_async(),
1750        )
1751        .await
1752        .unwrap();
1753        let worktree_b = project_b.update(&mut cx_b, |p, _| p.worktrees()[0].clone());
1754
1755        // See that a guest has joined as client A.
1756        project_a
1757            .condition(&cx_a, |p, _| p.collaborators().len() == 1)
1758            .await;
1759
1760        // Begin opening a buffer as client B, but leave the project before the open completes.
1761        let buffer_b = cx_b
1762            .background()
1763            .spawn(worktree_b.update(&mut cx_b, |worktree, cx| worktree.open_buffer("a.txt", cx)));
1764        cx_b.update(|_| drop(project_b));
1765        drop(buffer_b);
1766
1767        // See that the guest has left.
1768        project_a
1769            .condition(&cx_a, |p, _| p.collaborators().len() == 0)
1770            .await;
1771    }
1772
1773    #[gpui::test]
1774    async fn test_peer_disconnection(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1775        cx_a.foreground().forbid_parking();
1776        let lang_registry = Arc::new(LanguageRegistry::new());
1777        let fs = Arc::new(FakeFs::new());
1778
1779        // Connect to a server as 2 clients.
1780        let mut server = TestServer::start(cx_a.foreground()).await;
1781        let client_a = server.create_client(&mut cx_a, "user_a").await;
1782        let client_b = server.create_client(&mut cx_b, "user_b").await;
1783
1784        // Share a project as client A
1785        fs.insert_tree(
1786            "/a",
1787            json!({
1788                ".zed.toml": r#"collaborators = ["user_b"]"#,
1789                "a.txt": "a-contents",
1790                "b.txt": "b-contents",
1791            }),
1792        )
1793        .await;
1794        let project_a = cx_a.update(|cx| {
1795            Project::local(
1796                client_a.clone(),
1797                client_a.user_store.clone(),
1798                lang_registry.clone(),
1799                fs.clone(),
1800                cx,
1801            )
1802        });
1803        let worktree_a = project_a
1804            .update(&mut cx_a, |p, cx| p.add_local_worktree("/a", cx))
1805            .await
1806            .unwrap();
1807        worktree_a
1808            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1809            .await;
1810        let project_id = project_a
1811            .update(&mut cx_a, |project, _| project.next_remote_id())
1812            .await;
1813        project_a
1814            .update(&mut cx_a, |project, cx| project.share(cx))
1815            .await
1816            .unwrap();
1817
1818        // Join that project as client B
1819        let _project_b = Project::remote(
1820            project_id,
1821            client_b.clone(),
1822            client_b.user_store.clone(),
1823            lang_registry.clone(),
1824            fs.clone(),
1825            &mut cx_b.to_async(),
1826        )
1827        .await
1828        .unwrap();
1829
1830        // See that a guest has joined as client A.
1831        project_a
1832            .condition(&cx_a, |p, _| p.collaborators().len() == 1)
1833            .await;
1834
1835        // Drop client B's connection and ensure client A observes client B leaving the worktree.
1836        client_b.disconnect(&cx_b.to_async()).unwrap();
1837        project_a
1838            .condition(&cx_a, |p, _| p.collaborators().len() == 0)
1839            .await;
1840    }
1841
1842    #[gpui::test]
1843    async fn test_collaborating_with_diagnostics(
1844        mut cx_a: TestAppContext,
1845        mut cx_b: TestAppContext,
1846    ) {
1847        cx_a.foreground().forbid_parking();
1848        let mut lang_registry = Arc::new(LanguageRegistry::new());
1849        let fs = Arc::new(FakeFs::new());
1850
1851        // Set up a fake language server.
1852        let (language_server_config, mut fake_language_server) =
1853            LanguageServerConfig::fake(cx_a.background()).await;
1854        Arc::get_mut(&mut lang_registry)
1855            .unwrap()
1856            .add(Arc::new(Language::new(
1857                LanguageConfig {
1858                    name: "Rust".to_string(),
1859                    path_suffixes: vec!["rs".to_string()],
1860                    language_server: Some(language_server_config),
1861                    ..Default::default()
1862                },
1863                Some(tree_sitter_rust::language()),
1864            )));
1865
1866        // Connect to a server as 2 clients.
1867        let mut server = TestServer::start(cx_a.foreground()).await;
1868        let client_a = server.create_client(&mut cx_a, "user_a").await;
1869        let client_b = server.create_client(&mut cx_b, "user_b").await;
1870
1871        // Share a project as client A
1872        fs.insert_tree(
1873            "/a",
1874            json!({
1875                ".zed.toml": r#"collaborators = ["user_b"]"#,
1876                "a.rs": "let one = two",
1877                "other.rs": "",
1878            }),
1879        )
1880        .await;
1881        let project_a = cx_a.update(|cx| {
1882            Project::local(
1883                client_a.clone(),
1884                client_a.user_store.clone(),
1885                lang_registry.clone(),
1886                fs.clone(),
1887                cx,
1888            )
1889        });
1890        let worktree_a = project_a
1891            .update(&mut cx_a, |p, cx| p.add_local_worktree("/a", cx))
1892            .await
1893            .unwrap();
1894        worktree_a
1895            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1896            .await;
1897        let project_id = project_a
1898            .update(&mut cx_a, |project, _| project.next_remote_id())
1899            .await;
1900        let worktree_id = worktree_a.read_with(&cx_a, |tree, _| tree.id());
1901        project_a
1902            .update(&mut cx_a, |project, cx| project.share(cx))
1903            .await
1904            .unwrap();
1905
1906        // Cause the language server to start.
1907        let _ = cx_a
1908            .background()
1909            .spawn(project_a.update(&mut cx_a, |project, cx| {
1910                project.open_buffer(
1911                    ProjectPath {
1912                        worktree_id,
1913                        path: Path::new("other.rs").into(),
1914                    },
1915                    cx,
1916                )
1917            }))
1918            .await
1919            .unwrap();
1920
1921        // Simulate a language server reporting errors for a file.
1922        fake_language_server
1923            .notify::<lsp::notification::PublishDiagnostics>(lsp::PublishDiagnosticsParams {
1924                uri: lsp::Url::from_file_path("/a/a.rs").unwrap(),
1925                version: None,
1926                diagnostics: vec![lsp::Diagnostic {
1927                    severity: Some(lsp::DiagnosticSeverity::ERROR),
1928                    range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 7)),
1929                    message: "message 1".to_string(),
1930                    ..Default::default()
1931                }],
1932            })
1933            .await;
1934
1935        // Wait for server to see the diagnostics update.
1936        server
1937            .condition(|store| {
1938                let worktree = store
1939                    .project(project_id)
1940                    .unwrap()
1941                    .worktrees
1942                    .get(&worktree_id.to_proto())
1943                    .unwrap();
1944
1945                !worktree
1946                    .share
1947                    .as_ref()
1948                    .unwrap()
1949                    .diagnostic_summaries
1950                    .is_empty()
1951            })
1952            .await;
1953
1954        // Join the worktree as client B.
1955        let project_b = Project::remote(
1956            project_id,
1957            client_b.clone(),
1958            client_b.user_store.clone(),
1959            lang_registry.clone(),
1960            fs.clone(),
1961            &mut cx_b.to_async(),
1962        )
1963        .await
1964        .unwrap();
1965
1966        project_b.read_with(&cx_b, |project, cx| {
1967            assert_eq!(
1968                project.diagnostic_summaries(cx).collect::<Vec<_>>(),
1969                &[(
1970                    ProjectPath {
1971                        worktree_id,
1972                        path: Arc::from(Path::new("a.rs")),
1973                    },
1974                    DiagnosticSummary {
1975                        error_count: 1,
1976                        warning_count: 0,
1977                        ..Default::default()
1978                    },
1979                )]
1980            )
1981        });
1982
1983        // Simulate a language server reporting more errors for a file.
1984        fake_language_server
1985            .notify::<lsp::notification::PublishDiagnostics>(lsp::PublishDiagnosticsParams {
1986                uri: lsp::Url::from_file_path("/a/a.rs").unwrap(),
1987                version: None,
1988                diagnostics: vec![
1989                    lsp::Diagnostic {
1990                        severity: Some(lsp::DiagnosticSeverity::ERROR),
1991                        range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 7)),
1992                        message: "message 1".to_string(),
1993                        ..Default::default()
1994                    },
1995                    lsp::Diagnostic {
1996                        severity: Some(lsp::DiagnosticSeverity::WARNING),
1997                        range: lsp::Range::new(
1998                            lsp::Position::new(0, 10),
1999                            lsp::Position::new(0, 13),
2000                        ),
2001                        message: "message 2".to_string(),
2002                        ..Default::default()
2003                    },
2004                ],
2005            })
2006            .await;
2007
2008        // Client b gets the updated summaries
2009        project_b
2010            .condition(&cx_b, |project, cx| {
2011                project.diagnostic_summaries(cx).collect::<Vec<_>>()
2012                    == &[(
2013                        ProjectPath {
2014                            worktree_id,
2015                            path: Arc::from(Path::new("a.rs")),
2016                        },
2017                        DiagnosticSummary {
2018                            error_count: 1,
2019                            warning_count: 1,
2020                            ..Default::default()
2021                        },
2022                    )]
2023            })
2024            .await;
2025
2026        // Open the file with the errors on client B. They should be present.
2027        let worktree_b = project_b.update(&mut cx_b, |p, _| p.worktrees()[0].clone());
2028        let buffer_b = cx_b
2029            .background()
2030            .spawn(worktree_b.update(&mut cx_b, |worktree, cx| worktree.open_buffer("a.rs", cx)))
2031            .await
2032            .unwrap()
2033            .0;
2034
2035        buffer_b.read_with(&cx_b, |buffer, _| {
2036            assert_eq!(
2037                buffer
2038                    .snapshot()
2039                    .diagnostics_in_range::<_, Point>(0..buffer.len())
2040                    .map(|entry| entry)
2041                    .collect::<Vec<_>>(),
2042                &[
2043                    DiagnosticEntry {
2044                        range: Point::new(0, 4)..Point::new(0, 7),
2045                        diagnostic: Diagnostic {
2046                            group_id: 0,
2047                            message: "message 1".to_string(),
2048                            severity: lsp::DiagnosticSeverity::ERROR,
2049                            is_primary: true,
2050                            ..Default::default()
2051                        }
2052                    },
2053                    DiagnosticEntry {
2054                        range: Point::new(0, 10)..Point::new(0, 13),
2055                        diagnostic: Diagnostic {
2056                            group_id: 1,
2057                            severity: lsp::DiagnosticSeverity::WARNING,
2058                            message: "message 2".to_string(),
2059                            is_primary: true,
2060                            ..Default::default()
2061                        }
2062                    }
2063                ]
2064            );
2065        });
2066    }
2067
2068    #[gpui::test]
2069    async fn test_formatting_buffer(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
2070        cx_a.foreground().forbid_parking();
2071        let mut lang_registry = Arc::new(LanguageRegistry::new());
2072        let fs = Arc::new(FakeFs::new());
2073
2074        // Set up a fake language server.
2075        let (language_server_config, mut fake_language_server) =
2076            LanguageServerConfig::fake(cx_a.background()).await;
2077        Arc::get_mut(&mut lang_registry)
2078            .unwrap()
2079            .add(Arc::new(Language::new(
2080                LanguageConfig {
2081                    name: "Rust".to_string(),
2082                    path_suffixes: vec!["rs".to_string()],
2083                    language_server: Some(language_server_config),
2084                    ..Default::default()
2085                },
2086                Some(tree_sitter_rust::language()),
2087            )));
2088
2089        // Connect to a server as 2 clients.
2090        let mut server = TestServer::start(cx_a.foreground()).await;
2091        let client_a = server.create_client(&mut cx_a, "user_a").await;
2092        let client_b = server.create_client(&mut cx_b, "user_b").await;
2093
2094        // Share a project as client A
2095        fs.insert_tree(
2096            "/a",
2097            json!({
2098                ".zed.toml": r#"collaborators = ["user_b"]"#,
2099                "a.rs": "let one = two",
2100            }),
2101        )
2102        .await;
2103        let project_a = cx_a.update(|cx| {
2104            Project::local(
2105                client_a.clone(),
2106                client_a.user_store.clone(),
2107                lang_registry.clone(),
2108                fs.clone(),
2109                cx,
2110            )
2111        });
2112        let worktree_a = project_a
2113            .update(&mut cx_a, |p, cx| p.add_local_worktree("/a", cx))
2114            .await
2115            .unwrap();
2116        worktree_a
2117            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
2118            .await;
2119        let project_id = project_a
2120            .update(&mut cx_a, |project, _| project.next_remote_id())
2121            .await;
2122        project_a
2123            .update(&mut cx_a, |project, cx| project.share(cx))
2124            .await
2125            .unwrap();
2126
2127        // Join the worktree as client B.
2128        let project_b = Project::remote(
2129            project_id,
2130            client_b.clone(),
2131            client_b.user_store.clone(),
2132            lang_registry.clone(),
2133            fs.clone(),
2134            &mut cx_b.to_async(),
2135        )
2136        .await
2137        .unwrap();
2138
2139        // Open the file to be formatted on client B.
2140        let worktree_b = project_b.update(&mut cx_b, |p, _| p.worktrees()[0].clone());
2141        let buffer_b = cx_b
2142            .background()
2143            .spawn(worktree_b.update(&mut cx_b, |worktree, cx| worktree.open_buffer("a.rs", cx)))
2144            .await
2145            .unwrap()
2146            .0;
2147
2148        let format = buffer_b.update(&mut cx_b, |buffer, cx| buffer.format(cx));
2149        let (request_id, _) = fake_language_server
2150            .receive_request::<lsp::request::Formatting>()
2151            .await;
2152        fake_language_server
2153            .respond(
2154                request_id,
2155                Some(vec![
2156                    lsp::TextEdit {
2157                        range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 4)),
2158                        new_text: "h".to_string(),
2159                    },
2160                    lsp::TextEdit {
2161                        range: lsp::Range::new(lsp::Position::new(0, 7), lsp::Position::new(0, 7)),
2162                        new_text: "y".to_string(),
2163                    },
2164                ]),
2165            )
2166            .await;
2167        format.await.unwrap();
2168        assert_eq!(
2169            buffer_b.read_with(&cx_b, |buffer, _| buffer.text()),
2170            "let honey = two"
2171        );
2172    }
2173
2174    #[gpui::test]
2175    async fn test_basic_chat(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
2176        cx_a.foreground().forbid_parking();
2177
2178        // Connect to a server as 2 clients.
2179        let mut server = TestServer::start(cx_a.foreground()).await;
2180        let client_a = server.create_client(&mut cx_a, "user_a").await;
2181        let client_b = server.create_client(&mut cx_b, "user_b").await;
2182
2183        // Create an org that includes these 2 users.
2184        let db = &server.app_state.db;
2185        let org_id = db.create_org("Test Org", "test-org").await.unwrap();
2186        db.add_org_member(org_id, client_a.current_user_id(&cx_a), false)
2187            .await
2188            .unwrap();
2189        db.add_org_member(org_id, client_b.current_user_id(&cx_b), false)
2190            .await
2191            .unwrap();
2192
2193        // Create a channel that includes all the users.
2194        let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
2195        db.add_channel_member(channel_id, client_a.current_user_id(&cx_a), false)
2196            .await
2197            .unwrap();
2198        db.add_channel_member(channel_id, client_b.current_user_id(&cx_b), false)
2199            .await
2200            .unwrap();
2201        db.create_channel_message(
2202            channel_id,
2203            client_b.current_user_id(&cx_b),
2204            "hello A, it's B.",
2205            OffsetDateTime::now_utc(),
2206            1,
2207        )
2208        .await
2209        .unwrap();
2210
2211        let channels_a = cx_a
2212            .add_model(|cx| ChannelList::new(client_a.user_store.clone(), client_a.clone(), cx));
2213        channels_a
2214            .condition(&mut cx_a, |list, _| list.available_channels().is_some())
2215            .await;
2216        channels_a.read_with(&cx_a, |list, _| {
2217            assert_eq!(
2218                list.available_channels().unwrap(),
2219                &[ChannelDetails {
2220                    id: channel_id.to_proto(),
2221                    name: "test-channel".to_string()
2222                }]
2223            )
2224        });
2225        let channel_a = channels_a.update(&mut cx_a, |this, cx| {
2226            this.get_channel(channel_id.to_proto(), cx).unwrap()
2227        });
2228        channel_a.read_with(&cx_a, |channel, _| assert!(channel.messages().is_empty()));
2229        channel_a
2230            .condition(&cx_a, |channel, _| {
2231                channel_messages(channel)
2232                    == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2233            })
2234            .await;
2235
2236        let channels_b = cx_b
2237            .add_model(|cx| ChannelList::new(client_b.user_store.clone(), client_b.clone(), cx));
2238        channels_b
2239            .condition(&mut cx_b, |list, _| list.available_channels().is_some())
2240            .await;
2241        channels_b.read_with(&cx_b, |list, _| {
2242            assert_eq!(
2243                list.available_channels().unwrap(),
2244                &[ChannelDetails {
2245                    id: channel_id.to_proto(),
2246                    name: "test-channel".to_string()
2247                }]
2248            )
2249        });
2250
2251        let channel_b = channels_b.update(&mut cx_b, |this, cx| {
2252            this.get_channel(channel_id.to_proto(), cx).unwrap()
2253        });
2254        channel_b.read_with(&cx_b, |channel, _| assert!(channel.messages().is_empty()));
2255        channel_b
2256            .condition(&cx_b, |channel, _| {
2257                channel_messages(channel)
2258                    == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2259            })
2260            .await;
2261
2262        channel_a
2263            .update(&mut cx_a, |channel, cx| {
2264                channel
2265                    .send_message("oh, hi B.".to_string(), cx)
2266                    .unwrap()
2267                    .detach();
2268                let task = channel.send_message("sup".to_string(), cx).unwrap();
2269                assert_eq!(
2270                    channel_messages(channel),
2271                    &[
2272                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2273                        ("user_a".to_string(), "oh, hi B.".to_string(), true),
2274                        ("user_a".to_string(), "sup".to_string(), true)
2275                    ]
2276                );
2277                task
2278            })
2279            .await
2280            .unwrap();
2281
2282        channel_b
2283            .condition(&cx_b, |channel, _| {
2284                channel_messages(channel)
2285                    == [
2286                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2287                        ("user_a".to_string(), "oh, hi B.".to_string(), false),
2288                        ("user_a".to_string(), "sup".to_string(), false),
2289                    ]
2290            })
2291            .await;
2292
2293        assert_eq!(
2294            server
2295                .state()
2296                .await
2297                .channel(channel_id)
2298                .unwrap()
2299                .connection_ids
2300                .len(),
2301            2
2302        );
2303        cx_b.update(|_| drop(channel_b));
2304        server
2305            .condition(|state| state.channel(channel_id).unwrap().connection_ids.len() == 1)
2306            .await;
2307
2308        cx_a.update(|_| drop(channel_a));
2309        server
2310            .condition(|state| state.channel(channel_id).is_none())
2311            .await;
2312    }
2313
2314    #[gpui::test]
2315    async fn test_chat_message_validation(mut cx_a: TestAppContext) {
2316        cx_a.foreground().forbid_parking();
2317
2318        let mut server = TestServer::start(cx_a.foreground()).await;
2319        let client_a = server.create_client(&mut cx_a, "user_a").await;
2320
2321        let db = &server.app_state.db;
2322        let org_id = db.create_org("Test Org", "test-org").await.unwrap();
2323        let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
2324        db.add_org_member(org_id, client_a.current_user_id(&cx_a), false)
2325            .await
2326            .unwrap();
2327        db.add_channel_member(channel_id, client_a.current_user_id(&cx_a), false)
2328            .await
2329            .unwrap();
2330
2331        let channels_a = cx_a
2332            .add_model(|cx| ChannelList::new(client_a.user_store.clone(), client_a.clone(), cx));
2333        channels_a
2334            .condition(&mut cx_a, |list, _| list.available_channels().is_some())
2335            .await;
2336        let channel_a = channels_a.update(&mut cx_a, |this, cx| {
2337            this.get_channel(channel_id.to_proto(), cx).unwrap()
2338        });
2339
2340        // Messages aren't allowed to be too long.
2341        channel_a
2342            .update(&mut cx_a, |channel, cx| {
2343                let long_body = "this is long.\n".repeat(1024);
2344                channel.send_message(long_body, cx).unwrap()
2345            })
2346            .await
2347            .unwrap_err();
2348
2349        // Messages aren't allowed to be blank.
2350        channel_a.update(&mut cx_a, |channel, cx| {
2351            channel.send_message(String::new(), cx).unwrap_err()
2352        });
2353
2354        // Leading and trailing whitespace are trimmed.
2355        channel_a
2356            .update(&mut cx_a, |channel, cx| {
2357                channel
2358                    .send_message("\n surrounded by whitespace  \n".to_string(), cx)
2359                    .unwrap()
2360            })
2361            .await
2362            .unwrap();
2363        assert_eq!(
2364            db.get_channel_messages(channel_id, 10, None)
2365                .await
2366                .unwrap()
2367                .iter()
2368                .map(|m| &m.body)
2369                .collect::<Vec<_>>(),
2370            &["surrounded by whitespace"]
2371        );
2372    }
2373
2374    #[gpui::test]
2375    async fn test_chat_reconnection(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
2376        cx_a.foreground().forbid_parking();
2377
2378        // Connect to a server as 2 clients.
2379        let mut server = TestServer::start(cx_a.foreground()).await;
2380        let client_a = server.create_client(&mut cx_a, "user_a").await;
2381        let client_b = server.create_client(&mut cx_b, "user_b").await;
2382        let mut status_b = client_b.status();
2383
2384        // Create an org that includes these 2 users.
2385        let db = &server.app_state.db;
2386        let org_id = db.create_org("Test Org", "test-org").await.unwrap();
2387        db.add_org_member(org_id, client_a.current_user_id(&cx_a), false)
2388            .await
2389            .unwrap();
2390        db.add_org_member(org_id, client_b.current_user_id(&cx_b), false)
2391            .await
2392            .unwrap();
2393
2394        // Create a channel that includes all the users.
2395        let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
2396        db.add_channel_member(channel_id, client_a.current_user_id(&cx_a), false)
2397            .await
2398            .unwrap();
2399        db.add_channel_member(channel_id, client_b.current_user_id(&cx_b), false)
2400            .await
2401            .unwrap();
2402        db.create_channel_message(
2403            channel_id,
2404            client_b.current_user_id(&cx_b),
2405            "hello A, it's B.",
2406            OffsetDateTime::now_utc(),
2407            2,
2408        )
2409        .await
2410        .unwrap();
2411
2412        let channels_a = cx_a
2413            .add_model(|cx| ChannelList::new(client_a.user_store.clone(), client_a.clone(), cx));
2414        channels_a
2415            .condition(&mut cx_a, |list, _| list.available_channels().is_some())
2416            .await;
2417
2418        channels_a.read_with(&cx_a, |list, _| {
2419            assert_eq!(
2420                list.available_channels().unwrap(),
2421                &[ChannelDetails {
2422                    id: channel_id.to_proto(),
2423                    name: "test-channel".to_string()
2424                }]
2425            )
2426        });
2427        let channel_a = channels_a.update(&mut cx_a, |this, cx| {
2428            this.get_channel(channel_id.to_proto(), cx).unwrap()
2429        });
2430        channel_a.read_with(&cx_a, |channel, _| assert!(channel.messages().is_empty()));
2431        channel_a
2432            .condition(&cx_a, |channel, _| {
2433                channel_messages(channel)
2434                    == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2435            })
2436            .await;
2437
2438        let channels_b = cx_b
2439            .add_model(|cx| ChannelList::new(client_b.user_store.clone(), client_b.clone(), cx));
2440        channels_b
2441            .condition(&mut cx_b, |list, _| list.available_channels().is_some())
2442            .await;
2443        channels_b.read_with(&cx_b, |list, _| {
2444            assert_eq!(
2445                list.available_channels().unwrap(),
2446                &[ChannelDetails {
2447                    id: channel_id.to_proto(),
2448                    name: "test-channel".to_string()
2449                }]
2450            )
2451        });
2452
2453        let channel_b = channels_b.update(&mut cx_b, |this, cx| {
2454            this.get_channel(channel_id.to_proto(), cx).unwrap()
2455        });
2456        channel_b.read_with(&cx_b, |channel, _| assert!(channel.messages().is_empty()));
2457        channel_b
2458            .condition(&cx_b, |channel, _| {
2459                channel_messages(channel)
2460                    == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2461            })
2462            .await;
2463
2464        // Disconnect client B, ensuring we can still access its cached channel data.
2465        server.forbid_connections();
2466        server.disconnect_client(client_b.current_user_id(&cx_b));
2467        while !matches!(
2468            status_b.next().await,
2469            Some(client::Status::ReconnectionError { .. })
2470        ) {}
2471
2472        channels_b.read_with(&cx_b, |channels, _| {
2473            assert_eq!(
2474                channels.available_channels().unwrap(),
2475                [ChannelDetails {
2476                    id: channel_id.to_proto(),
2477                    name: "test-channel".to_string()
2478                }]
2479            )
2480        });
2481        channel_b.read_with(&cx_b, |channel, _| {
2482            assert_eq!(
2483                channel_messages(channel),
2484                [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2485            )
2486        });
2487
2488        // Send a message from client B while it is disconnected.
2489        channel_b
2490            .update(&mut cx_b, |channel, cx| {
2491                let task = channel
2492                    .send_message("can you see this?".to_string(), cx)
2493                    .unwrap();
2494                assert_eq!(
2495                    channel_messages(channel),
2496                    &[
2497                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2498                        ("user_b".to_string(), "can you see this?".to_string(), true)
2499                    ]
2500                );
2501                task
2502            })
2503            .await
2504            .unwrap_err();
2505
2506        // Send a message from client A while B is disconnected.
2507        channel_a
2508            .update(&mut cx_a, |channel, cx| {
2509                channel
2510                    .send_message("oh, hi B.".to_string(), cx)
2511                    .unwrap()
2512                    .detach();
2513                let task = channel.send_message("sup".to_string(), cx).unwrap();
2514                assert_eq!(
2515                    channel_messages(channel),
2516                    &[
2517                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2518                        ("user_a".to_string(), "oh, hi B.".to_string(), true),
2519                        ("user_a".to_string(), "sup".to_string(), true)
2520                    ]
2521                );
2522                task
2523            })
2524            .await
2525            .unwrap();
2526
2527        // Give client B a chance to reconnect.
2528        server.allow_connections();
2529        cx_b.foreground().advance_clock(Duration::from_secs(10));
2530
2531        // Verify that B sees the new messages upon reconnection, as well as the message client B
2532        // sent while offline.
2533        channel_b
2534            .condition(&cx_b, |channel, _| {
2535                channel_messages(channel)
2536                    == [
2537                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2538                        ("user_a".to_string(), "oh, hi B.".to_string(), false),
2539                        ("user_a".to_string(), "sup".to_string(), false),
2540                        ("user_b".to_string(), "can you see this?".to_string(), false),
2541                    ]
2542            })
2543            .await;
2544
2545        // Ensure client A and B can communicate normally after reconnection.
2546        channel_a
2547            .update(&mut cx_a, |channel, cx| {
2548                channel.send_message("you online?".to_string(), cx).unwrap()
2549            })
2550            .await
2551            .unwrap();
2552        channel_b
2553            .condition(&cx_b, |channel, _| {
2554                channel_messages(channel)
2555                    == [
2556                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2557                        ("user_a".to_string(), "oh, hi B.".to_string(), false),
2558                        ("user_a".to_string(), "sup".to_string(), false),
2559                        ("user_b".to_string(), "can you see this?".to_string(), false),
2560                        ("user_a".to_string(), "you online?".to_string(), false),
2561                    ]
2562            })
2563            .await;
2564
2565        channel_b
2566            .update(&mut cx_b, |channel, cx| {
2567                channel.send_message("yep".to_string(), cx).unwrap()
2568            })
2569            .await
2570            .unwrap();
2571        channel_a
2572            .condition(&cx_a, |channel, _| {
2573                channel_messages(channel)
2574                    == [
2575                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2576                        ("user_a".to_string(), "oh, hi B.".to_string(), false),
2577                        ("user_a".to_string(), "sup".to_string(), false),
2578                        ("user_b".to_string(), "can you see this?".to_string(), false),
2579                        ("user_a".to_string(), "you online?".to_string(), false),
2580                        ("user_b".to_string(), "yep".to_string(), false),
2581                    ]
2582            })
2583            .await;
2584    }
2585
2586    #[gpui::test]
2587    async fn test_contacts(
2588        mut cx_a: TestAppContext,
2589        mut cx_b: TestAppContext,
2590        mut cx_c: TestAppContext,
2591    ) {
2592        cx_a.foreground().forbid_parking();
2593        let lang_registry = Arc::new(LanguageRegistry::new());
2594        let fs = Arc::new(FakeFs::new());
2595
2596        // Connect to a server as 3 clients.
2597        let mut server = TestServer::start(cx_a.foreground()).await;
2598        let client_a = server.create_client(&mut cx_a, "user_a").await;
2599        let client_b = server.create_client(&mut cx_b, "user_b").await;
2600        let client_c = server.create_client(&mut cx_c, "user_c").await;
2601
2602        // Share a worktree as client A.
2603        fs.insert_tree(
2604            "/a",
2605            json!({
2606                ".zed.toml": r#"collaborators = ["user_b", "user_c"]"#,
2607            }),
2608        )
2609        .await;
2610
2611        let project_a = cx_a.update(|cx| {
2612            Project::local(
2613                client_a.clone(),
2614                client_a.user_store.clone(),
2615                lang_registry.clone(),
2616                fs.clone(),
2617                cx,
2618            )
2619        });
2620        let worktree_a = project_a
2621            .update(&mut cx_a, |p, cx| p.add_local_worktree("/a", cx))
2622            .await
2623            .unwrap();
2624        worktree_a
2625            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
2626            .await;
2627
2628        client_a
2629            .user_store
2630            .condition(&cx_a, |user_store, _| {
2631                contacts(user_store) == vec![("user_a", vec![("a", vec![])])]
2632            })
2633            .await;
2634        client_b
2635            .user_store
2636            .condition(&cx_b, |user_store, _| {
2637                contacts(user_store) == vec![("user_a", vec![("a", vec![])])]
2638            })
2639            .await;
2640        client_c
2641            .user_store
2642            .condition(&cx_c, |user_store, _| {
2643                contacts(user_store) == vec![("user_a", vec![("a", vec![])])]
2644            })
2645            .await;
2646
2647        let project_id = project_a
2648            .update(&mut cx_a, |project, _| project.next_remote_id())
2649            .await;
2650        project_a
2651            .update(&mut cx_a, |project, cx| project.share(cx))
2652            .await
2653            .unwrap();
2654
2655        let _project_b = Project::remote(
2656            project_id,
2657            client_b.clone(),
2658            client_b.user_store.clone(),
2659            lang_registry.clone(),
2660            fs.clone(),
2661            &mut cx_b.to_async(),
2662        )
2663        .await
2664        .unwrap();
2665
2666        client_a
2667            .user_store
2668            .condition(&cx_a, |user_store, _| {
2669                contacts(user_store) == vec![("user_a", vec![("a", vec!["user_b"])])]
2670            })
2671            .await;
2672        client_b
2673            .user_store
2674            .condition(&cx_b, |user_store, _| {
2675                contacts(user_store) == vec![("user_a", vec![("a", vec!["user_b"])])]
2676            })
2677            .await;
2678        client_c
2679            .user_store
2680            .condition(&cx_c, |user_store, _| {
2681                contacts(user_store) == vec![("user_a", vec![("a", vec!["user_b"])])]
2682            })
2683            .await;
2684
2685        project_a
2686            .condition(&cx_a, |project, _| {
2687                project.collaborators().contains_key(&client_b.peer_id)
2688            })
2689            .await;
2690
2691        cx_a.update(move |_| drop(project_a));
2692        client_a
2693            .user_store
2694            .condition(&cx_a, |user_store, _| contacts(user_store) == vec![])
2695            .await;
2696        client_b
2697            .user_store
2698            .condition(&cx_b, |user_store, _| contacts(user_store) == vec![])
2699            .await;
2700        client_c
2701            .user_store
2702            .condition(&cx_c, |user_store, _| contacts(user_store) == vec![])
2703            .await;
2704
2705        fn contacts(user_store: &UserStore) -> Vec<(&str, Vec<(&str, Vec<&str>)>)> {
2706            user_store
2707                .contacts()
2708                .iter()
2709                .map(|contact| {
2710                    let worktrees = contact
2711                        .projects
2712                        .iter()
2713                        .map(|p| {
2714                            (
2715                                p.worktree_root_names[0].as_str(),
2716                                p.guests.iter().map(|p| p.github_login.as_str()).collect(),
2717                            )
2718                        })
2719                        .collect();
2720                    (contact.user.github_login.as_str(), worktrees)
2721                })
2722                .collect()
2723        }
2724    }
2725
2726    struct TestServer {
2727        peer: Arc<Peer>,
2728        app_state: Arc<AppState>,
2729        server: Arc<Server>,
2730        foreground: Rc<executor::Foreground>,
2731        notifications: mpsc::Receiver<()>,
2732        connection_killers: Arc<Mutex<HashMap<UserId, watch::Sender<Option<()>>>>>,
2733        forbid_connections: Arc<AtomicBool>,
2734        _test_db: TestDb,
2735    }
2736
2737    impl TestServer {
2738        async fn start(foreground: Rc<executor::Foreground>) -> Self {
2739            let test_db = TestDb::new();
2740            let app_state = Self::build_app_state(&test_db).await;
2741            let peer = Peer::new();
2742            let notifications = mpsc::channel(128);
2743            let server = Server::new(app_state.clone(), peer.clone(), Some(notifications.0));
2744            Self {
2745                peer,
2746                app_state,
2747                server,
2748                foreground,
2749                notifications: notifications.1,
2750                connection_killers: Default::default(),
2751                forbid_connections: Default::default(),
2752                _test_db: test_db,
2753            }
2754        }
2755
2756        async fn create_client(&mut self, cx: &mut TestAppContext, name: &str) -> TestClient {
2757            let http = FakeHttpClient::with_404_response();
2758            let user_id = self.app_state.db.create_user(name, false).await.unwrap();
2759            let client_name = name.to_string();
2760            let mut client = Client::new(http.clone());
2761            let server = self.server.clone();
2762            let connection_killers = self.connection_killers.clone();
2763            let forbid_connections = self.forbid_connections.clone();
2764            let (connection_id_tx, mut connection_id_rx) = postage::mpsc::channel(16);
2765
2766            Arc::get_mut(&mut client)
2767                .unwrap()
2768                .override_authenticate(move |cx| {
2769                    cx.spawn(|_| async move {
2770                        let access_token = "the-token".to_string();
2771                        Ok(Credentials {
2772                            user_id: user_id.0 as u64,
2773                            access_token,
2774                        })
2775                    })
2776                })
2777                .override_establish_connection(move |credentials, cx| {
2778                    assert_eq!(credentials.user_id, user_id.0 as u64);
2779                    assert_eq!(credentials.access_token, "the-token");
2780
2781                    let server = server.clone();
2782                    let connection_killers = connection_killers.clone();
2783                    let forbid_connections = forbid_connections.clone();
2784                    let client_name = client_name.clone();
2785                    let connection_id_tx = connection_id_tx.clone();
2786                    cx.spawn(move |cx| async move {
2787                        if forbid_connections.load(SeqCst) {
2788                            Err(EstablishConnectionError::other(anyhow!(
2789                                "server is forbidding connections"
2790                            )))
2791                        } else {
2792                            let (client_conn, server_conn, kill_conn) = Connection::in_memory();
2793                            connection_killers.lock().insert(user_id, kill_conn);
2794                            cx.background()
2795                                .spawn(server.handle_connection(
2796                                    server_conn,
2797                                    client_name,
2798                                    user_id,
2799                                    Some(connection_id_tx),
2800                                ))
2801                                .detach();
2802                            Ok(client_conn)
2803                        }
2804                    })
2805                });
2806
2807            client
2808                .authenticate_and_connect(&cx.to_async())
2809                .await
2810                .unwrap();
2811
2812            let peer_id = PeerId(connection_id_rx.next().await.unwrap().0);
2813            let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http, cx));
2814            let mut authed_user =
2815                user_store.read_with(cx, |user_store, _| user_store.watch_current_user());
2816            while authed_user.next().await.unwrap().is_none() {}
2817
2818            TestClient {
2819                client,
2820                peer_id,
2821                user_store,
2822            }
2823        }
2824
2825        fn disconnect_client(&self, user_id: UserId) {
2826            if let Some(mut kill_conn) = self.connection_killers.lock().remove(&user_id) {
2827                let _ = kill_conn.try_send(Some(()));
2828            }
2829        }
2830
2831        fn forbid_connections(&self) {
2832            self.forbid_connections.store(true, SeqCst);
2833        }
2834
2835        fn allow_connections(&self) {
2836            self.forbid_connections.store(false, SeqCst);
2837        }
2838
2839        async fn build_app_state(test_db: &TestDb) -> Arc<AppState> {
2840            let mut config = Config::default();
2841            config.session_secret = "a".repeat(32);
2842            config.database_url = test_db.url.clone();
2843            let github_client = github::AppClient::test();
2844            Arc::new(AppState {
2845                db: test_db.db().clone(),
2846                handlebars: Default::default(),
2847                auth_client: auth::build_client("", ""),
2848                repo_client: github::RepoClient::test(&github_client),
2849                github_client,
2850                config,
2851            })
2852        }
2853
2854        async fn state<'a>(&'a self) -> RwLockReadGuard<'a, Store> {
2855            self.server.store.read()
2856        }
2857
2858        async fn condition<F>(&mut self, mut predicate: F)
2859        where
2860            F: FnMut(&Store) -> bool,
2861        {
2862            async_std::future::timeout(Duration::from_millis(500), async {
2863                while !(predicate)(&*self.server.store.read()) {
2864                    self.foreground.start_waiting();
2865                    self.notifications.next().await;
2866                    self.foreground.finish_waiting();
2867                }
2868            })
2869            .await
2870            .expect("condition timed out");
2871        }
2872    }
2873
2874    impl Drop for TestServer {
2875        fn drop(&mut self) {
2876            self.peer.reset();
2877        }
2878    }
2879
2880    struct TestClient {
2881        client: Arc<Client>,
2882        pub peer_id: PeerId,
2883        pub user_store: ModelHandle<UserStore>,
2884    }
2885
2886    impl Deref for TestClient {
2887        type Target = Arc<Client>;
2888
2889        fn deref(&self) -> &Self::Target {
2890            &self.client
2891        }
2892    }
2893
2894    impl TestClient {
2895        pub fn current_user_id(&self, cx: &TestAppContext) -> UserId {
2896            UserId::from_proto(
2897                self.user_store
2898                    .read_with(cx, |user_store, _| user_store.current_user().unwrap().id),
2899            )
2900        }
2901    }
2902
2903    fn channel_messages(channel: &Channel) -> Vec<(String, String, bool)> {
2904        channel
2905            .messages()
2906            .cursor::<()>()
2907            .map(|m| {
2908                (
2909                    m.sender.github_login.clone(),
2910                    m.body.clone(),
2911                    m.is_pending(),
2912                )
2913            })
2914            .collect()
2915    }
2916
2917    struct EmptyView;
2918
2919    impl gpui::Entity for EmptyView {
2920        type Event = ();
2921    }
2922
2923    impl gpui::View for EmptyView {
2924        fn ui_name() -> &'static str {
2925            "empty view"
2926        }
2927
2928        fn render(&mut self, _: &mut gpui::RenderContext<Self>) -> gpui::ElementBox {
2929            gpui::Element::boxed(gpui::elements::Empty)
2930        }
2931    }
2932}