rpc.rs

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