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, MultiBuffer},
 948        fs::{FakeFs, Fs as _},
 949        language::{
 950            tree_sitter_rust, Diagnostic, DiagnosticEntry, Language, LanguageConfig,
 951            LanguageRegistry, 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        let buffer_b = cx_b.add_model(|cx| MultiBuffer::singleton(buffer_b, cx));
1039        buffer_b.read_with(&cx_b, |buf, cx| {
1040            assert_eq!(buf.read(cx).text(), "b-contents")
1041        });
1042        worktree_a.read_with(&cx_a, |tree, cx| assert!(tree.has_open_buffer("b.txt", cx)));
1043        let buffer_a = worktree_a
1044            .update(&mut cx_a, |tree, cx| tree.open_buffer("b.txt", cx))
1045            .await
1046            .unwrap();
1047
1048        let editor_b = cx_b.add_view(window_b, |cx| {
1049            Editor::for_buffer(buffer_b, |cx| EditorSettings::test(cx), cx)
1050        });
1051        // TODO
1052        // // Create a selection set as client B and see that selection set as client A.
1053        // buffer_a
1054        //     .condition(&cx_a, |buffer, _| buffer.selection_sets().count() == 1)
1055        //     .await;
1056
1057        // Edit the buffer as client B and see that edit as client A.
1058        editor_b.update(&mut cx_b, |editor, cx| {
1059            editor.handle_input(&Input("ok, ".into()), cx)
1060        });
1061        buffer_a
1062            .condition(&cx_a, |buffer, _| buffer.text() == "ok, b-contents")
1063            .await;
1064
1065        // TODO
1066        // // Remove the selection set as client B, see those selections disappear as client A.
1067        // cx_b.update(move |_| drop(editor_b));
1068        // buffer_a
1069        //     .condition(&cx_a, |buffer, _| buffer.selection_sets().count() == 0)
1070        //     .await;
1071
1072        // Close the buffer as client A, see that the buffer is closed.
1073        cx_a.update(move |_| drop(buffer_a));
1074        worktree_a
1075            .condition(&cx_a, |tree, cx| !tree.has_open_buffer("b.txt", cx))
1076            .await;
1077
1078        // Dropping the worktree removes client B from client A's collaborators.
1079        cx_b.update(move |_| drop(worktree_b));
1080        worktree_a
1081            .condition(&cx_a, |tree, _| tree.collaborators().is_empty())
1082            .await;
1083    }
1084
1085    #[gpui::test]
1086    async fn test_unshare_worktree(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1087        cx_b.update(zed::contacts_panel::init);
1088        let mut app_state_a = cx_a.update(test_app_state);
1089        let mut app_state_b = cx_b.update(test_app_state);
1090
1091        // Connect to a server as 2 clients.
1092        let mut server = TestServer::start().await;
1093        let client_a = server.create_client(&mut cx_a, "user_a").await;
1094        let client_b = server.create_client(&mut cx_b, "user_b").await;
1095        Arc::get_mut(&mut app_state_a).unwrap().client = client_a.clone();
1096        Arc::get_mut(&mut app_state_a).unwrap().user_store = client_a.user_store.clone();
1097        Arc::get_mut(&mut app_state_b).unwrap().client = client_b.clone();
1098        Arc::get_mut(&mut app_state_b).unwrap().user_store = client_b.user_store.clone();
1099
1100        cx_a.foreground().forbid_parking();
1101
1102        // Share a local worktree as client A
1103        let fs = Arc::new(FakeFs::new());
1104        fs.insert_tree(
1105            "/a",
1106            json!({
1107                ".zed.toml": r#"collaborators = ["user_b"]"#,
1108                "a.txt": "a-contents",
1109                "b.txt": "b-contents",
1110            }),
1111        )
1112        .await;
1113        let worktree_a = Worktree::open_local(
1114            app_state_a.client.clone(),
1115            app_state_a.user_store.clone(),
1116            "/a".as_ref(),
1117            fs,
1118            app_state_a.languages.clone(),
1119            &mut cx_a.to_async(),
1120        )
1121        .await
1122        .unwrap();
1123        worktree_a
1124            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1125            .await;
1126
1127        let remote_worktree_id = worktree_a
1128            .update(&mut cx_a, |tree, cx| tree.as_local_mut().unwrap().share(cx))
1129            .await
1130            .unwrap();
1131
1132        let (window_b, workspace_b) =
1133            cx_b.add_window(|cx| Workspace::new(&app_state_b.as_ref().into(), cx));
1134        cx_b.update(|cx| {
1135            cx.dispatch_action(
1136                window_b,
1137                vec![workspace_b.id()],
1138                &JoinWorktree(remote_worktree_id),
1139            );
1140        });
1141        workspace_b
1142            .condition(&cx_b, |workspace, cx| workspace.worktrees(cx).len() == 1)
1143            .await;
1144
1145        let local_worktree_id_b = workspace_b.read_with(&cx_b, |workspace, cx| {
1146            let active_pane = workspace.active_pane().read(cx);
1147            assert!(active_pane.active_item().is_none());
1148            workspace.worktrees(cx).first().unwrap().id()
1149        });
1150        workspace_b
1151            .update(&mut cx_b, |workspace, cx| {
1152                workspace.open_entry(
1153                    ProjectPath {
1154                        worktree_id: local_worktree_id_b,
1155                        path: Path::new("a.txt").into(),
1156                    },
1157                    cx,
1158                )
1159            })
1160            .unwrap()
1161            .await;
1162        workspace_b.read_with(&cx_b, |workspace, cx| {
1163            let active_pane = workspace.active_pane().read(cx);
1164            assert!(active_pane.active_item().is_some());
1165        });
1166
1167        worktree_a.update(&mut cx_a, |tree, cx| {
1168            tree.as_local_mut().unwrap().unshare(cx);
1169        });
1170        workspace_b
1171            .condition(&cx_b, |workspace, cx| workspace.worktrees(cx).len() == 0)
1172            .await;
1173        workspace_b.read_with(&cx_b, |workspace, cx| {
1174            let active_pane = workspace.active_pane().read(cx);
1175            assert!(active_pane.active_item().is_none());
1176        });
1177    }
1178
1179    #[gpui::test]
1180    async fn test_propagate_saves_and_fs_changes_in_shared_worktree(
1181        mut cx_a: TestAppContext,
1182        mut cx_b: TestAppContext,
1183        mut cx_c: TestAppContext,
1184    ) {
1185        cx_a.foreground().forbid_parking();
1186        let lang_registry = Arc::new(LanguageRegistry::new());
1187
1188        // Connect to a server as 3 clients.
1189        let mut server = TestServer::start().await;
1190        let client_a = server.create_client(&mut cx_a, "user_a").await;
1191        let client_b = server.create_client(&mut cx_b, "user_b").await;
1192        let client_c = server.create_client(&mut cx_c, "user_c").await;
1193
1194        let fs = Arc::new(FakeFs::new());
1195
1196        // Share a worktree as client A.
1197        fs.insert_tree(
1198            "/a",
1199            json!({
1200                ".zed.toml": r#"collaborators = ["user_b", "user_c"]"#,
1201                "file1": "",
1202                "file2": ""
1203            }),
1204        )
1205        .await;
1206
1207        let worktree_a = Worktree::open_local(
1208            client_a.clone(),
1209            client_a.user_store.clone(),
1210            "/a".as_ref(),
1211            fs.clone(),
1212            lang_registry.clone(),
1213            &mut cx_a.to_async(),
1214        )
1215        .await
1216        .unwrap();
1217        worktree_a
1218            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1219            .await;
1220        let worktree_id = worktree_a
1221            .update(&mut cx_a, |tree, cx| tree.as_local_mut().unwrap().share(cx))
1222            .await
1223            .unwrap();
1224
1225        // Join that worktree as clients B and C.
1226        let worktree_b = Worktree::open_remote(
1227            client_b.clone(),
1228            worktree_id,
1229            lang_registry.clone(),
1230            client_b.user_store.clone(),
1231            &mut cx_b.to_async(),
1232        )
1233        .await
1234        .unwrap();
1235        let worktree_c = Worktree::open_remote(
1236            client_c.clone(),
1237            worktree_id,
1238            lang_registry.clone(),
1239            client_c.user_store.clone(),
1240            &mut cx_c.to_async(),
1241        )
1242        .await
1243        .unwrap();
1244
1245        // Open and edit a buffer as both guests B and C.
1246        let buffer_b = worktree_b
1247            .update(&mut cx_b, |tree, cx| tree.open_buffer("file1", cx))
1248            .await
1249            .unwrap();
1250        let buffer_c = worktree_c
1251            .update(&mut cx_c, |tree, cx| tree.open_buffer("file1", cx))
1252            .await
1253            .unwrap();
1254        buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "i-am-b, ", cx));
1255        buffer_c.update(&mut cx_c, |buf, cx| buf.edit([0..0], "i-am-c, ", cx));
1256
1257        // Open and edit that buffer as the host.
1258        let buffer_a = worktree_a
1259            .update(&mut cx_a, |tree, cx| tree.open_buffer("file1", cx))
1260            .await
1261            .unwrap();
1262
1263        buffer_a
1264            .condition(&mut cx_a, |buf, _| buf.text() == "i-am-c, i-am-b, ")
1265            .await;
1266        buffer_a.update(&mut cx_a, |buf, cx| {
1267            buf.edit([buf.len()..buf.len()], "i-am-a", cx)
1268        });
1269
1270        // Wait for edits to propagate
1271        buffer_a
1272            .condition(&mut cx_a, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1273            .await;
1274        buffer_b
1275            .condition(&mut cx_b, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1276            .await;
1277        buffer_c
1278            .condition(&mut cx_c, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1279            .await;
1280
1281        // Edit the buffer as the host and concurrently save as guest B.
1282        let save_b = buffer_b.update(&mut cx_b, |buf, cx| buf.save(cx).unwrap());
1283        buffer_a.update(&mut cx_a, |buf, cx| buf.edit([0..0], "hi-a, ", cx));
1284        save_b.await.unwrap();
1285        assert_eq!(
1286            fs.load("/a/file1".as_ref()).await.unwrap(),
1287            "hi-a, i-am-c, i-am-b, i-am-a"
1288        );
1289        buffer_a.read_with(&cx_a, |buf, _| assert!(!buf.is_dirty()));
1290        buffer_b.read_with(&cx_b, |buf, _| assert!(!buf.is_dirty()));
1291        buffer_c.condition(&cx_c, |buf, _| !buf.is_dirty()).await;
1292
1293        // Make changes on host's file system, see those changes on the guests.
1294        fs.rename("/a/file2".as_ref(), "/a/file3".as_ref())
1295            .await
1296            .unwrap();
1297        fs.insert_file(Path::new("/a/file4"), "4".into())
1298            .await
1299            .unwrap();
1300
1301        worktree_b
1302            .condition(&cx_b, |tree, _| tree.file_count() == 4)
1303            .await;
1304        worktree_c
1305            .condition(&cx_c, |tree, _| tree.file_count() == 4)
1306            .await;
1307        worktree_b.read_with(&cx_b, |tree, _| {
1308            assert_eq!(
1309                tree.paths()
1310                    .map(|p| p.to_string_lossy())
1311                    .collect::<Vec<_>>(),
1312                &[".zed.toml", "file1", "file3", "file4"]
1313            )
1314        });
1315        worktree_c.read_with(&cx_c, |tree, _| {
1316            assert_eq!(
1317                tree.paths()
1318                    .map(|p| p.to_string_lossy())
1319                    .collect::<Vec<_>>(),
1320                &[".zed.toml", "file1", "file3", "file4"]
1321            )
1322        });
1323    }
1324
1325    #[gpui::test]
1326    async fn test_buffer_conflict_after_save(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1327        cx_a.foreground().forbid_parking();
1328        let lang_registry = Arc::new(LanguageRegistry::new());
1329
1330        // Connect to a server as 2 clients.
1331        let mut server = TestServer::start().await;
1332        let client_a = server.create_client(&mut cx_a, "user_a").await;
1333        let client_b = server.create_client(&mut cx_b, "user_b").await;
1334
1335        // Share a local worktree as client A
1336        let fs = Arc::new(FakeFs::new());
1337        fs.insert_tree(
1338            "/dir",
1339            json!({
1340                ".zed.toml": r#"collaborators = ["user_b", "user_c"]"#,
1341                "a.txt": "a-contents",
1342            }),
1343        )
1344        .await;
1345
1346        let worktree_a = Worktree::open_local(
1347            client_a.clone(),
1348            client_a.user_store.clone(),
1349            "/dir".as_ref(),
1350            fs,
1351            lang_registry.clone(),
1352            &mut cx_a.to_async(),
1353        )
1354        .await
1355        .unwrap();
1356        worktree_a
1357            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1358            .await;
1359        let worktree_id = worktree_a
1360            .update(&mut cx_a, |tree, cx| tree.as_local_mut().unwrap().share(cx))
1361            .await
1362            .unwrap();
1363
1364        // Join that worktree as client B, and see that a guest has joined as client A.
1365        let worktree_b = Worktree::open_remote(
1366            client_b.clone(),
1367            worktree_id,
1368            lang_registry.clone(),
1369            client_b.user_store.clone(),
1370            &mut cx_b.to_async(),
1371        )
1372        .await
1373        .unwrap();
1374
1375        let buffer_b = worktree_b
1376            .update(&mut cx_b, |worktree, cx| worktree.open_buffer("a.txt", cx))
1377            .await
1378            .unwrap();
1379        let mtime = buffer_b.read_with(&cx_b, |buf, _| buf.file().unwrap().mtime());
1380
1381        buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "world ", cx));
1382        buffer_b.read_with(&cx_b, |buf, _| {
1383            assert!(buf.is_dirty());
1384            assert!(!buf.has_conflict());
1385        });
1386
1387        buffer_b
1388            .update(&mut cx_b, |buf, cx| buf.save(cx))
1389            .unwrap()
1390            .await
1391            .unwrap();
1392        worktree_b
1393            .condition(&cx_b, |_, cx| {
1394                buffer_b.read(cx).file().unwrap().mtime() != mtime
1395            })
1396            .await;
1397        buffer_b.read_with(&cx_b, |buf, _| {
1398            assert!(!buf.is_dirty());
1399            assert!(!buf.has_conflict());
1400        });
1401
1402        buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "hello ", cx));
1403        buffer_b.read_with(&cx_b, |buf, _| {
1404            assert!(buf.is_dirty());
1405            assert!(!buf.has_conflict());
1406        });
1407    }
1408
1409    #[gpui::test]
1410    async fn test_editing_while_guest_opens_buffer(
1411        mut cx_a: TestAppContext,
1412        mut cx_b: TestAppContext,
1413    ) {
1414        cx_a.foreground().forbid_parking();
1415        let lang_registry = Arc::new(LanguageRegistry::new());
1416
1417        // Connect to a server as 2 clients.
1418        let mut server = TestServer::start().await;
1419        let client_a = server.create_client(&mut cx_a, "user_a").await;
1420        let client_b = server.create_client(&mut cx_b, "user_b").await;
1421
1422        // Share a local worktree as client A
1423        let fs = Arc::new(FakeFs::new());
1424        fs.insert_tree(
1425            "/dir",
1426            json!({
1427                ".zed.toml": r#"collaborators = ["user_b"]"#,
1428                "a.txt": "a-contents",
1429            }),
1430        )
1431        .await;
1432        let worktree_a = Worktree::open_local(
1433            client_a.clone(),
1434            client_a.user_store.clone(),
1435            "/dir".as_ref(),
1436            fs,
1437            lang_registry.clone(),
1438            &mut cx_a.to_async(),
1439        )
1440        .await
1441        .unwrap();
1442        worktree_a
1443            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1444            .await;
1445        let worktree_id = worktree_a
1446            .update(&mut cx_a, |tree, cx| tree.as_local_mut().unwrap().share(cx))
1447            .await
1448            .unwrap();
1449
1450        // Join that worktree as client B, and see that a guest has joined as client A.
1451        let worktree_b = Worktree::open_remote(
1452            client_b.clone(),
1453            worktree_id,
1454            lang_registry.clone(),
1455            client_b.user_store.clone(),
1456            &mut cx_b.to_async(),
1457        )
1458        .await
1459        .unwrap();
1460
1461        let buffer_a = worktree_a
1462            .update(&mut cx_a, |tree, cx| tree.open_buffer("a.txt", cx))
1463            .await
1464            .unwrap();
1465        let buffer_b = cx_b
1466            .background()
1467            .spawn(worktree_b.update(&mut cx_b, |worktree, cx| worktree.open_buffer("a.txt", cx)));
1468
1469        task::yield_now().await;
1470        buffer_a.update(&mut cx_a, |buf, cx| buf.edit([0..0], "z", cx));
1471
1472        let text = buffer_a.read_with(&cx_a, |buf, _| buf.text());
1473        let buffer_b = buffer_b.await.unwrap();
1474        buffer_b.condition(&cx_b, |buf, _| buf.text() == text).await;
1475    }
1476
1477    #[gpui::test]
1478    async fn test_leaving_worktree_while_opening_buffer(
1479        mut cx_a: TestAppContext,
1480        mut cx_b: TestAppContext,
1481    ) {
1482        cx_a.foreground().forbid_parking();
1483        let lang_registry = Arc::new(LanguageRegistry::new());
1484
1485        // Connect to a server as 2 clients.
1486        let mut server = TestServer::start().await;
1487        let client_a = server.create_client(&mut cx_a, "user_a").await;
1488        let client_b = server.create_client(&mut cx_b, "user_b").await;
1489
1490        // Share a local worktree as client A
1491        let fs = Arc::new(FakeFs::new());
1492        fs.insert_tree(
1493            "/dir",
1494            json!({
1495                ".zed.toml": r#"collaborators = ["user_b"]"#,
1496                "a.txt": "a-contents",
1497            }),
1498        )
1499        .await;
1500        let worktree_a = Worktree::open_local(
1501            client_a.clone(),
1502            client_a.user_store.clone(),
1503            "/dir".as_ref(),
1504            fs,
1505            lang_registry.clone(),
1506            &mut cx_a.to_async(),
1507        )
1508        .await
1509        .unwrap();
1510        worktree_a
1511            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1512            .await;
1513        let worktree_id = worktree_a
1514            .update(&mut cx_a, |tree, cx| tree.as_local_mut().unwrap().share(cx))
1515            .await
1516            .unwrap();
1517
1518        // Join that worktree as client B, and see that a guest has joined as client A.
1519        let worktree_b = Worktree::open_remote(
1520            client_b.clone(),
1521            worktree_id,
1522            lang_registry.clone(),
1523            client_b.user_store.clone(),
1524            &mut cx_b.to_async(),
1525        )
1526        .await
1527        .unwrap();
1528        worktree_a
1529            .condition(&cx_a, |tree, _| tree.collaborators().len() == 1)
1530            .await;
1531
1532        let buffer_b = cx_b
1533            .background()
1534            .spawn(worktree_b.update(&mut cx_b, |worktree, cx| worktree.open_buffer("a.txt", cx)));
1535        cx_b.update(|_| drop(worktree_b));
1536        drop(buffer_b);
1537        worktree_a
1538            .condition(&cx_a, |tree, _| tree.collaborators().len() == 0)
1539            .await;
1540    }
1541
1542    #[gpui::test]
1543    async fn test_peer_disconnection(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1544        cx_a.foreground().forbid_parking();
1545        let lang_registry = Arc::new(LanguageRegistry::new());
1546
1547        // Connect to a server as 2 clients.
1548        let mut server = TestServer::start().await;
1549        let client_a = server.create_client(&mut cx_a, "user_a").await;
1550        let client_b = server.create_client(&mut cx_b, "user_b").await;
1551
1552        // Share a local worktree as client A
1553        let fs = Arc::new(FakeFs::new());
1554        fs.insert_tree(
1555            "/a",
1556            json!({
1557                ".zed.toml": r#"collaborators = ["user_b"]"#,
1558                "a.txt": "a-contents",
1559                "b.txt": "b-contents",
1560            }),
1561        )
1562        .await;
1563        let worktree_a = Worktree::open_local(
1564            client_a.clone(),
1565            client_a.user_store.clone(),
1566            "/a".as_ref(),
1567            fs,
1568            lang_registry.clone(),
1569            &mut cx_a.to_async(),
1570        )
1571        .await
1572        .unwrap();
1573        worktree_a
1574            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1575            .await;
1576        let worktree_id = worktree_a
1577            .update(&mut cx_a, |tree, cx| tree.as_local_mut().unwrap().share(cx))
1578            .await
1579            .unwrap();
1580
1581        // Join that worktree as client B, and see that a guest has joined as client A.
1582        let _worktree_b = Worktree::open_remote(
1583            client_b.clone(),
1584            worktree_id,
1585            lang_registry.clone(),
1586            client_b.user_store.clone(),
1587            &mut cx_b.to_async(),
1588        )
1589        .await
1590        .unwrap();
1591        worktree_a
1592            .condition(&cx_a, |tree, _| tree.collaborators().len() == 1)
1593            .await;
1594
1595        // Drop client B's connection and ensure client A observes client B leaving the worktree.
1596        client_b.disconnect(&cx_b.to_async()).await.unwrap();
1597        worktree_a
1598            .condition(&cx_a, |tree, _| tree.collaborators().len() == 0)
1599            .await;
1600    }
1601
1602    #[gpui::test]
1603    async fn test_collaborating_with_diagnostics(
1604        mut cx_a: TestAppContext,
1605        mut cx_b: TestAppContext,
1606    ) {
1607        cx_a.foreground().forbid_parking();
1608        let (language_server_config, mut fake_language_server) =
1609            LanguageServerConfig::fake(cx_a.background()).await;
1610        let mut lang_registry = LanguageRegistry::new();
1611        lang_registry.add(Arc::new(Language::new(
1612            LanguageConfig {
1613                name: "Rust".to_string(),
1614                path_suffixes: vec!["rs".to_string()],
1615                language_server: Some(language_server_config),
1616                ..Default::default()
1617            },
1618            Some(tree_sitter_rust::language()),
1619        )));
1620
1621        let lang_registry = Arc::new(lang_registry);
1622
1623        // Connect to a server as 2 clients.
1624        let mut server = TestServer::start().await;
1625        let client_a = server.create_client(&mut cx_a, "user_a").await;
1626        let client_b = server.create_client(&mut cx_b, "user_b").await;
1627
1628        // Share a local worktree as client A
1629        let fs = Arc::new(FakeFs::new());
1630        fs.insert_tree(
1631            "/a",
1632            json!({
1633                ".zed.toml": r#"collaborators = ["user_b"]"#,
1634                "a.rs": "let one = two",
1635                "other.rs": "",
1636            }),
1637        )
1638        .await;
1639        let worktree_a = Worktree::open_local(
1640            client_a.clone(),
1641            client_a.user_store.clone(),
1642            "/a".as_ref(),
1643            fs,
1644            lang_registry.clone(),
1645            &mut cx_a.to_async(),
1646        )
1647        .await
1648        .unwrap();
1649        worktree_a
1650            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1651            .await;
1652        let worktree_id = worktree_a
1653            .update(&mut cx_a, |tree, cx| tree.as_local_mut().unwrap().share(cx))
1654            .await
1655            .unwrap();
1656
1657        // Cause language server to start.
1658        let _ = cx_a
1659            .background()
1660            .spawn(worktree_a.update(&mut cx_a, |worktree, cx| {
1661                worktree.open_buffer("other.rs", cx)
1662            }))
1663            .await
1664            .unwrap();
1665
1666        // Simulate a language server reporting errors for a file.
1667        fake_language_server
1668            .notify::<lsp::notification::PublishDiagnostics>(lsp::PublishDiagnosticsParams {
1669                uri: lsp::Url::from_file_path("/a/a.rs").unwrap(),
1670                version: None,
1671                diagnostics: vec![
1672                    lsp::Diagnostic {
1673                        severity: Some(lsp::DiagnosticSeverity::ERROR),
1674                        range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 7)),
1675                        message: "message 1".to_string(),
1676                        ..Default::default()
1677                    },
1678                    lsp::Diagnostic {
1679                        severity: Some(lsp::DiagnosticSeverity::WARNING),
1680                        range: lsp::Range::new(
1681                            lsp::Position::new(0, 10),
1682                            lsp::Position::new(0, 13),
1683                        ),
1684                        message: "message 2".to_string(),
1685                        ..Default::default()
1686                    },
1687                ],
1688            })
1689            .await;
1690
1691        // Join the worktree as client B.
1692        let worktree_b = Worktree::open_remote(
1693            client_b.clone(),
1694            worktree_id,
1695            lang_registry.clone(),
1696            client_b.user_store.clone(),
1697            &mut cx_b.to_async(),
1698        )
1699        .await
1700        .unwrap();
1701
1702        // Open the file with the errors.
1703        let buffer_b = cx_b
1704            .background()
1705            .spawn(worktree_b.update(&mut cx_b, |worktree, cx| worktree.open_buffer("a.rs", cx)))
1706            .await
1707            .unwrap();
1708
1709        buffer_b.read_with(&cx_b, |buffer, _| {
1710            assert_eq!(
1711                buffer
1712                    .snapshot()
1713                    .diagnostics_in_range::<_, Point>(0..buffer.len())
1714                    .collect::<Vec<_>>(),
1715                &[
1716                    DiagnosticEntry {
1717                        range: Point::new(0, 4)..Point::new(0, 7),
1718                        diagnostic: Diagnostic {
1719                            group_id: 0,
1720                            message: "message 1".to_string(),
1721                            severity: lsp::DiagnosticSeverity::ERROR,
1722                            is_primary: true
1723                        }
1724                    },
1725                    DiagnosticEntry {
1726                        range: Point::new(0, 10)..Point::new(0, 13),
1727                        diagnostic: Diagnostic {
1728                            group_id: 1,
1729                            severity: lsp::DiagnosticSeverity::WARNING,
1730                            message: "message 2".to_string(),
1731                            is_primary: true
1732                        }
1733                    }
1734                ]
1735            );
1736        });
1737    }
1738
1739    #[gpui::test]
1740    async fn test_basic_chat(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1741        cx_a.foreground().forbid_parking();
1742
1743        // Connect to a server as 2 clients.
1744        let mut server = TestServer::start().await;
1745        let client_a = server.create_client(&mut cx_a, "user_a").await;
1746        let client_b = server.create_client(&mut cx_b, "user_b").await;
1747
1748        // Create an org that includes these 2 users.
1749        let db = &server.app_state.db;
1750        let org_id = db.create_org("Test Org", "test-org").await.unwrap();
1751        db.add_org_member(org_id, client_a.current_user_id(&cx_a), false)
1752            .await
1753            .unwrap();
1754        db.add_org_member(org_id, client_b.current_user_id(&cx_b), false)
1755            .await
1756            .unwrap();
1757
1758        // Create a channel that includes all the users.
1759        let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
1760        db.add_channel_member(channel_id, client_a.current_user_id(&cx_a), false)
1761            .await
1762            .unwrap();
1763        db.add_channel_member(channel_id, client_b.current_user_id(&cx_b), false)
1764            .await
1765            .unwrap();
1766        db.create_channel_message(
1767            channel_id,
1768            client_b.current_user_id(&cx_b),
1769            "hello A, it's B.",
1770            OffsetDateTime::now_utc(),
1771            1,
1772        )
1773        .await
1774        .unwrap();
1775
1776        let channels_a = cx_a
1777            .add_model(|cx| ChannelList::new(client_a.user_store.clone(), client_a.clone(), cx));
1778        channels_a
1779            .condition(&mut cx_a, |list, _| list.available_channels().is_some())
1780            .await;
1781        channels_a.read_with(&cx_a, |list, _| {
1782            assert_eq!(
1783                list.available_channels().unwrap(),
1784                &[ChannelDetails {
1785                    id: channel_id.to_proto(),
1786                    name: "test-channel".to_string()
1787                }]
1788            )
1789        });
1790        let channel_a = channels_a.update(&mut cx_a, |this, cx| {
1791            this.get_channel(channel_id.to_proto(), cx).unwrap()
1792        });
1793        channel_a.read_with(&cx_a, |channel, _| assert!(channel.messages().is_empty()));
1794        channel_a
1795            .condition(&cx_a, |channel, _| {
1796                channel_messages(channel)
1797                    == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
1798            })
1799            .await;
1800
1801        let channels_b = cx_b
1802            .add_model(|cx| ChannelList::new(client_b.user_store.clone(), client_b.clone(), cx));
1803        channels_b
1804            .condition(&mut cx_b, |list, _| list.available_channels().is_some())
1805            .await;
1806        channels_b.read_with(&cx_b, |list, _| {
1807            assert_eq!(
1808                list.available_channels().unwrap(),
1809                &[ChannelDetails {
1810                    id: channel_id.to_proto(),
1811                    name: "test-channel".to_string()
1812                }]
1813            )
1814        });
1815
1816        let channel_b = channels_b.update(&mut cx_b, |this, cx| {
1817            this.get_channel(channel_id.to_proto(), cx).unwrap()
1818        });
1819        channel_b.read_with(&cx_b, |channel, _| assert!(channel.messages().is_empty()));
1820        channel_b
1821            .condition(&cx_b, |channel, _| {
1822                channel_messages(channel)
1823                    == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
1824            })
1825            .await;
1826
1827        channel_a
1828            .update(&mut cx_a, |channel, cx| {
1829                channel
1830                    .send_message("oh, hi B.".to_string(), cx)
1831                    .unwrap()
1832                    .detach();
1833                let task = channel.send_message("sup".to_string(), cx).unwrap();
1834                assert_eq!(
1835                    channel_messages(channel),
1836                    &[
1837                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
1838                        ("user_a".to_string(), "oh, hi B.".to_string(), true),
1839                        ("user_a".to_string(), "sup".to_string(), true)
1840                    ]
1841                );
1842                task
1843            })
1844            .await
1845            .unwrap();
1846
1847        channel_b
1848            .condition(&cx_b, |channel, _| {
1849                channel_messages(channel)
1850                    == [
1851                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
1852                        ("user_a".to_string(), "oh, hi B.".to_string(), false),
1853                        ("user_a".to_string(), "sup".to_string(), false),
1854                    ]
1855            })
1856            .await;
1857
1858        assert_eq!(
1859            server
1860                .state()
1861                .await
1862                .channel(channel_id)
1863                .unwrap()
1864                .connection_ids
1865                .len(),
1866            2
1867        );
1868        cx_b.update(|_| drop(channel_b));
1869        server
1870            .condition(|state| state.channel(channel_id).unwrap().connection_ids.len() == 1)
1871            .await;
1872
1873        cx_a.update(|_| drop(channel_a));
1874        server
1875            .condition(|state| state.channel(channel_id).is_none())
1876            .await;
1877    }
1878
1879    #[gpui::test]
1880    async fn test_chat_message_validation(mut cx_a: TestAppContext) {
1881        cx_a.foreground().forbid_parking();
1882
1883        let mut server = TestServer::start().await;
1884        let client_a = server.create_client(&mut cx_a, "user_a").await;
1885
1886        let db = &server.app_state.db;
1887        let org_id = db.create_org("Test Org", "test-org").await.unwrap();
1888        let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
1889        db.add_org_member(org_id, client_a.current_user_id(&cx_a), false)
1890            .await
1891            .unwrap();
1892        db.add_channel_member(channel_id, client_a.current_user_id(&cx_a), false)
1893            .await
1894            .unwrap();
1895
1896        let channels_a = cx_a
1897            .add_model(|cx| ChannelList::new(client_a.user_store.clone(), client_a.clone(), cx));
1898        channels_a
1899            .condition(&mut cx_a, |list, _| list.available_channels().is_some())
1900            .await;
1901        let channel_a = channels_a.update(&mut cx_a, |this, cx| {
1902            this.get_channel(channel_id.to_proto(), cx).unwrap()
1903        });
1904
1905        // Messages aren't allowed to be too long.
1906        channel_a
1907            .update(&mut cx_a, |channel, cx| {
1908                let long_body = "this is long.\n".repeat(1024);
1909                channel.send_message(long_body, cx).unwrap()
1910            })
1911            .await
1912            .unwrap_err();
1913
1914        // Messages aren't allowed to be blank.
1915        channel_a.update(&mut cx_a, |channel, cx| {
1916            channel.send_message(String::new(), cx).unwrap_err()
1917        });
1918
1919        // Leading and trailing whitespace are trimmed.
1920        channel_a
1921            .update(&mut cx_a, |channel, cx| {
1922                channel
1923                    .send_message("\n surrounded by whitespace  \n".to_string(), cx)
1924                    .unwrap()
1925            })
1926            .await
1927            .unwrap();
1928        assert_eq!(
1929            db.get_channel_messages(channel_id, 10, None)
1930                .await
1931                .unwrap()
1932                .iter()
1933                .map(|m| &m.body)
1934                .collect::<Vec<_>>(),
1935            &["surrounded by whitespace"]
1936        );
1937    }
1938
1939    #[gpui::test]
1940    async fn test_chat_reconnection(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1941        cx_a.foreground().forbid_parking();
1942
1943        // Connect to a server as 2 clients.
1944        let mut server = TestServer::start().await;
1945        let client_a = server.create_client(&mut cx_a, "user_a").await;
1946        let client_b = server.create_client(&mut cx_b, "user_b").await;
1947        let mut status_b = client_b.status();
1948
1949        // Create an org that includes these 2 users.
1950        let db = &server.app_state.db;
1951        let org_id = db.create_org("Test Org", "test-org").await.unwrap();
1952        db.add_org_member(org_id, client_a.current_user_id(&cx_a), false)
1953            .await
1954            .unwrap();
1955        db.add_org_member(org_id, client_b.current_user_id(&cx_b), false)
1956            .await
1957            .unwrap();
1958
1959        // Create a channel that includes all the users.
1960        let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
1961        db.add_channel_member(channel_id, client_a.current_user_id(&cx_a), false)
1962            .await
1963            .unwrap();
1964        db.add_channel_member(channel_id, client_b.current_user_id(&cx_b), false)
1965            .await
1966            .unwrap();
1967        db.create_channel_message(
1968            channel_id,
1969            client_b.current_user_id(&cx_b),
1970            "hello A, it's B.",
1971            OffsetDateTime::now_utc(),
1972            2,
1973        )
1974        .await
1975        .unwrap();
1976
1977        let channels_a = cx_a
1978            .add_model(|cx| ChannelList::new(client_a.user_store.clone(), client_a.clone(), cx));
1979        channels_a
1980            .condition(&mut cx_a, |list, _| list.available_channels().is_some())
1981            .await;
1982
1983        channels_a.read_with(&cx_a, |list, _| {
1984            assert_eq!(
1985                list.available_channels().unwrap(),
1986                &[ChannelDetails {
1987                    id: channel_id.to_proto(),
1988                    name: "test-channel".to_string()
1989                }]
1990            )
1991        });
1992        let channel_a = channels_a.update(&mut cx_a, |this, cx| {
1993            this.get_channel(channel_id.to_proto(), cx).unwrap()
1994        });
1995        channel_a.read_with(&cx_a, |channel, _| assert!(channel.messages().is_empty()));
1996        channel_a
1997            .condition(&cx_a, |channel, _| {
1998                channel_messages(channel)
1999                    == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2000            })
2001            .await;
2002
2003        let channels_b = cx_b
2004            .add_model(|cx| ChannelList::new(client_b.user_store.clone(), client_b.clone(), cx));
2005        channels_b
2006            .condition(&mut cx_b, |list, _| list.available_channels().is_some())
2007            .await;
2008        channels_b.read_with(&cx_b, |list, _| {
2009            assert_eq!(
2010                list.available_channels().unwrap(),
2011                &[ChannelDetails {
2012                    id: channel_id.to_proto(),
2013                    name: "test-channel".to_string()
2014                }]
2015            )
2016        });
2017
2018        let channel_b = channels_b.update(&mut cx_b, |this, cx| {
2019            this.get_channel(channel_id.to_proto(), cx).unwrap()
2020        });
2021        channel_b.read_with(&cx_b, |channel, _| assert!(channel.messages().is_empty()));
2022        channel_b
2023            .condition(&cx_b, |channel, _| {
2024                channel_messages(channel)
2025                    == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2026            })
2027            .await;
2028
2029        // Disconnect client B, ensuring we can still access its cached channel data.
2030        server.forbid_connections();
2031        server.disconnect_client(client_b.current_user_id(&cx_b));
2032        while !matches!(
2033            status_b.recv().await,
2034            Some(client::Status::ReconnectionError { .. })
2035        ) {}
2036
2037        channels_b.read_with(&cx_b, |channels, _| {
2038            assert_eq!(
2039                channels.available_channels().unwrap(),
2040                [ChannelDetails {
2041                    id: channel_id.to_proto(),
2042                    name: "test-channel".to_string()
2043                }]
2044            )
2045        });
2046        channel_b.read_with(&cx_b, |channel, _| {
2047            assert_eq!(
2048                channel_messages(channel),
2049                [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2050            )
2051        });
2052
2053        // Send a message from client B while it is disconnected.
2054        channel_b
2055            .update(&mut cx_b, |channel, cx| {
2056                let task = channel
2057                    .send_message("can you see this?".to_string(), cx)
2058                    .unwrap();
2059                assert_eq!(
2060                    channel_messages(channel),
2061                    &[
2062                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2063                        ("user_b".to_string(), "can you see this?".to_string(), true)
2064                    ]
2065                );
2066                task
2067            })
2068            .await
2069            .unwrap_err();
2070
2071        // Send a message from client A while B is disconnected.
2072        channel_a
2073            .update(&mut cx_a, |channel, cx| {
2074                channel
2075                    .send_message("oh, hi B.".to_string(), cx)
2076                    .unwrap()
2077                    .detach();
2078                let task = channel.send_message("sup".to_string(), cx).unwrap();
2079                assert_eq!(
2080                    channel_messages(channel),
2081                    &[
2082                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2083                        ("user_a".to_string(), "oh, hi B.".to_string(), true),
2084                        ("user_a".to_string(), "sup".to_string(), true)
2085                    ]
2086                );
2087                task
2088            })
2089            .await
2090            .unwrap();
2091
2092        // Give client B a chance to reconnect.
2093        server.allow_connections();
2094        cx_b.foreground().advance_clock(Duration::from_secs(10));
2095
2096        // Verify that B sees the new messages upon reconnection, as well as the message client B
2097        // sent while offline.
2098        channel_b
2099            .condition(&cx_b, |channel, _| {
2100                channel_messages(channel)
2101                    == [
2102                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2103                        ("user_a".to_string(), "oh, hi B.".to_string(), false),
2104                        ("user_a".to_string(), "sup".to_string(), false),
2105                        ("user_b".to_string(), "can you see this?".to_string(), false),
2106                    ]
2107            })
2108            .await;
2109
2110        // Ensure client A and B can communicate normally after reconnection.
2111        channel_a
2112            .update(&mut cx_a, |channel, cx| {
2113                channel.send_message("you online?".to_string(), cx).unwrap()
2114            })
2115            .await
2116            .unwrap();
2117        channel_b
2118            .condition(&cx_b, |channel, _| {
2119                channel_messages(channel)
2120                    == [
2121                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2122                        ("user_a".to_string(), "oh, hi B.".to_string(), false),
2123                        ("user_a".to_string(), "sup".to_string(), false),
2124                        ("user_b".to_string(), "can you see this?".to_string(), false),
2125                        ("user_a".to_string(), "you online?".to_string(), false),
2126                    ]
2127            })
2128            .await;
2129
2130        channel_b
2131            .update(&mut cx_b, |channel, cx| {
2132                channel.send_message("yep".to_string(), cx).unwrap()
2133            })
2134            .await
2135            .unwrap();
2136        channel_a
2137            .condition(&cx_a, |channel, _| {
2138                channel_messages(channel)
2139                    == [
2140                        ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2141                        ("user_a".to_string(), "oh, hi B.".to_string(), false),
2142                        ("user_a".to_string(), "sup".to_string(), false),
2143                        ("user_b".to_string(), "can you see this?".to_string(), false),
2144                        ("user_a".to_string(), "you online?".to_string(), false),
2145                        ("user_b".to_string(), "yep".to_string(), false),
2146                    ]
2147            })
2148            .await;
2149    }
2150
2151    #[gpui::test]
2152    async fn test_contacts(
2153        mut cx_a: TestAppContext,
2154        mut cx_b: TestAppContext,
2155        mut cx_c: TestAppContext,
2156    ) {
2157        cx_a.foreground().forbid_parking();
2158        let lang_registry = Arc::new(LanguageRegistry::new());
2159
2160        // Connect to a server as 3 clients.
2161        let mut server = TestServer::start().await;
2162        let client_a = server.create_client(&mut cx_a, "user_a").await;
2163        let client_b = server.create_client(&mut cx_b, "user_b").await;
2164        let client_c = server.create_client(&mut cx_c, "user_c").await;
2165
2166        let fs = Arc::new(FakeFs::new());
2167
2168        // Share a worktree as client A.
2169        fs.insert_tree(
2170            "/a",
2171            json!({
2172                ".zed.toml": r#"collaborators = ["user_b", "user_c"]"#,
2173            }),
2174        )
2175        .await;
2176
2177        let worktree_a = Worktree::open_local(
2178            client_a.clone(),
2179            client_a.user_store.clone(),
2180            "/a".as_ref(),
2181            fs.clone(),
2182            lang_registry.clone(),
2183            &mut cx_a.to_async(),
2184        )
2185        .await
2186        .unwrap();
2187
2188        client_a
2189            .user_store
2190            .condition(&cx_a, |user_store, _| {
2191                contacts(user_store) == vec![("user_a", vec![("a", vec![])])]
2192            })
2193            .await;
2194        client_b
2195            .user_store
2196            .condition(&cx_b, |user_store, _| {
2197                contacts(user_store) == vec![("user_a", vec![("a", vec![])])]
2198            })
2199            .await;
2200        client_c
2201            .user_store
2202            .condition(&cx_c, |user_store, _| {
2203                contacts(user_store) == vec![("user_a", vec![("a", vec![])])]
2204            })
2205            .await;
2206
2207        let worktree_id = worktree_a
2208            .update(&mut cx_a, |tree, cx| tree.as_local_mut().unwrap().share(cx))
2209            .await
2210            .unwrap();
2211
2212        let _worktree_b = Worktree::open_remote(
2213            client_b.clone(),
2214            worktree_id,
2215            lang_registry.clone(),
2216            client_b.user_store.clone(),
2217            &mut cx_b.to_async(),
2218        )
2219        .await
2220        .unwrap();
2221
2222        client_a
2223            .user_store
2224            .condition(&cx_a, |user_store, _| {
2225                contacts(user_store) == vec![("user_a", vec![("a", vec!["user_b"])])]
2226            })
2227            .await;
2228        client_b
2229            .user_store
2230            .condition(&cx_b, |user_store, _| {
2231                contacts(user_store) == vec![("user_a", vec![("a", vec!["user_b"])])]
2232            })
2233            .await;
2234        client_c
2235            .user_store
2236            .condition(&cx_c, |user_store, _| {
2237                contacts(user_store) == vec![("user_a", vec![("a", vec!["user_b"])])]
2238            })
2239            .await;
2240
2241        worktree_a
2242            .condition(&cx_a, |worktree, _| {
2243                worktree.collaborators().contains_key(&client_b.peer_id)
2244            })
2245            .await;
2246
2247        cx_a.update(move |_| drop(worktree_a));
2248        client_a
2249            .user_store
2250            .condition(&cx_a, |user_store, _| contacts(user_store) == vec![])
2251            .await;
2252        client_b
2253            .user_store
2254            .condition(&cx_b, |user_store, _| contacts(user_store) == vec![])
2255            .await;
2256        client_c
2257            .user_store
2258            .condition(&cx_c, |user_store, _| contacts(user_store) == vec![])
2259            .await;
2260
2261        fn contacts(user_store: &UserStore) -> Vec<(&str, Vec<(&str, Vec<&str>)>)> {
2262            user_store
2263                .contacts()
2264                .iter()
2265                .map(|contact| {
2266                    let worktrees = contact
2267                        .worktrees
2268                        .iter()
2269                        .map(|w| {
2270                            (
2271                                w.root_name.as_str(),
2272                                w.guests.iter().map(|p| p.github_login.as_str()).collect(),
2273                            )
2274                        })
2275                        .collect();
2276                    (contact.user.github_login.as_str(), worktrees)
2277                })
2278                .collect()
2279        }
2280    }
2281
2282    struct TestServer {
2283        peer: Arc<Peer>,
2284        app_state: Arc<AppState>,
2285        server: Arc<Server>,
2286        notifications: mpsc::Receiver<()>,
2287        connection_killers: Arc<Mutex<HashMap<UserId, watch::Sender<Option<()>>>>>,
2288        forbid_connections: Arc<AtomicBool>,
2289        _test_db: TestDb,
2290    }
2291
2292    impl TestServer {
2293        async fn start() -> Self {
2294            let test_db = TestDb::new();
2295            let app_state = Self::build_app_state(&test_db).await;
2296            let peer = Peer::new();
2297            let notifications = mpsc::channel(128);
2298            let server = Server::new(app_state.clone(), peer.clone(), Some(notifications.0));
2299            Self {
2300                peer,
2301                app_state,
2302                server,
2303                notifications: notifications.1,
2304                connection_killers: Default::default(),
2305                forbid_connections: Default::default(),
2306                _test_db: test_db,
2307            }
2308        }
2309
2310        async fn create_client(&mut self, cx: &mut TestAppContext, name: &str) -> TestClient {
2311            let user_id = self.app_state.db.create_user(name, false).await.unwrap();
2312            let client_name = name.to_string();
2313            let mut client = Client::new();
2314            let server = self.server.clone();
2315            let connection_killers = self.connection_killers.clone();
2316            let forbid_connections = self.forbid_connections.clone();
2317            let (connection_id_tx, mut connection_id_rx) = postage::mpsc::channel(16);
2318
2319            Arc::get_mut(&mut client)
2320                .unwrap()
2321                .override_authenticate(move |cx| {
2322                    cx.spawn(|_| async move {
2323                        let access_token = "the-token".to_string();
2324                        Ok(Credentials {
2325                            user_id: user_id.0 as u64,
2326                            access_token,
2327                        })
2328                    })
2329                })
2330                .override_establish_connection(move |credentials, cx| {
2331                    assert_eq!(credentials.user_id, user_id.0 as u64);
2332                    assert_eq!(credentials.access_token, "the-token");
2333
2334                    let server = server.clone();
2335                    let connection_killers = connection_killers.clone();
2336                    let forbid_connections = forbid_connections.clone();
2337                    let client_name = client_name.clone();
2338                    let connection_id_tx = connection_id_tx.clone();
2339                    cx.spawn(move |cx| async move {
2340                        if forbid_connections.load(SeqCst) {
2341                            Err(EstablishConnectionError::other(anyhow!(
2342                                "server is forbidding connections"
2343                            )))
2344                        } else {
2345                            let (client_conn, server_conn, kill_conn) = Connection::in_memory();
2346                            connection_killers.lock().insert(user_id, kill_conn);
2347                            cx.background()
2348                                .spawn(server.handle_connection(
2349                                    server_conn,
2350                                    client_name,
2351                                    user_id,
2352                                    Some(connection_id_tx),
2353                                ))
2354                                .detach();
2355                            Ok(client_conn)
2356                        }
2357                    })
2358                });
2359
2360            let http = FakeHttpClient::new(|_| async move { Ok(surf::http::Response::new(404)) });
2361            client
2362                .authenticate_and_connect(&cx.to_async())
2363                .await
2364                .unwrap();
2365
2366            let peer_id = PeerId(connection_id_rx.recv().await.unwrap().0);
2367            let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http, cx));
2368            let mut authed_user =
2369                user_store.read_with(cx, |user_store, _| user_store.watch_current_user());
2370            while authed_user.recv().await.unwrap().is_none() {}
2371
2372            TestClient {
2373                client,
2374                peer_id,
2375                user_store,
2376            }
2377        }
2378
2379        fn disconnect_client(&self, user_id: UserId) {
2380            if let Some(mut kill_conn) = self.connection_killers.lock().remove(&user_id) {
2381                let _ = kill_conn.try_send(Some(()));
2382            }
2383        }
2384
2385        fn forbid_connections(&self) {
2386            self.forbid_connections.store(true, SeqCst);
2387        }
2388
2389        fn allow_connections(&self) {
2390            self.forbid_connections.store(false, SeqCst);
2391        }
2392
2393        async fn build_app_state(test_db: &TestDb) -> Arc<AppState> {
2394            let mut config = Config::default();
2395            config.session_secret = "a".repeat(32);
2396            config.database_url = test_db.url.clone();
2397            let github_client = github::AppClient::test();
2398            Arc::new(AppState {
2399                db: test_db.db().clone(),
2400                handlebars: Default::default(),
2401                auth_client: auth::build_client("", ""),
2402                repo_client: github::RepoClient::test(&github_client),
2403                github_client,
2404                config,
2405            })
2406        }
2407
2408        async fn state<'a>(&'a self) -> RwLockReadGuard<'a, Store> {
2409            self.server.store.read()
2410        }
2411
2412        async fn condition<F>(&mut self, mut predicate: F)
2413        where
2414            F: FnMut(&Store) -> bool,
2415        {
2416            async_std::future::timeout(Duration::from_millis(500), async {
2417                while !(predicate)(&*self.server.store.read()) {
2418                    self.notifications.recv().await;
2419                }
2420            })
2421            .await
2422            .expect("condition timed out");
2423        }
2424    }
2425
2426    impl Drop for TestServer {
2427        fn drop(&mut self) {
2428            task::block_on(self.peer.reset());
2429        }
2430    }
2431
2432    struct TestClient {
2433        client: Arc<Client>,
2434        pub peer_id: PeerId,
2435        pub user_store: ModelHandle<UserStore>,
2436    }
2437
2438    impl Deref for TestClient {
2439        type Target = Arc<Client>;
2440
2441        fn deref(&self) -> &Self::Target {
2442            &self.client
2443        }
2444    }
2445
2446    impl TestClient {
2447        pub fn current_user_id(&self, cx: &TestAppContext) -> UserId {
2448            UserId::from_proto(
2449                self.user_store
2450                    .read_with(cx, |user_store, _| user_store.current_user().unwrap().id),
2451            )
2452        }
2453    }
2454
2455    fn channel_messages(channel: &Channel) -> Vec<(String, String, bool)> {
2456        channel
2457            .messages()
2458            .cursor::<()>()
2459            .map(|m| {
2460                (
2461                    m.sender.github_login.clone(),
2462                    m.body.clone(),
2463                    m.is_pending(),
2464                )
2465            })
2466            .collect()
2467    }
2468
2469    struct EmptyView;
2470
2471    impl gpui::Entity for EmptyView {
2472        type Event = ();
2473    }
2474
2475    impl gpui::View for EmptyView {
2476        fn ui_name() -> &'static str {
2477            "empty view"
2478        }
2479
2480        fn render(&mut self, _: &mut gpui::RenderContext<Self>) -> gpui::ElementBox {
2481            gpui::Element::boxed(gpui::elements::Empty)
2482        }
2483    }
2484}