rpc.rs

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