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