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 rooms(&self) -> &BTreeMap<RoomId, proto::Room> {
 523        &self.rooms
 524    }
 525
 526    pub fn call(
 527        &mut self,
 528        room_id: RoomId,
 529        recipient_user_id: UserId,
 530        initial_project_id: Option<ProjectId>,
 531        from_connection_id: ConnectionId,
 532    ) -> Result<(&proto::Room, Vec<ConnectionId>, proto::IncomingCall)> {
 533        let caller_user_id = self.user_id_for_connection(from_connection_id)?;
 534
 535        let recipient_connection_ids = self
 536            .connection_ids_for_user(recipient_user_id)
 537            .collect::<Vec<_>>();
 538        let mut recipient = self
 539            .connected_users
 540            .get_mut(&recipient_user_id)
 541            .ok_or_else(|| anyhow!("no such connection"))?;
 542        anyhow::ensure!(
 543            recipient.active_call.is_none(),
 544            "recipient is already on another call"
 545        );
 546
 547        let room = self
 548            .rooms
 549            .get_mut(&room_id)
 550            .ok_or_else(|| anyhow!("no such room"))?;
 551        anyhow::ensure!(
 552            room.participants
 553                .iter()
 554                .any(|participant| participant.peer_id == from_connection_id.0),
 555            "no such room"
 556        );
 557        anyhow::ensure!(
 558            room.pending_participant_user_ids
 559                .iter()
 560                .all(|user_id| UserId::from_proto(*user_id) != recipient_user_id),
 561            "cannot call the same user more than once"
 562        );
 563        room.pending_participant_user_ids
 564            .push(recipient_user_id.to_proto());
 565
 566        if let Some(initial_project_id) = initial_project_id {
 567            let project = self
 568                .projects
 569                .get(&initial_project_id)
 570                .ok_or_else(|| anyhow!("no such project"))?;
 571            anyhow::ensure!(project.room_id == room_id, "no such project");
 572        }
 573
 574        recipient.active_call = Some(Call {
 575            caller_user_id,
 576            room_id,
 577            connection_id: None,
 578            initial_project_id,
 579        });
 580
 581        Ok((
 582            room,
 583            recipient_connection_ids,
 584            proto::IncomingCall {
 585                room_id,
 586                caller_user_id: caller_user_id.to_proto(),
 587                participant_user_ids: room
 588                    .participants
 589                    .iter()
 590                    .map(|participant| participant.user_id)
 591                    .collect(),
 592                initial_project: initial_project_id
 593                    .and_then(|id| Self::build_participant_project(id, &self.projects)),
 594            },
 595        ))
 596    }
 597
 598    pub fn call_failed(&mut self, room_id: RoomId, to_user_id: UserId) -> Result<&proto::Room> {
 599        let mut recipient = self
 600            .connected_users
 601            .get_mut(&to_user_id)
 602            .ok_or_else(|| anyhow!("no such connection"))?;
 603        anyhow::ensure!(recipient
 604            .active_call
 605            .map_or(false, |call| call.room_id == room_id
 606                && call.connection_id.is_none()));
 607        recipient.active_call = None;
 608        let room = self
 609            .rooms
 610            .get_mut(&room_id)
 611            .ok_or_else(|| anyhow!("no such room"))?;
 612        room.pending_participant_user_ids
 613            .retain(|user_id| UserId::from_proto(*user_id) != to_user_id);
 614        Ok(room)
 615    }
 616
 617    pub fn cancel_call(
 618        &mut self,
 619        room_id: RoomId,
 620        recipient_user_id: UserId,
 621        canceller_connection_id: ConnectionId,
 622    ) -> Result<(&proto::Room, HashSet<ConnectionId>)> {
 623        let canceller_user_id = self.user_id_for_connection(canceller_connection_id)?;
 624        let canceller = self
 625            .connected_users
 626            .get(&canceller_user_id)
 627            .ok_or_else(|| anyhow!("no such connection"))?;
 628        let recipient = self
 629            .connected_users
 630            .get(&recipient_user_id)
 631            .ok_or_else(|| anyhow!("no such connection"))?;
 632        let canceller_active_call = canceller
 633            .active_call
 634            .as_ref()
 635            .ok_or_else(|| anyhow!("no active call"))?;
 636        let recipient_active_call = recipient
 637            .active_call
 638            .as_ref()
 639            .ok_or_else(|| anyhow!("no active call for recipient"))?;
 640
 641        anyhow::ensure!(
 642            canceller_active_call.room_id == room_id,
 643            "users are on different calls"
 644        );
 645        anyhow::ensure!(
 646            recipient_active_call.room_id == room_id,
 647            "users are on different calls"
 648        );
 649        anyhow::ensure!(
 650            recipient_active_call.connection_id.is_none(),
 651            "recipient has already answered"
 652        );
 653        let room_id = recipient_active_call.room_id;
 654        let room = self
 655            .rooms
 656            .get_mut(&room_id)
 657            .ok_or_else(|| anyhow!("no such room"))?;
 658        room.pending_participant_user_ids
 659            .retain(|user_id| UserId::from_proto(*user_id) != recipient_user_id);
 660
 661        let recipient = self.connected_users.get_mut(&recipient_user_id).unwrap();
 662        recipient.active_call.take();
 663
 664        Ok((room, recipient.connection_ids.clone()))
 665    }
 666
 667    pub fn decline_call(
 668        &mut self,
 669        room_id: RoomId,
 670        recipient_connection_id: ConnectionId,
 671    ) -> Result<(&proto::Room, Vec<ConnectionId>)> {
 672        let recipient_user_id = self.user_id_for_connection(recipient_connection_id)?;
 673        let recipient = self
 674            .connected_users
 675            .get_mut(&recipient_user_id)
 676            .ok_or_else(|| anyhow!("no such connection"))?;
 677        if let Some(active_call) = recipient.active_call.take() {
 678            anyhow::ensure!(active_call.room_id == room_id, "no such room");
 679            let recipient_connection_ids = self
 680                .connection_ids_for_user(recipient_user_id)
 681                .collect::<Vec<_>>();
 682            let room = self
 683                .rooms
 684                .get_mut(&active_call.room_id)
 685                .ok_or_else(|| anyhow!("no such room"))?;
 686            room.pending_participant_user_ids
 687                .retain(|user_id| UserId::from_proto(*user_id) != recipient_user_id);
 688            Ok((room, recipient_connection_ids))
 689        } else {
 690            Err(anyhow!("user is not being called"))
 691        }
 692    }
 693
 694    pub fn update_participant_location(
 695        &mut self,
 696        room_id: RoomId,
 697        location: proto::ParticipantLocation,
 698        connection_id: ConnectionId,
 699    ) -> Result<&proto::Room> {
 700        let room = self
 701            .rooms
 702            .get_mut(&room_id)
 703            .ok_or_else(|| anyhow!("no such room"))?;
 704        if let Some(proto::participant_location::Variant::SharedProject(project)) =
 705            location.variant.as_ref()
 706        {
 707            anyhow::ensure!(
 708                room.participants
 709                    .iter()
 710                    .flat_map(|participant| &participant.projects)
 711                    .any(|participant_project| participant_project.id == project.id),
 712                "no such project"
 713            );
 714        }
 715
 716        let participant = room
 717            .participants
 718            .iter_mut()
 719            .find(|participant| participant.peer_id == connection_id.0)
 720            .ok_or_else(|| anyhow!("no such room"))?;
 721        participant.location = Some(location);
 722
 723        Ok(room)
 724    }
 725
 726    pub fn share_project(
 727        &mut self,
 728        room_id: RoomId,
 729        project_id: ProjectId,
 730        worktrees: Vec<proto::WorktreeMetadata>,
 731        host_connection_id: ConnectionId,
 732    ) -> Result<&proto::Room> {
 733        let connection = self
 734            .connections
 735            .get_mut(&host_connection_id)
 736            .ok_or_else(|| anyhow!("no such connection"))?;
 737
 738        let room = self
 739            .rooms
 740            .get_mut(&room_id)
 741            .ok_or_else(|| anyhow!("no such room"))?;
 742        let participant = room
 743            .participants
 744            .iter_mut()
 745            .find(|participant| participant.peer_id == host_connection_id.0)
 746            .ok_or_else(|| anyhow!("no such room"))?;
 747
 748        connection.projects.insert(project_id);
 749        self.projects.insert(
 750            project_id,
 751            Project {
 752                id: project_id,
 753                room_id,
 754                host_connection_id,
 755                host: Collaborator {
 756                    user_id: connection.user_id,
 757                    replica_id: 0,
 758                    last_activity: None,
 759                    admin: connection.admin,
 760                },
 761                guests: Default::default(),
 762                active_replica_ids: Default::default(),
 763                worktrees: worktrees
 764                    .into_iter()
 765                    .map(|worktree| {
 766                        (
 767                            worktree.id,
 768                            Worktree {
 769                                root_name: worktree.root_name,
 770                                visible: worktree.visible,
 771                                ..Default::default()
 772                            },
 773                        )
 774                    })
 775                    .collect(),
 776                language_servers: Default::default(),
 777            },
 778        );
 779
 780        participant
 781            .projects
 782            .extend(Self::build_participant_project(project_id, &self.projects));
 783
 784        Ok(room)
 785    }
 786
 787    pub fn unshare_project(
 788        &mut self,
 789        project_id: ProjectId,
 790        connection_id: ConnectionId,
 791    ) -> Result<(&proto::Room, Project)> {
 792        match self.projects.entry(project_id) {
 793            btree_map::Entry::Occupied(e) => {
 794                if e.get().host_connection_id == connection_id {
 795                    let project = e.remove();
 796
 797                    if let Some(host_connection) = self.connections.get_mut(&connection_id) {
 798                        host_connection.projects.remove(&project_id);
 799                    }
 800
 801                    for guest_connection in project.guests.keys() {
 802                        if let Some(connection) = self.connections.get_mut(guest_connection) {
 803                            connection.projects.remove(&project_id);
 804                        }
 805                    }
 806
 807                    let room = self
 808                        .rooms
 809                        .get_mut(&project.room_id)
 810                        .ok_or_else(|| anyhow!("no such room"))?;
 811                    let participant = room
 812                        .participants
 813                        .iter_mut()
 814                        .find(|participant| participant.peer_id == connection_id.0)
 815                        .ok_or_else(|| anyhow!("no such room"))?;
 816                    participant
 817                        .projects
 818                        .retain(|project| project.id != project_id.to_proto());
 819
 820                    Ok((room, project))
 821                } else {
 822                    Err(anyhow!("no such project"))?
 823                }
 824            }
 825            btree_map::Entry::Vacant(_) => Err(anyhow!("no such project"))?,
 826        }
 827    }
 828
 829    pub fn update_project(
 830        &mut self,
 831        project_id: ProjectId,
 832        worktrees: &[proto::WorktreeMetadata],
 833        connection_id: ConnectionId,
 834    ) -> Result<&proto::Room> {
 835        let project = self
 836            .projects
 837            .get_mut(&project_id)
 838            .ok_or_else(|| anyhow!("no such project"))?;
 839        if project.host_connection_id == connection_id {
 840            let mut old_worktrees = mem::take(&mut project.worktrees);
 841            for worktree in worktrees {
 842                if let Some(old_worktree) = old_worktrees.remove(&worktree.id) {
 843                    project.worktrees.insert(worktree.id, old_worktree);
 844                } else {
 845                    project.worktrees.insert(
 846                        worktree.id,
 847                        Worktree {
 848                            root_name: worktree.root_name.clone(),
 849                            visible: worktree.visible,
 850                            ..Default::default()
 851                        },
 852                    );
 853                }
 854            }
 855
 856            let room = self
 857                .rooms
 858                .get_mut(&project.room_id)
 859                .ok_or_else(|| anyhow!("no such room"))?;
 860            let participant_project = room
 861                .participants
 862                .iter_mut()
 863                .flat_map(|participant| &mut participant.projects)
 864                .find(|project| project.id == project_id.to_proto())
 865                .ok_or_else(|| anyhow!("no such project"))?;
 866            participant_project.worktree_root_names = worktrees
 867                .iter()
 868                .filter(|worktree| worktree.visible)
 869                .map(|worktree| worktree.root_name.clone())
 870                .collect();
 871
 872            Ok(room)
 873        } else {
 874            Err(anyhow!("no such project"))?
 875        }
 876    }
 877
 878    pub fn update_diagnostic_summary(
 879        &mut self,
 880        project_id: ProjectId,
 881        worktree_id: u64,
 882        connection_id: ConnectionId,
 883        summary: proto::DiagnosticSummary,
 884    ) -> Result<Vec<ConnectionId>> {
 885        let project = self
 886            .projects
 887            .get_mut(&project_id)
 888            .ok_or_else(|| anyhow!("no such project"))?;
 889        if project.host_connection_id == connection_id {
 890            let worktree = project
 891                .worktrees
 892                .get_mut(&worktree_id)
 893                .ok_or_else(|| anyhow!("no such worktree"))?;
 894            worktree
 895                .diagnostic_summaries
 896                .insert(summary.path.clone().into(), summary);
 897            return Ok(project.connection_ids());
 898        }
 899
 900        Err(anyhow!("no such worktree"))?
 901    }
 902
 903    pub fn start_language_server(
 904        &mut self,
 905        project_id: ProjectId,
 906        connection_id: ConnectionId,
 907        language_server: proto::LanguageServer,
 908    ) -> Result<Vec<ConnectionId>> {
 909        let project = self
 910            .projects
 911            .get_mut(&project_id)
 912            .ok_or_else(|| anyhow!("no such project"))?;
 913        if project.host_connection_id == connection_id {
 914            project.language_servers.push(language_server);
 915            return Ok(project.connection_ids());
 916        }
 917
 918        Err(anyhow!("no such project"))?
 919    }
 920
 921    pub fn join_project(
 922        &mut self,
 923        requester_connection_id: ConnectionId,
 924        project_id: ProjectId,
 925    ) -> Result<(&Project, ReplicaId)> {
 926        let connection = self
 927            .connections
 928            .get_mut(&requester_connection_id)
 929            .ok_or_else(|| anyhow!("no such connection"))?;
 930        let user = self
 931            .connected_users
 932            .get(&connection.user_id)
 933            .ok_or_else(|| anyhow!("no such connection"))?;
 934        let active_call = user.active_call.ok_or_else(|| anyhow!("no such project"))?;
 935        anyhow::ensure!(
 936            active_call.connection_id == Some(requester_connection_id),
 937            "no such project"
 938        );
 939
 940        let project = self
 941            .projects
 942            .get_mut(&project_id)
 943            .ok_or_else(|| anyhow!("no such project"))?;
 944        anyhow::ensure!(project.room_id == active_call.room_id, "no such project");
 945
 946        connection.projects.insert(project_id);
 947        let mut replica_id = 1;
 948        while project.active_replica_ids.contains(&replica_id) {
 949            replica_id += 1;
 950        }
 951        project.active_replica_ids.insert(replica_id);
 952        project.guests.insert(
 953            requester_connection_id,
 954            Collaborator {
 955                replica_id,
 956                user_id: connection.user_id,
 957                last_activity: Some(OffsetDateTime::now_utc()),
 958                admin: connection.admin,
 959            },
 960        );
 961
 962        project.host.last_activity = Some(OffsetDateTime::now_utc());
 963        Ok((project, replica_id))
 964    }
 965
 966    pub fn leave_project(
 967        &mut self,
 968        project_id: ProjectId,
 969        connection_id: ConnectionId,
 970    ) -> Result<LeftProject> {
 971        let project = self
 972            .projects
 973            .get_mut(&project_id)
 974            .ok_or_else(|| anyhow!("no such project"))?;
 975
 976        // If the connection leaving the project is a collaborator, remove it.
 977        let remove_collaborator = if let Some(guest) = project.guests.remove(&connection_id) {
 978            project.active_replica_ids.remove(&guest.replica_id);
 979            true
 980        } else {
 981            false
 982        };
 983
 984        if let Some(connection) = self.connections.get_mut(&connection_id) {
 985            connection.projects.remove(&project_id);
 986        }
 987
 988        Ok(LeftProject {
 989            id: project.id,
 990            host_connection_id: project.host_connection_id,
 991            host_user_id: project.host.user_id,
 992            connection_ids: project.connection_ids(),
 993            remove_collaborator,
 994        })
 995    }
 996
 997    #[allow(clippy::too_many_arguments)]
 998    pub fn update_worktree(
 999        &mut self,
1000        connection_id: ConnectionId,
1001        project_id: ProjectId,
1002        worktree_id: u64,
1003        worktree_root_name: &str,
1004        removed_entries: &[u64],
1005        updated_entries: &[proto::Entry],
1006        scan_id: u64,
1007        is_last_update: bool,
1008    ) -> Result<Vec<ConnectionId>> {
1009        let project = self.write_project(project_id, connection_id)?;
1010
1011        let connection_ids = project.connection_ids();
1012        let mut worktree = project.worktrees.entry(worktree_id).or_default();
1013        worktree.root_name = worktree_root_name.to_string();
1014
1015        for entry_id in removed_entries {
1016            worktree.entries.remove(entry_id);
1017        }
1018
1019        for entry in updated_entries {
1020            worktree.entries.insert(entry.id, entry.clone());
1021        }
1022
1023        worktree.scan_id = scan_id;
1024        worktree.is_complete = is_last_update;
1025        Ok(connection_ids)
1026    }
1027
1028    fn build_participant_project(
1029        project_id: ProjectId,
1030        projects: &BTreeMap<ProjectId, Project>,
1031    ) -> Option<proto::ParticipantProject> {
1032        Some(proto::ParticipantProject {
1033            id: project_id.to_proto(),
1034            worktree_root_names: projects
1035                .get(&project_id)?
1036                .worktrees
1037                .values()
1038                .filter(|worktree| worktree.visible)
1039                .map(|worktree| worktree.root_name.clone())
1040                .collect(),
1041        })
1042    }
1043
1044    pub fn project_connection_ids(
1045        &self,
1046        project_id: ProjectId,
1047        acting_connection_id: ConnectionId,
1048    ) -> Result<Vec<ConnectionId>> {
1049        Ok(self
1050            .read_project(project_id, acting_connection_id)?
1051            .connection_ids())
1052    }
1053
1054    pub fn channel_connection_ids(&self, channel_id: ChannelId) -> Result<Vec<ConnectionId>> {
1055        Ok(self
1056            .channels
1057            .get(&channel_id)
1058            .ok_or_else(|| anyhow!("no such channel"))?
1059            .connection_ids())
1060    }
1061
1062    pub fn project(&self, project_id: ProjectId) -> Result<&Project> {
1063        self.projects
1064            .get(&project_id)
1065            .ok_or_else(|| anyhow!("no such project"))
1066    }
1067
1068    pub fn register_project_activity(
1069        &mut self,
1070        project_id: ProjectId,
1071        connection_id: ConnectionId,
1072    ) -> Result<()> {
1073        let project = self
1074            .projects
1075            .get_mut(&project_id)
1076            .ok_or_else(|| anyhow!("no such project"))?;
1077        let collaborator = if connection_id == project.host_connection_id {
1078            &mut project.host
1079        } else if let Some(guest) = project.guests.get_mut(&connection_id) {
1080            guest
1081        } else {
1082            return Err(anyhow!("no such project"))?;
1083        };
1084        collaborator.last_activity = Some(OffsetDateTime::now_utc());
1085        Ok(())
1086    }
1087
1088    pub fn projects(&self) -> impl Iterator<Item = (&ProjectId, &Project)> {
1089        self.projects.iter()
1090    }
1091
1092    pub fn read_project(
1093        &self,
1094        project_id: ProjectId,
1095        connection_id: ConnectionId,
1096    ) -> Result<&Project> {
1097        let project = self
1098            .projects
1099            .get(&project_id)
1100            .ok_or_else(|| anyhow!("no such project"))?;
1101        if project.host_connection_id == connection_id
1102            || project.guests.contains_key(&connection_id)
1103        {
1104            Ok(project)
1105        } else {
1106            Err(anyhow!("no such project"))?
1107        }
1108    }
1109
1110    fn write_project(
1111        &mut self,
1112        project_id: ProjectId,
1113        connection_id: ConnectionId,
1114    ) -> Result<&mut Project> {
1115        let project = self
1116            .projects
1117            .get_mut(&project_id)
1118            .ok_or_else(|| anyhow!("no such project"))?;
1119        if project.host_connection_id == connection_id
1120            || project.guests.contains_key(&connection_id)
1121        {
1122            Ok(project)
1123        } else {
1124            Err(anyhow!("no such project"))?
1125        }
1126    }
1127
1128    #[cfg(test)]
1129    pub fn check_invariants(&self) {
1130        for (connection_id, connection) in &self.connections {
1131            for project_id in &connection.projects {
1132                let project = &self.projects.get(project_id).unwrap();
1133                if project.host_connection_id != *connection_id {
1134                    assert!(project.guests.contains_key(connection_id));
1135                }
1136
1137                for (worktree_id, worktree) in project.worktrees.iter() {
1138                    let mut paths = HashMap::default();
1139                    for entry in worktree.entries.values() {
1140                        let prev_entry = paths.insert(&entry.path, entry);
1141                        assert_eq!(
1142                            prev_entry,
1143                            None,
1144                            "worktree {:?}, duplicate path for entries {:?} and {:?}",
1145                            worktree_id,
1146                            prev_entry.unwrap(),
1147                            entry
1148                        );
1149                    }
1150                }
1151            }
1152            for channel_id in &connection.channels {
1153                let channel = self.channels.get(channel_id).unwrap();
1154                assert!(channel.connection_ids.contains(connection_id));
1155            }
1156            assert!(self
1157                .connected_users
1158                .get(&connection.user_id)
1159                .unwrap()
1160                .connection_ids
1161                .contains(connection_id));
1162        }
1163
1164        for (user_id, state) in &self.connected_users {
1165            for connection_id in &state.connection_ids {
1166                assert_eq!(
1167                    self.connections.get(connection_id).unwrap().user_id,
1168                    *user_id
1169                );
1170            }
1171
1172            if let Some(active_call) = state.active_call.as_ref() {
1173                if let Some(active_call_connection_id) = active_call.connection_id {
1174                    assert!(
1175                        state.connection_ids.contains(&active_call_connection_id),
1176                        "call is active on a dead connection"
1177                    );
1178                    assert!(
1179                        state.connection_ids.contains(&active_call_connection_id),
1180                        "call is active on a dead connection"
1181                    );
1182                }
1183            }
1184        }
1185
1186        for (room_id, room) in &self.rooms {
1187            for pending_user_id in &room.pending_participant_user_ids {
1188                assert!(
1189                    self.connected_users
1190                        .contains_key(&UserId::from_proto(*pending_user_id)),
1191                    "call is active on a user that has disconnected"
1192                );
1193            }
1194
1195            for participant in &room.participants {
1196                assert!(
1197                    self.connections
1198                        .contains_key(&ConnectionId(participant.peer_id)),
1199                    "room contains participant that has disconnected"
1200                );
1201
1202                for participant_project in &participant.projects {
1203                    let project = &self.projects[&ProjectId::from_proto(participant_project.id)];
1204                    assert_eq!(
1205                        project.room_id, *room_id,
1206                        "project was shared on a different room"
1207                    );
1208                }
1209            }
1210
1211            assert!(
1212                !room.pending_participant_user_ids.is_empty() || !room.participants.is_empty(),
1213                "room can't be empty"
1214            );
1215        }
1216
1217        for (project_id, project) in &self.projects {
1218            let host_connection = self.connections.get(&project.host_connection_id).unwrap();
1219            assert!(host_connection.projects.contains(project_id));
1220
1221            for guest_connection_id in project.guests.keys() {
1222                let guest_connection = self.connections.get(guest_connection_id).unwrap();
1223                assert!(guest_connection.projects.contains(project_id));
1224            }
1225            assert_eq!(project.active_replica_ids.len(), project.guests.len());
1226            assert_eq!(
1227                project.active_replica_ids,
1228                project
1229                    .guests
1230                    .values()
1231                    .map(|guest| guest.replica_id)
1232                    .collect::<HashSet<_>>(),
1233            );
1234
1235            let room = &self.rooms[&project.room_id];
1236            let room_participant = room
1237                .participants
1238                .iter()
1239                .find(|participant| participant.peer_id == project.host_connection_id.0)
1240                .unwrap();
1241            assert!(
1242                room_participant
1243                    .projects
1244                    .iter()
1245                    .any(|project| project.id == project_id.to_proto()),
1246                "project was not shared in room"
1247            );
1248        }
1249
1250        for (channel_id, channel) in &self.channels {
1251            for connection_id in &channel.connection_ids {
1252                let connection = self.connections.get(connection_id).unwrap();
1253                assert!(connection.channels.contains(channel_id));
1254            }
1255        }
1256    }
1257}
1258
1259impl Project {
1260    fn is_active_since(&self, start_time: OffsetDateTime) -> bool {
1261        self.guests
1262            .values()
1263            .chain([&self.host])
1264            .any(|collaborator| {
1265                collaborator
1266                    .last_activity
1267                    .map_or(false, |active_time| active_time > start_time)
1268            })
1269    }
1270
1271    pub fn guest_connection_ids(&self) -> Vec<ConnectionId> {
1272        self.guests.keys().copied().collect()
1273    }
1274
1275    pub fn connection_ids(&self) -> Vec<ConnectionId> {
1276        self.guests
1277            .keys()
1278            .copied()
1279            .chain(Some(self.host_connection_id))
1280            .collect()
1281    }
1282}
1283
1284impl Channel {
1285    fn connection_ids(&self) -> Vec<ConnectionId> {
1286        self.connection_ids.iter().copied().collect()
1287    }
1288}