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(worktree_a.update(&mut cx_a, |worktree, cx| {
1910                worktree.open_buffer("other.rs", cx)
1911            }))
1912            .await
1913            .unwrap();
1914
1915        // Simulate a language server reporting errors for a file.
1916        fake_language_server
1917            .notify::<lsp::notification::PublishDiagnostics>(lsp::PublishDiagnosticsParams {
1918                uri: lsp::Url::from_file_path("/a/a.rs").unwrap(),
1919                version: None,
1920                diagnostics: vec![lsp::Diagnostic {
1921                    severity: Some(lsp::DiagnosticSeverity::ERROR),
1922                    range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 7)),
1923                    message: "message 1".to_string(),
1924                    ..Default::default()
1925                }],
1926            })
1927            .await;
1928
1929        // Wait for server to see the diagnostics update.
1930        server
1931            .condition(|store| {
1932                let worktree = store
1933                    .project(project_id)
1934                    .unwrap()
1935                    .worktrees
1936                    .get(&worktree_id.to_proto())
1937                    .unwrap();
1938
1939                !worktree
1940                    .share
1941                    .as_ref()
1942                    .unwrap()
1943                    .diagnostic_summaries
1944                    .is_empty()
1945            })
1946            .await;
1947
1948        // Join the worktree as client B.
1949        let project_b = Project::remote(
1950            project_id,
1951            client_b.clone(),
1952            client_b.user_store.clone(),
1953            lang_registry.clone(),
1954            fs.clone(),
1955            &mut cx_b.to_async(),
1956        )
1957        .await
1958        .unwrap();
1959
1960        project_b.read_with(&cx_b, |project, cx| {
1961            assert_eq!(
1962                project.diagnostic_summaries(cx).collect::<Vec<_>>(),
1963                &[(
1964                    ProjectPath {
1965                        worktree_id,
1966                        path: Arc::from(Path::new("a.rs")),
1967                    },
1968                    DiagnosticSummary {
1969                        error_count: 1,
1970                        warning_count: 0,
1971                        ..Default::default()
1972                    },
1973                )]
1974            )
1975        });
1976
1977        // Simulate a language server reporting more errors for a file.
1978        fake_language_server
1979            .notify::<lsp::notification::PublishDiagnostics>(lsp::PublishDiagnosticsParams {
1980                uri: lsp::Url::from_file_path("/a/a.rs").unwrap(),
1981                version: None,
1982                diagnostics: vec![
1983                    lsp::Diagnostic {
1984                        severity: Some(lsp::DiagnosticSeverity::ERROR),
1985                        range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 7)),
1986                        message: "message 1".to_string(),
1987                        ..Default::default()
1988                    },
1989                    lsp::Diagnostic {
1990                        severity: Some(lsp::DiagnosticSeverity::WARNING),
1991                        range: lsp::Range::new(
1992                            lsp::Position::new(0, 10),
1993                            lsp::Position::new(0, 13),
1994                        ),
1995                        message: "message 2".to_string(),
1996                        ..Default::default()
1997                    },
1998                ],
1999            })
2000            .await;
2001
2002        // Client b gets the updated summaries
2003        project_b
2004            .condition(&cx_b, |project, cx| {
2005                project.diagnostic_summaries(cx).collect::<Vec<_>>()
2006                    == &[(
2007                        ProjectPath {
2008                            worktree_id,
2009                            path: Arc::from(Path::new("a.rs")),
2010                        },
2011                        DiagnosticSummary {
2012                            error_count: 1,
2013                            warning_count: 1,
2014                            ..Default::default()
2015                        },
2016                    )]
2017            })
2018            .await;
2019
2020        // Open the file with the errors on client B. They should be present.
2021        let worktree_b = project_b.update(&mut cx_b, |p, _| p.worktrees()[0].clone());
2022        let buffer_b = cx_b
2023            .background()
2024            .spawn(worktree_b.update(&mut cx_b, |worktree, cx| worktree.open_buffer("a.rs", cx)))
2025            .await
2026            .unwrap()
2027            .0;
2028
2029        buffer_b.read_with(&cx_b, |buffer, _| {
2030            assert_eq!(
2031                buffer
2032                    .snapshot()
2033                    .diagnostics_in_range::<_, Point>(0..buffer.len())
2034                    .map(|entry| entry)
2035                    .collect::<Vec<_>>(),
2036                &[
2037                    DiagnosticEntry {
2038                        range: Point::new(0, 4)..Point::new(0, 7),
2039                        diagnostic: Diagnostic {
2040                            group_id: 0,
2041                            message: "message 1".to_string(),
2042                            severity: lsp::DiagnosticSeverity::ERROR,
2043                            is_primary: true,
2044                            ..Default::default()
2045                        }
2046                    },
2047                    DiagnosticEntry {
2048                        range: Point::new(0, 10)..Point::new(0, 13),
2049                        diagnostic: Diagnostic {
2050                            group_id: 1,
2051                            severity: lsp::DiagnosticSeverity::WARNING,
2052                            message: "message 2".to_string(),
2053                            is_primary: true,
2054                            ..Default::default()
2055                        }
2056                    }
2057                ]
2058            );
2059        });
2060    }
2061
2062    #[gpui::test]
2063    async fn test_formatting_buffer(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
2064        cx_a.foreground().forbid_parking();
2065        let mut lang_registry = Arc::new(LanguageRegistry::new());
2066        let fs = Arc::new(FakeFs::new());
2067
2068        // Set up a fake language server.
2069        let (language_server_config, mut fake_language_server) =
2070            LanguageServerConfig::fake(cx_a.background()).await;
2071        Arc::get_mut(&mut lang_registry)
2072            .unwrap()
2073            .add(Arc::new(Language::new(
2074                LanguageConfig {
2075                    name: "Rust".to_string(),
2076                    path_suffixes: vec!["rs".to_string()],
2077                    language_server: Some(language_server_config),
2078                    ..Default::default()
2079                },
2080                Some(tree_sitter_rust::language()),
2081            )));
2082
2083        // Connect to a server as 2 clients.
2084        let mut server = TestServer::start(cx_a.foreground()).await;
2085        let client_a = server.create_client(&mut cx_a, "user_a").await;
2086        let client_b = server.create_client(&mut cx_b, "user_b").await;
2087
2088        // Share a project as client A
2089        fs.insert_tree(
2090            "/a",
2091            json!({
2092                ".zed.toml": r#"collaborators = ["user_b"]"#,
2093                "a.rs": "let one = two",
2094            }),
2095        )
2096        .await;
2097        let project_a = cx_a.update(|cx| {
2098            Project::local(
2099                client_a.clone(),
2100                client_a.user_store.clone(),
2101                lang_registry.clone(),
2102                fs.clone(),
2103                cx,
2104            )
2105        });
2106        let worktree_a = project_a
2107            .update(&mut cx_a, |p, cx| p.add_local_worktree("/a", cx))
2108            .await
2109            .unwrap();
2110        worktree_a
2111            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
2112            .await;
2113        let project_id = project_a
2114            .update(&mut cx_a, |project, _| project.next_remote_id())
2115            .await;
2116        project_a
2117            .update(&mut cx_a, |project, cx| project.share(cx))
2118            .await
2119            .unwrap();
2120
2121        // Join the worktree as client B.
2122        let project_b = Project::remote(
2123            project_id,
2124            client_b.clone(),
2125            client_b.user_store.clone(),
2126            lang_registry.clone(),
2127            fs.clone(),
2128            &mut cx_b.to_async(),
2129        )
2130        .await
2131        .unwrap();
2132
2133        // Open the file to be formatted on client B.
2134        let worktree_b = project_b.update(&mut cx_b, |p, _| p.worktrees()[0].clone());
2135        let buffer_b = cx_b
2136            .background()
2137            .spawn(worktree_b.update(&mut cx_b, |worktree, cx| worktree.open_buffer("a.rs", cx)))
2138            .await
2139            .unwrap()
2140            .0;
2141
2142        let format = buffer_b.update(&mut cx_b, |buffer, cx| buffer.format(cx));
2143        let (request_id, _) = fake_language_server
2144            .receive_request::<lsp::request::Formatting>()
2145            .await;
2146        fake_language_server
2147            .respond(
2148                request_id,
2149                Some(vec![
2150                    lsp::TextEdit {
2151                        range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 4)),
2152                        new_text: "h".to_string(),
2153                    },
2154                    lsp::TextEdit {
2155                        range: lsp::Range::new(lsp::Position::new(0, 7), lsp::Position::new(0, 7)),
2156                        new_text: "y".to_string(),
2157                    },
2158                ]),
2159            )
2160            .await;
2161        format.await.unwrap();
2162        assert_eq!(
2163            buffer_b.read_with(&cx_b, |buffer, _| buffer.text()),
2164            "let honey = two"
2165        );
2166    }
2167
2168    #[gpui::test]
2169    async fn test_basic_chat(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
2170        cx_a.foreground().forbid_parking();
2171
2172        // Connect to a server as 2 clients.
2173        let mut server = TestServer::start(cx_a.foreground()).await;
2174        let client_a = server.create_client(&mut cx_a, "user_a").await;
2175        let client_b = server.create_client(&mut cx_b, "user_b").await;
2176
2177        // Create an org that includes these 2 users.
2178        let db = &server.app_state.db;
2179        let org_id = db.create_org("Test Org", "test-org").await.unwrap();
2180        db.add_org_member(org_id, client_a.current_user_id(&cx_a), false)
2181            .await
2182            .unwrap();
2183        db.add_org_member(org_id, client_b.current_user_id(&cx_b), false)
2184            .await
2185            .unwrap();
2186
2187        // Create a channel that includes all the users.
2188        let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
2189        db.add_channel_member(channel_id, client_a.current_user_id(&cx_a), false)
2190            .await
2191            .unwrap();
2192        db.add_channel_member(channel_id, client_b.current_user_id(&cx_b), false)
2193            .await
2194            .unwrap();
2195        db.create_channel_message(
2196            channel_id,
2197            client_b.current_user_id(&cx_b),
2198            "hello A, it's B.",
2199            OffsetDateTime::now_utc(),
2200            1,
2201        )
2202        .await
2203        .unwrap();
2204
2205        let channels_a = cx_a
2206            .add_model(|cx| ChannelList::new(client_a.user_store.clone(), client_a.clone(), cx));
2207        channels_a
2208            .condition(&mut cx_a, |list, _| list.available_channels().is_some())
2209            .await;
2210        channels_a.read_with(&cx_a, |list, _| {
2211            assert_eq!(
2212                list.available_channels().unwrap(),
2213                &[ChannelDetails {
2214                    id: channel_id.to_proto(),
2215                    name: "test-channel".to_string()
2216                }]
2217            )
2218        });
2219        let channel_a = channels_a.update(&mut cx_a, |this, cx| {
2220            this.get_channel(channel_id.to_proto(), cx).unwrap()
2221        });
2222        channel_a.read_with(&cx_a, |channel, _| assert!(channel.messages().is_empty()));
2223        channel_a
2224            .condition(&cx_a, |channel, _| {
2225                channel_messages(channel)
2226                    == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2227            })
2228            .await;
2229
2230        let channels_b = cx_b
2231            .add_model(|cx| ChannelList::new(client_b.user_store.clone(), client_b.clone(), cx));
2232        channels_b
2233            .condition(&mut cx_b, |list, _| list.available_channels().is_some())
2234            .await;
2235        channels_b.read_with(&cx_b, |list, _| {
2236            assert_eq!(
2237                list.available_channels().unwrap(),
2238                &[ChannelDetails {
2239                    id: channel_id.to_proto(),
2240                    name: "test-channel".to_string()
2241                }]
2242            )
2243        });
2244
2245        let channel_b = channels_b.update(&mut cx_b, |this, cx| {
2246            this.get_channel(channel_id.to_proto(), cx).unwrap()
2247        });
2248        channel_b.read_with(&cx_b, |channel, _| assert!(channel.messages().is_empty()));
2249        channel_b
2250            .condition(&cx_b, |channel, _| {
2251                channel_messages(channel)
2252                    == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2253            })
2254            .await;
2255
2256        channel_a
2257            .update(&mut cx_a, |channel, cx| {
2258                channel
2259                    .send_message("oh, hi B.".to_string(), cx)
2260                    .unwrap()
2261                    .detach();
2262                let task = channel.send_message("sup".to_string(), cx).unwrap();
2263                assert_eq!(
2264                    channel_messages(channel),
2265                    &[
2266                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2267                        ("user_a".to_string(), "oh, hi B.".to_string(), true),
2268                        ("user_a".to_string(), "sup".to_string(), true)
2269                    ]
2270                );
2271                task
2272            })
2273            .await
2274            .unwrap();
2275
2276        channel_b
2277            .condition(&cx_b, |channel, _| {
2278                channel_messages(channel)
2279                    == [
2280                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2281                        ("user_a".to_string(), "oh, hi B.".to_string(), false),
2282                        ("user_a".to_string(), "sup".to_string(), false),
2283                    ]
2284            })
2285            .await;
2286
2287        assert_eq!(
2288            server
2289                .state()
2290                .await
2291                .channel(channel_id)
2292                .unwrap()
2293                .connection_ids
2294                .len(),
2295            2
2296        );
2297        cx_b.update(|_| drop(channel_b));
2298        server
2299            .condition(|state| state.channel(channel_id).unwrap().connection_ids.len() == 1)
2300            .await;
2301
2302        cx_a.update(|_| drop(channel_a));
2303        server
2304            .condition(|state| state.channel(channel_id).is_none())
2305            .await;
2306    }
2307
2308    #[gpui::test]
2309    async fn test_chat_message_validation(mut cx_a: TestAppContext) {
2310        cx_a.foreground().forbid_parking();
2311
2312        let mut server = TestServer::start(cx_a.foreground()).await;
2313        let client_a = server.create_client(&mut cx_a, "user_a").await;
2314
2315        let db = &server.app_state.db;
2316        let org_id = db.create_org("Test Org", "test-org").await.unwrap();
2317        let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
2318        db.add_org_member(org_id, client_a.current_user_id(&cx_a), false)
2319            .await
2320            .unwrap();
2321        db.add_channel_member(channel_id, client_a.current_user_id(&cx_a), false)
2322            .await
2323            .unwrap();
2324
2325        let channels_a = cx_a
2326            .add_model(|cx| ChannelList::new(client_a.user_store.clone(), client_a.clone(), cx));
2327        channels_a
2328            .condition(&mut cx_a, |list, _| list.available_channels().is_some())
2329            .await;
2330        let channel_a = channels_a.update(&mut cx_a, |this, cx| {
2331            this.get_channel(channel_id.to_proto(), cx).unwrap()
2332        });
2333
2334        // Messages aren't allowed to be too long.
2335        channel_a
2336            .update(&mut cx_a, |channel, cx| {
2337                let long_body = "this is long.\n".repeat(1024);
2338                channel.send_message(long_body, cx).unwrap()
2339            })
2340            .await
2341            .unwrap_err();
2342
2343        // Messages aren't allowed to be blank.
2344        channel_a.update(&mut cx_a, |channel, cx| {
2345            channel.send_message(String::new(), cx).unwrap_err()
2346        });
2347
2348        // Leading and trailing whitespace are trimmed.
2349        channel_a
2350            .update(&mut cx_a, |channel, cx| {
2351                channel
2352                    .send_message("\n surrounded by whitespace  \n".to_string(), cx)
2353                    .unwrap()
2354            })
2355            .await
2356            .unwrap();
2357        assert_eq!(
2358            db.get_channel_messages(channel_id, 10, None)
2359                .await
2360                .unwrap()
2361                .iter()
2362                .map(|m| &m.body)
2363                .collect::<Vec<_>>(),
2364            &["surrounded by whitespace"]
2365        );
2366    }
2367
2368    #[gpui::test]
2369    async fn test_chat_reconnection(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
2370        cx_a.foreground().forbid_parking();
2371
2372        // Connect to a server as 2 clients.
2373        let mut server = TestServer::start(cx_a.foreground()).await;
2374        let client_a = server.create_client(&mut cx_a, "user_a").await;
2375        let client_b = server.create_client(&mut cx_b, "user_b").await;
2376        let mut status_b = client_b.status();
2377
2378        // Create an org that includes these 2 users.
2379        let db = &server.app_state.db;
2380        let org_id = db.create_org("Test Org", "test-org").await.unwrap();
2381        db.add_org_member(org_id, client_a.current_user_id(&cx_a), false)
2382            .await
2383            .unwrap();
2384        db.add_org_member(org_id, client_b.current_user_id(&cx_b), false)
2385            .await
2386            .unwrap();
2387
2388        // Create a channel that includes all the users.
2389        let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
2390        db.add_channel_member(channel_id, client_a.current_user_id(&cx_a), false)
2391            .await
2392            .unwrap();
2393        db.add_channel_member(channel_id, client_b.current_user_id(&cx_b), false)
2394            .await
2395            .unwrap();
2396        db.create_channel_message(
2397            channel_id,
2398            client_b.current_user_id(&cx_b),
2399            "hello A, it's B.",
2400            OffsetDateTime::now_utc(),
2401            2,
2402        )
2403        .await
2404        .unwrap();
2405
2406        let channels_a = cx_a
2407            .add_model(|cx| ChannelList::new(client_a.user_store.clone(), client_a.clone(), cx));
2408        channels_a
2409            .condition(&mut cx_a, |list, _| list.available_channels().is_some())
2410            .await;
2411
2412        channels_a.read_with(&cx_a, |list, _| {
2413            assert_eq!(
2414                list.available_channels().unwrap(),
2415                &[ChannelDetails {
2416                    id: channel_id.to_proto(),
2417                    name: "test-channel".to_string()
2418                }]
2419            )
2420        });
2421        let channel_a = channels_a.update(&mut cx_a, |this, cx| {
2422            this.get_channel(channel_id.to_proto(), cx).unwrap()
2423        });
2424        channel_a.read_with(&cx_a, |channel, _| assert!(channel.messages().is_empty()));
2425        channel_a
2426            .condition(&cx_a, |channel, _| {
2427                channel_messages(channel)
2428                    == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2429            })
2430            .await;
2431
2432        let channels_b = cx_b
2433            .add_model(|cx| ChannelList::new(client_b.user_store.clone(), client_b.clone(), cx));
2434        channels_b
2435            .condition(&mut cx_b, |list, _| list.available_channels().is_some())
2436            .await;
2437        channels_b.read_with(&cx_b, |list, _| {
2438            assert_eq!(
2439                list.available_channels().unwrap(),
2440                &[ChannelDetails {
2441                    id: channel_id.to_proto(),
2442                    name: "test-channel".to_string()
2443                }]
2444            )
2445        });
2446
2447        let channel_b = channels_b.update(&mut cx_b, |this, cx| {
2448            this.get_channel(channel_id.to_proto(), cx).unwrap()
2449        });
2450        channel_b.read_with(&cx_b, |channel, _| assert!(channel.messages().is_empty()));
2451        channel_b
2452            .condition(&cx_b, |channel, _| {
2453                channel_messages(channel)
2454                    == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2455            })
2456            .await;
2457
2458        // Disconnect client B, ensuring we can still access its cached channel data.
2459        server.forbid_connections();
2460        server.disconnect_client(client_b.current_user_id(&cx_b));
2461        while !matches!(
2462            status_b.next().await,
2463            Some(client::Status::ReconnectionError { .. })
2464        ) {}
2465
2466        channels_b.read_with(&cx_b, |channels, _| {
2467            assert_eq!(
2468                channels.available_channels().unwrap(),
2469                [ChannelDetails {
2470                    id: channel_id.to_proto(),
2471                    name: "test-channel".to_string()
2472                }]
2473            )
2474        });
2475        channel_b.read_with(&cx_b, |channel, _| {
2476            assert_eq!(
2477                channel_messages(channel),
2478                [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2479            )
2480        });
2481
2482        // Send a message from client B while it is disconnected.
2483        channel_b
2484            .update(&mut cx_b, |channel, cx| {
2485                let task = channel
2486                    .send_message("can you see this?".to_string(), cx)
2487                    .unwrap();
2488                assert_eq!(
2489                    channel_messages(channel),
2490                    &[
2491                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2492                        ("user_b".to_string(), "can you see this?".to_string(), true)
2493                    ]
2494                );
2495                task
2496            })
2497            .await
2498            .unwrap_err();
2499
2500        // Send a message from client A while B is disconnected.
2501        channel_a
2502            .update(&mut cx_a, |channel, cx| {
2503                channel
2504                    .send_message("oh, hi B.".to_string(), cx)
2505                    .unwrap()
2506                    .detach();
2507                let task = channel.send_message("sup".to_string(), cx).unwrap();
2508                assert_eq!(
2509                    channel_messages(channel),
2510                    &[
2511                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2512                        ("user_a".to_string(), "oh, hi B.".to_string(), true),
2513                        ("user_a".to_string(), "sup".to_string(), true)
2514                    ]
2515                );
2516                task
2517            })
2518            .await
2519            .unwrap();
2520
2521        // Give client B a chance to reconnect.
2522        server.allow_connections();
2523        cx_b.foreground().advance_clock(Duration::from_secs(10));
2524
2525        // Verify that B sees the new messages upon reconnection, as well as the message client B
2526        // sent while offline.
2527        channel_b
2528            .condition(&cx_b, |channel, _| {
2529                channel_messages(channel)
2530                    == [
2531                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2532                        ("user_a".to_string(), "oh, hi B.".to_string(), false),
2533                        ("user_a".to_string(), "sup".to_string(), false),
2534                        ("user_b".to_string(), "can you see this?".to_string(), false),
2535                    ]
2536            })
2537            .await;
2538
2539        // Ensure client A and B can communicate normally after reconnection.
2540        channel_a
2541            .update(&mut cx_a, |channel, cx| {
2542                channel.send_message("you online?".to_string(), cx).unwrap()
2543            })
2544            .await
2545            .unwrap();
2546        channel_b
2547            .condition(&cx_b, |channel, _| {
2548                channel_messages(channel)
2549                    == [
2550                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2551                        ("user_a".to_string(), "oh, hi B.".to_string(), false),
2552                        ("user_a".to_string(), "sup".to_string(), false),
2553                        ("user_b".to_string(), "can you see this?".to_string(), false),
2554                        ("user_a".to_string(), "you online?".to_string(), false),
2555                    ]
2556            })
2557            .await;
2558
2559        channel_b
2560            .update(&mut cx_b, |channel, cx| {
2561                channel.send_message("yep".to_string(), cx).unwrap()
2562            })
2563            .await
2564            .unwrap();
2565        channel_a
2566            .condition(&cx_a, |channel, _| {
2567                channel_messages(channel)
2568                    == [
2569                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2570                        ("user_a".to_string(), "oh, hi B.".to_string(), false),
2571                        ("user_a".to_string(), "sup".to_string(), false),
2572                        ("user_b".to_string(), "can you see this?".to_string(), false),
2573                        ("user_a".to_string(), "you online?".to_string(), false),
2574                        ("user_b".to_string(), "yep".to_string(), false),
2575                    ]
2576            })
2577            .await;
2578    }
2579
2580    #[gpui::test]
2581    async fn test_contacts(
2582        mut cx_a: TestAppContext,
2583        mut cx_b: TestAppContext,
2584        mut cx_c: TestAppContext,
2585    ) {
2586        cx_a.foreground().forbid_parking();
2587        let lang_registry = Arc::new(LanguageRegistry::new());
2588        let fs = Arc::new(FakeFs::new());
2589
2590        // Connect to a server as 3 clients.
2591        let mut server = TestServer::start(cx_a.foreground()).await;
2592        let client_a = server.create_client(&mut cx_a, "user_a").await;
2593        let client_b = server.create_client(&mut cx_b, "user_b").await;
2594        let client_c = server.create_client(&mut cx_c, "user_c").await;
2595
2596        // Share a worktree as client A.
2597        fs.insert_tree(
2598            "/a",
2599            json!({
2600                ".zed.toml": r#"collaborators = ["user_b", "user_c"]"#,
2601            }),
2602        )
2603        .await;
2604
2605        let project_a = cx_a.update(|cx| {
2606            Project::local(
2607                client_a.clone(),
2608                client_a.user_store.clone(),
2609                lang_registry.clone(),
2610                fs.clone(),
2611                cx,
2612            )
2613        });
2614        let worktree_a = project_a
2615            .update(&mut cx_a, |p, cx| p.add_local_worktree("/a", cx))
2616            .await
2617            .unwrap();
2618        worktree_a
2619            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
2620            .await;
2621
2622        client_a
2623            .user_store
2624            .condition(&cx_a, |user_store, _| {
2625                contacts(user_store) == vec![("user_a", vec![("a", vec![])])]
2626            })
2627            .await;
2628        client_b
2629            .user_store
2630            .condition(&cx_b, |user_store, _| {
2631                contacts(user_store) == vec![("user_a", vec![("a", vec![])])]
2632            })
2633            .await;
2634        client_c
2635            .user_store
2636            .condition(&cx_c, |user_store, _| {
2637                contacts(user_store) == vec![("user_a", vec![("a", vec![])])]
2638            })
2639            .await;
2640
2641        let project_id = project_a
2642            .update(&mut cx_a, |project, _| project.next_remote_id())
2643            .await;
2644        project_a
2645            .update(&mut cx_a, |project, cx| project.share(cx))
2646            .await
2647            .unwrap();
2648
2649        let _project_b = Project::remote(
2650            project_id,
2651            client_b.clone(),
2652            client_b.user_store.clone(),
2653            lang_registry.clone(),
2654            fs.clone(),
2655            &mut cx_b.to_async(),
2656        )
2657        .await
2658        .unwrap();
2659
2660        client_a
2661            .user_store
2662            .condition(&cx_a, |user_store, _| {
2663                contacts(user_store) == vec![("user_a", vec![("a", vec!["user_b"])])]
2664            })
2665            .await;
2666        client_b
2667            .user_store
2668            .condition(&cx_b, |user_store, _| {
2669                contacts(user_store) == vec![("user_a", vec![("a", vec!["user_b"])])]
2670            })
2671            .await;
2672        client_c
2673            .user_store
2674            .condition(&cx_c, |user_store, _| {
2675                contacts(user_store) == vec![("user_a", vec![("a", vec!["user_b"])])]
2676            })
2677            .await;
2678
2679        project_a
2680            .condition(&cx_a, |project, _| {
2681                project.collaborators().contains_key(&client_b.peer_id)
2682            })
2683            .await;
2684
2685        cx_a.update(move |_| drop(project_a));
2686        client_a
2687            .user_store
2688            .condition(&cx_a, |user_store, _| contacts(user_store) == vec![])
2689            .await;
2690        client_b
2691            .user_store
2692            .condition(&cx_b, |user_store, _| contacts(user_store) == vec![])
2693            .await;
2694        client_c
2695            .user_store
2696            .condition(&cx_c, |user_store, _| contacts(user_store) == vec![])
2697            .await;
2698
2699        fn contacts(user_store: &UserStore) -> Vec<(&str, Vec<(&str, Vec<&str>)>)> {
2700            user_store
2701                .contacts()
2702                .iter()
2703                .map(|contact| {
2704                    let worktrees = contact
2705                        .projects
2706                        .iter()
2707                        .map(|p| {
2708                            (
2709                                p.worktree_root_names[0].as_str(),
2710                                p.guests.iter().map(|p| p.github_login.as_str()).collect(),
2711                            )
2712                        })
2713                        .collect();
2714                    (contact.user.github_login.as_str(), worktrees)
2715                })
2716                .collect()
2717        }
2718    }
2719
2720    struct TestServer {
2721        peer: Arc<Peer>,
2722        app_state: Arc<AppState>,
2723        server: Arc<Server>,
2724        foreground: Rc<executor::Foreground>,
2725        notifications: mpsc::Receiver<()>,
2726        connection_killers: Arc<Mutex<HashMap<UserId, watch::Sender<Option<()>>>>>,
2727        forbid_connections: Arc<AtomicBool>,
2728        _test_db: TestDb,
2729    }
2730
2731    impl TestServer {
2732        async fn start(foreground: Rc<executor::Foreground>) -> Self {
2733            let test_db = TestDb::new();
2734            let app_state = Self::build_app_state(&test_db).await;
2735            let peer = Peer::new();
2736            let notifications = mpsc::channel(128);
2737            let server = Server::new(app_state.clone(), peer.clone(), Some(notifications.0));
2738            Self {
2739                peer,
2740                app_state,
2741                server,
2742                foreground,
2743                notifications: notifications.1,
2744                connection_killers: Default::default(),
2745                forbid_connections: Default::default(),
2746                _test_db: test_db,
2747            }
2748        }
2749
2750        async fn create_client(&mut self, cx: &mut TestAppContext, name: &str) -> TestClient {
2751            let http = FakeHttpClient::with_404_response();
2752            let user_id = self.app_state.db.create_user(name, false).await.unwrap();
2753            let client_name = name.to_string();
2754            let mut client = Client::new(http.clone());
2755            let server = self.server.clone();
2756            let connection_killers = self.connection_killers.clone();
2757            let forbid_connections = self.forbid_connections.clone();
2758            let (connection_id_tx, mut connection_id_rx) = postage::mpsc::channel(16);
2759
2760            Arc::get_mut(&mut client)
2761                .unwrap()
2762                .override_authenticate(move |cx| {
2763                    cx.spawn(|_| async move {
2764                        let access_token = "the-token".to_string();
2765                        Ok(Credentials {
2766                            user_id: user_id.0 as u64,
2767                            access_token,
2768                        })
2769                    })
2770                })
2771                .override_establish_connection(move |credentials, cx| {
2772                    assert_eq!(credentials.user_id, user_id.0 as u64);
2773                    assert_eq!(credentials.access_token, "the-token");
2774
2775                    let server = server.clone();
2776                    let connection_killers = connection_killers.clone();
2777                    let forbid_connections = forbid_connections.clone();
2778                    let client_name = client_name.clone();
2779                    let connection_id_tx = connection_id_tx.clone();
2780                    cx.spawn(move |cx| async move {
2781                        if forbid_connections.load(SeqCst) {
2782                            Err(EstablishConnectionError::other(anyhow!(
2783                                "server is forbidding connections"
2784                            )))
2785                        } else {
2786                            let (client_conn, server_conn, kill_conn) = Connection::in_memory();
2787                            connection_killers.lock().insert(user_id, kill_conn);
2788                            cx.background()
2789                                .spawn(server.handle_connection(
2790                                    server_conn,
2791                                    client_name,
2792                                    user_id,
2793                                    Some(connection_id_tx),
2794                                ))
2795                                .detach();
2796                            Ok(client_conn)
2797                        }
2798                    })
2799                });
2800
2801            client
2802                .authenticate_and_connect(&cx.to_async())
2803                .await
2804                .unwrap();
2805
2806            let peer_id = PeerId(connection_id_rx.next().await.unwrap().0);
2807            let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http, cx));
2808            let mut authed_user =
2809                user_store.read_with(cx, |user_store, _| user_store.watch_current_user());
2810            while authed_user.next().await.unwrap().is_none() {}
2811
2812            TestClient {
2813                client,
2814                peer_id,
2815                user_store,
2816            }
2817        }
2818
2819        fn disconnect_client(&self, user_id: UserId) {
2820            if let Some(mut kill_conn) = self.connection_killers.lock().remove(&user_id) {
2821                let _ = kill_conn.try_send(Some(()));
2822            }
2823        }
2824
2825        fn forbid_connections(&self) {
2826            self.forbid_connections.store(true, SeqCst);
2827        }
2828
2829        fn allow_connections(&self) {
2830            self.forbid_connections.store(false, SeqCst);
2831        }
2832
2833        async fn build_app_state(test_db: &TestDb) -> Arc<AppState> {
2834            let mut config = Config::default();
2835            config.session_secret = "a".repeat(32);
2836            config.database_url = test_db.url.clone();
2837            let github_client = github::AppClient::test();
2838            Arc::new(AppState {
2839                db: test_db.db().clone(),
2840                handlebars: Default::default(),
2841                auth_client: auth::build_client("", ""),
2842                repo_client: github::RepoClient::test(&github_client),
2843                github_client,
2844                config,
2845            })
2846        }
2847
2848        async fn state<'a>(&'a self) -> RwLockReadGuard<'a, Store> {
2849            self.server.store.read()
2850        }
2851
2852        async fn condition<F>(&mut self, mut predicate: F)
2853        where
2854            F: FnMut(&Store) -> bool,
2855        {
2856            async_std::future::timeout(Duration::from_millis(500), async {
2857                while !(predicate)(&*self.server.store.read()) {
2858                    self.foreground.start_waiting();
2859                    self.notifications.next().await;
2860                    self.foreground.finish_waiting();
2861                }
2862            })
2863            .await
2864            .expect("condition timed out");
2865        }
2866    }
2867
2868    impl Drop for TestServer {
2869        fn drop(&mut self) {
2870            self.peer.reset();
2871        }
2872    }
2873
2874    struct TestClient {
2875        client: Arc<Client>,
2876        pub peer_id: PeerId,
2877        pub user_store: ModelHandle<UserStore>,
2878    }
2879
2880    impl Deref for TestClient {
2881        type Target = Arc<Client>;
2882
2883        fn deref(&self) -> &Self::Target {
2884            &self.client
2885        }
2886    }
2887
2888    impl TestClient {
2889        pub fn current_user_id(&self, cx: &TestAppContext) -> UserId {
2890            UserId::from_proto(
2891                self.user_store
2892                    .read_with(cx, |user_store, _| user_store.current_user().unwrap().id),
2893            )
2894        }
2895    }
2896
2897    fn channel_messages(channel: &Channel) -> Vec<(String, String, bool)> {
2898        channel
2899            .messages()
2900            .cursor::<()>()
2901            .map(|m| {
2902                (
2903                    m.sender.github_login.clone(),
2904                    m.body.clone(),
2905                    m.is_pending(),
2906                )
2907            })
2908            .collect()
2909    }
2910
2911    struct EmptyView;
2912
2913    impl gpui::Entity for EmptyView {
2914        type Event = ();
2915    }
2916
2917    impl gpui::View for EmptyView {
2918        fn ui_name() -> &'static str {
2919            "empty view"
2920        }
2921
2922        fn render(&mut self, _: &mut gpui::RenderContext<Self>) -> gpui::ElementBox {
2923            gpui::Element::boxed(gpui::elements::Empty)
2924        }
2925    }
2926}