rpc.rs

   1use super::{
   2    auth,
   3    db::{ChannelId, UserId},
   4    AppState,
   5};
   6use anyhow::anyhow;
   7use async_std::{sync::RwLock, task};
   8use async_tungstenite::{
   9    tungstenite::{protocol::Role, Error as WebSocketError, Message as WebSocketMessage},
  10    WebSocketStream,
  11};
  12use futures::{future::BoxFuture, FutureExt};
  13use postage::{mpsc, prelude::Sink as _, prelude::Stream as _};
  14use sha1::{Digest as _, Sha1};
  15use std::{
  16    any::TypeId,
  17    collections::{hash_map, HashMap, HashSet},
  18    future::Future,
  19    mem,
  20    sync::Arc,
  21    time::Instant,
  22};
  23use surf::StatusCode;
  24use tide::log;
  25use tide::{
  26    http::headers::{HeaderName, CONNECTION, UPGRADE},
  27    Request, Response,
  28};
  29use time::OffsetDateTime;
  30use zrpc::{
  31    auth::random_token,
  32    proto::{self, AnyTypedEnvelope, EnvelopedMessage},
  33    ConnectionId, Peer, TypedEnvelope,
  34};
  35
  36type ReplicaId = u16;
  37
  38type MessageHandler = Box<
  39    dyn Send
  40        + Sync
  41        + Fn(Arc<Server>, Box<dyn AnyTypedEnvelope>) -> BoxFuture<'static, tide::Result<()>>,
  42>;
  43
  44pub struct Server {
  45    peer: Arc<Peer>,
  46    state: RwLock<ServerState>,
  47    app_state: Arc<AppState>,
  48    handlers: HashMap<TypeId, MessageHandler>,
  49    notifications: Option<mpsc::Sender<()>>,
  50}
  51
  52#[derive(Default)]
  53struct ServerState {
  54    connections: HashMap<ConnectionId, Connection>,
  55    pub worktrees: HashMap<u64, Worktree>,
  56    channels: HashMap<ChannelId, Channel>,
  57    next_worktree_id: u64,
  58}
  59
  60struct Connection {
  61    user_id: UserId,
  62    worktrees: HashSet<u64>,
  63    channels: HashSet<ChannelId>,
  64}
  65
  66struct Worktree {
  67    host_connection_id: Option<ConnectionId>,
  68    guest_connection_ids: HashMap<ConnectionId, ReplicaId>,
  69    active_replica_ids: HashSet<ReplicaId>,
  70    access_token: String,
  71    root_name: String,
  72    entries: HashMap<u64, proto::Entry>,
  73}
  74
  75#[derive(Default)]
  76struct Channel {
  77    connection_ids: HashSet<ConnectionId>,
  78}
  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::share_worktree)
  96            .add_handler(Server::join_worktree)
  97            .add_handler(Server::update_worktree)
  98            .add_handler(Server::close_worktree)
  99            .add_handler(Server::open_buffer)
 100            .add_handler(Server::close_buffer)
 101            .add_handler(Server::update_buffer)
 102            .add_handler(Server::buffer_saved)
 103            .add_handler(Server::save_buffer)
 104            .add_handler(Server::get_channels)
 105            .add_handler(Server::get_users)
 106            .add_handler(Server::join_channel)
 107            .add_handler(Server::leave_channel)
 108            .add_handler(Server::send_channel_message);
 109
 110        Arc::new(server)
 111    }
 112
 113    fn add_handler<F, Fut, M>(&mut self, handler: F) -> &mut Self
 114    where
 115        F: 'static + Send + Sync + Fn(Arc<Self>, TypedEnvelope<M>) -> Fut,
 116        Fut: 'static + Send + Future<Output = tide::Result<()>>,
 117        M: EnvelopedMessage,
 118    {
 119        let prev_handler = self.handlers.insert(
 120            TypeId::of::<M>(),
 121            Box::new(move |server, envelope| {
 122                let envelope = envelope.into_any().downcast::<TypedEnvelope<M>>().unwrap();
 123                (handler)(server, *envelope).boxed()
 124            }),
 125        );
 126        if prev_handler.is_some() {
 127            panic!("registered a handler for the same message twice");
 128        }
 129        self
 130    }
 131
 132    pub fn handle_connection<Conn>(
 133        self: &Arc<Self>,
 134        connection: Conn,
 135        addr: String,
 136        user_id: UserId,
 137    ) -> impl Future<Output = ()>
 138    where
 139        Conn: 'static
 140            + futures::Sink<WebSocketMessage, Error = WebSocketError>
 141            + futures::Stream<Item = Result<WebSocketMessage, WebSocketError>>
 142            + Send
 143            + Unpin,
 144    {
 145        let this = self.clone();
 146        async move {
 147            let (connection_id, handle_io, mut incoming_rx) =
 148                this.peer.add_connection(connection).await;
 149            this.add_connection(connection_id, user_id).await;
 150
 151            let handle_io = handle_io.fuse();
 152            futures::pin_mut!(handle_io);
 153            loop {
 154                let next_message = incoming_rx.recv().fuse();
 155                futures::pin_mut!(next_message);
 156                futures::select_biased! {
 157                    message = next_message => {
 158                        if let Some(message) = message {
 159                            let start_time = Instant::now();
 160                            log::info!("RPC message received: {}", message.payload_type_name());
 161                            if let Some(handler) = this.handlers.get(&message.payload_type_id()) {
 162                                if let Err(err) = (handler)(this.clone(), message).await {
 163                                    log::error!("error handling message: {:?}", err);
 164                                } else {
 165                                    log::info!("RPC message handled. duration:{:?}", start_time.elapsed());
 166                                }
 167
 168                                if let Some(mut notifications) = this.notifications.clone() {
 169                                    let _ = notifications.send(()).await;
 170                                }
 171                            } else {
 172                                log::warn!("unhandled message: {}", message.payload_type_name());
 173                            }
 174                        } else {
 175                            log::info!("rpc connection closed {:?}", addr);
 176                            break;
 177                        }
 178                    }
 179                    handle_io = handle_io => {
 180                        if let Err(err) = handle_io {
 181                            log::error!("error handling rpc connection {:?} - {:?}", addr, err);
 182                        }
 183                        break;
 184                    }
 185                }
 186            }
 187
 188            if let Err(err) = this.sign_out(connection_id).await {
 189                log::error!("error signing out connection {:?} - {:?}", addr, err);
 190            }
 191        }
 192    }
 193
 194    async fn sign_out(self: &Arc<Self>, connection_id: zrpc::ConnectionId) -> tide::Result<()> {
 195        self.peer.disconnect(connection_id).await;
 196        let worktree_ids = self.remove_connection(connection_id).await;
 197        for worktree_id in worktree_ids {
 198            let state = self.state.read().await;
 199            if let Some(worktree) = state.worktrees.get(&worktree_id) {
 200                broadcast(connection_id, worktree.connection_ids(), |conn_id| {
 201                    self.peer.send(
 202                        conn_id,
 203                        proto::RemovePeer {
 204                            worktree_id,
 205                            peer_id: connection_id.0,
 206                        },
 207                    )
 208                })
 209                .await?;
 210            }
 211        }
 212        Ok(())
 213    }
 214
 215    // Add a new connection associated with a given user.
 216    async fn add_connection(&self, connection_id: ConnectionId, user_id: UserId) {
 217        self.state.write().await.connections.insert(
 218            connection_id,
 219            Connection {
 220                user_id,
 221                worktrees: Default::default(),
 222                channels: Default::default(),
 223            },
 224        );
 225    }
 226
 227    // Remove the given connection and its association with any worktrees.
 228    async fn remove_connection(&self, connection_id: ConnectionId) -> Vec<u64> {
 229        let mut worktree_ids = Vec::new();
 230        let mut state = self.state.write().await;
 231        if let Some(connection) = state.connections.remove(&connection_id) {
 232            for channel_id in connection.channels {
 233                if let Some(channel) = state.channels.get_mut(&channel_id) {
 234                    channel.connection_ids.remove(&connection_id);
 235                }
 236            }
 237            for worktree_id in connection.worktrees {
 238                if let Some(worktree) = state.worktrees.get_mut(&worktree_id) {
 239                    if worktree.host_connection_id == Some(connection_id) {
 240                        worktree_ids.push(worktree_id);
 241                    } else if let Some(replica_id) =
 242                        worktree.guest_connection_ids.remove(&connection_id)
 243                    {
 244                        worktree.active_replica_ids.remove(&replica_id);
 245                        worktree_ids.push(worktree_id);
 246                    }
 247                }
 248            }
 249        }
 250        worktree_ids
 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    }
 504
 505    async fn buffer_saved(
 506        self: Arc<Server>,
 507        request: TypedEnvelope<proto::BufferSaved>,
 508    ) -> tide::Result<()> {
 509        self.broadcast_in_worktree(request.payload.worktree_id, &request)
 510            .await
 511    }
 512
 513    async fn get_channels(
 514        self: Arc<Server>,
 515        request: TypedEnvelope<proto::GetChannels>,
 516    ) -> tide::Result<()> {
 517        let user_id = self
 518            .state
 519            .read()
 520            .await
 521            .user_id_for_connection(request.sender_id)?;
 522        let channels = self.app_state.db.get_channels_for_user(user_id).await?;
 523        self.peer
 524            .respond(
 525                request.receipt(),
 526                proto::GetChannelsResponse {
 527                    channels: channels
 528                        .into_iter()
 529                        .map(|chan| proto::Channel {
 530                            id: chan.id.to_proto(),
 531                            name: chan.name,
 532                        })
 533                        .collect(),
 534                },
 535            )
 536            .await?;
 537        Ok(())
 538    }
 539
 540    async fn get_users(
 541        self: Arc<Server>,
 542        request: TypedEnvelope<proto::GetUsers>,
 543    ) -> tide::Result<()> {
 544        let user_id = self
 545            .state
 546            .read()
 547            .await
 548            .user_id_for_connection(request.sender_id)?;
 549        let receipt = request.receipt();
 550        let user_ids = request.payload.user_ids.into_iter().map(UserId::from_proto);
 551        let users = self
 552            .app_state
 553            .db
 554            .get_users_by_ids(user_id, user_ids)
 555            .await?
 556            .into_iter()
 557            .map(|user| proto::User {
 558                id: user.id.to_proto(),
 559                github_login: user.github_login,
 560                avatar_url: String::new(),
 561            })
 562            .collect();
 563        self.peer
 564            .respond(receipt, proto::GetUsersResponse { users })
 565            .await?;
 566        Ok(())
 567    }
 568
 569    async fn join_channel(
 570        self: Arc<Self>,
 571        request: TypedEnvelope<proto::JoinChannel>,
 572    ) -> tide::Result<()> {
 573        let user_id = self
 574            .state
 575            .read()
 576            .await
 577            .user_id_for_connection(request.sender_id)?;
 578        let channel_id = ChannelId::from_proto(request.payload.channel_id);
 579        if !self
 580            .app_state
 581            .db
 582            .can_user_access_channel(user_id, channel_id)
 583            .await?
 584        {
 585            Err(anyhow!("access denied"))?;
 586        }
 587
 588        self.state
 589            .write()
 590            .await
 591            .join_channel(request.sender_id, channel_id);
 592        let messages = self
 593            .app_state
 594            .db
 595            .get_recent_channel_messages(channel_id, 50)
 596            .await?
 597            .into_iter()
 598            .map(|msg| proto::ChannelMessage {
 599                id: msg.id.to_proto(),
 600                body: msg.body,
 601                timestamp: msg.sent_at.unix_timestamp() as u64,
 602                sender_id: msg.sender_id.to_proto(),
 603            })
 604            .collect();
 605        self.peer
 606            .respond(request.receipt(), proto::JoinChannelResponse { messages })
 607            .await?;
 608        Ok(())
 609    }
 610
 611    async fn leave_channel(
 612        self: Arc<Self>,
 613        request: TypedEnvelope<proto::LeaveChannel>,
 614    ) -> tide::Result<()> {
 615        let user_id = self
 616            .state
 617            .read()
 618            .await
 619            .user_id_for_connection(request.sender_id)?;
 620        let channel_id = ChannelId::from_proto(request.payload.channel_id);
 621        if !self
 622            .app_state
 623            .db
 624            .can_user_access_channel(user_id, channel_id)
 625            .await?
 626        {
 627            Err(anyhow!("access denied"))?;
 628        }
 629
 630        self.state
 631            .write()
 632            .await
 633            .leave_channel(request.sender_id, channel_id);
 634
 635        Ok(())
 636    }
 637
 638    async fn send_channel_message(
 639        self: Arc<Self>,
 640        request: TypedEnvelope<proto::SendChannelMessage>,
 641    ) -> tide::Result<()> {
 642        let channel_id = ChannelId::from_proto(request.payload.channel_id);
 643        let user_id;
 644        let connection_ids;
 645        {
 646            let state = self.state.read().await;
 647            user_id = state.user_id_for_connection(request.sender_id)?;
 648            if let Some(channel) = state.channels.get(&channel_id) {
 649                connection_ids = channel.connection_ids();
 650            } else {
 651                return Ok(());
 652            }
 653        }
 654
 655        let timestamp = OffsetDateTime::now_utc();
 656        let message_id = self
 657            .app_state
 658            .db
 659            .create_channel_message(channel_id, user_id, &request.payload.body, timestamp)
 660            .await?
 661            .to_proto();
 662        let receipt = request.receipt();
 663        let message = proto::ChannelMessageSent {
 664            channel_id: channel_id.to_proto(),
 665            message: Some(proto::ChannelMessage {
 666                sender_id: user_id.to_proto(),
 667                id: message_id,
 668                body: request.payload.body,
 669                timestamp: timestamp.unix_timestamp() as u64,
 670            }),
 671        };
 672        broadcast(request.sender_id, connection_ids, |conn_id| {
 673            self.peer.send(conn_id, message.clone())
 674        })
 675        .await?;
 676        self.peer
 677            .respond(
 678                receipt,
 679                proto::SendChannelMessageResponse {
 680                    message_id,
 681                    timestamp: timestamp.unix_timestamp() as u64,
 682                },
 683            )
 684            .await?;
 685        Ok(())
 686    }
 687
 688    async fn broadcast_in_worktree<T: proto::EnvelopedMessage>(
 689        &self,
 690        worktree_id: u64,
 691        message: &TypedEnvelope<T>,
 692    ) -> tide::Result<()> {
 693        let connection_ids = self
 694            .state
 695            .read()
 696            .await
 697            .read_worktree(worktree_id, message.sender_id)?
 698            .connection_ids();
 699
 700        broadcast(message.sender_id, connection_ids, |conn_id| {
 701            self.peer
 702                .forward_send(message.sender_id, conn_id, message.payload.clone())
 703        })
 704        .await?;
 705
 706        Ok(())
 707    }
 708}
 709
 710pub async fn broadcast<F, T>(
 711    sender_id: ConnectionId,
 712    receiver_ids: Vec<ConnectionId>,
 713    mut f: F,
 714) -> anyhow::Result<()>
 715where
 716    F: FnMut(ConnectionId) -> T,
 717    T: Future<Output = anyhow::Result<()>>,
 718{
 719    let futures = receiver_ids
 720        .into_iter()
 721        .filter(|id| *id != sender_id)
 722        .map(|id| f(id));
 723    futures::future::try_join_all(futures).await?;
 724    Ok(())
 725}
 726
 727impl ServerState {
 728    fn join_channel(&mut self, connection_id: ConnectionId, channel_id: ChannelId) {
 729        if let Some(connection) = self.connections.get_mut(&connection_id) {
 730            connection.channels.insert(channel_id);
 731            self.channels
 732                .entry(channel_id)
 733                .or_default()
 734                .connection_ids
 735                .insert(connection_id);
 736        }
 737    }
 738
 739    fn leave_channel(&mut self, connection_id: ConnectionId, channel_id: ChannelId) {
 740        if let Some(connection) = self.connections.get_mut(&connection_id) {
 741            connection.channels.remove(&channel_id);
 742            if let hash_map::Entry::Occupied(mut entry) = self.channels.entry(channel_id) {
 743                entry.get_mut().connection_ids.remove(&connection_id);
 744                if entry.get_mut().connection_ids.is_empty() {
 745                    entry.remove();
 746                }
 747            }
 748        }
 749    }
 750
 751    fn user_id_for_connection(&self, connection_id: ConnectionId) -> tide::Result<UserId> {
 752        Ok(self
 753            .connections
 754            .get(&connection_id)
 755            .ok_or_else(|| anyhow!("unknown connection"))?
 756            .user_id)
 757    }
 758
 759    // Add the given connection as a guest of the given worktree
 760    fn join_worktree(
 761        &mut self,
 762        connection_id: ConnectionId,
 763        worktree_id: u64,
 764        access_token: &str,
 765    ) -> Option<(ReplicaId, &Worktree)> {
 766        if let Some(worktree) = self.worktrees.get_mut(&worktree_id) {
 767            if access_token == worktree.access_token {
 768                if let Some(connection) = self.connections.get_mut(&connection_id) {
 769                    connection.worktrees.insert(worktree_id);
 770                }
 771
 772                let mut replica_id = 1;
 773                while worktree.active_replica_ids.contains(&replica_id) {
 774                    replica_id += 1;
 775                }
 776                worktree.active_replica_ids.insert(replica_id);
 777                worktree
 778                    .guest_connection_ids
 779                    .insert(connection_id, replica_id);
 780                Some((replica_id, worktree))
 781            } else {
 782                None
 783            }
 784        } else {
 785            None
 786        }
 787    }
 788
 789    fn read_worktree(
 790        &self,
 791        worktree_id: u64,
 792        connection_id: ConnectionId,
 793    ) -> tide::Result<&Worktree> {
 794        let worktree = self
 795            .worktrees
 796            .get(&worktree_id)
 797            .ok_or_else(|| anyhow!("worktree not found"))?;
 798
 799        if worktree.host_connection_id == Some(connection_id)
 800            || worktree.guest_connection_ids.contains_key(&connection_id)
 801        {
 802            Ok(worktree)
 803        } else {
 804            Err(anyhow!(
 805                "{} is not a member of worktree {}",
 806                connection_id,
 807                worktree_id
 808            ))?
 809        }
 810    }
 811
 812    fn write_worktree(
 813        &mut self,
 814        worktree_id: u64,
 815        connection_id: ConnectionId,
 816    ) -> tide::Result<&mut Worktree> {
 817        let worktree = self
 818            .worktrees
 819            .get_mut(&worktree_id)
 820            .ok_or_else(|| anyhow!("worktree not found"))?;
 821
 822        if worktree.host_connection_id == Some(connection_id)
 823            || worktree.guest_connection_ids.contains_key(&connection_id)
 824        {
 825            Ok(worktree)
 826        } else {
 827            Err(anyhow!(
 828                "{} is not a member of worktree {}",
 829                connection_id,
 830                worktree_id
 831            ))?
 832        }
 833    }
 834}
 835
 836impl Worktree {
 837    pub fn connection_ids(&self) -> Vec<ConnectionId> {
 838        self.guest_connection_ids
 839            .keys()
 840            .copied()
 841            .chain(self.host_connection_id)
 842            .collect()
 843    }
 844
 845    fn host_connection_id(&self) -> tide::Result<ConnectionId> {
 846        Ok(self
 847            .host_connection_id
 848            .ok_or_else(|| anyhow!("host disconnected from worktree"))?)
 849    }
 850}
 851
 852impl Channel {
 853    fn connection_ids(&self) -> Vec<ConnectionId> {
 854        self.connection_ids.iter().copied().collect()
 855    }
 856}
 857
 858pub fn add_routes(app: &mut tide::Server<Arc<AppState>>, rpc: &Arc<Peer>) {
 859    let server = Server::new(app.state().clone(), rpc.clone(), None);
 860    app.at("/rpc").with(auth::VerifyToken).get(move |request: Request<Arc<AppState>>| {
 861        let user_id = request.ext::<UserId>().copied();
 862        let server = server.clone();
 863        async move {
 864            const WEBSOCKET_GUID: &str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
 865
 866            let connection_upgrade = header_contains_ignore_case(&request, CONNECTION, "upgrade");
 867            let upgrade_to_websocket = header_contains_ignore_case(&request, UPGRADE, "websocket");
 868            let upgrade_requested = connection_upgrade && upgrade_to_websocket;
 869
 870            if !upgrade_requested {
 871                return Ok(Response::new(StatusCode::UpgradeRequired));
 872            }
 873
 874            let header = match request.header("Sec-Websocket-Key") {
 875                Some(h) => h.as_str(),
 876                None => return Err(anyhow!("expected sec-websocket-key"))?,
 877            };
 878
 879            let mut response = Response::new(StatusCode::SwitchingProtocols);
 880            response.insert_header(UPGRADE, "websocket");
 881            response.insert_header(CONNECTION, "Upgrade");
 882            let hash = Sha1::new().chain(header).chain(WEBSOCKET_GUID).finalize();
 883            response.insert_header("Sec-Websocket-Accept", base64::encode(&hash[..]));
 884            response.insert_header("Sec-Websocket-Version", "13");
 885
 886            let http_res: &mut tide::http::Response = response.as_mut();
 887            let upgrade_receiver = http_res.recv_upgrade().await;
 888            let addr = request.remote().unwrap_or("unknown").to_string();
 889            let user_id = user_id.ok_or_else(|| anyhow!("user_id is not present on request. ensure auth::VerifyToken middleware is present"))?;
 890            task::spawn(async move {
 891                if let Some(stream) = upgrade_receiver.await {
 892                    let stream = WebSocketStream::from_raw_socket(stream, Role::Server, None).await;
 893                    server.handle_connection(stream, addr, user_id).await;
 894                }
 895            });
 896
 897            Ok(response)
 898        }
 899    });
 900}
 901
 902fn header_contains_ignore_case<T>(
 903    request: &tide::Request<T>,
 904    header_name: HeaderName,
 905    value: &str,
 906) -> bool {
 907    request
 908        .header(header_name)
 909        .map(|h| {
 910            h.as_str()
 911                .split(',')
 912                .any(|s| s.trim().eq_ignore_ascii_case(value.trim()))
 913        })
 914        .unwrap_or(false)
 915}
 916
 917#[cfg(test)]
 918mod tests {
 919    use super::*;
 920    use crate::{
 921        auth,
 922        db::{self, UserId},
 923        github, AppState, Config,
 924    };
 925    use async_std::{
 926        sync::RwLockReadGuard,
 927        task::{self, block_on},
 928    };
 929    use gpui::TestAppContext;
 930    use postage::mpsc;
 931    use rand::prelude::*;
 932    use serde_json::json;
 933    use sqlx::{migrate::MigrateDatabase, types::time::OffsetDateTime, Postgres};
 934    use std::{path::Path, sync::Arc, time::Duration};
 935    use zed::{
 936        channel::{Channel, ChannelDetails, ChannelList},
 937        editor::{Editor, Insert},
 938        fs::{FakeFs, Fs as _},
 939        language::LanguageRegistry,
 940        rpc::Client,
 941        settings, test,
 942        user::UserStore,
 943        worktree::Worktree,
 944    };
 945    use zrpc::Peer;
 946
 947    #[gpui::test]
 948    async fn test_share_worktree(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
 949        let (window_b, _) = cx_b.add_window(|_| EmptyView);
 950        let settings = settings::channel(&cx_b.font_cache()).unwrap().1;
 951        let lang_registry = Arc::new(LanguageRegistry::new());
 952
 953        // Connect to a server as 2 clients.
 954        let mut server = TestServer::start().await;
 955        let (_, client_a) = server.create_client(&mut cx_a, "user_a").await;
 956        let (_, client_b) = server.create_client(&mut cx_b, "user_b").await;
 957
 958        cx_a.foreground().forbid_parking();
 959
 960        // Share a local worktree as client A
 961        let fs = Arc::new(FakeFs::new());
 962        fs.insert_tree(
 963            "/a",
 964            json!({
 965                "a.txt": "a-contents",
 966                "b.txt": "b-contents",
 967            }),
 968        )
 969        .await;
 970        let worktree_a = Worktree::open_local(
 971            "/a".as_ref(),
 972            lang_registry.clone(),
 973            fs,
 974            &mut cx_a.to_async(),
 975        )
 976        .await
 977        .unwrap();
 978        worktree_a
 979            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
 980            .await;
 981        let (worktree_id, worktree_token) = worktree_a
 982            .update(&mut cx_a, |tree, cx| {
 983                tree.as_local_mut().unwrap().share(client_a.clone(), cx)
 984            })
 985            .await
 986            .unwrap();
 987
 988        // Join that worktree as client B, and see that a guest has joined as client A.
 989        let worktree_b = Worktree::open_remote(
 990            client_b.clone(),
 991            worktree_id,
 992            worktree_token,
 993            lang_registry.clone(),
 994            &mut cx_b.to_async(),
 995        )
 996        .await
 997        .unwrap();
 998        let replica_id_b = worktree_b.read_with(&cx_b, |tree, _| tree.replica_id());
 999        worktree_a
1000            .condition(&cx_a, |tree, _| {
1001                tree.peers()
1002                    .values()
1003                    .any(|replica_id| *replica_id == replica_id_b)
1004            })
1005            .await;
1006
1007        // Open the same file as client B and client A.
1008        let buffer_b = worktree_b
1009            .update(&mut cx_b, |worktree, cx| worktree.open_buffer("b.txt", cx))
1010            .await
1011            .unwrap();
1012        buffer_b.read_with(&cx_b, |buf, _| assert_eq!(buf.text(), "b-contents"));
1013        worktree_a.read_with(&cx_a, |tree, cx| assert!(tree.has_open_buffer("b.txt", cx)));
1014        let buffer_a = worktree_a
1015            .update(&mut cx_a, |tree, cx| tree.open_buffer("b.txt", cx))
1016            .await
1017            .unwrap();
1018
1019        // Create a selection set as client B and see that selection set as client A.
1020        let editor_b = cx_b.add_view(window_b, |cx| Editor::for_buffer(buffer_b, settings, cx));
1021        buffer_a
1022            .condition(&cx_a, |buffer, _| buffer.selection_sets().count() == 1)
1023            .await;
1024
1025        // Edit the buffer as client B and see that edit as client A.
1026        editor_b.update(&mut cx_b, |editor, cx| {
1027            editor.insert(&Insert("ok, ".into()), cx)
1028        });
1029        buffer_a
1030            .condition(&cx_a, |buffer, _| buffer.text() == "ok, b-contents")
1031            .await;
1032
1033        // Remove the selection set as client B, see those selections disappear as client A.
1034        cx_b.update(move |_| drop(editor_b));
1035        buffer_a
1036            .condition(&cx_a, |buffer, _| buffer.selection_sets().count() == 0)
1037            .await;
1038
1039        // Close the buffer as client A, see that the buffer is closed.
1040        drop(buffer_a);
1041        worktree_a
1042            .condition(&cx_a, |tree, cx| !tree.has_open_buffer("b.txt", cx))
1043            .await;
1044
1045        // Dropping the worktree removes client B from client A's peers.
1046        cx_b.update(move |_| drop(worktree_b));
1047        worktree_a
1048            .condition(&cx_a, |tree, _| tree.peers().is_empty())
1049            .await;
1050    }
1051
1052    #[gpui::test]
1053    async fn test_propagate_saves_and_fs_changes_in_shared_worktree(
1054        mut cx_a: TestAppContext,
1055        mut cx_b: TestAppContext,
1056        mut cx_c: TestAppContext,
1057    ) {
1058        cx_a.foreground().forbid_parking();
1059        let lang_registry = Arc::new(LanguageRegistry::new());
1060
1061        // Connect to a server as 3 clients.
1062        let mut server = TestServer::start().await;
1063        let (_, client_a) = server.create_client(&mut cx_a, "user_a").await;
1064        let (_, client_b) = server.create_client(&mut cx_b, "user_b").await;
1065        let (_, client_c) = server.create_client(&mut cx_c, "user_c").await;
1066
1067        let fs = Arc::new(FakeFs::new());
1068
1069        // Share a worktree as client A.
1070        fs.insert_tree(
1071            "/a",
1072            json!({
1073                "file1": "",
1074                "file2": ""
1075            }),
1076        )
1077        .await;
1078
1079        let worktree_a = Worktree::open_local(
1080            "/a".as_ref(),
1081            lang_registry.clone(),
1082            fs.clone(),
1083            &mut cx_a.to_async(),
1084        )
1085        .await
1086        .unwrap();
1087        worktree_a
1088            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1089            .await;
1090        let (worktree_id, worktree_token) = worktree_a
1091            .update(&mut cx_a, |tree, cx| {
1092                tree.as_local_mut().unwrap().share(client_a.clone(), cx)
1093            })
1094            .await
1095            .unwrap();
1096
1097        // Join that worktree as clients B and C.
1098        let worktree_b = Worktree::open_remote(
1099            client_b.clone(),
1100            worktree_id,
1101            worktree_token.clone(),
1102            lang_registry.clone(),
1103            &mut cx_b.to_async(),
1104        )
1105        .await
1106        .unwrap();
1107        let worktree_c = Worktree::open_remote(
1108            client_c.clone(),
1109            worktree_id,
1110            worktree_token,
1111            lang_registry.clone(),
1112            &mut cx_c.to_async(),
1113        )
1114        .await
1115        .unwrap();
1116
1117        // Open and edit a buffer as both guests B and C.
1118        let buffer_b = worktree_b
1119            .update(&mut cx_b, |tree, cx| tree.open_buffer("file1", cx))
1120            .await
1121            .unwrap();
1122        let buffer_c = worktree_c
1123            .update(&mut cx_c, |tree, cx| tree.open_buffer("file1", cx))
1124            .await
1125            .unwrap();
1126        buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "i-am-b, ", cx));
1127        buffer_c.update(&mut cx_c, |buf, cx| buf.edit([0..0], "i-am-c, ", cx));
1128
1129        // Open and edit that buffer as the host.
1130        let buffer_a = worktree_a
1131            .update(&mut cx_a, |tree, cx| tree.open_buffer("file1", cx))
1132            .await
1133            .unwrap();
1134
1135        buffer_a
1136            .condition(&mut cx_a, |buf, _| buf.text() == "i-am-c, i-am-b, ")
1137            .await;
1138        buffer_a.update(&mut cx_a, |buf, cx| {
1139            buf.edit([buf.len()..buf.len()], "i-am-a", cx)
1140        });
1141
1142        // Wait for edits to propagate
1143        buffer_a
1144            .condition(&mut cx_a, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1145            .await;
1146        buffer_b
1147            .condition(&mut cx_b, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1148            .await;
1149        buffer_c
1150            .condition(&mut cx_c, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1151            .await;
1152
1153        // Edit the buffer as the host and concurrently save as guest B.
1154        let save_b = buffer_b.update(&mut cx_b, |buf, cx| buf.save(cx).unwrap());
1155        buffer_a.update(&mut cx_a, |buf, cx| buf.edit([0..0], "hi-a, ", cx));
1156        save_b.await.unwrap();
1157        assert_eq!(
1158            fs.load("/a/file1".as_ref()).await.unwrap(),
1159            "hi-a, i-am-c, i-am-b, i-am-a"
1160        );
1161        buffer_a.read_with(&cx_a, |buf, _| assert!(!buf.is_dirty()));
1162        buffer_b.read_with(&cx_b, |buf, _| assert!(!buf.is_dirty()));
1163        buffer_c.condition(&cx_c, |buf, _| !buf.is_dirty()).await;
1164
1165        // Make changes on host's file system, see those changes on the guests.
1166        fs.rename("/a/file2".as_ref(), "/a/file3".as_ref())
1167            .await
1168            .unwrap();
1169        fs.insert_file(Path::new("/a/file4"), "4".into())
1170            .await
1171            .unwrap();
1172
1173        worktree_b
1174            .condition(&cx_b, |tree, _| tree.file_count() == 3)
1175            .await;
1176        worktree_c
1177            .condition(&cx_c, |tree, _| tree.file_count() == 3)
1178            .await;
1179        worktree_b.read_with(&cx_b, |tree, _| {
1180            assert_eq!(
1181                tree.paths()
1182                    .map(|p| p.to_string_lossy())
1183                    .collect::<Vec<_>>(),
1184                &["file1", "file3", "file4"]
1185            )
1186        });
1187        worktree_c.read_with(&cx_c, |tree, _| {
1188            assert_eq!(
1189                tree.paths()
1190                    .map(|p| p.to_string_lossy())
1191                    .collect::<Vec<_>>(),
1192                &["file1", "file3", "file4"]
1193            )
1194        });
1195    }
1196
1197    #[gpui::test]
1198    async fn test_buffer_conflict_after_save(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1199        cx_a.foreground().forbid_parking();
1200        let lang_registry = Arc::new(LanguageRegistry::new());
1201
1202        // Connect to a server as 2 clients.
1203        let mut server = TestServer::start().await;
1204        let (_, client_a) = server.create_client(&mut cx_a, "user_a").await;
1205        let (_, client_b) = server.create_client(&mut cx_b, "user_b").await;
1206
1207        // Share a local worktree as client A
1208        let fs = Arc::new(FakeFs::new());
1209        fs.save(Path::new("/a.txt"), &"a-contents".into())
1210            .await
1211            .unwrap();
1212        let worktree_a = Worktree::open_local(
1213            "/".as_ref(),
1214            lang_registry.clone(),
1215            fs,
1216            &mut cx_a.to_async(),
1217        )
1218        .await
1219        .unwrap();
1220        worktree_a
1221            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1222            .await;
1223        let (worktree_id, worktree_token) = worktree_a
1224            .update(&mut cx_a, |tree, cx| {
1225                tree.as_local_mut().unwrap().share(client_a.clone(), cx)
1226            })
1227            .await
1228            .unwrap();
1229
1230        // Join that worktree as client B, and see that a guest has joined as client A.
1231        let worktree_b = Worktree::open_remote(
1232            client_b.clone(),
1233            worktree_id,
1234            worktree_token,
1235            lang_registry.clone(),
1236            &mut cx_b.to_async(),
1237        )
1238        .await
1239        .unwrap();
1240
1241        let buffer_b = worktree_b
1242            .update(&mut cx_b, |worktree, cx| worktree.open_buffer("a.txt", cx))
1243            .await
1244            .unwrap();
1245        let mtime = buffer_b.read_with(&cx_b, |buf, _| buf.file().unwrap().mtime);
1246
1247        buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "world ", cx));
1248        buffer_b.read_with(&cx_b, |buf, _| {
1249            assert!(buf.is_dirty());
1250            assert!(!buf.has_conflict());
1251        });
1252
1253        buffer_b
1254            .update(&mut cx_b, |buf, cx| buf.save(cx))
1255            .unwrap()
1256            .await
1257            .unwrap();
1258        worktree_b
1259            .condition(&cx_b, |_, cx| {
1260                buffer_b.read(cx).file().unwrap().mtime != mtime
1261            })
1262            .await;
1263        buffer_b.read_with(&cx_b, |buf, _| {
1264            assert!(!buf.is_dirty());
1265            assert!(!buf.has_conflict());
1266        });
1267
1268        buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "hello ", cx));
1269        buffer_b.read_with(&cx_b, |buf, _| {
1270            assert!(buf.is_dirty());
1271            assert!(!buf.has_conflict());
1272        });
1273    }
1274
1275    #[gpui::test]
1276    async fn test_editing_while_guest_opens_buffer(
1277        mut cx_a: TestAppContext,
1278        mut cx_b: TestAppContext,
1279    ) {
1280        cx_a.foreground().forbid_parking();
1281        let lang_registry = Arc::new(LanguageRegistry::new());
1282
1283        // Connect to a server as 2 clients.
1284        let mut server = TestServer::start().await;
1285        let (_, client_a) = server.create_client(&mut cx_a, "user_a").await;
1286        let (_, client_b) = server.create_client(&mut cx_b, "user_b").await;
1287
1288        // Share a local worktree as client A
1289        let fs = Arc::new(FakeFs::new());
1290        fs.save(Path::new("/a.txt"), &"a-contents".into())
1291            .await
1292            .unwrap();
1293        let worktree_a = Worktree::open_local(
1294            "/".as_ref(),
1295            lang_registry.clone(),
1296            fs,
1297            &mut cx_a.to_async(),
1298        )
1299        .await
1300        .unwrap();
1301        worktree_a
1302            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1303            .await;
1304        let (worktree_id, worktree_token) = worktree_a
1305            .update(&mut cx_a, |tree, cx| {
1306                tree.as_local_mut().unwrap().share(client_a.clone(), cx)
1307            })
1308            .await
1309            .unwrap();
1310
1311        // Join that worktree as client B, and see that a guest has joined as client A.
1312        let worktree_b = Worktree::open_remote(
1313            client_b.clone(),
1314            worktree_id,
1315            worktree_token,
1316            lang_registry.clone(),
1317            &mut cx_b.to_async(),
1318        )
1319        .await
1320        .unwrap();
1321
1322        let buffer_a = worktree_a
1323            .update(&mut cx_a, |tree, cx| tree.open_buffer("a.txt", cx))
1324            .await
1325            .unwrap();
1326        let buffer_b = cx_b
1327            .background()
1328            .spawn(worktree_b.update(&mut cx_b, |worktree, cx| worktree.open_buffer("a.txt", cx)));
1329
1330        task::yield_now().await;
1331        buffer_a.update(&mut cx_a, |buf, cx| buf.edit([0..0], "z", cx));
1332
1333        let text = buffer_a.read_with(&cx_a, |buf, _| buf.text());
1334        let buffer_b = buffer_b.await.unwrap();
1335        buffer_b.condition(&cx_b, |buf, _| buf.text() == text).await;
1336    }
1337
1338    #[gpui::test]
1339    async fn test_peer_disconnection(mut cx_a: TestAppContext, cx_b: TestAppContext) {
1340        cx_a.foreground().forbid_parking();
1341        let lang_registry = Arc::new(LanguageRegistry::new());
1342
1343        // Connect to a server as 2 clients.
1344        let mut server = TestServer::start().await;
1345        let (_, client_a) = server.create_client(&mut cx_a, "user_a").await;
1346        let (_, client_b) = server.create_client(&mut cx_a, "user_b").await;
1347
1348        // Share a local worktree as client A
1349        let fs = Arc::new(FakeFs::new());
1350        fs.insert_tree(
1351            "/a",
1352            json!({
1353                "a.txt": "a-contents",
1354                "b.txt": "b-contents",
1355            }),
1356        )
1357        .await;
1358        let worktree_a = Worktree::open_local(
1359            "/a".as_ref(),
1360            lang_registry.clone(),
1361            fs,
1362            &mut cx_a.to_async(),
1363        )
1364        .await
1365        .unwrap();
1366        worktree_a
1367            .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1368            .await;
1369        let (worktree_id, worktree_token) = worktree_a
1370            .update(&mut cx_a, |tree, cx| {
1371                tree.as_local_mut().unwrap().share(client_a.clone(), cx)
1372            })
1373            .await
1374            .unwrap();
1375
1376        // Join that worktree as client B, and see that a guest has joined as client A.
1377        let _worktree_b = Worktree::open_remote(
1378            client_b.clone(),
1379            worktree_id,
1380            worktree_token,
1381            lang_registry.clone(),
1382            &mut cx_b.to_async(),
1383        )
1384        .await
1385        .unwrap();
1386        worktree_a
1387            .condition(&cx_a, |tree, _| tree.peers().len() == 1)
1388            .await;
1389
1390        // Drop client B's connection and ensure client A observes client B leaving the worktree.
1391        client_b.disconnect().await.unwrap();
1392        worktree_a
1393            .condition(&cx_a, |tree, _| tree.peers().len() == 0)
1394            .await;
1395    }
1396
1397    #[gpui::test]
1398    async fn test_basic_chat(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1399        cx_a.foreground().forbid_parking();
1400
1401        // Connect to a server as 2 clients.
1402        let mut server = TestServer::start().await;
1403        let (user_id_a, client_a) = server.create_client(&mut cx_a, "user_a").await;
1404        let (user_id_b, client_b) = server.create_client(&mut cx_b, "user_b").await;
1405
1406        // Create an org that includes these 2 users.
1407        let db = &server.app_state.db;
1408        let org_id = db.create_org("Test Org", "test-org").await.unwrap();
1409        db.add_org_member(org_id, user_id_a, false).await.unwrap();
1410        db.add_org_member(org_id, user_id_b, false).await.unwrap();
1411
1412        // Create a channel that includes all the users.
1413        let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
1414        db.add_channel_member(channel_id, user_id_a, false)
1415            .await
1416            .unwrap();
1417        db.add_channel_member(channel_id, user_id_b, false)
1418            .await
1419            .unwrap();
1420        db.create_channel_message(
1421            channel_id,
1422            user_id_b,
1423            "hello A, it's B.",
1424            OffsetDateTime::now_utc(),
1425        )
1426        .await
1427        .unwrap();
1428
1429        let user_store_a = Arc::new(UserStore::new(client_a.clone()));
1430        let channels_a = cx_a.add_model(|cx| ChannelList::new(user_store_a, client_a, cx));
1431        channels_a
1432            .condition(&mut cx_a, |list, _| list.available_channels().is_some())
1433            .await;
1434        channels_a.read_with(&cx_a, |list, _| {
1435            assert_eq!(
1436                list.available_channels().unwrap(),
1437                &[ChannelDetails {
1438                    id: channel_id.to_proto(),
1439                    name: "test-channel".to_string()
1440                }]
1441            )
1442        });
1443        let channel_a = channels_a.update(&mut cx_a, |this, cx| {
1444            this.get_channel(channel_id.to_proto(), cx).unwrap()
1445        });
1446        channel_a.read_with(&cx_a, |channel, _| assert!(channel.messages().is_empty()));
1447        channel_a
1448            .condition(&cx_a, |channel, _| {
1449                channel_messages(channel)
1450                    == [("user_b".to_string(), "hello A, it's B.".to_string())]
1451            })
1452            .await;
1453
1454        let user_store_b = Arc::new(UserStore::new(client_b.clone()));
1455        let channels_b = cx_b.add_model(|cx| ChannelList::new(user_store_b, client_b, cx));
1456        channels_b
1457            .condition(&mut cx_b, |list, _| list.available_channels().is_some())
1458            .await;
1459        channels_b.read_with(&cx_b, |list, _| {
1460            assert_eq!(
1461                list.available_channels().unwrap(),
1462                &[ChannelDetails {
1463                    id: channel_id.to_proto(),
1464                    name: "test-channel".to_string()
1465                }]
1466            )
1467        });
1468
1469        let channel_b = channels_b.update(&mut cx_b, |this, cx| {
1470            this.get_channel(channel_id.to_proto(), cx).unwrap()
1471        });
1472        channel_b.read_with(&cx_b, |channel, _| assert!(channel.messages().is_empty()));
1473        channel_b
1474            .condition(&cx_b, |channel, _| {
1475                channel_messages(channel)
1476                    == [("user_b".to_string(), "hello A, it's B.".to_string())]
1477            })
1478            .await;
1479
1480        channel_a.update(&mut cx_a, |channel, cx| {
1481            channel.send_message("oh, hi B.".to_string(), cx).unwrap();
1482            channel.send_message("sup".to_string(), cx).unwrap();
1483            assert_eq!(
1484                channel
1485                    .pending_messages()
1486                    .iter()
1487                    .map(|m| &m.body)
1488                    .collect::<Vec<_>>(),
1489                &["oh, hi B.", "sup"]
1490            )
1491        });
1492
1493        channel_a
1494            .condition(&cx_a, |channel, _| channel.pending_messages().is_empty())
1495            .await;
1496        channel_b
1497            .condition(&cx_b, |channel, _| {
1498                channel_messages(channel)
1499                    == [
1500                        ("user_b".to_string(), "hello A, it's B.".to_string()),
1501                        ("user_a".to_string(), "oh, hi B.".to_string()),
1502                        ("user_a".to_string(), "sup".to_string()),
1503                    ]
1504            })
1505            .await;
1506
1507        assert_eq!(
1508            server.state().await.channels[&channel_id]
1509                .connection_ids
1510                .len(),
1511            2
1512        );
1513        cx_b.update(|_| drop(channel_b));
1514        server
1515            .condition(|state| state.channels[&channel_id].connection_ids.len() == 1)
1516            .await;
1517
1518        cx_a.update(|_| drop(channel_a));
1519        server
1520            .condition(|state| !state.channels.contains_key(&channel_id))
1521            .await;
1522
1523        fn channel_messages(channel: &Channel) -> Vec<(String, String)> {
1524            channel
1525                .messages()
1526                .cursor::<(), ()>()
1527                .map(|m| (m.sender.github_login.clone(), m.body.clone()))
1528                .collect()
1529        }
1530    }
1531
1532    struct TestServer {
1533        peer: Arc<Peer>,
1534        app_state: Arc<AppState>,
1535        server: Arc<Server>,
1536        db_name: String,
1537        notifications: mpsc::Receiver<()>,
1538    }
1539
1540    impl TestServer {
1541        async fn start() -> Self {
1542            let mut rng = StdRng::from_entropy();
1543            let db_name = format!("zed-test-{}", rng.gen::<u128>());
1544            let app_state = Self::build_app_state(&db_name).await;
1545            let peer = Peer::new();
1546            let notifications = mpsc::channel(128);
1547            let server = Server::new(app_state.clone(), peer.clone(), Some(notifications.0));
1548            Self {
1549                peer,
1550                app_state,
1551                server,
1552                db_name,
1553                notifications: notifications.1,
1554            }
1555        }
1556
1557        async fn create_client(
1558            &mut self,
1559            cx: &mut TestAppContext,
1560            name: &str,
1561        ) -> (UserId, Arc<Client>) {
1562            let user_id = self.app_state.db.create_user(name, false).await.unwrap();
1563            let client = Client::new();
1564            let (client_conn, server_conn) = test::Channel::bidirectional();
1565            cx.background()
1566                .spawn(
1567                    self.server
1568                        .handle_connection(server_conn, name.to_string(), user_id),
1569                )
1570                .detach();
1571            client
1572                .add_connection(user_id.to_proto(), client_conn, cx.to_async())
1573                .await
1574                .unwrap();
1575            (user_id, client)
1576        }
1577
1578        async fn build_app_state(db_name: &str) -> Arc<AppState> {
1579            let mut config = Config::default();
1580            config.session_secret = "a".repeat(32);
1581            config.database_url = format!("postgres://postgres@localhost/{}", db_name);
1582
1583            Self::create_db(&config.database_url);
1584            let db = db::Db::test(&config.database_url, 5);
1585            db.migrate(Path::new(concat!(
1586                env!("CARGO_MANIFEST_DIR"),
1587                "/migrations"
1588            )));
1589
1590            let github_client = github::AppClient::test();
1591            Arc::new(AppState {
1592                db,
1593                handlebars: Default::default(),
1594                auth_client: auth::build_client("", ""),
1595                repo_client: github::RepoClient::test(&github_client),
1596                github_client,
1597                config,
1598            })
1599        }
1600
1601        fn create_db(url: &str) {
1602            // Enable tests to run in parallel by serializing the creation of each test database.
1603            lazy_static::lazy_static! {
1604                static ref DB_CREATION: std::sync::Mutex<()> = std::sync::Mutex::new(());
1605            }
1606
1607            let _lock = DB_CREATION.lock();
1608            block_on(Postgres::create_database(url)).expect("failed to create test database");
1609        }
1610
1611        async fn state<'a>(&'a self) -> RwLockReadGuard<'a, ServerState> {
1612            self.server.state.read().await
1613        }
1614
1615        async fn condition<F>(&mut self, mut predicate: F)
1616        where
1617            F: FnMut(&ServerState) -> bool,
1618        {
1619            async_std::future::timeout(Duration::from_millis(500), async {
1620                while !(predicate)(&*self.server.state.read().await) {
1621                    self.notifications.recv().await;
1622                }
1623            })
1624            .await
1625            .expect("condition timed out");
1626        }
1627    }
1628
1629    impl Drop for TestServer {
1630        fn drop(&mut self) {
1631            task::block_on(async {
1632                self.peer.reset().await;
1633                self.app_state.db.close(&self.db_name).await;
1634                Postgres::drop_database(&self.app_state.config.database_url)
1635                    .await
1636                    .unwrap();
1637            });
1638        }
1639    }
1640
1641    struct EmptyView;
1642
1643    impl gpui::Entity for EmptyView {
1644        type Event = ();
1645    }
1646
1647    impl gpui::View for EmptyView {
1648        fn ui_name() -> &'static str {
1649            "empty view"
1650        }
1651
1652        fn render<'a>(&self, _: &gpui::RenderContext<Self>) -> gpui::ElementBox {
1653            gpui::Element::boxed(gpui::elements::Empty)
1654        }
1655    }
1656}