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        let buffer_b = cx_b.add_model(|cx| MultiBuffer::singleton(buffer_b, cx));
1218        buffer_b.read_with(&cx_b, |buf, cx| {
1219            assert_eq!(buf.read(cx).text(), "b-contents")
1220        });
1221        worktree_a.read_with(&cx_a, |tree, cx| assert!(tree.has_open_buffer("b.txt", cx)));
1222        let buffer_a = worktree_a
1223            .update(&mut cx_a, |tree, cx| tree.open_buffer("b.txt", cx))
1224            .await
1225            .unwrap();
1226
1227        let editor_b = cx_b.add_view(window_b, |cx| {
1228            Editor::for_buffer(buffer_b, Arc::new(|cx| EditorSettings::test(cx)), cx)
1229        });
1230        // TODO
1231        // // Create a selection set as client B and see that selection set as client A.
1232        // buffer_a
1233        //     .condition(&cx_a, |buffer, _| buffer.selection_sets().count() == 1)
1234        //     .await;
1235
1236        // Edit the buffer as client B and see that edit as client A.
1237        editor_b.update(&mut cx_b, |editor, cx| {
1238            editor.handle_input(&Input("ok, ".into()), cx)
1239        });
1240        buffer_a
1241            .condition(&cx_a, |buffer, _| buffer.text() == "ok, b-contents")
1242            .await;
1243
1244        // TODO
1245        // // Remove the selection set as client B, see those selections disappear as client A.
1246        cx_b.update(move |_| drop(editor_b));
1247        // buffer_a
1248        //     .condition(&cx_a, |buffer, _| buffer.selection_sets().count() == 0)
1249        //     .await;
1250
1251        // Close the buffer as client A, see that the buffer is closed.
1252        cx_a.update(move |_| drop(buffer_a));
1253        worktree_a
1254            .condition(&cx_a, |tree, cx| !tree.has_open_buffer("b.txt", cx))
1255            .await;
1256
1257        // Dropping the client B's project removes client B from client A's collaborators.
1258        cx_b.update(move |_| drop(project_b));
1259        project_a
1260            .condition(&cx_a, |project, _| project.collaborators().is_empty())
1261            .await;
1262    }
1263
1264    #[gpui::test]
1265    async fn test_unshare_project(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1266        let lang_registry = Arc::new(LanguageRegistry::new());
1267        let fs = Arc::new(FakeFs::new());
1268        cx_a.foreground().forbid_parking();
1269
1270        // Connect to a server as 2 clients.
1271        let mut server = TestServer::start(cx_a.foreground()).await;
1272        let client_a = server.create_client(&mut cx_a, "user_a").await;
1273        let client_b = server.create_client(&mut cx_b, "user_b").await;
1274
1275        // Share a project as client A
1276        fs.insert_tree(
1277            "/a",
1278            json!({
1279                ".zed.toml": r#"collaborators = ["user_b"]"#,
1280                "a.txt": "a-contents",
1281                "b.txt": "b-contents",
1282            }),
1283        )
1284        .await;
1285        let project_a = cx_a.update(|cx| {
1286            Project::local(
1287                client_a.clone(),
1288                client_a.user_store.clone(),
1289                lang_registry.clone(),
1290                fs.clone(),
1291                cx,
1292            )
1293        });
1294        let worktree_a = project_a
1295            .update(&mut cx_a, |p, cx| p.add_local_worktree("/a", cx))
1296            .await
1297            .unwrap();
1298        worktree_a
1299            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1300            .await;
1301        let project_id = project_a
1302            .update(&mut cx_a, |project, _| project.next_remote_id())
1303            .await;
1304        project_a
1305            .update(&mut cx_a, |project, cx| project.share(cx))
1306            .await
1307            .unwrap();
1308        assert!(worktree_a.read_with(&cx_a, |tree, _| tree.as_local().unwrap().is_shared()));
1309
1310        // Join that project as client B
1311        let project_b = Project::remote(
1312            project_id,
1313            client_b.clone(),
1314            client_b.user_store.clone(),
1315            lang_registry.clone(),
1316            fs.clone(),
1317            &mut cx_b.to_async(),
1318        )
1319        .await
1320        .unwrap();
1321
1322        let worktree_b = project_b.read_with(&cx_b, |p, _| p.worktrees()[0].clone());
1323        worktree_b
1324            .update(&mut cx_b, |tree, cx| tree.open_buffer("a.txt", cx))
1325            .await
1326            .unwrap();
1327
1328        project_a
1329            .update(&mut cx_a, |project, cx| project.unshare(cx))
1330            .await
1331            .unwrap();
1332        project_b
1333            .condition(&mut cx_b, |project, _| project.is_read_only())
1334            .await;
1335        assert!(worktree_a.read_with(&cx_a, |tree, _| !tree.as_local().unwrap().is_shared()));
1336        drop(project_b);
1337
1338        // Share the project again and ensure guests can still join.
1339        project_a
1340            .update(&mut cx_a, |project, cx| project.share(cx))
1341            .await
1342            .unwrap();
1343        assert!(worktree_a.read_with(&cx_a, |tree, _| tree.as_local().unwrap().is_shared()));
1344        let project_c = Project::remote(
1345            project_id,
1346            client_b.clone(),
1347            client_b.user_store.clone(),
1348            lang_registry.clone(),
1349            fs.clone(),
1350            &mut cx_b.to_async(),
1351        )
1352        .await
1353        .unwrap();
1354        let worktree_c = project_c.read_with(&cx_b, |p, _| p.worktrees()[0].clone());
1355        worktree_c
1356            .update(&mut cx_b, |tree, cx| tree.open_buffer("a.txt", cx))
1357            .await
1358            .unwrap();
1359    }
1360
1361    #[gpui::test]
1362    async fn test_propagate_saves_and_fs_changes(
1363        mut cx_a: TestAppContext,
1364        mut cx_b: TestAppContext,
1365        mut cx_c: TestAppContext,
1366    ) {
1367        let lang_registry = Arc::new(LanguageRegistry::new());
1368        let fs = Arc::new(FakeFs::new());
1369        cx_a.foreground().forbid_parking();
1370
1371        // Connect to a server as 3 clients.
1372        let mut server = TestServer::start(cx_a.foreground()).await;
1373        let client_a = server.create_client(&mut cx_a, "user_a").await;
1374        let client_b = server.create_client(&mut cx_b, "user_b").await;
1375        let client_c = server.create_client(&mut cx_c, "user_c").await;
1376
1377        // Share a worktree as client A.
1378        fs.insert_tree(
1379            "/a",
1380            json!({
1381                ".zed.toml": r#"collaborators = ["user_b", "user_c"]"#,
1382                "file1": "",
1383                "file2": ""
1384            }),
1385        )
1386        .await;
1387        let project_a = cx_a.update(|cx| {
1388            Project::local(
1389                client_a.clone(),
1390                client_a.user_store.clone(),
1391                lang_registry.clone(),
1392                fs.clone(),
1393                cx,
1394            )
1395        });
1396        let worktree_a = project_a
1397            .update(&mut cx_a, |p, cx| p.add_local_worktree("/a", cx))
1398            .await
1399            .unwrap();
1400        worktree_a
1401            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1402            .await;
1403        let project_id = project_a
1404            .update(&mut cx_a, |project, _| project.next_remote_id())
1405            .await;
1406        project_a
1407            .update(&mut cx_a, |project, cx| project.share(cx))
1408            .await
1409            .unwrap();
1410
1411        // Join that worktree as clients B and C.
1412        let project_b = Project::remote(
1413            project_id,
1414            client_b.clone(),
1415            client_b.user_store.clone(),
1416            lang_registry.clone(),
1417            fs.clone(),
1418            &mut cx_b.to_async(),
1419        )
1420        .await
1421        .unwrap();
1422        let project_c = Project::remote(
1423            project_id,
1424            client_c.clone(),
1425            client_c.user_store.clone(),
1426            lang_registry.clone(),
1427            fs.clone(),
1428            &mut cx_c.to_async(),
1429        )
1430        .await
1431        .unwrap();
1432
1433        // Open and edit a buffer as both guests B and C.
1434        let worktree_b = project_b.read_with(&cx_b, |p, _| p.worktrees()[0].clone());
1435        let worktree_c = project_c.read_with(&cx_c, |p, _| p.worktrees()[0].clone());
1436        let buffer_b = worktree_b
1437            .update(&mut cx_b, |tree, cx| tree.open_buffer("file1", cx))
1438            .await
1439            .unwrap();
1440        let buffer_c = worktree_c
1441            .update(&mut cx_c, |tree, cx| tree.open_buffer("file1", cx))
1442            .await
1443            .unwrap();
1444        buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "i-am-b, ", cx));
1445        buffer_c.update(&mut cx_c, |buf, cx| buf.edit([0..0], "i-am-c, ", cx));
1446
1447        // Open and edit that buffer as the host.
1448        let buffer_a = worktree_a
1449            .update(&mut cx_a, |tree, cx| tree.open_buffer("file1", cx))
1450            .await
1451            .unwrap();
1452
1453        buffer_a
1454            .condition(&mut cx_a, |buf, _| buf.text() == "i-am-c, i-am-b, ")
1455            .await;
1456        buffer_a.update(&mut cx_a, |buf, cx| {
1457            buf.edit([buf.len()..buf.len()], "i-am-a", cx)
1458        });
1459
1460        // Wait for edits to propagate
1461        buffer_a
1462            .condition(&mut cx_a, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1463            .await;
1464        buffer_b
1465            .condition(&mut cx_b, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1466            .await;
1467        buffer_c
1468            .condition(&mut cx_c, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1469            .await;
1470
1471        // Edit the buffer as the host and concurrently save as guest B.
1472        let save_b = buffer_b.update(&mut cx_b, |buf, cx| buf.save(cx).unwrap());
1473        buffer_a.update(&mut cx_a, |buf, cx| buf.edit([0..0], "hi-a, ", cx));
1474        save_b.await.unwrap();
1475        assert_eq!(
1476            fs.load("/a/file1".as_ref()).await.unwrap(),
1477            "hi-a, i-am-c, i-am-b, i-am-a"
1478        );
1479        buffer_a.read_with(&cx_a, |buf, _| assert!(!buf.is_dirty()));
1480        buffer_b.read_with(&cx_b, |buf, _| assert!(!buf.is_dirty()));
1481        buffer_c.condition(&cx_c, |buf, _| !buf.is_dirty()).await;
1482
1483        // Make changes on host's file system, see those changes on the guests.
1484        fs.rename("/a/file2".as_ref(), "/a/file3".as_ref())
1485            .await
1486            .unwrap();
1487        fs.insert_file(Path::new("/a/file4"), "4".into())
1488            .await
1489            .unwrap();
1490
1491        worktree_b
1492            .condition(&cx_b, |tree, _| tree.file_count() == 4)
1493            .await;
1494        worktree_c
1495            .condition(&cx_c, |tree, _| tree.file_count() == 4)
1496            .await;
1497        worktree_b.read_with(&cx_b, |tree, _| {
1498            assert_eq!(
1499                tree.paths()
1500                    .map(|p| p.to_string_lossy())
1501                    .collect::<Vec<_>>(),
1502                &[".zed.toml", "file1", "file3", "file4"]
1503            )
1504        });
1505        worktree_c.read_with(&cx_c, |tree, _| {
1506            assert_eq!(
1507                tree.paths()
1508                    .map(|p| p.to_string_lossy())
1509                    .collect::<Vec<_>>(),
1510                &[".zed.toml", "file1", "file3", "file4"]
1511            )
1512        });
1513    }
1514
1515    #[gpui::test]
1516    async fn test_buffer_conflict_after_save(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1517        cx_a.foreground().forbid_parking();
1518        let lang_registry = Arc::new(LanguageRegistry::new());
1519        let fs = Arc::new(FakeFs::new());
1520
1521        // Connect to a server as 2 clients.
1522        let mut server = TestServer::start(cx_a.foreground()).await;
1523        let client_a = server.create_client(&mut cx_a, "user_a").await;
1524        let client_b = server.create_client(&mut cx_b, "user_b").await;
1525
1526        // Share a project as client A
1527        fs.insert_tree(
1528            "/dir",
1529            json!({
1530                ".zed.toml": r#"collaborators = ["user_b", "user_c"]"#,
1531                "a.txt": "a-contents",
1532            }),
1533        )
1534        .await;
1535
1536        let project_a = cx_a.update(|cx| {
1537            Project::local(
1538                client_a.clone(),
1539                client_a.user_store.clone(),
1540                lang_registry.clone(),
1541                fs.clone(),
1542                cx,
1543            )
1544        });
1545        let worktree_a = project_a
1546            .update(&mut cx_a, |p, cx| p.add_local_worktree("/dir", cx))
1547            .await
1548            .unwrap();
1549        worktree_a
1550            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1551            .await;
1552        let project_id = project_a
1553            .update(&mut cx_a, |project, _| project.next_remote_id())
1554            .await;
1555        project_a
1556            .update(&mut cx_a, |project, cx| project.share(cx))
1557            .await
1558            .unwrap();
1559
1560        // Join that project as client B
1561        let project_b = Project::remote(
1562            project_id,
1563            client_b.clone(),
1564            client_b.user_store.clone(),
1565            lang_registry.clone(),
1566            fs.clone(),
1567            &mut cx_b.to_async(),
1568        )
1569        .await
1570        .unwrap();
1571        let worktree_b = project_b.update(&mut cx_b, |p, _| p.worktrees()[0].clone());
1572
1573        // Open a buffer as client B
1574        let buffer_b = worktree_b
1575            .update(&mut cx_b, |worktree, cx| worktree.open_buffer("a.txt", cx))
1576            .await
1577            .unwrap();
1578        let mtime = buffer_b.read_with(&cx_b, |buf, _| buf.file().unwrap().mtime());
1579
1580        buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "world ", cx));
1581        buffer_b.read_with(&cx_b, |buf, _| {
1582            assert!(buf.is_dirty());
1583            assert!(!buf.has_conflict());
1584        });
1585
1586        buffer_b
1587            .update(&mut cx_b, |buf, cx| buf.save(cx))
1588            .unwrap()
1589            .await
1590            .unwrap();
1591        worktree_b
1592            .condition(&cx_b, |_, cx| {
1593                buffer_b.read(cx).file().unwrap().mtime() != mtime
1594            })
1595            .await;
1596        buffer_b.read_with(&cx_b, |buf, _| {
1597            assert!(!buf.is_dirty());
1598            assert!(!buf.has_conflict());
1599        });
1600
1601        buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "hello ", cx));
1602        buffer_b.read_with(&cx_b, |buf, _| {
1603            assert!(buf.is_dirty());
1604            assert!(!buf.has_conflict());
1605        });
1606    }
1607
1608    #[gpui::test]
1609    async fn test_editing_while_guest_opens_buffer(
1610        mut cx_a: TestAppContext,
1611        mut cx_b: TestAppContext,
1612    ) {
1613        cx_a.foreground().forbid_parking();
1614        let lang_registry = Arc::new(LanguageRegistry::new());
1615        let fs = Arc::new(FakeFs::new());
1616
1617        // Connect to a server as 2 clients.
1618        let mut server = TestServer::start(cx_a.foreground()).await;
1619        let client_a = server.create_client(&mut cx_a, "user_a").await;
1620        let client_b = server.create_client(&mut cx_b, "user_b").await;
1621
1622        // Share a project as client A
1623        fs.insert_tree(
1624            "/dir",
1625            json!({
1626                ".zed.toml": r#"collaborators = ["user_b"]"#,
1627                "a.txt": "a-contents",
1628            }),
1629        )
1630        .await;
1631        let project_a = cx_a.update(|cx| {
1632            Project::local(
1633                client_a.clone(),
1634                client_a.user_store.clone(),
1635                lang_registry.clone(),
1636                fs.clone(),
1637                cx,
1638            )
1639        });
1640        let worktree_a = project_a
1641            .update(&mut cx_a, |p, cx| p.add_local_worktree("/dir", cx))
1642            .await
1643            .unwrap();
1644        worktree_a
1645            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1646            .await;
1647        let project_id = project_a
1648            .update(&mut cx_a, |project, _| project.next_remote_id())
1649            .await;
1650        project_a
1651            .update(&mut cx_a, |project, cx| project.share(cx))
1652            .await
1653            .unwrap();
1654
1655        // Join that project as client B
1656        let project_b = Project::remote(
1657            project_id,
1658            client_b.clone(),
1659            client_b.user_store.clone(),
1660            lang_registry.clone(),
1661            fs.clone(),
1662            &mut cx_b.to_async(),
1663        )
1664        .await
1665        .unwrap();
1666        let worktree_b = project_b.update(&mut cx_b, |p, _| p.worktrees()[0].clone());
1667
1668        // Open a buffer as client A
1669        let buffer_a = worktree_a
1670            .update(&mut cx_a, |tree, cx| tree.open_buffer("a.txt", cx))
1671            .await
1672            .unwrap();
1673
1674        // Start opening the same buffer as client B
1675        let buffer_b = cx_b
1676            .background()
1677            .spawn(worktree_b.update(&mut cx_b, |worktree, cx| worktree.open_buffer("a.txt", cx)));
1678        task::yield_now().await;
1679
1680        // Edit the buffer as client A while client B is still opening it.
1681        buffer_a.update(&mut cx_a, |buf, cx| buf.edit([0..0], "z", cx));
1682
1683        let text = buffer_a.read_with(&cx_a, |buf, _| buf.text());
1684        let buffer_b = buffer_b.await.unwrap();
1685        buffer_b.condition(&cx_b, |buf, _| buf.text() == text).await;
1686    }
1687
1688    #[gpui::test]
1689    async fn test_leaving_worktree_while_opening_buffer(
1690        mut cx_a: TestAppContext,
1691        mut cx_b: TestAppContext,
1692    ) {
1693        cx_a.foreground().forbid_parking();
1694        let lang_registry = Arc::new(LanguageRegistry::new());
1695        let fs = Arc::new(FakeFs::new());
1696
1697        // Connect to a server as 2 clients.
1698        let mut server = TestServer::start(cx_a.foreground()).await;
1699        let client_a = server.create_client(&mut cx_a, "user_a").await;
1700        let client_b = server.create_client(&mut cx_b, "user_b").await;
1701
1702        // Share a project as client A
1703        fs.insert_tree(
1704            "/dir",
1705            json!({
1706                ".zed.toml": r#"collaborators = ["user_b"]"#,
1707                "a.txt": "a-contents",
1708            }),
1709        )
1710        .await;
1711        let project_a = cx_a.update(|cx| {
1712            Project::local(
1713                client_a.clone(),
1714                client_a.user_store.clone(),
1715                lang_registry.clone(),
1716                fs.clone(),
1717                cx,
1718            )
1719        });
1720        let worktree_a = project_a
1721            .update(&mut cx_a, |p, cx| p.add_local_worktree("/dir", cx))
1722            .await
1723            .unwrap();
1724        worktree_a
1725            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1726            .await;
1727        let project_id = project_a
1728            .update(&mut cx_a, |project, _| project.next_remote_id())
1729            .await;
1730        project_a
1731            .update(&mut cx_a, |project, cx| project.share(cx))
1732            .await
1733            .unwrap();
1734
1735        // Join that project as client B
1736        let project_b = Project::remote(
1737            project_id,
1738            client_b.clone(),
1739            client_b.user_store.clone(),
1740            lang_registry.clone(),
1741            fs.clone(),
1742            &mut cx_b.to_async(),
1743        )
1744        .await
1745        .unwrap();
1746        let worktree_b = project_b.update(&mut cx_b, |p, _| p.worktrees()[0].clone());
1747
1748        // See that a guest has joined as client A.
1749        project_a
1750            .condition(&cx_a, |p, _| p.collaborators().len() == 1)
1751            .await;
1752
1753        // Begin opening a buffer as client B, but leave the project before the open completes.
1754        let buffer_b = cx_b
1755            .background()
1756            .spawn(worktree_b.update(&mut cx_b, |worktree, cx| worktree.open_buffer("a.txt", cx)));
1757        cx_b.update(|_| drop(project_b));
1758        drop(buffer_b);
1759
1760        // See that the guest has left.
1761        project_a
1762            .condition(&cx_a, |p, _| p.collaborators().len() == 0)
1763            .await;
1764    }
1765
1766    #[gpui::test]
1767    async fn test_peer_disconnection(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1768        cx_a.foreground().forbid_parking();
1769        let lang_registry = Arc::new(LanguageRegistry::new());
1770        let fs = Arc::new(FakeFs::new());
1771
1772        // Connect to a server as 2 clients.
1773        let mut server = TestServer::start(cx_a.foreground()).await;
1774        let client_a = server.create_client(&mut cx_a, "user_a").await;
1775        let client_b = server.create_client(&mut cx_b, "user_b").await;
1776
1777        // Share a project as client A
1778        fs.insert_tree(
1779            "/a",
1780            json!({
1781                ".zed.toml": r#"collaborators = ["user_b"]"#,
1782                "a.txt": "a-contents",
1783                "b.txt": "b-contents",
1784            }),
1785        )
1786        .await;
1787        let project_a = cx_a.update(|cx| {
1788            Project::local(
1789                client_a.clone(),
1790                client_a.user_store.clone(),
1791                lang_registry.clone(),
1792                fs.clone(),
1793                cx,
1794            )
1795        });
1796        let worktree_a = project_a
1797            .update(&mut cx_a, |p, cx| p.add_local_worktree("/a", cx))
1798            .await
1799            .unwrap();
1800        worktree_a
1801            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1802            .await;
1803        let project_id = project_a
1804            .update(&mut cx_a, |project, _| project.next_remote_id())
1805            .await;
1806        project_a
1807            .update(&mut cx_a, |project, cx| project.share(cx))
1808            .await
1809            .unwrap();
1810
1811        // Join that project as client B
1812        let _project_b = Project::remote(
1813            project_id,
1814            client_b.clone(),
1815            client_b.user_store.clone(),
1816            lang_registry.clone(),
1817            fs.clone(),
1818            &mut cx_b.to_async(),
1819        )
1820        .await
1821        .unwrap();
1822
1823        // See that a guest has joined as client A.
1824        project_a
1825            .condition(&cx_a, |p, _| p.collaborators().len() == 1)
1826            .await;
1827
1828        // Drop client B's connection and ensure client A observes client B leaving the worktree.
1829        client_b.disconnect(&cx_b.to_async()).unwrap();
1830        project_a
1831            .condition(&cx_a, |p, _| p.collaborators().len() == 0)
1832            .await;
1833    }
1834
1835    #[gpui::test]
1836    async fn test_collaborating_with_diagnostics(
1837        mut cx_a: TestAppContext,
1838        mut cx_b: TestAppContext,
1839    ) {
1840        cx_a.foreground().forbid_parking();
1841        let mut lang_registry = Arc::new(LanguageRegistry::new());
1842        let fs = Arc::new(FakeFs::new());
1843
1844        // Set up a fake language server.
1845        let (language_server_config, mut fake_language_server) =
1846            LanguageServerConfig::fake(cx_a.background()).await;
1847        Arc::get_mut(&mut lang_registry)
1848            .unwrap()
1849            .add(Arc::new(Language::new(
1850                LanguageConfig {
1851                    name: "Rust".to_string(),
1852                    path_suffixes: vec!["rs".to_string()],
1853                    language_server: Some(language_server_config),
1854                    ..Default::default()
1855                },
1856                Some(tree_sitter_rust::language()),
1857            )));
1858
1859        // Connect to a server as 2 clients.
1860        let mut server = TestServer::start(cx_a.foreground()).await;
1861        let client_a = server.create_client(&mut cx_a, "user_a").await;
1862        let client_b = server.create_client(&mut cx_b, "user_b").await;
1863
1864        // Share a project as client A
1865        fs.insert_tree(
1866            "/a",
1867            json!({
1868                ".zed.toml": r#"collaborators = ["user_b"]"#,
1869                "a.rs": "let one = two",
1870                "other.rs": "",
1871            }),
1872        )
1873        .await;
1874        let project_a = cx_a.update(|cx| {
1875            Project::local(
1876                client_a.clone(),
1877                client_a.user_store.clone(),
1878                lang_registry.clone(),
1879                fs.clone(),
1880                cx,
1881            )
1882        });
1883        let worktree_a = project_a
1884            .update(&mut cx_a, |p, cx| p.add_local_worktree("/a", cx))
1885            .await
1886            .unwrap();
1887        worktree_a
1888            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1889            .await;
1890        let project_id = project_a
1891            .update(&mut cx_a, |project, _| project.next_remote_id())
1892            .await;
1893        let worktree_id = worktree_a.read_with(&cx_a, |tree, _| tree.id());
1894        project_a
1895            .update(&mut cx_a, |project, cx| project.share(cx))
1896            .await
1897            .unwrap();
1898
1899        // Cause the language server to start.
1900        let _ = cx_a
1901            .background()
1902            .spawn(worktree_a.update(&mut cx_a, |worktree, cx| {
1903                worktree.open_buffer("other.rs", cx)
1904            }))
1905            .await
1906            .unwrap();
1907
1908        // Simulate a language server reporting errors for a file.
1909        fake_language_server
1910            .notify::<lsp::notification::PublishDiagnostics>(lsp::PublishDiagnosticsParams {
1911                uri: lsp::Url::from_file_path("/a/a.rs").unwrap(),
1912                version: None,
1913                diagnostics: vec![lsp::Diagnostic {
1914                    severity: Some(lsp::DiagnosticSeverity::ERROR),
1915                    range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 7)),
1916                    message: "message 1".to_string(),
1917                    ..Default::default()
1918                }],
1919            })
1920            .await;
1921
1922        // Wait for server to see the diagnostics update.
1923        server
1924            .condition(|store| {
1925                let worktree = store
1926                    .project(project_id)
1927                    .unwrap()
1928                    .worktrees
1929                    .get(&worktree_id.to_proto())
1930                    .unwrap();
1931
1932                !worktree
1933                    .share
1934                    .as_ref()
1935                    .unwrap()
1936                    .diagnostic_summaries
1937                    .is_empty()
1938            })
1939            .await;
1940
1941        // Join the worktree as client B.
1942        let project_b = Project::remote(
1943            project_id,
1944            client_b.clone(),
1945            client_b.user_store.clone(),
1946            lang_registry.clone(),
1947            fs.clone(),
1948            &mut cx_b.to_async(),
1949        )
1950        .await
1951        .unwrap();
1952
1953        project_b.read_with(&cx_b, |project, cx| {
1954            assert_eq!(
1955                project.diagnostic_summaries(cx).collect::<Vec<_>>(),
1956                &[(
1957                    ProjectPath {
1958                        worktree_id,
1959                        path: Arc::from(Path::new("a.rs")),
1960                    },
1961                    DiagnosticSummary {
1962                        error_count: 1,
1963                        warning_count: 0,
1964                        ..Default::default()
1965                    },
1966                )]
1967            )
1968        });
1969
1970        // Simulate a language server reporting more errors for a file.
1971        fake_language_server
1972            .notify::<lsp::notification::PublishDiagnostics>(lsp::PublishDiagnosticsParams {
1973                uri: lsp::Url::from_file_path("/a/a.rs").unwrap(),
1974                version: None,
1975                diagnostics: vec![
1976                    lsp::Diagnostic {
1977                        severity: Some(lsp::DiagnosticSeverity::ERROR),
1978                        range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 7)),
1979                        message: "message 1".to_string(),
1980                        ..Default::default()
1981                    },
1982                    lsp::Diagnostic {
1983                        severity: Some(lsp::DiagnosticSeverity::WARNING),
1984                        range: lsp::Range::new(
1985                            lsp::Position::new(0, 10),
1986                            lsp::Position::new(0, 13),
1987                        ),
1988                        message: "message 2".to_string(),
1989                        ..Default::default()
1990                    },
1991                ],
1992            })
1993            .await;
1994
1995        // Client b gets the updated summaries
1996        project_b
1997            .condition(&cx_b, |project, cx| {
1998                project.diagnostic_summaries(cx).collect::<Vec<_>>()
1999                    == &[(
2000                        ProjectPath {
2001                            worktree_id,
2002                            path: Arc::from(Path::new("a.rs")),
2003                        },
2004                        DiagnosticSummary {
2005                            error_count: 1,
2006                            warning_count: 1,
2007                            ..Default::default()
2008                        },
2009                    )]
2010            })
2011            .await;
2012
2013        // Open the file with the errors on client B. They should be present.
2014        let worktree_b = project_b.update(&mut cx_b, |p, _| p.worktrees()[0].clone());
2015        let buffer_b = cx_b
2016            .background()
2017            .spawn(worktree_b.update(&mut cx_b, |worktree, cx| worktree.open_buffer("a.rs", cx)))
2018            .await
2019            .unwrap();
2020
2021        buffer_b.read_with(&cx_b, |buffer, _| {
2022            assert_eq!(
2023                buffer
2024                    .snapshot()
2025                    .diagnostics_in_range::<_, Point>(0..buffer.len())
2026                    .map(|entry| entry)
2027                    .collect::<Vec<_>>(),
2028                &[
2029                    DiagnosticEntry {
2030                        range: Point::new(0, 4)..Point::new(0, 7),
2031                        diagnostic: Diagnostic {
2032                            group_id: 0,
2033                            message: "message 1".to_string(),
2034                            severity: lsp::DiagnosticSeverity::ERROR,
2035                            is_primary: true,
2036                            ..Default::default()
2037                        }
2038                    },
2039                    DiagnosticEntry {
2040                        range: Point::new(0, 10)..Point::new(0, 13),
2041                        diagnostic: Diagnostic {
2042                            group_id: 1,
2043                            severity: lsp::DiagnosticSeverity::WARNING,
2044                            message: "message 2".to_string(),
2045                            is_primary: true,
2046                            ..Default::default()
2047                        }
2048                    }
2049                ]
2050            );
2051        });
2052    }
2053
2054    #[gpui::test]
2055    async fn test_formatting_buffer(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
2056        cx_a.foreground().forbid_parking();
2057        let mut lang_registry = Arc::new(LanguageRegistry::new());
2058        let fs = Arc::new(FakeFs::new());
2059
2060        // Set up a fake language server.
2061        let (language_server_config, mut fake_language_server) =
2062            LanguageServerConfig::fake(cx_a.background()).await;
2063        Arc::get_mut(&mut lang_registry)
2064            .unwrap()
2065            .add(Arc::new(Language::new(
2066                LanguageConfig {
2067                    name: "Rust".to_string(),
2068                    path_suffixes: vec!["rs".to_string()],
2069                    language_server: Some(language_server_config),
2070                    ..Default::default()
2071                },
2072                Some(tree_sitter_rust::language()),
2073            )));
2074
2075        // Connect to a server as 2 clients.
2076        let mut server = TestServer::start(cx_a.foreground()).await;
2077        let client_a = server.create_client(&mut cx_a, "user_a").await;
2078        let client_b = server.create_client(&mut cx_b, "user_b").await;
2079
2080        // Share a project as client A
2081        fs.insert_tree(
2082            "/a",
2083            json!({
2084                ".zed.toml": r#"collaborators = ["user_b"]"#,
2085                "a.rs": "let one = two",
2086            }),
2087        )
2088        .await;
2089        let project_a = cx_a.update(|cx| {
2090            Project::local(
2091                client_a.clone(),
2092                client_a.user_store.clone(),
2093                lang_registry.clone(),
2094                fs.clone(),
2095                cx,
2096            )
2097        });
2098        let worktree_a = project_a
2099            .update(&mut cx_a, |p, cx| p.add_local_worktree("/a", cx))
2100            .await
2101            .unwrap();
2102        worktree_a
2103            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
2104            .await;
2105        let project_id = project_a
2106            .update(&mut cx_a, |project, _| project.next_remote_id())
2107            .await;
2108        project_a
2109            .update(&mut cx_a, |project, cx| project.share(cx))
2110            .await
2111            .unwrap();
2112
2113        // Join the worktree as client B.
2114        let project_b = Project::remote(
2115            project_id,
2116            client_b.clone(),
2117            client_b.user_store.clone(),
2118            lang_registry.clone(),
2119            fs.clone(),
2120            &mut cx_b.to_async(),
2121        )
2122        .await
2123        .unwrap();
2124
2125        // Open the file to be formatted on client B.
2126        let worktree_b = project_b.update(&mut cx_b, |p, _| p.worktrees()[0].clone());
2127        let buffer_b = cx_b
2128            .background()
2129            .spawn(worktree_b.update(&mut cx_b, |worktree, cx| worktree.open_buffer("a.rs", cx)))
2130            .await
2131            .unwrap();
2132
2133        let format = buffer_b.update(&mut cx_b, |buffer, cx| buffer.format(cx));
2134        let (request_id, _) = fake_language_server
2135            .receive_request::<lsp::request::Formatting>()
2136            .await;
2137        fake_language_server
2138            .respond(
2139                request_id,
2140                Some(vec![
2141                    lsp::TextEdit {
2142                        range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 4)),
2143                        new_text: "h".to_string(),
2144                    },
2145                    lsp::TextEdit {
2146                        range: lsp::Range::new(lsp::Position::new(0, 7), lsp::Position::new(0, 7)),
2147                        new_text: "y".to_string(),
2148                    },
2149                ]),
2150            )
2151            .await;
2152        format.await.unwrap();
2153        assert_eq!(
2154            buffer_b.read_with(&cx_b, |buffer, _| buffer.text()),
2155            "let honey = two"
2156        );
2157    }
2158
2159    #[gpui::test]
2160    async fn test_basic_chat(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
2161        cx_a.foreground().forbid_parking();
2162
2163        // Connect to a server as 2 clients.
2164        let mut server = TestServer::start(cx_a.foreground()).await;
2165        let client_a = server.create_client(&mut cx_a, "user_a").await;
2166        let client_b = server.create_client(&mut cx_b, "user_b").await;
2167
2168        // Create an org that includes these 2 users.
2169        let db = &server.app_state.db;
2170        let org_id = db.create_org("Test Org", "test-org").await.unwrap();
2171        db.add_org_member(org_id, client_a.current_user_id(&cx_a), false)
2172            .await
2173            .unwrap();
2174        db.add_org_member(org_id, client_b.current_user_id(&cx_b), false)
2175            .await
2176            .unwrap();
2177
2178        // Create a channel that includes all the users.
2179        let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
2180        db.add_channel_member(channel_id, client_a.current_user_id(&cx_a), false)
2181            .await
2182            .unwrap();
2183        db.add_channel_member(channel_id, client_b.current_user_id(&cx_b), false)
2184            .await
2185            .unwrap();
2186        db.create_channel_message(
2187            channel_id,
2188            client_b.current_user_id(&cx_b),
2189            "hello A, it's B.",
2190            OffsetDateTime::now_utc(),
2191            1,
2192        )
2193        .await
2194        .unwrap();
2195
2196        let channels_a = cx_a
2197            .add_model(|cx| ChannelList::new(client_a.user_store.clone(), client_a.clone(), cx));
2198        channels_a
2199            .condition(&mut cx_a, |list, _| list.available_channels().is_some())
2200            .await;
2201        channels_a.read_with(&cx_a, |list, _| {
2202            assert_eq!(
2203                list.available_channels().unwrap(),
2204                &[ChannelDetails {
2205                    id: channel_id.to_proto(),
2206                    name: "test-channel".to_string()
2207                }]
2208            )
2209        });
2210        let channel_a = channels_a.update(&mut cx_a, |this, cx| {
2211            this.get_channel(channel_id.to_proto(), cx).unwrap()
2212        });
2213        channel_a.read_with(&cx_a, |channel, _| assert!(channel.messages().is_empty()));
2214        channel_a
2215            .condition(&cx_a, |channel, _| {
2216                channel_messages(channel)
2217                    == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2218            })
2219            .await;
2220
2221        let channels_b = cx_b
2222            .add_model(|cx| ChannelList::new(client_b.user_store.clone(), client_b.clone(), cx));
2223        channels_b
2224            .condition(&mut cx_b, |list, _| list.available_channels().is_some())
2225            .await;
2226        channels_b.read_with(&cx_b, |list, _| {
2227            assert_eq!(
2228                list.available_channels().unwrap(),
2229                &[ChannelDetails {
2230                    id: channel_id.to_proto(),
2231                    name: "test-channel".to_string()
2232                }]
2233            )
2234        });
2235
2236        let channel_b = channels_b.update(&mut cx_b, |this, cx| {
2237            this.get_channel(channel_id.to_proto(), cx).unwrap()
2238        });
2239        channel_b.read_with(&cx_b, |channel, _| assert!(channel.messages().is_empty()));
2240        channel_b
2241            .condition(&cx_b, |channel, _| {
2242                channel_messages(channel)
2243                    == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2244            })
2245            .await;
2246
2247        channel_a
2248            .update(&mut cx_a, |channel, cx| {
2249                channel
2250                    .send_message("oh, hi B.".to_string(), cx)
2251                    .unwrap()
2252                    .detach();
2253                let task = channel.send_message("sup".to_string(), cx).unwrap();
2254                assert_eq!(
2255                    channel_messages(channel),
2256                    &[
2257                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2258                        ("user_a".to_string(), "oh, hi B.".to_string(), true),
2259                        ("user_a".to_string(), "sup".to_string(), true)
2260                    ]
2261                );
2262                task
2263            })
2264            .await
2265            .unwrap();
2266
2267        channel_b
2268            .condition(&cx_b, |channel, _| {
2269                channel_messages(channel)
2270                    == [
2271                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2272                        ("user_a".to_string(), "oh, hi B.".to_string(), false),
2273                        ("user_a".to_string(), "sup".to_string(), false),
2274                    ]
2275            })
2276            .await;
2277
2278        assert_eq!(
2279            server
2280                .state()
2281                .await
2282                .channel(channel_id)
2283                .unwrap()
2284                .connection_ids
2285                .len(),
2286            2
2287        );
2288        cx_b.update(|_| drop(channel_b));
2289        server
2290            .condition(|state| state.channel(channel_id).unwrap().connection_ids.len() == 1)
2291            .await;
2292
2293        cx_a.update(|_| drop(channel_a));
2294        server
2295            .condition(|state| state.channel(channel_id).is_none())
2296            .await;
2297    }
2298
2299    #[gpui::test]
2300    async fn test_chat_message_validation(mut cx_a: TestAppContext) {
2301        cx_a.foreground().forbid_parking();
2302
2303        let mut server = TestServer::start(cx_a.foreground()).await;
2304        let client_a = server.create_client(&mut cx_a, "user_a").await;
2305
2306        let db = &server.app_state.db;
2307        let org_id = db.create_org("Test Org", "test-org").await.unwrap();
2308        let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
2309        db.add_org_member(org_id, client_a.current_user_id(&cx_a), false)
2310            .await
2311            .unwrap();
2312        db.add_channel_member(channel_id, client_a.current_user_id(&cx_a), false)
2313            .await
2314            .unwrap();
2315
2316        let channels_a = cx_a
2317            .add_model(|cx| ChannelList::new(client_a.user_store.clone(), client_a.clone(), cx));
2318        channels_a
2319            .condition(&mut cx_a, |list, _| list.available_channels().is_some())
2320            .await;
2321        let channel_a = channels_a.update(&mut cx_a, |this, cx| {
2322            this.get_channel(channel_id.to_proto(), cx).unwrap()
2323        });
2324
2325        // Messages aren't allowed to be too long.
2326        channel_a
2327            .update(&mut cx_a, |channel, cx| {
2328                let long_body = "this is long.\n".repeat(1024);
2329                channel.send_message(long_body, cx).unwrap()
2330            })
2331            .await
2332            .unwrap_err();
2333
2334        // Messages aren't allowed to be blank.
2335        channel_a.update(&mut cx_a, |channel, cx| {
2336            channel.send_message(String::new(), cx).unwrap_err()
2337        });
2338
2339        // Leading and trailing whitespace are trimmed.
2340        channel_a
2341            .update(&mut cx_a, |channel, cx| {
2342                channel
2343                    .send_message("\n surrounded by whitespace  \n".to_string(), cx)
2344                    .unwrap()
2345            })
2346            .await
2347            .unwrap();
2348        assert_eq!(
2349            db.get_channel_messages(channel_id, 10, None)
2350                .await
2351                .unwrap()
2352                .iter()
2353                .map(|m| &m.body)
2354                .collect::<Vec<_>>(),
2355            &["surrounded by whitespace"]
2356        );
2357    }
2358
2359    #[gpui::test]
2360    async fn test_chat_reconnection(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
2361        cx_a.foreground().forbid_parking();
2362
2363        // Connect to a server as 2 clients.
2364        let mut server = TestServer::start(cx_a.foreground()).await;
2365        let client_a = server.create_client(&mut cx_a, "user_a").await;
2366        let client_b = server.create_client(&mut cx_b, "user_b").await;
2367        let mut status_b = client_b.status();
2368
2369        // Create an org that includes these 2 users.
2370        let db = &server.app_state.db;
2371        let org_id = db.create_org("Test Org", "test-org").await.unwrap();
2372        db.add_org_member(org_id, client_a.current_user_id(&cx_a), false)
2373            .await
2374            .unwrap();
2375        db.add_org_member(org_id, client_b.current_user_id(&cx_b), false)
2376            .await
2377            .unwrap();
2378
2379        // Create a channel that includes all the users.
2380        let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
2381        db.add_channel_member(channel_id, client_a.current_user_id(&cx_a), false)
2382            .await
2383            .unwrap();
2384        db.add_channel_member(channel_id, client_b.current_user_id(&cx_b), false)
2385            .await
2386            .unwrap();
2387        db.create_channel_message(
2388            channel_id,
2389            client_b.current_user_id(&cx_b),
2390            "hello A, it's B.",
2391            OffsetDateTime::now_utc(),
2392            2,
2393        )
2394        .await
2395        .unwrap();
2396
2397        let channels_a = cx_a
2398            .add_model(|cx| ChannelList::new(client_a.user_store.clone(), client_a.clone(), cx));
2399        channels_a
2400            .condition(&mut cx_a, |list, _| list.available_channels().is_some())
2401            .await;
2402
2403        channels_a.read_with(&cx_a, |list, _| {
2404            assert_eq!(
2405                list.available_channels().unwrap(),
2406                &[ChannelDetails {
2407                    id: channel_id.to_proto(),
2408                    name: "test-channel".to_string()
2409                }]
2410            )
2411        });
2412        let channel_a = channels_a.update(&mut cx_a, |this, cx| {
2413            this.get_channel(channel_id.to_proto(), cx).unwrap()
2414        });
2415        channel_a.read_with(&cx_a, |channel, _| assert!(channel.messages().is_empty()));
2416        channel_a
2417            .condition(&cx_a, |channel, _| {
2418                channel_messages(channel)
2419                    == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2420            })
2421            .await;
2422
2423        let channels_b = cx_b
2424            .add_model(|cx| ChannelList::new(client_b.user_store.clone(), client_b.clone(), cx));
2425        channels_b
2426            .condition(&mut cx_b, |list, _| list.available_channels().is_some())
2427            .await;
2428        channels_b.read_with(&cx_b, |list, _| {
2429            assert_eq!(
2430                list.available_channels().unwrap(),
2431                &[ChannelDetails {
2432                    id: channel_id.to_proto(),
2433                    name: "test-channel".to_string()
2434                }]
2435            )
2436        });
2437
2438        let channel_b = channels_b.update(&mut cx_b, |this, cx| {
2439            this.get_channel(channel_id.to_proto(), cx).unwrap()
2440        });
2441        channel_b.read_with(&cx_b, |channel, _| assert!(channel.messages().is_empty()));
2442        channel_b
2443            .condition(&cx_b, |channel, _| {
2444                channel_messages(channel)
2445                    == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2446            })
2447            .await;
2448
2449        // Disconnect client B, ensuring we can still access its cached channel data.
2450        server.forbid_connections();
2451        server.disconnect_client(client_b.current_user_id(&cx_b));
2452        while !matches!(
2453            status_b.next().await,
2454            Some(client::Status::ReconnectionError { .. })
2455        ) {}
2456
2457        channels_b.read_with(&cx_b, |channels, _| {
2458            assert_eq!(
2459                channels.available_channels().unwrap(),
2460                [ChannelDetails {
2461                    id: channel_id.to_proto(),
2462                    name: "test-channel".to_string()
2463                }]
2464            )
2465        });
2466        channel_b.read_with(&cx_b, |channel, _| {
2467            assert_eq!(
2468                channel_messages(channel),
2469                [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2470            )
2471        });
2472
2473        // Send a message from client B while it is disconnected.
2474        channel_b
2475            .update(&mut cx_b, |channel, cx| {
2476                let task = channel
2477                    .send_message("can you see this?".to_string(), cx)
2478                    .unwrap();
2479                assert_eq!(
2480                    channel_messages(channel),
2481                    &[
2482                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2483                        ("user_b".to_string(), "can you see this?".to_string(), true)
2484                    ]
2485                );
2486                task
2487            })
2488            .await
2489            .unwrap_err();
2490
2491        // Send a message from client A while B is disconnected.
2492        channel_a
2493            .update(&mut cx_a, |channel, cx| {
2494                channel
2495                    .send_message("oh, hi B.".to_string(), cx)
2496                    .unwrap()
2497                    .detach();
2498                let task = channel.send_message("sup".to_string(), cx).unwrap();
2499                assert_eq!(
2500                    channel_messages(channel),
2501                    &[
2502                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2503                        ("user_a".to_string(), "oh, hi B.".to_string(), true),
2504                        ("user_a".to_string(), "sup".to_string(), true)
2505                    ]
2506                );
2507                task
2508            })
2509            .await
2510            .unwrap();
2511
2512        // Give client B a chance to reconnect.
2513        server.allow_connections();
2514        cx_b.foreground().advance_clock(Duration::from_secs(10));
2515
2516        // Verify that B sees the new messages upon reconnection, as well as the message client B
2517        // sent while offline.
2518        channel_b
2519            .condition(&cx_b, |channel, _| {
2520                channel_messages(channel)
2521                    == [
2522                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2523                        ("user_a".to_string(), "oh, hi B.".to_string(), false),
2524                        ("user_a".to_string(), "sup".to_string(), false),
2525                        ("user_b".to_string(), "can you see this?".to_string(), false),
2526                    ]
2527            })
2528            .await;
2529
2530        // Ensure client A and B can communicate normally after reconnection.
2531        channel_a
2532            .update(&mut cx_a, |channel, cx| {
2533                channel.send_message("you online?".to_string(), cx).unwrap()
2534            })
2535            .await
2536            .unwrap();
2537        channel_b
2538            .condition(&cx_b, |channel, _| {
2539                channel_messages(channel)
2540                    == [
2541                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2542                        ("user_a".to_string(), "oh, hi B.".to_string(), false),
2543                        ("user_a".to_string(), "sup".to_string(), false),
2544                        ("user_b".to_string(), "can you see this?".to_string(), false),
2545                        ("user_a".to_string(), "you online?".to_string(), false),
2546                    ]
2547            })
2548            .await;
2549
2550        channel_b
2551            .update(&mut cx_b, |channel, cx| {
2552                channel.send_message("yep".to_string(), cx).unwrap()
2553            })
2554            .await
2555            .unwrap();
2556        channel_a
2557            .condition(&cx_a, |channel, _| {
2558                channel_messages(channel)
2559                    == [
2560                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2561                        ("user_a".to_string(), "oh, hi B.".to_string(), false),
2562                        ("user_a".to_string(), "sup".to_string(), false),
2563                        ("user_b".to_string(), "can you see this?".to_string(), false),
2564                        ("user_a".to_string(), "you online?".to_string(), false),
2565                        ("user_b".to_string(), "yep".to_string(), false),
2566                    ]
2567            })
2568            .await;
2569    }
2570
2571    #[gpui::test]
2572    async fn test_contacts(
2573        mut cx_a: TestAppContext,
2574        mut cx_b: TestAppContext,
2575        mut cx_c: TestAppContext,
2576    ) {
2577        cx_a.foreground().forbid_parking();
2578        let lang_registry = Arc::new(LanguageRegistry::new());
2579        let fs = Arc::new(FakeFs::new());
2580
2581        // Connect to a server as 3 clients.
2582        let mut server = TestServer::start(cx_a.foreground()).await;
2583        let client_a = server.create_client(&mut cx_a, "user_a").await;
2584        let client_b = server.create_client(&mut cx_b, "user_b").await;
2585        let client_c = server.create_client(&mut cx_c, "user_c").await;
2586
2587        // Share a worktree as client A.
2588        fs.insert_tree(
2589            "/a",
2590            json!({
2591                ".zed.toml": r#"collaborators = ["user_b", "user_c"]"#,
2592            }),
2593        )
2594        .await;
2595
2596        let project_a = cx_a.update(|cx| {
2597            Project::local(
2598                client_a.clone(),
2599                client_a.user_store.clone(),
2600                lang_registry.clone(),
2601                fs.clone(),
2602                cx,
2603            )
2604        });
2605        let worktree_a = project_a
2606            .update(&mut cx_a, |p, cx| p.add_local_worktree("/a", cx))
2607            .await
2608            .unwrap();
2609        worktree_a
2610            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
2611            .await;
2612
2613        client_a
2614            .user_store
2615            .condition(&cx_a, |user_store, _| {
2616                contacts(user_store) == vec![("user_a", vec![("a", vec![])])]
2617            })
2618            .await;
2619        client_b
2620            .user_store
2621            .condition(&cx_b, |user_store, _| {
2622                contacts(user_store) == vec![("user_a", vec![("a", vec![])])]
2623            })
2624            .await;
2625        client_c
2626            .user_store
2627            .condition(&cx_c, |user_store, _| {
2628                contacts(user_store) == vec![("user_a", vec![("a", vec![])])]
2629            })
2630            .await;
2631
2632        let project_id = project_a
2633            .update(&mut cx_a, |project, _| project.next_remote_id())
2634            .await;
2635        project_a
2636            .update(&mut cx_a, |project, cx| project.share(cx))
2637            .await
2638            .unwrap();
2639
2640        let _project_b = Project::remote(
2641            project_id,
2642            client_b.clone(),
2643            client_b.user_store.clone(),
2644            lang_registry.clone(),
2645            fs.clone(),
2646            &mut cx_b.to_async(),
2647        )
2648        .await
2649        .unwrap();
2650
2651        client_a
2652            .user_store
2653            .condition(&cx_a, |user_store, _| {
2654                contacts(user_store) == vec![("user_a", vec![("a", vec!["user_b"])])]
2655            })
2656            .await;
2657        client_b
2658            .user_store
2659            .condition(&cx_b, |user_store, _| {
2660                contacts(user_store) == vec![("user_a", vec![("a", vec!["user_b"])])]
2661            })
2662            .await;
2663        client_c
2664            .user_store
2665            .condition(&cx_c, |user_store, _| {
2666                contacts(user_store) == vec![("user_a", vec![("a", vec!["user_b"])])]
2667            })
2668            .await;
2669
2670        project_a
2671            .condition(&cx_a, |project, _| {
2672                project.collaborators().contains_key(&client_b.peer_id)
2673            })
2674            .await;
2675
2676        cx_a.update(move |_| drop(project_a));
2677        client_a
2678            .user_store
2679            .condition(&cx_a, |user_store, _| contacts(user_store) == vec![])
2680            .await;
2681        client_b
2682            .user_store
2683            .condition(&cx_b, |user_store, _| contacts(user_store) == vec![])
2684            .await;
2685        client_c
2686            .user_store
2687            .condition(&cx_c, |user_store, _| contacts(user_store) == vec![])
2688            .await;
2689
2690        fn contacts(user_store: &UserStore) -> Vec<(&str, Vec<(&str, Vec<&str>)>)> {
2691            user_store
2692                .contacts()
2693                .iter()
2694                .map(|contact| {
2695                    let worktrees = contact
2696                        .projects
2697                        .iter()
2698                        .map(|p| {
2699                            (
2700                                p.worktree_root_names[0].as_str(),
2701                                p.guests.iter().map(|p| p.github_login.as_str()).collect(),
2702                            )
2703                        })
2704                        .collect();
2705                    (contact.user.github_login.as_str(), worktrees)
2706                })
2707                .collect()
2708        }
2709    }
2710
2711    struct TestServer {
2712        peer: Arc<Peer>,
2713        app_state: Arc<AppState>,
2714        server: Arc<Server>,
2715        foreground: Rc<executor::Foreground>,
2716        notifications: mpsc::Receiver<()>,
2717        connection_killers: Arc<Mutex<HashMap<UserId, watch::Sender<Option<()>>>>>,
2718        forbid_connections: Arc<AtomicBool>,
2719        _test_db: TestDb,
2720    }
2721
2722    impl TestServer {
2723        async fn start(foreground: Rc<executor::Foreground>) -> Self {
2724            let test_db = TestDb::new();
2725            let app_state = Self::build_app_state(&test_db).await;
2726            let peer = Peer::new();
2727            let notifications = mpsc::channel(128);
2728            let server = Server::new(app_state.clone(), peer.clone(), Some(notifications.0));
2729            Self {
2730                peer,
2731                app_state,
2732                server,
2733                foreground,
2734                notifications: notifications.1,
2735                connection_killers: Default::default(),
2736                forbid_connections: Default::default(),
2737                _test_db: test_db,
2738            }
2739        }
2740
2741        async fn create_client(&mut self, cx: &mut TestAppContext, name: &str) -> TestClient {
2742            let http = FakeHttpClient::with_404_response();
2743            let user_id = self.app_state.db.create_user(name, false).await.unwrap();
2744            let client_name = name.to_string();
2745            let mut client = Client::new(http.clone());
2746            let server = self.server.clone();
2747            let connection_killers = self.connection_killers.clone();
2748            let forbid_connections = self.forbid_connections.clone();
2749            let (connection_id_tx, mut connection_id_rx) = postage::mpsc::channel(16);
2750
2751            Arc::get_mut(&mut client)
2752                .unwrap()
2753                .override_authenticate(move |cx| {
2754                    cx.spawn(|_| async move {
2755                        let access_token = "the-token".to_string();
2756                        Ok(Credentials {
2757                            user_id: user_id.0 as u64,
2758                            access_token,
2759                        })
2760                    })
2761                })
2762                .override_establish_connection(move |credentials, cx| {
2763                    assert_eq!(credentials.user_id, user_id.0 as u64);
2764                    assert_eq!(credentials.access_token, "the-token");
2765
2766                    let server = server.clone();
2767                    let connection_killers = connection_killers.clone();
2768                    let forbid_connections = forbid_connections.clone();
2769                    let client_name = client_name.clone();
2770                    let connection_id_tx = connection_id_tx.clone();
2771                    cx.spawn(move |cx| async move {
2772                        if forbid_connections.load(SeqCst) {
2773                            Err(EstablishConnectionError::other(anyhow!(
2774                                "server is forbidding connections"
2775                            )))
2776                        } else {
2777                            let (client_conn, server_conn, kill_conn) = Connection::in_memory();
2778                            connection_killers.lock().insert(user_id, kill_conn);
2779                            cx.background()
2780                                .spawn(server.handle_connection(
2781                                    server_conn,
2782                                    client_name,
2783                                    user_id,
2784                                    Some(connection_id_tx),
2785                                ))
2786                                .detach();
2787                            Ok(client_conn)
2788                        }
2789                    })
2790                });
2791
2792            client
2793                .authenticate_and_connect(&cx.to_async())
2794                .await
2795                .unwrap();
2796
2797            let peer_id = PeerId(connection_id_rx.next().await.unwrap().0);
2798            let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http, cx));
2799            let mut authed_user =
2800                user_store.read_with(cx, |user_store, _| user_store.watch_current_user());
2801            while authed_user.next().await.unwrap().is_none() {}
2802
2803            TestClient {
2804                client,
2805                peer_id,
2806                user_store,
2807            }
2808        }
2809
2810        fn disconnect_client(&self, user_id: UserId) {
2811            if let Some(mut kill_conn) = self.connection_killers.lock().remove(&user_id) {
2812                let _ = kill_conn.try_send(Some(()));
2813            }
2814        }
2815
2816        fn forbid_connections(&self) {
2817            self.forbid_connections.store(true, SeqCst);
2818        }
2819
2820        fn allow_connections(&self) {
2821            self.forbid_connections.store(false, SeqCst);
2822        }
2823
2824        async fn build_app_state(test_db: &TestDb) -> Arc<AppState> {
2825            let mut config = Config::default();
2826            config.session_secret = "a".repeat(32);
2827            config.database_url = test_db.url.clone();
2828            let github_client = github::AppClient::test();
2829            Arc::new(AppState {
2830                db: test_db.db().clone(),
2831                handlebars: Default::default(),
2832                auth_client: auth::build_client("", ""),
2833                repo_client: github::RepoClient::test(&github_client),
2834                github_client,
2835                config,
2836            })
2837        }
2838
2839        async fn state<'a>(&'a self) -> RwLockReadGuard<'a, Store> {
2840            self.server.store.read()
2841        }
2842
2843        async fn condition<F>(&mut self, mut predicate: F)
2844        where
2845            F: FnMut(&Store) -> bool,
2846        {
2847            async_std::future::timeout(Duration::from_millis(500), async {
2848                while !(predicate)(&*self.server.store.read()) {
2849                    self.foreground.start_waiting();
2850                    self.notifications.next().await;
2851                    self.foreground.finish_waiting();
2852                }
2853            })
2854            .await
2855            .expect("condition timed out");
2856        }
2857    }
2858
2859    impl Drop for TestServer {
2860        fn drop(&mut self) {
2861            self.peer.reset();
2862        }
2863    }
2864
2865    struct TestClient {
2866        client: Arc<Client>,
2867        pub peer_id: PeerId,
2868        pub user_store: ModelHandle<UserStore>,
2869    }
2870
2871    impl Deref for TestClient {
2872        type Target = Arc<Client>;
2873
2874        fn deref(&self) -> &Self::Target {
2875            &self.client
2876        }
2877    }
2878
2879    impl TestClient {
2880        pub fn current_user_id(&self, cx: &TestAppContext) -> UserId {
2881            UserId::from_proto(
2882                self.user_store
2883                    .read_with(cx, |user_store, _| user_store.current_user().unwrap().id),
2884            )
2885        }
2886    }
2887
2888    fn channel_messages(channel: &Channel) -> Vec<(String, String, bool)> {
2889        channel
2890            .messages()
2891            .cursor::<()>()
2892            .map(|m| {
2893                (
2894                    m.sender.github_login.clone(),
2895                    m.body.clone(),
2896                    m.is_pending(),
2897                )
2898            })
2899            .collect()
2900    }
2901
2902    struct EmptyView;
2903
2904    impl gpui::Entity for EmptyView {
2905        type Event = ();
2906    }
2907
2908    impl gpui::View for EmptyView {
2909        fn ui_name() -> &'static str {
2910            "empty view"
2911        }
2912
2913        fn render(&mut self, _: &mut gpui::RenderContext<Self>) -> gpui::ElementBox {
2914            gpui::Element::boxed(gpui::elements::Empty)
2915        }
2916    }
2917}