store.rs

   1use crate::db::{self, ChannelId, ProjectId, UserId};
   2use anyhow::{anyhow, Result};
   3use collections::{btree_map, BTreeMap, BTreeSet, HashMap, HashSet};
   4use nanoid::nanoid;
   5use rpc::{proto, ConnectionId};
   6use serde::Serialize;
   7use std::{borrow::Cow, mem, path::PathBuf, str, time::Duration};
   8use time::OffsetDateTime;
   9use tracing::instrument;
  10use util::post_inc;
  11
  12pub type RoomId = u64;
  13
  14#[derive(Default, Serialize)]
  15pub struct Store {
  16    connections: BTreeMap<ConnectionId, ConnectionState>,
  17    connected_users: BTreeMap<UserId, ConnectedUser>,
  18    next_room_id: RoomId,
  19    rooms: BTreeMap<RoomId, proto::Room>,
  20    projects: BTreeMap<ProjectId, Project>,
  21    #[serde(skip)]
  22    channels: BTreeMap<ChannelId, Channel>,
  23}
  24
  25#[derive(Default, Serialize)]
  26struct ConnectedUser {
  27    connection_ids: HashSet<ConnectionId>,
  28    active_call: Option<Call>,
  29}
  30
  31#[derive(Serialize)]
  32struct ConnectionState {
  33    user_id: UserId,
  34    admin: bool,
  35    projects: BTreeSet<ProjectId>,
  36    channels: HashSet<ChannelId>,
  37}
  38
  39#[derive(Copy, Clone, Eq, PartialEq, Serialize)]
  40pub struct Call {
  41    pub caller_user_id: UserId,
  42    pub room_id: RoomId,
  43    pub connection_id: Option<ConnectionId>,
  44    pub initial_project_id: Option<ProjectId>,
  45}
  46
  47#[derive(Serialize)]
  48pub struct Project {
  49    pub id: ProjectId,
  50    pub room_id: RoomId,
  51    pub host_connection_id: ConnectionId,
  52    pub host: Collaborator,
  53    pub guests: HashMap<ConnectionId, Collaborator>,
  54    pub active_replica_ids: HashSet<ReplicaId>,
  55    pub worktrees: BTreeMap<u64, Worktree>,
  56    pub language_servers: Vec<proto::LanguageServer>,
  57}
  58
  59#[derive(Serialize)]
  60pub struct Collaborator {
  61    pub replica_id: ReplicaId,
  62    pub user_id: UserId,
  63    #[serde(skip)]
  64    pub last_activity: Option<OffsetDateTime>,
  65    pub admin: bool,
  66}
  67
  68#[derive(Default, Serialize)]
  69pub struct Worktree {
  70    pub abs_path: PathBuf,
  71    pub root_name: String,
  72    pub visible: bool,
  73    #[serde(skip)]
  74    pub entries: BTreeMap<u64, proto::Entry>,
  75    #[serde(skip)]
  76    pub diagnostic_summaries: BTreeMap<PathBuf, proto::DiagnosticSummary>,
  77    pub scan_id: u64,
  78    pub is_complete: bool,
  79}
  80
  81#[derive(Default)]
  82pub struct Channel {
  83    pub connection_ids: HashSet<ConnectionId>,
  84}
  85
  86pub type ReplicaId = u16;
  87
  88#[derive(Default)]
  89pub struct RemovedConnectionState<'a> {
  90    pub user_id: UserId,
  91    pub hosted_projects: Vec<Project>,
  92    pub guest_projects: Vec<LeftProject>,
  93    pub contact_ids: HashSet<UserId>,
  94    pub room: Option<Cow<'a, proto::Room>>,
  95    pub canceled_call_connection_ids: Vec<ConnectionId>,
  96}
  97
  98pub struct LeftProject {
  99    pub id: ProjectId,
 100    pub host_user_id: UserId,
 101    pub host_connection_id: ConnectionId,
 102    pub connection_ids: Vec<ConnectionId>,
 103    pub remove_collaborator: bool,
 104}
 105
 106pub struct LeftRoom<'a> {
 107    pub room: Cow<'a, proto::Room>,
 108    pub unshared_projects: Vec<Project>,
 109    pub left_projects: Vec<LeftProject>,
 110    pub canceled_call_connection_ids: Vec<ConnectionId>,
 111}
 112
 113#[derive(Copy, Clone)]
 114pub struct Metrics {
 115    pub connections: usize,
 116    pub registered_projects: usize,
 117    pub active_projects: usize,
 118    pub shared_projects: usize,
 119}
 120
 121impl Store {
 122    pub fn metrics(&self) -> Metrics {
 123        const ACTIVE_PROJECT_TIMEOUT: Duration = Duration::from_secs(60);
 124        let active_window_start = OffsetDateTime::now_utc() - ACTIVE_PROJECT_TIMEOUT;
 125
 126        let connections = self.connections.values().filter(|c| !c.admin).count();
 127        let mut registered_projects = 0;
 128        let mut active_projects = 0;
 129        let mut shared_projects = 0;
 130        for project in self.projects.values() {
 131            if let Some(connection) = self.connections.get(&project.host_connection_id) {
 132                if !connection.admin {
 133                    registered_projects += 1;
 134                    if project.is_active_since(active_window_start) {
 135                        active_projects += 1;
 136                        if !project.guests.is_empty() {
 137                            shared_projects += 1;
 138                        }
 139                    }
 140                }
 141            }
 142        }
 143
 144        Metrics {
 145            connections,
 146            registered_projects,
 147            active_projects,
 148            shared_projects,
 149        }
 150    }
 151
 152    #[instrument(skip(self))]
 153    pub fn add_connection(
 154        &mut self,
 155        connection_id: ConnectionId,
 156        user_id: UserId,
 157        admin: bool,
 158    ) -> Option<proto::IncomingCall> {
 159        self.connections.insert(
 160            connection_id,
 161            ConnectionState {
 162                user_id,
 163                admin,
 164                projects: Default::default(),
 165                channels: Default::default(),
 166            },
 167        );
 168        let connected_user = self.connected_users.entry(user_id).or_default();
 169        connected_user.connection_ids.insert(connection_id);
 170        if let Some(active_call) = connected_user.active_call {
 171            if active_call.connection_id.is_some() {
 172                None
 173            } else {
 174                let room = self.room(active_call.room_id)?;
 175                Some(proto::IncomingCall {
 176                    room_id: active_call.room_id,
 177                    caller_user_id: active_call.caller_user_id.to_proto(),
 178                    participant_user_ids: room
 179                        .participants
 180                        .iter()
 181                        .map(|participant| participant.user_id)
 182                        .collect(),
 183                    initial_project: active_call
 184                        .initial_project_id
 185                        .and_then(|id| Self::build_participant_project(id, &self.projects)),
 186                })
 187            }
 188        } else {
 189            None
 190        }
 191    }
 192
 193    #[instrument(skip(self))]
 194    pub fn remove_connection(
 195        &mut self,
 196        connection_id: ConnectionId,
 197    ) -> Result<RemovedConnectionState> {
 198        let connection = self
 199            .connections
 200            .get_mut(&connection_id)
 201            .ok_or_else(|| anyhow!("no such connection"))?;
 202
 203        let user_id = connection.user_id;
 204        let connection_channels = mem::take(&mut connection.channels);
 205
 206        let mut result = RemovedConnectionState {
 207            user_id,
 208            ..Default::default()
 209        };
 210
 211        // Leave all channels.
 212        for channel_id in connection_channels {
 213            self.leave_channel(connection_id, channel_id);
 214        }
 215
 216        let connected_user = self.connected_users.get(&user_id).unwrap();
 217        if let Some(active_call) = connected_user.active_call.as_ref() {
 218            let room_id = active_call.room_id;
 219            if active_call.connection_id == Some(connection_id) {
 220                let left_room = self.leave_room(room_id, connection_id)?;
 221                result.hosted_projects = left_room.unshared_projects;
 222                result.guest_projects = left_room.left_projects;
 223                result.room = Some(Cow::Owned(left_room.room.into_owned()));
 224                result.canceled_call_connection_ids = left_room.canceled_call_connection_ids;
 225            } else if connected_user.connection_ids.len() == 1 {
 226                let (room, _) = self.decline_call(room_id, connection_id)?;
 227                result.room = Some(Cow::Owned(room.clone()));
 228            }
 229        }
 230
 231        let connected_user = self.connected_users.get_mut(&user_id).unwrap();
 232        connected_user.connection_ids.remove(&connection_id);
 233        if connected_user.connection_ids.is_empty() {
 234            self.connected_users.remove(&user_id);
 235        }
 236        self.connections.remove(&connection_id).unwrap();
 237
 238        Ok(result)
 239    }
 240
 241    #[cfg(test)]
 242    pub fn channel(&self, id: ChannelId) -> Option<&Channel> {
 243        self.channels.get(&id)
 244    }
 245
 246    pub fn join_channel(&mut self, connection_id: ConnectionId, channel_id: ChannelId) {
 247        if let Some(connection) = self.connections.get_mut(&connection_id) {
 248            connection.channels.insert(channel_id);
 249            self.channels
 250                .entry(channel_id)
 251                .or_default()
 252                .connection_ids
 253                .insert(connection_id);
 254        }
 255    }
 256
 257    pub fn leave_channel(&mut self, connection_id: ConnectionId, channel_id: ChannelId) {
 258        if let Some(connection) = self.connections.get_mut(&connection_id) {
 259            connection.channels.remove(&channel_id);
 260            if let btree_map::Entry::Occupied(mut entry) = self.channels.entry(channel_id) {
 261                entry.get_mut().connection_ids.remove(&connection_id);
 262                if entry.get_mut().connection_ids.is_empty() {
 263                    entry.remove();
 264                }
 265            }
 266        }
 267    }
 268
 269    pub fn user_id_for_connection(&self, connection_id: ConnectionId) -> Result<UserId> {
 270        Ok(self
 271            .connections
 272            .get(&connection_id)
 273            .ok_or_else(|| anyhow!("unknown connection"))?
 274            .user_id)
 275    }
 276
 277    pub fn connection_ids_for_user(
 278        &self,
 279        user_id: UserId,
 280    ) -> impl Iterator<Item = ConnectionId> + '_ {
 281        self.connected_users
 282            .get(&user_id)
 283            .into_iter()
 284            .map(|state| &state.connection_ids)
 285            .flatten()
 286            .copied()
 287    }
 288
 289    pub fn is_user_online(&self, user_id: UserId) -> bool {
 290        !self
 291            .connected_users
 292            .get(&user_id)
 293            .unwrap_or(&Default::default())
 294            .connection_ids
 295            .is_empty()
 296    }
 297
 298    fn is_user_busy(&self, user_id: UserId) -> bool {
 299        self.connected_users
 300            .get(&user_id)
 301            .unwrap_or(&Default::default())
 302            .active_call
 303            .is_some()
 304    }
 305
 306    pub fn build_initial_contacts_update(
 307        &self,
 308        contacts: Vec<db::Contact>,
 309    ) -> proto::UpdateContacts {
 310        let mut update = proto::UpdateContacts::default();
 311
 312        for contact in contacts {
 313            match contact {
 314                db::Contact::Accepted {
 315                    user_id,
 316                    should_notify,
 317                } => {
 318                    update
 319                        .contacts
 320                        .push(self.contact_for_user(user_id, should_notify));
 321                }
 322                db::Contact::Outgoing { user_id } => {
 323                    update.outgoing_requests.push(user_id.to_proto())
 324                }
 325                db::Contact::Incoming {
 326                    user_id,
 327                    should_notify,
 328                } => update
 329                    .incoming_requests
 330                    .push(proto::IncomingContactRequest {
 331                        requester_id: user_id.to_proto(),
 332                        should_notify,
 333                    }),
 334            }
 335        }
 336
 337        update
 338    }
 339
 340    pub fn contact_for_user(&self, user_id: UserId, should_notify: bool) -> proto::Contact {
 341        proto::Contact {
 342            user_id: user_id.to_proto(),
 343            online: self.is_user_online(user_id),
 344            busy: self.is_user_busy(user_id),
 345            should_notify,
 346        }
 347    }
 348
 349    pub fn create_room(&mut self, creator_connection_id: ConnectionId) -> Result<&proto::Room> {
 350        let connection = self
 351            .connections
 352            .get_mut(&creator_connection_id)
 353            .ok_or_else(|| anyhow!("no such connection"))?;
 354        let connected_user = self
 355            .connected_users
 356            .get_mut(&connection.user_id)
 357            .ok_or_else(|| anyhow!("no such connection"))?;
 358        anyhow::ensure!(
 359            connected_user.active_call.is_none(),
 360            "can't create a room with an active call"
 361        );
 362
 363        let room_id = post_inc(&mut self.next_room_id);
 364        let room = proto::Room {
 365            id: room_id,
 366            participants: vec![proto::Participant {
 367                user_id: connection.user_id.to_proto(),
 368                peer_id: creator_connection_id.0,
 369                projects: Default::default(),
 370                location: Some(proto::ParticipantLocation {
 371                    variant: Some(proto::participant_location::Variant::External(
 372                        proto::participant_location::External {},
 373                    )),
 374                }),
 375            }],
 376            pending_participant_user_ids: Default::default(),
 377            live_kit_room: nanoid!(30),
 378        };
 379
 380        self.rooms.insert(room_id, room);
 381        connected_user.active_call = Some(Call {
 382            caller_user_id: connection.user_id,
 383            room_id,
 384            connection_id: Some(creator_connection_id),
 385            initial_project_id: None,
 386        });
 387        Ok(self.rooms.get(&room_id).unwrap())
 388    }
 389
 390    pub fn join_room(
 391        &mut self,
 392        room_id: RoomId,
 393        connection_id: ConnectionId,
 394    ) -> Result<(&proto::Room, Vec<ConnectionId>)> {
 395        let connection = self
 396            .connections
 397            .get_mut(&connection_id)
 398            .ok_or_else(|| anyhow!("no such connection"))?;
 399        let user_id = connection.user_id;
 400        let recipient_connection_ids = self.connection_ids_for_user(user_id).collect::<Vec<_>>();
 401
 402        let connected_user = self
 403            .connected_users
 404            .get_mut(&user_id)
 405            .ok_or_else(|| anyhow!("no such connection"))?;
 406        let active_call = connected_user
 407            .active_call
 408            .as_mut()
 409            .ok_or_else(|| anyhow!("not being called"))?;
 410        anyhow::ensure!(
 411            active_call.room_id == room_id && active_call.connection_id.is_none(),
 412            "not being called on this room"
 413        );
 414
 415        let room = self
 416            .rooms
 417            .get_mut(&room_id)
 418            .ok_or_else(|| anyhow!("no such room"))?;
 419        anyhow::ensure!(
 420            room.pending_participant_user_ids
 421                .contains(&user_id.to_proto()),
 422            anyhow!("no such room")
 423        );
 424        room.pending_participant_user_ids
 425            .retain(|pending| *pending != user_id.to_proto());
 426        room.participants.push(proto::Participant {
 427            user_id: user_id.to_proto(),
 428            peer_id: connection_id.0,
 429            projects: Default::default(),
 430            location: Some(proto::ParticipantLocation {
 431                variant: Some(proto::participant_location::Variant::External(
 432                    proto::participant_location::External {},
 433                )),
 434            }),
 435        });
 436        active_call.connection_id = Some(connection_id);
 437
 438        Ok((room, recipient_connection_ids))
 439    }
 440
 441    pub fn leave_room(&mut self, room_id: RoomId, connection_id: ConnectionId) -> Result<LeftRoom> {
 442        let connection = self
 443            .connections
 444            .get_mut(&connection_id)
 445            .ok_or_else(|| anyhow!("no such connection"))?;
 446        let user_id = connection.user_id;
 447
 448        let connected_user = self
 449            .connected_users
 450            .get(&user_id)
 451            .ok_or_else(|| anyhow!("no such connection"))?;
 452        anyhow::ensure!(
 453            connected_user
 454                .active_call
 455                .map_or(false, |call| call.room_id == room_id
 456                    && call.connection_id == Some(connection_id)),
 457            "cannot leave a room before joining it"
 458        );
 459
 460        // Given that users can only join one room at a time, we can safely unshare
 461        // and leave all projects associated with the connection.
 462        let mut unshared_projects = Vec::new();
 463        let mut left_projects = Vec::new();
 464        for project_id in connection.projects.clone() {
 465            if let Ok((_, project)) = self.unshare_project(project_id, connection_id) {
 466                unshared_projects.push(project);
 467            } else if let Ok(project) = self.leave_project(project_id, connection_id) {
 468                left_projects.push(project);
 469            }
 470        }
 471        self.connected_users.get_mut(&user_id).unwrap().active_call = None;
 472
 473        let room = self
 474            .rooms
 475            .get_mut(&room_id)
 476            .ok_or_else(|| anyhow!("no such room"))?;
 477        room.participants
 478            .retain(|participant| participant.peer_id != connection_id.0);
 479
 480        let mut canceled_call_connection_ids = Vec::new();
 481        room.pending_participant_user_ids
 482            .retain(|pending_participant_user_id| {
 483                if let Some(connected_user) = self
 484                    .connected_users
 485                    .get_mut(&UserId::from_proto(*pending_participant_user_id))
 486                {
 487                    if let Some(call) = connected_user.active_call.as_ref() {
 488                        if call.caller_user_id == user_id {
 489                            connected_user.active_call.take();
 490                            canceled_call_connection_ids
 491                                .extend(connected_user.connection_ids.iter().copied());
 492                            false
 493                        } else {
 494                            true
 495                        }
 496                    } else {
 497                        true
 498                    }
 499                } else {
 500                    true
 501                }
 502            });
 503
 504        let room = if room.participants.is_empty() {
 505            Cow::Owned(self.rooms.remove(&room_id).unwrap())
 506        } else {
 507            Cow::Borrowed(self.rooms.get(&room_id).unwrap())
 508        };
 509
 510        Ok(LeftRoom {
 511            room,
 512            unshared_projects,
 513            left_projects,
 514            canceled_call_connection_ids,
 515        })
 516    }
 517
 518    pub fn room(&self, room_id: RoomId) -> Option<&proto::Room> {
 519        self.rooms.get(&room_id)
 520    }
 521
 522    pub fn call(
 523        &mut self,
 524        room_id: RoomId,
 525        recipient_user_id: UserId,
 526        initial_project_id: Option<ProjectId>,
 527        from_connection_id: ConnectionId,
 528    ) -> Result<(&proto::Room, Vec<ConnectionId>, proto::IncomingCall)> {
 529        let caller_user_id = self.user_id_for_connection(from_connection_id)?;
 530
 531        let recipient_connection_ids = self
 532            .connection_ids_for_user(recipient_user_id)
 533            .collect::<Vec<_>>();
 534        let mut recipient = self
 535            .connected_users
 536            .get_mut(&recipient_user_id)
 537            .ok_or_else(|| anyhow!("no such connection"))?;
 538        anyhow::ensure!(
 539            recipient.active_call.is_none(),
 540            "recipient is already on another call"
 541        );
 542
 543        let room = self
 544            .rooms
 545            .get_mut(&room_id)
 546            .ok_or_else(|| anyhow!("no such room"))?;
 547        anyhow::ensure!(
 548            room.participants
 549                .iter()
 550                .any(|participant| participant.peer_id == from_connection_id.0),
 551            "no such room"
 552        );
 553        anyhow::ensure!(
 554            room.pending_participant_user_ids
 555                .iter()
 556                .all(|user_id| UserId::from_proto(*user_id) != recipient_user_id),
 557            "cannot call the same user more than once"
 558        );
 559        room.pending_participant_user_ids
 560            .push(recipient_user_id.to_proto());
 561
 562        if let Some(initial_project_id) = initial_project_id {
 563            let project = self
 564                .projects
 565                .get(&initial_project_id)
 566                .ok_or_else(|| anyhow!("no such project"))?;
 567            anyhow::ensure!(project.room_id == room_id, "no such project");
 568        }
 569
 570        recipient.active_call = Some(Call {
 571            caller_user_id,
 572            room_id,
 573            connection_id: None,
 574            initial_project_id,
 575        });
 576
 577        Ok((
 578            room,
 579            recipient_connection_ids,
 580            proto::IncomingCall {
 581                room_id,
 582                caller_user_id: caller_user_id.to_proto(),
 583                participant_user_ids: room
 584                    .participants
 585                    .iter()
 586                    .map(|participant| participant.user_id)
 587                    .collect(),
 588                initial_project: initial_project_id
 589                    .and_then(|id| Self::build_participant_project(id, &self.projects)),
 590            },
 591        ))
 592    }
 593
 594    pub fn call_failed(&mut self, room_id: RoomId, to_user_id: UserId) -> Result<&proto::Room> {
 595        let mut recipient = self
 596            .connected_users
 597            .get_mut(&to_user_id)
 598            .ok_or_else(|| anyhow!("no such connection"))?;
 599        anyhow::ensure!(recipient
 600            .active_call
 601            .map_or(false, |call| call.room_id == room_id
 602                && call.connection_id.is_none()));
 603        recipient.active_call = None;
 604        let room = self
 605            .rooms
 606            .get_mut(&room_id)
 607            .ok_or_else(|| anyhow!("no such room"))?;
 608        room.pending_participant_user_ids
 609            .retain(|user_id| UserId::from_proto(*user_id) != to_user_id);
 610        Ok(room)
 611    }
 612
 613    pub fn cancel_call(
 614        &mut self,
 615        room_id: RoomId,
 616        recipient_user_id: UserId,
 617        canceller_connection_id: ConnectionId,
 618    ) -> Result<(&proto::Room, HashSet<ConnectionId>)> {
 619        let canceller_user_id = self.user_id_for_connection(canceller_connection_id)?;
 620        let canceller = self
 621            .connected_users
 622            .get(&canceller_user_id)
 623            .ok_or_else(|| anyhow!("no such connection"))?;
 624        let recipient = self
 625            .connected_users
 626            .get(&recipient_user_id)
 627            .ok_or_else(|| anyhow!("no such connection"))?;
 628        let canceller_active_call = canceller
 629            .active_call
 630            .as_ref()
 631            .ok_or_else(|| anyhow!("no active call"))?;
 632        let recipient_active_call = recipient
 633            .active_call
 634            .as_ref()
 635            .ok_or_else(|| anyhow!("no active call for recipient"))?;
 636
 637        anyhow::ensure!(
 638            canceller_active_call.room_id == room_id,
 639            "users are on different calls"
 640        );
 641        anyhow::ensure!(
 642            recipient_active_call.room_id == room_id,
 643            "users are on different calls"
 644        );
 645        anyhow::ensure!(
 646            recipient_active_call.connection_id.is_none(),
 647            "recipient has already answered"
 648        );
 649        let room_id = recipient_active_call.room_id;
 650        let room = self
 651            .rooms
 652            .get_mut(&room_id)
 653            .ok_or_else(|| anyhow!("no such room"))?;
 654        room.pending_participant_user_ids
 655            .retain(|user_id| UserId::from_proto(*user_id) != recipient_user_id);
 656
 657        let recipient = self.connected_users.get_mut(&recipient_user_id).unwrap();
 658        recipient.active_call.take();
 659
 660        Ok((room, recipient.connection_ids.clone()))
 661    }
 662
 663    pub fn decline_call(
 664        &mut self,
 665        room_id: RoomId,
 666        recipient_connection_id: ConnectionId,
 667    ) -> Result<(&proto::Room, Vec<ConnectionId>)> {
 668        let recipient_user_id = self.user_id_for_connection(recipient_connection_id)?;
 669        let recipient = self
 670            .connected_users
 671            .get_mut(&recipient_user_id)
 672            .ok_or_else(|| anyhow!("no such connection"))?;
 673        if let Some(active_call) = recipient.active_call.take() {
 674            anyhow::ensure!(active_call.room_id == room_id, "no such room");
 675            let recipient_connection_ids = self
 676                .connection_ids_for_user(recipient_user_id)
 677                .collect::<Vec<_>>();
 678            let room = self
 679                .rooms
 680                .get_mut(&active_call.room_id)
 681                .ok_or_else(|| anyhow!("no such room"))?;
 682            room.pending_participant_user_ids
 683                .retain(|user_id| UserId::from_proto(*user_id) != recipient_user_id);
 684            Ok((room, recipient_connection_ids))
 685        } else {
 686            Err(anyhow!("user is not being called"))
 687        }
 688    }
 689
 690    pub fn update_participant_location(
 691        &mut self,
 692        room_id: RoomId,
 693        location: proto::ParticipantLocation,
 694        connection_id: ConnectionId,
 695    ) -> Result<&proto::Room> {
 696        let room = self
 697            .rooms
 698            .get_mut(&room_id)
 699            .ok_or_else(|| anyhow!("no such room"))?;
 700        if let Some(proto::participant_location::Variant::SharedProject(project)) =
 701            location.variant.as_ref()
 702        {
 703            anyhow::ensure!(
 704                room.participants
 705                    .iter()
 706                    .flat_map(|participant| &participant.projects)
 707                    .any(|participant_project| participant_project.id == project.id),
 708                "no such project"
 709            );
 710        }
 711
 712        let participant = room
 713            .participants
 714            .iter_mut()
 715            .find(|participant| participant.peer_id == connection_id.0)
 716            .ok_or_else(|| anyhow!("no such room"))?;
 717        participant.location = Some(location);
 718
 719        Ok(room)
 720    }
 721
 722    pub fn share_project(
 723        &mut self,
 724        room_id: RoomId,
 725        project_id: ProjectId,
 726        worktrees: Vec<proto::WorktreeMetadata>,
 727        host_connection_id: ConnectionId,
 728    ) -> Result<&proto::Room> {
 729        let connection = self
 730            .connections
 731            .get_mut(&host_connection_id)
 732            .ok_or_else(|| anyhow!("no such connection"))?;
 733
 734        let room = self
 735            .rooms
 736            .get_mut(&room_id)
 737            .ok_or_else(|| anyhow!("no such room"))?;
 738        let participant = room
 739            .participants
 740            .iter_mut()
 741            .find(|participant| participant.peer_id == host_connection_id.0)
 742            .ok_or_else(|| anyhow!("no such room"))?;
 743
 744        connection.projects.insert(project_id);
 745        self.projects.insert(
 746            project_id,
 747            Project {
 748                id: project_id,
 749                room_id,
 750                host_connection_id,
 751                host: Collaborator {
 752                    user_id: connection.user_id,
 753                    replica_id: 0,
 754                    last_activity: None,
 755                    admin: connection.admin,
 756                },
 757                guests: Default::default(),
 758                active_replica_ids: Default::default(),
 759                worktrees: worktrees
 760                    .into_iter()
 761                    .map(|worktree| {
 762                        (
 763                            worktree.id,
 764                            Worktree {
 765                                root_name: worktree.root_name,
 766                                visible: worktree.visible,
 767                                ..Default::default()
 768                            },
 769                        )
 770                    })
 771                    .collect(),
 772                language_servers: Default::default(),
 773            },
 774        );
 775
 776        participant
 777            .projects
 778            .extend(Self::build_participant_project(project_id, &self.projects));
 779
 780        Ok(room)
 781    }
 782
 783    pub fn unshare_project(
 784        &mut self,
 785        project_id: ProjectId,
 786        connection_id: ConnectionId,
 787    ) -> Result<(&proto::Room, Project)> {
 788        match self.projects.entry(project_id) {
 789            btree_map::Entry::Occupied(e) => {
 790                if e.get().host_connection_id == connection_id {
 791                    let project = e.remove();
 792
 793                    if let Some(host_connection) = self.connections.get_mut(&connection_id) {
 794                        host_connection.projects.remove(&project_id);
 795                    }
 796
 797                    for guest_connection in project.guests.keys() {
 798                        if let Some(connection) = self.connections.get_mut(guest_connection) {
 799                            connection.projects.remove(&project_id);
 800                        }
 801                    }
 802
 803                    let room = self
 804                        .rooms
 805                        .get_mut(&project.room_id)
 806                        .ok_or_else(|| anyhow!("no such room"))?;
 807                    let participant = room
 808                        .participants
 809                        .iter_mut()
 810                        .find(|participant| participant.peer_id == connection_id.0)
 811                        .ok_or_else(|| anyhow!("no such room"))?;
 812                    participant
 813                        .projects
 814                        .retain(|project| project.id != project_id.to_proto());
 815
 816                    Ok((room, project))
 817                } else {
 818                    Err(anyhow!("no such project"))?
 819                }
 820            }
 821            btree_map::Entry::Vacant(_) => Err(anyhow!("no such project"))?,
 822        }
 823    }
 824
 825    pub fn update_project(
 826        &mut self,
 827        project_id: ProjectId,
 828        worktrees: &[proto::WorktreeMetadata],
 829        connection_id: ConnectionId,
 830    ) -> Result<&proto::Room> {
 831        let project = self
 832            .projects
 833            .get_mut(&project_id)
 834            .ok_or_else(|| anyhow!("no such project"))?;
 835        if project.host_connection_id == connection_id {
 836            let mut old_worktrees = mem::take(&mut project.worktrees);
 837            for worktree in worktrees {
 838                if let Some(old_worktree) = old_worktrees.remove(&worktree.id) {
 839                    project.worktrees.insert(worktree.id, old_worktree);
 840                } else {
 841                    project.worktrees.insert(
 842                        worktree.id,
 843                        Worktree {
 844                            root_name: worktree.root_name.clone(),
 845                            visible: worktree.visible,
 846                            ..Default::default()
 847                        },
 848                    );
 849                }
 850            }
 851
 852            let room = self
 853                .rooms
 854                .get_mut(&project.room_id)
 855                .ok_or_else(|| anyhow!("no such room"))?;
 856            let participant_project = room
 857                .participants
 858                .iter_mut()
 859                .flat_map(|participant| &mut participant.projects)
 860                .find(|project| project.id == project_id.to_proto())
 861                .ok_or_else(|| anyhow!("no such project"))?;
 862            participant_project.worktree_root_names = worktrees
 863                .iter()
 864                .filter(|worktree| worktree.visible)
 865                .map(|worktree| worktree.root_name.clone())
 866                .collect();
 867
 868            Ok(room)
 869        } else {
 870            Err(anyhow!("no such project"))?
 871        }
 872    }
 873
 874    pub fn update_diagnostic_summary(
 875        &mut self,
 876        project_id: ProjectId,
 877        worktree_id: u64,
 878        connection_id: ConnectionId,
 879        summary: proto::DiagnosticSummary,
 880    ) -> Result<Vec<ConnectionId>> {
 881        let project = self
 882            .projects
 883            .get_mut(&project_id)
 884            .ok_or_else(|| anyhow!("no such project"))?;
 885        if project.host_connection_id == connection_id {
 886            let worktree = project
 887                .worktrees
 888                .get_mut(&worktree_id)
 889                .ok_or_else(|| anyhow!("no such worktree"))?;
 890            worktree
 891                .diagnostic_summaries
 892                .insert(summary.path.clone().into(), summary);
 893            return Ok(project.connection_ids());
 894        }
 895
 896        Err(anyhow!("no such worktree"))?
 897    }
 898
 899    pub fn start_language_server(
 900        &mut self,
 901        project_id: ProjectId,
 902        connection_id: ConnectionId,
 903        language_server: proto::LanguageServer,
 904    ) -> Result<Vec<ConnectionId>> {
 905        let project = self
 906            .projects
 907            .get_mut(&project_id)
 908            .ok_or_else(|| anyhow!("no such project"))?;
 909        if project.host_connection_id == connection_id {
 910            project.language_servers.push(language_server);
 911            return Ok(project.connection_ids());
 912        }
 913
 914        Err(anyhow!("no such project"))?
 915    }
 916
 917    pub fn join_project(
 918        &mut self,
 919        requester_connection_id: ConnectionId,
 920        project_id: ProjectId,
 921    ) -> Result<(&Project, ReplicaId)> {
 922        let connection = self
 923            .connections
 924            .get_mut(&requester_connection_id)
 925            .ok_or_else(|| anyhow!("no such connection"))?;
 926        let user = self
 927            .connected_users
 928            .get(&connection.user_id)
 929            .ok_or_else(|| anyhow!("no such connection"))?;
 930        let active_call = user.active_call.ok_or_else(|| anyhow!("no such project"))?;
 931        anyhow::ensure!(
 932            active_call.connection_id == Some(requester_connection_id),
 933            "no such project"
 934        );
 935
 936        let project = self
 937            .projects
 938            .get_mut(&project_id)
 939            .ok_or_else(|| anyhow!("no such project"))?;
 940        anyhow::ensure!(project.room_id == active_call.room_id, "no such project");
 941
 942        connection.projects.insert(project_id);
 943        let mut replica_id = 1;
 944        while project.active_replica_ids.contains(&replica_id) {
 945            replica_id += 1;
 946        }
 947        project.active_replica_ids.insert(replica_id);
 948        project.guests.insert(
 949            requester_connection_id,
 950            Collaborator {
 951                replica_id,
 952                user_id: connection.user_id,
 953                last_activity: Some(OffsetDateTime::now_utc()),
 954                admin: connection.admin,
 955            },
 956        );
 957
 958        project.host.last_activity = Some(OffsetDateTime::now_utc());
 959        Ok((project, replica_id))
 960    }
 961
 962    pub fn leave_project(
 963        &mut self,
 964        project_id: ProjectId,
 965        connection_id: ConnectionId,
 966    ) -> Result<LeftProject> {
 967        let project = self
 968            .projects
 969            .get_mut(&project_id)
 970            .ok_or_else(|| anyhow!("no such project"))?;
 971
 972        // If the connection leaving the project is a collaborator, remove it.
 973        let remove_collaborator = if let Some(guest) = project.guests.remove(&connection_id) {
 974            project.active_replica_ids.remove(&guest.replica_id);
 975            true
 976        } else {
 977            false
 978        };
 979
 980        if let Some(connection) = self.connections.get_mut(&connection_id) {
 981            connection.projects.remove(&project_id);
 982        }
 983
 984        Ok(LeftProject {
 985            id: project.id,
 986            host_connection_id: project.host_connection_id,
 987            host_user_id: project.host.user_id,
 988            connection_ids: project.connection_ids(),
 989            remove_collaborator,
 990        })
 991    }
 992
 993    #[allow(clippy::too_many_arguments)]
 994    pub fn update_worktree(
 995        &mut self,
 996        connection_id: ConnectionId,
 997        project_id: ProjectId,
 998        worktree_id: u64,
 999        worktree_root_name: &str,
1000        removed_entries: &[u64],
1001        updated_entries: &[proto::Entry],
1002        scan_id: u64,
1003        is_last_update: bool,
1004    ) -> Result<Vec<ConnectionId>> {
1005        let project = self.write_project(project_id, connection_id)?;
1006
1007        let connection_ids = project.connection_ids();
1008        let mut worktree = project.worktrees.entry(worktree_id).or_default();
1009        worktree.root_name = worktree_root_name.to_string();
1010
1011        for entry_id in removed_entries {
1012            worktree.entries.remove(entry_id);
1013        }
1014
1015        for entry in updated_entries {
1016            worktree.entries.insert(entry.id, entry.clone());
1017        }
1018
1019        worktree.scan_id = scan_id;
1020        worktree.is_complete = is_last_update;
1021        Ok(connection_ids)
1022    }
1023
1024    fn build_participant_project(
1025        project_id: ProjectId,
1026        projects: &BTreeMap<ProjectId, Project>,
1027    ) -> Option<proto::ParticipantProject> {
1028        Some(proto::ParticipantProject {
1029            id: project_id.to_proto(),
1030            worktree_root_names: projects
1031                .get(&project_id)?
1032                .worktrees
1033                .values()
1034                .filter(|worktree| worktree.visible)
1035                .map(|worktree| worktree.root_name.clone())
1036                .collect(),
1037        })
1038    }
1039
1040    pub fn project_connection_ids(
1041        &self,
1042        project_id: ProjectId,
1043        acting_connection_id: ConnectionId,
1044    ) -> Result<Vec<ConnectionId>> {
1045        Ok(self
1046            .read_project(project_id, acting_connection_id)?
1047            .connection_ids())
1048    }
1049
1050    pub fn channel_connection_ids(&self, channel_id: ChannelId) -> Result<Vec<ConnectionId>> {
1051        Ok(self
1052            .channels
1053            .get(&channel_id)
1054            .ok_or_else(|| anyhow!("no such channel"))?
1055            .connection_ids())
1056    }
1057
1058    pub fn project(&self, project_id: ProjectId) -> Result<&Project> {
1059        self.projects
1060            .get(&project_id)
1061            .ok_or_else(|| anyhow!("no such project"))
1062    }
1063
1064    pub fn register_project_activity(
1065        &mut self,
1066        project_id: ProjectId,
1067        connection_id: ConnectionId,
1068    ) -> Result<()> {
1069        let project = self
1070            .projects
1071            .get_mut(&project_id)
1072            .ok_or_else(|| anyhow!("no such project"))?;
1073        let collaborator = if connection_id == project.host_connection_id {
1074            &mut project.host
1075        } else if let Some(guest) = project.guests.get_mut(&connection_id) {
1076            guest
1077        } else {
1078            return Err(anyhow!("no such project"))?;
1079        };
1080        collaborator.last_activity = Some(OffsetDateTime::now_utc());
1081        Ok(())
1082    }
1083
1084    pub fn projects(&self) -> impl Iterator<Item = (&ProjectId, &Project)> {
1085        self.projects.iter()
1086    }
1087
1088    pub fn read_project(
1089        &self,
1090        project_id: ProjectId,
1091        connection_id: ConnectionId,
1092    ) -> Result<&Project> {
1093        let project = self
1094            .projects
1095            .get(&project_id)
1096            .ok_or_else(|| anyhow!("no such project"))?;
1097        if project.host_connection_id == connection_id
1098            || project.guests.contains_key(&connection_id)
1099        {
1100            Ok(project)
1101        } else {
1102            Err(anyhow!("no such project"))?
1103        }
1104    }
1105
1106    fn write_project(
1107        &mut self,
1108        project_id: ProjectId,
1109        connection_id: ConnectionId,
1110    ) -> Result<&mut Project> {
1111        let project = self
1112            .projects
1113            .get_mut(&project_id)
1114            .ok_or_else(|| anyhow!("no such project"))?;
1115        if project.host_connection_id == connection_id
1116            || project.guests.contains_key(&connection_id)
1117        {
1118            Ok(project)
1119        } else {
1120            Err(anyhow!("no such project"))?
1121        }
1122    }
1123
1124    #[cfg(test)]
1125    pub fn check_invariants(&self) {
1126        for (connection_id, connection) in &self.connections {
1127            for project_id in &connection.projects {
1128                let project = &self.projects.get(project_id).unwrap();
1129                if project.host_connection_id != *connection_id {
1130                    assert!(project.guests.contains_key(connection_id));
1131                }
1132
1133                for (worktree_id, worktree) in project.worktrees.iter() {
1134                    let mut paths = HashMap::default();
1135                    for entry in worktree.entries.values() {
1136                        let prev_entry = paths.insert(&entry.path, entry);
1137                        assert_eq!(
1138                            prev_entry,
1139                            None,
1140                            "worktree {:?}, duplicate path for entries {:?} and {:?}",
1141                            worktree_id,
1142                            prev_entry.unwrap(),
1143                            entry
1144                        );
1145                    }
1146                }
1147            }
1148            for channel_id in &connection.channels {
1149                let channel = self.channels.get(channel_id).unwrap();
1150                assert!(channel.connection_ids.contains(connection_id));
1151            }
1152            assert!(self
1153                .connected_users
1154                .get(&connection.user_id)
1155                .unwrap()
1156                .connection_ids
1157                .contains(connection_id));
1158        }
1159
1160        for (user_id, state) in &self.connected_users {
1161            for connection_id in &state.connection_ids {
1162                assert_eq!(
1163                    self.connections.get(connection_id).unwrap().user_id,
1164                    *user_id
1165                );
1166            }
1167
1168            if let Some(active_call) = state.active_call.as_ref() {
1169                if let Some(active_call_connection_id) = active_call.connection_id {
1170                    assert!(
1171                        state.connection_ids.contains(&active_call_connection_id),
1172                        "call is active on a dead connection"
1173                    );
1174                    assert!(
1175                        state.connection_ids.contains(&active_call_connection_id),
1176                        "call is active on a dead connection"
1177                    );
1178                }
1179            }
1180        }
1181
1182        for (room_id, room) in &self.rooms {
1183            for pending_user_id in &room.pending_participant_user_ids {
1184                assert!(
1185                    self.connected_users
1186                        .contains_key(&UserId::from_proto(*pending_user_id)),
1187                    "call is active on a user that has disconnected"
1188                );
1189            }
1190
1191            for participant in &room.participants {
1192                assert!(
1193                    self.connections
1194                        .contains_key(&ConnectionId(participant.peer_id)),
1195                    "room contains participant that has disconnected"
1196                );
1197
1198                for participant_project in &participant.projects {
1199                    let project = &self.projects[&ProjectId::from_proto(participant_project.id)];
1200                    assert_eq!(
1201                        project.room_id, *room_id,
1202                        "project was shared on a different room"
1203                    );
1204                }
1205            }
1206
1207            assert!(
1208                !room.pending_participant_user_ids.is_empty() || !room.participants.is_empty(),
1209                "room can't be empty"
1210            );
1211        }
1212
1213        for (project_id, project) in &self.projects {
1214            let host_connection = self.connections.get(&project.host_connection_id).unwrap();
1215            assert!(host_connection.projects.contains(project_id));
1216
1217            for guest_connection_id in project.guests.keys() {
1218                let guest_connection = self.connections.get(guest_connection_id).unwrap();
1219                assert!(guest_connection.projects.contains(project_id));
1220            }
1221            assert_eq!(project.active_replica_ids.len(), project.guests.len());
1222            assert_eq!(
1223                project.active_replica_ids,
1224                project
1225                    .guests
1226                    .values()
1227                    .map(|guest| guest.replica_id)
1228                    .collect::<HashSet<_>>(),
1229            );
1230
1231            let room = &self.rooms[&project.room_id];
1232            let room_participant = room
1233                .participants
1234                .iter()
1235                .find(|participant| participant.peer_id == project.host_connection_id.0)
1236                .unwrap();
1237            assert!(
1238                room_participant
1239                    .projects
1240                    .iter()
1241                    .any(|project| project.id == project_id.to_proto()),
1242                "project was not shared in room"
1243            );
1244        }
1245
1246        for (channel_id, channel) in &self.channels {
1247            for connection_id in &channel.connection_ids {
1248                let connection = self.connections.get(connection_id).unwrap();
1249                assert!(connection.channels.contains(channel_id));
1250            }
1251        }
1252    }
1253}
1254
1255impl Project {
1256    fn is_active_since(&self, start_time: OffsetDateTime) -> bool {
1257        self.guests
1258            .values()
1259            .chain([&self.host])
1260            .any(|collaborator| {
1261                collaborator
1262                    .last_activity
1263                    .map_or(false, |active_time| active_time > start_time)
1264            })
1265    }
1266
1267    pub fn guest_connection_ids(&self) -> Vec<ConnectionId> {
1268        self.guests.keys().copied().collect()
1269    }
1270
1271    pub fn connection_ids(&self) -> Vec<ConnectionId> {
1272        self.guests
1273            .keys()
1274            .copied()
1275            .chain(Some(self.host_connection_id))
1276            .collect()
1277    }
1278}
1279
1280impl Channel {
1281    fn connection_ids(&self) -> Vec<ConnectionId> {
1282        self.connection_ids.iter().copied().collect()
1283    }
1284}