rooms.rs

   1use super::*;
   2
   3impl Database {
   4    /// Clears all room participants in rooms attached to a stale server.
   5    pub async fn clear_stale_room_participants(
   6        &self,
   7        room_id: RoomId,
   8        new_server_id: ServerId,
   9    ) -> Result<TransactionGuard<RefreshedRoom>> {
  10        self.room_transaction(room_id, |tx| async move {
  11            let stale_participant_filter = Condition::all()
  12                .add(room_participant::Column::RoomId.eq(room_id))
  13                .add(room_participant::Column::AnsweringConnectionId.is_not_null())
  14                .add(room_participant::Column::AnsweringConnectionServerId.ne(new_server_id));
  15
  16            let stale_participant_user_ids = room_participant::Entity::find()
  17                .filter(stale_participant_filter.clone())
  18                .all(&*tx)
  19                .await?
  20                .into_iter()
  21                .map(|participant| participant.user_id)
  22                .collect::<Vec<_>>();
  23
  24            // Delete participants who failed to reconnect and cancel their calls.
  25            let mut canceled_calls_to_user_ids = Vec::new();
  26            room_participant::Entity::delete_many()
  27                .filter(stale_participant_filter)
  28                .exec(&*tx)
  29                .await?;
  30            let called_participants = room_participant::Entity::find()
  31                .filter(
  32                    Condition::all()
  33                        .add(
  34                            room_participant::Column::CallingUserId
  35                                .is_in(stale_participant_user_ids.iter().copied()),
  36                        )
  37                        .add(room_participant::Column::AnsweringConnectionId.is_null()),
  38                )
  39                .all(&*tx)
  40                .await?;
  41            room_participant::Entity::delete_many()
  42                .filter(
  43                    room_participant::Column::Id
  44                        .is_in(called_participants.iter().map(|participant| participant.id)),
  45                )
  46                .exec(&*tx)
  47                .await?;
  48            canceled_calls_to_user_ids.extend(
  49                called_participants
  50                    .into_iter()
  51                    .map(|participant| participant.user_id),
  52            );
  53
  54            let (channel, room) = self.get_channel_room(room_id, &tx).await?;
  55            if channel.is_none() {
  56                // Delete the room if it becomes empty.
  57                if room.participants.is_empty() {
  58                    project::Entity::delete_many()
  59                        .filter(project::Column::RoomId.eq(room_id))
  60                        .exec(&*tx)
  61                        .await?;
  62                    room::Entity::delete_by_id(room_id).exec(&*tx).await?;
  63                }
  64            };
  65
  66            Ok(RefreshedRoom {
  67                room,
  68                channel,
  69                stale_participant_user_ids,
  70                canceled_calls_to_user_ids,
  71            })
  72        })
  73        .await
  74    }
  75
  76    /// Returns the incoming calls for user with the given ID.
  77    pub async fn incoming_call_for_user(
  78        &self,
  79        user_id: UserId,
  80    ) -> Result<Option<proto::IncomingCall>> {
  81        self.transaction(|tx| async move {
  82            let pending_participant = room_participant::Entity::find()
  83                .filter(
  84                    room_participant::Column::UserId
  85                        .eq(user_id)
  86                        .and(room_participant::Column::AnsweringConnectionId.is_null()),
  87                )
  88                .one(&*tx)
  89                .await?;
  90
  91            if let Some(pending_participant) = pending_participant {
  92                let room = self.get_room(pending_participant.room_id, &tx).await?;
  93                Ok(Self::build_incoming_call(&room, user_id))
  94            } else {
  95                Ok(None)
  96            }
  97        })
  98        .await
  99    }
 100
 101    /// Creates a new room.
 102    pub async fn create_room(
 103        &self,
 104        user_id: UserId,
 105        connection: ConnectionId,
 106        livekit_room: &str,
 107    ) -> Result<proto::Room> {
 108        self.transaction(|tx| async move {
 109            let room = room::ActiveModel {
 110                live_kit_room: ActiveValue::set(livekit_room.into()),
 111                ..Default::default()
 112            }
 113            .insert(&*tx)
 114            .await?;
 115            room_participant::ActiveModel {
 116                room_id: ActiveValue::set(room.id),
 117                user_id: ActiveValue::set(user_id),
 118                answering_connection_id: ActiveValue::set(Some(connection.id as i32)),
 119                answering_connection_server_id: ActiveValue::set(Some(ServerId(
 120                    connection.owner_id as i32,
 121                ))),
 122                answering_connection_lost: ActiveValue::set(false),
 123                calling_user_id: ActiveValue::set(user_id),
 124                calling_connection_id: ActiveValue::set(connection.id as i32),
 125                calling_connection_server_id: ActiveValue::set(Some(ServerId(
 126                    connection.owner_id as i32,
 127                ))),
 128                participant_index: ActiveValue::set(Some(0)),
 129                role: ActiveValue::set(Some(ChannelRole::Admin)),
 130
 131                id: ActiveValue::NotSet,
 132                location_kind: ActiveValue::NotSet,
 133                location_project_id: ActiveValue::NotSet,
 134                initial_project_id: ActiveValue::NotSet,
 135            }
 136            .insert(&*tx)
 137            .await?;
 138
 139            let room = self.get_room(room.id, &tx).await?;
 140            Ok(room)
 141        })
 142        .await
 143    }
 144
 145    pub async fn call(
 146        &self,
 147        room_id: RoomId,
 148        calling_user_id: UserId,
 149        calling_connection: ConnectionId,
 150        called_user_id: UserId,
 151        initial_project_id: Option<ProjectId>,
 152    ) -> Result<TransactionGuard<(proto::Room, proto::IncomingCall)>> {
 153        self.room_transaction(room_id, |tx| async move {
 154            let caller = room_participant::Entity::find()
 155                .filter(
 156                    room_participant::Column::UserId
 157                        .eq(calling_user_id)
 158                        .and(room_participant::Column::RoomId.eq(room_id)),
 159                )
 160                .one(&*tx)
 161                .await?
 162                .ok_or_else(|| anyhow!("user is not in the room"))?;
 163
 164            let called_user_role = match caller.role.unwrap_or(ChannelRole::Member) {
 165                ChannelRole::Admin | ChannelRole::Member => ChannelRole::Member,
 166                ChannelRole::Guest | ChannelRole::Talker => ChannelRole::Guest,
 167                ChannelRole::Banned => return Err(anyhow!("banned users cannot invite").into()),
 168            };
 169
 170            room_participant::ActiveModel {
 171                room_id: ActiveValue::set(room_id),
 172                user_id: ActiveValue::set(called_user_id),
 173                answering_connection_lost: ActiveValue::set(false),
 174                participant_index: ActiveValue::NotSet,
 175                calling_user_id: ActiveValue::set(calling_user_id),
 176                calling_connection_id: ActiveValue::set(calling_connection.id as i32),
 177                calling_connection_server_id: ActiveValue::set(Some(ServerId(
 178                    calling_connection.owner_id as i32,
 179                ))),
 180                initial_project_id: ActiveValue::set(initial_project_id),
 181                role: ActiveValue::set(Some(called_user_role)),
 182
 183                id: ActiveValue::NotSet,
 184                answering_connection_id: ActiveValue::NotSet,
 185                answering_connection_server_id: ActiveValue::NotSet,
 186                location_kind: ActiveValue::NotSet,
 187                location_project_id: ActiveValue::NotSet,
 188            }
 189            .insert(&*tx)
 190            .await?;
 191
 192            let room = self.get_room(room_id, &tx).await?;
 193            let incoming_call = Self::build_incoming_call(&room, called_user_id)
 194                .ok_or_else(|| anyhow!("failed to build incoming call"))?;
 195            Ok((room, incoming_call))
 196        })
 197        .await
 198    }
 199
 200    pub async fn call_failed(
 201        &self,
 202        room_id: RoomId,
 203        called_user_id: UserId,
 204    ) -> Result<TransactionGuard<proto::Room>> {
 205        self.room_transaction(room_id, |tx| async move {
 206            room_participant::Entity::delete_many()
 207                .filter(
 208                    room_participant::Column::RoomId
 209                        .eq(room_id)
 210                        .and(room_participant::Column::UserId.eq(called_user_id)),
 211                )
 212                .exec(&*tx)
 213                .await?;
 214            let room = self.get_room(room_id, &tx).await?;
 215            Ok(room)
 216        })
 217        .await
 218    }
 219
 220    pub async fn decline_call(
 221        &self,
 222        expected_room_id: Option<RoomId>,
 223        user_id: UserId,
 224    ) -> Result<Option<TransactionGuard<proto::Room>>> {
 225        self.optional_room_transaction(|tx| async move {
 226            let mut filter = Condition::all()
 227                .add(room_participant::Column::UserId.eq(user_id))
 228                .add(room_participant::Column::AnsweringConnectionId.is_null());
 229            if let Some(room_id) = expected_room_id {
 230                filter = filter.add(room_participant::Column::RoomId.eq(room_id));
 231            }
 232            let participant = room_participant::Entity::find()
 233                .filter(filter)
 234                .one(&*tx)
 235                .await?;
 236
 237            let participant = if let Some(participant) = participant {
 238                participant
 239            } else if expected_room_id.is_some() {
 240                return Err(anyhow!("could not find call to decline"))?;
 241            } else {
 242                return Ok(None);
 243            };
 244
 245            let room_id = participant.room_id;
 246            room_participant::Entity::delete(participant.into_active_model())
 247                .exec(&*tx)
 248                .await?;
 249
 250            let room = self.get_room(room_id, &tx).await?;
 251            Ok(Some((room_id, room)))
 252        })
 253        .await
 254    }
 255
 256    pub async fn cancel_call(
 257        &self,
 258        room_id: RoomId,
 259        calling_connection: ConnectionId,
 260        called_user_id: UserId,
 261    ) -> Result<TransactionGuard<proto::Room>> {
 262        self.room_transaction(room_id, |tx| async move {
 263            let participant = room_participant::Entity::find()
 264                .filter(
 265                    Condition::all()
 266                        .add(room_participant::Column::UserId.eq(called_user_id))
 267                        .add(room_participant::Column::RoomId.eq(room_id))
 268                        .add(
 269                            room_participant::Column::CallingConnectionId
 270                                .eq(calling_connection.id as i32),
 271                        )
 272                        .add(
 273                            room_participant::Column::CallingConnectionServerId
 274                                .eq(calling_connection.owner_id as i32),
 275                        )
 276                        .add(room_participant::Column::AnsweringConnectionId.is_null()),
 277                )
 278                .one(&*tx)
 279                .await?
 280                .ok_or_else(|| anyhow!("no call to cancel"))?;
 281
 282            room_participant::Entity::delete(participant.into_active_model())
 283                .exec(&*tx)
 284                .await?;
 285
 286            let room = self.get_room(room_id, &tx).await?;
 287            Ok(room)
 288        })
 289        .await
 290    }
 291
 292    pub async fn join_room(
 293        &self,
 294        room_id: RoomId,
 295        user_id: UserId,
 296        connection: ConnectionId,
 297    ) -> Result<TransactionGuard<JoinRoom>> {
 298        self.room_transaction(room_id, |tx| async move {
 299            #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
 300            enum QueryChannelId {
 301                ChannelId,
 302            }
 303
 304            let channel_id: Option<ChannelId> = room::Entity::find()
 305                .select_only()
 306                .column(room::Column::ChannelId)
 307                .filter(room::Column::Id.eq(room_id))
 308                .into_values::<_, QueryChannelId>()
 309                .one(&*tx)
 310                .await?
 311                .ok_or_else(|| anyhow!("no such room"))?;
 312
 313            if channel_id.is_some() {
 314                Err(anyhow!("tried to join channel call directly"))?
 315            }
 316
 317            let participant_index = self
 318                .get_next_participant_index_internal(room_id, &tx)
 319                .await?;
 320
 321            let result = room_participant::Entity::update_many()
 322                .filter(
 323                    Condition::all()
 324                        .add(room_participant::Column::RoomId.eq(room_id))
 325                        .add(room_participant::Column::UserId.eq(user_id))
 326                        .add(room_participant::Column::AnsweringConnectionId.is_null()),
 327                )
 328                .set(room_participant::ActiveModel {
 329                    participant_index: ActiveValue::Set(Some(participant_index)),
 330                    answering_connection_id: ActiveValue::set(Some(connection.id as i32)),
 331                    answering_connection_server_id: ActiveValue::set(Some(ServerId(
 332                        connection.owner_id as i32,
 333                    ))),
 334                    answering_connection_lost: ActiveValue::set(false),
 335                    ..Default::default()
 336                })
 337                .exec(&*tx)
 338                .await?;
 339            if result.rows_affected == 0 {
 340                Err(anyhow!("room does not exist or was already joined"))?;
 341            }
 342
 343            let room = self.get_room(room_id, &tx).await?;
 344            Ok(JoinRoom {
 345                room,
 346                channel: None,
 347            })
 348        })
 349        .await
 350    }
 351
 352    pub async fn stale_room_connection(&self, user_id: UserId) -> Result<Option<ConnectionId>> {
 353        self.transaction(|tx| async move {
 354            let participant = room_participant::Entity::find()
 355                .filter(room_participant::Column::UserId.eq(user_id))
 356                .one(&*tx)
 357                .await?;
 358            Ok(participant.and_then(|p| p.answering_connection()))
 359        })
 360        .await
 361    }
 362
 363    async fn get_next_participant_index_internal(
 364        &self,
 365        room_id: RoomId,
 366        tx: &DatabaseTransaction,
 367    ) -> Result<i32> {
 368        #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
 369        enum QueryParticipantIndices {
 370            ParticipantIndex,
 371        }
 372        let existing_participant_indices: Vec<i32> = room_participant::Entity::find()
 373            .filter(
 374                room_participant::Column::RoomId
 375                    .eq(room_id)
 376                    .and(room_participant::Column::ParticipantIndex.is_not_null()),
 377            )
 378            .select_only()
 379            .column(room_participant::Column::ParticipantIndex)
 380            .into_values::<_, QueryParticipantIndices>()
 381            .all(tx)
 382            .await?;
 383
 384        let mut participant_index = 0;
 385        while existing_participant_indices.contains(&participant_index) {
 386            participant_index += 1;
 387        }
 388
 389        Ok(participant_index)
 390    }
 391
 392    /// Returns the channel ID for the given room, if it has one.
 393    pub async fn channel_id_for_room(&self, room_id: RoomId) -> Result<Option<ChannelId>> {
 394        self.transaction(|tx| async move {
 395            let room: Option<room::Model> = room::Entity::find()
 396                .filter(room::Column::Id.eq(room_id))
 397                .one(&*tx)
 398                .await?;
 399
 400            Ok(room.and_then(|room| room.channel_id))
 401        })
 402        .await
 403    }
 404
 405    pub(crate) async fn join_channel_room_internal(
 406        &self,
 407        room_id: RoomId,
 408        user_id: UserId,
 409        connection: ConnectionId,
 410        role: ChannelRole,
 411        tx: &DatabaseTransaction,
 412    ) -> Result<JoinRoom> {
 413        let participant_index = self
 414            .get_next_participant_index_internal(room_id, tx)
 415            .await?;
 416
 417        // If someone has been invited into the room, accept the invite instead of inserting
 418        let result = room_participant::Entity::update_many()
 419            .filter(
 420                Condition::all()
 421                    .add(room_participant::Column::RoomId.eq(room_id))
 422                    .add(room_participant::Column::UserId.eq(user_id))
 423                    .add(room_participant::Column::AnsweringConnectionId.is_null()),
 424            )
 425            .set(room_participant::ActiveModel {
 426                participant_index: ActiveValue::Set(Some(participant_index)),
 427                answering_connection_id: ActiveValue::set(Some(connection.id as i32)),
 428                answering_connection_server_id: ActiveValue::set(Some(ServerId(
 429                    connection.owner_id as i32,
 430                ))),
 431                answering_connection_lost: ActiveValue::set(false),
 432                ..Default::default()
 433            })
 434            .exec(tx)
 435            .await?;
 436
 437        if result.rows_affected == 0 {
 438            room_participant::Entity::insert(room_participant::ActiveModel {
 439                room_id: ActiveValue::set(room_id),
 440                user_id: ActiveValue::set(user_id),
 441                answering_connection_id: ActiveValue::set(Some(connection.id as i32)),
 442                answering_connection_server_id: ActiveValue::set(Some(ServerId(
 443                    connection.owner_id as i32,
 444                ))),
 445                answering_connection_lost: ActiveValue::set(false),
 446                calling_user_id: ActiveValue::set(user_id),
 447                calling_connection_id: ActiveValue::set(connection.id as i32),
 448                calling_connection_server_id: ActiveValue::set(Some(ServerId(
 449                    connection.owner_id as i32,
 450                ))),
 451                participant_index: ActiveValue::Set(Some(participant_index)),
 452                role: ActiveValue::set(Some(role)),
 453                id: ActiveValue::NotSet,
 454                location_kind: ActiveValue::NotSet,
 455                location_project_id: ActiveValue::NotSet,
 456                initial_project_id: ActiveValue::NotSet,
 457            })
 458            .exec(tx)
 459            .await?;
 460        }
 461
 462        let (channel, room) = self.get_channel_room(room_id, tx).await?;
 463        let channel = channel.ok_or_else(|| anyhow!("no channel for room"))?;
 464        Ok(JoinRoom {
 465            room,
 466            channel: Some(channel),
 467        })
 468    }
 469
 470    pub async fn rejoin_room(
 471        &self,
 472        rejoin_room: proto::RejoinRoom,
 473        user_id: UserId,
 474        connection: ConnectionId,
 475    ) -> Result<TransactionGuard<RejoinedRoom>> {
 476        let room_id = RoomId::from_proto(rejoin_room.id);
 477        self.room_transaction(room_id, |tx| async {
 478            let tx = tx;
 479            let participant_update = room_participant::Entity::update_many()
 480                .filter(
 481                    Condition::all()
 482                        .add(room_participant::Column::RoomId.eq(room_id))
 483                        .add(room_participant::Column::UserId.eq(user_id))
 484                        .add(room_participant::Column::AnsweringConnectionId.is_not_null()),
 485                )
 486                .set(room_participant::ActiveModel {
 487                    answering_connection_id: ActiveValue::set(Some(connection.id as i32)),
 488                    answering_connection_server_id: ActiveValue::set(Some(ServerId(
 489                        connection.owner_id as i32,
 490                    ))),
 491                    answering_connection_lost: ActiveValue::set(false),
 492                    ..Default::default()
 493                })
 494                .exec(&*tx)
 495                .await?;
 496            if participant_update.rows_affected == 0 {
 497                return Err(anyhow!("room does not exist or was already joined"))?;
 498            }
 499
 500            let mut reshared_projects = Vec::new();
 501            for reshared_project in &rejoin_room.reshared_projects {
 502                let project_id = ProjectId::from_proto(reshared_project.project_id);
 503                let project = project::Entity::find_by_id(project_id)
 504                    .one(&*tx)
 505                    .await?
 506                    .ok_or_else(|| anyhow!("project does not exist"))?;
 507                if project.host_user_id != Some(user_id) {
 508                    return Err(anyhow!("no such project"))?;
 509                }
 510
 511                let mut collaborators = project
 512                    .find_related(project_collaborator::Entity)
 513                    .all(&*tx)
 514                    .await?;
 515                let host_ix = collaborators
 516                    .iter()
 517                    .position(|collaborator| {
 518                        collaborator.user_id == user_id && collaborator.is_host
 519                    })
 520                    .ok_or_else(|| anyhow!("host not found among collaborators"))?;
 521                let host = collaborators.swap_remove(host_ix);
 522                let old_connection_id = host.connection();
 523
 524                project::Entity::update(project::ActiveModel {
 525                    host_connection_id: ActiveValue::set(Some(connection.id as i32)),
 526                    host_connection_server_id: ActiveValue::set(Some(ServerId(
 527                        connection.owner_id as i32,
 528                    ))),
 529                    ..project.into_active_model()
 530                })
 531                .exec(&*tx)
 532                .await?;
 533                project_collaborator::Entity::update(project_collaborator::ActiveModel {
 534                    connection_id: ActiveValue::set(connection.id as i32),
 535                    connection_server_id: ActiveValue::set(ServerId(connection.owner_id as i32)),
 536                    ..host.into_active_model()
 537                })
 538                .exec(&*tx)
 539                .await?;
 540
 541                self.update_project_worktrees(project_id, &reshared_project.worktrees, &tx)
 542                    .await?;
 543
 544                reshared_projects.push(ResharedProject {
 545                    id: project_id,
 546                    old_connection_id,
 547                    collaborators: collaborators
 548                        .iter()
 549                        .map(|collaborator| ProjectCollaborator {
 550                            connection_id: collaborator.connection(),
 551                            user_id: collaborator.user_id,
 552                            replica_id: collaborator.replica_id,
 553                            is_host: collaborator.is_host,
 554                        })
 555                        .collect(),
 556                    worktrees: reshared_project.worktrees.clone(),
 557                });
 558            }
 559
 560            project::Entity::delete_many()
 561                .filter(
 562                    Condition::all()
 563                        .add(project::Column::RoomId.eq(room_id))
 564                        .add(project::Column::HostUserId.eq(user_id))
 565                        .add(
 566                            project::Column::Id
 567                                .is_not_in(reshared_projects.iter().map(|project| project.id)),
 568                        ),
 569                )
 570                .exec(&*tx)
 571                .await?;
 572
 573            let mut rejoined_projects = Vec::new();
 574            for rejoined_project in &rejoin_room.rejoined_projects {
 575                if let Some(rejoined_project) = self
 576                    .rejoin_project_internal(&tx, rejoined_project, user_id, connection)
 577                    .await?
 578                {
 579                    rejoined_projects.push(rejoined_project);
 580                }
 581            }
 582
 583            let (channel, room) = self.get_channel_room(room_id, &tx).await?;
 584
 585            Ok(RejoinedRoom {
 586                room,
 587                channel,
 588                rejoined_projects,
 589                reshared_projects,
 590            })
 591        })
 592        .await
 593    }
 594
 595    pub async fn rejoin_project_internal(
 596        &self,
 597        tx: &DatabaseTransaction,
 598        rejoined_project: &proto::RejoinProject,
 599        user_id: UserId,
 600        connection: ConnectionId,
 601    ) -> Result<Option<RejoinedProject>> {
 602        let project_id = ProjectId::from_proto(rejoined_project.id);
 603        let Some(project) = project::Entity::find_by_id(project_id).one(tx).await? else {
 604            return Ok(None);
 605        };
 606
 607        let mut worktrees = Vec::new();
 608        let db_worktrees = project.find_related(worktree::Entity).all(tx).await?;
 609        for db_worktree in db_worktrees {
 610            let mut worktree = RejoinedWorktree {
 611                id: db_worktree.id as u64,
 612                abs_path: db_worktree.abs_path,
 613                root_name: db_worktree.root_name,
 614                visible: db_worktree.visible,
 615                updated_entries: Default::default(),
 616                removed_entries: Default::default(),
 617                updated_repositories: Default::default(),
 618                removed_repositories: Default::default(),
 619                diagnostic_summaries: Default::default(),
 620                settings_files: Default::default(),
 621                scan_id: db_worktree.scan_id as u64,
 622                completed_scan_id: db_worktree.completed_scan_id as u64,
 623            };
 624
 625            let rejoined_worktree = rejoined_project
 626                .worktrees
 627                .iter()
 628                .find(|worktree| worktree.id == db_worktree.id as u64);
 629
 630            // File entries
 631            {
 632                let entry_filter = if let Some(rejoined_worktree) = rejoined_worktree {
 633                    worktree_entry::Column::ScanId.gt(rejoined_worktree.scan_id)
 634                } else {
 635                    worktree_entry::Column::IsDeleted.eq(false)
 636                };
 637
 638                let mut db_entries = worktree_entry::Entity::find()
 639                    .filter(
 640                        Condition::all()
 641                            .add(worktree_entry::Column::ProjectId.eq(project.id))
 642                            .add(worktree_entry::Column::WorktreeId.eq(worktree.id))
 643                            .add(entry_filter),
 644                    )
 645                    .stream(tx)
 646                    .await?;
 647
 648                while let Some(db_entry) = db_entries.next().await {
 649                    let db_entry = db_entry?;
 650                    if db_entry.is_deleted {
 651                        worktree.removed_entries.push(db_entry.id as u64);
 652                    } else {
 653                        worktree.updated_entries.push(proto::Entry {
 654                            id: db_entry.id as u64,
 655                            is_dir: db_entry.is_dir,
 656                            path: db_entry.path,
 657                            inode: db_entry.inode as u64,
 658                            mtime: Some(proto::Timestamp {
 659                                seconds: db_entry.mtime_seconds as u64,
 660                                nanos: db_entry.mtime_nanos as u32,
 661                            }),
 662                            canonical_path: db_entry.canonical_path,
 663                            is_ignored: db_entry.is_ignored,
 664                            is_external: db_entry.is_external,
 665                            // This is only used in the summarization backlog, so if it's None,
 666                            // that just means we won't be able to detect when to resummarize
 667                            // based on total number of backlogged bytes - instead, we'd go
 668                            // on number of files only. That shouldn't be a huge deal in practice.
 669                            size: None,
 670                            is_fifo: db_entry.is_fifo,
 671                        });
 672                    }
 673                }
 674            }
 675
 676            // Repository Entries
 677            {
 678                let repository_entry_filter = if let Some(rejoined_worktree) = rejoined_worktree {
 679                    worktree_repository::Column::ScanId.gt(rejoined_worktree.scan_id)
 680                } else {
 681                    worktree_repository::Column::IsDeleted.eq(false)
 682                };
 683
 684                let db_repositories = worktree_repository::Entity::find()
 685                    .filter(
 686                        Condition::all()
 687                            .add(worktree_repository::Column::ProjectId.eq(project.id))
 688                            .add(worktree_repository::Column::WorktreeId.eq(worktree.id))
 689                            .add(repository_entry_filter),
 690                    )
 691                    .all(tx)
 692                    .await?;
 693
 694                for db_repository in db_repositories.into_iter() {
 695                    if db_repository.is_deleted {
 696                        worktree
 697                            .removed_repositories
 698                            .push(db_repository.work_directory_id as u64);
 699                    } else {
 700                        let status_entry_filter = if let Some(rejoined_worktree) = rejoined_worktree
 701                        {
 702                            worktree_repository_statuses::Column::ScanId
 703                                .gt(rejoined_worktree.scan_id)
 704                        } else {
 705                            worktree_repository_statuses::Column::IsDeleted.eq(false)
 706                        };
 707
 708                        let mut db_statuses = worktree_repository_statuses::Entity::find()
 709                            .filter(
 710                                Condition::all()
 711                                    .add(
 712                                        worktree_repository_statuses::Column::ProjectId
 713                                            .eq(project.id),
 714                                    )
 715                                    .add(
 716                                        worktree_repository_statuses::Column::WorktreeId
 717                                            .eq(worktree.id),
 718                                    )
 719                                    .add(
 720                                        worktree_repository_statuses::Column::WorkDirectoryId
 721                                            .eq(db_repository.work_directory_id),
 722                                    )
 723                                    .add(status_entry_filter),
 724                            )
 725                            .stream(tx)
 726                            .await?;
 727                        let mut removed_statuses = Vec::new();
 728                        let mut updated_statuses = Vec::new();
 729
 730                        while let Some(db_status) = db_statuses.next().await {
 731                            let db_status: worktree_repository_statuses::Model = db_status?;
 732                            if db_status.is_deleted {
 733                                removed_statuses.push(db_status.repo_path);
 734                            } else {
 735                                updated_statuses.push(db_status_to_proto(db_status)?);
 736                            }
 737                        }
 738
 739                        let current_merge_conflicts = db_repository
 740                            .current_merge_conflicts
 741                            .as_ref()
 742                            .map(|conflicts| serde_json::from_str(&conflicts))
 743                            .transpose()?
 744                            .unwrap_or_default();
 745
 746                        let branch_summary = db_repository
 747                            .branch_summary
 748                            .as_ref()
 749                            .map(|branch_summary| serde_json::from_str(&branch_summary))
 750                            .transpose()?
 751                            .unwrap_or_default();
 752
 753                        worktree.updated_repositories.push(proto::RepositoryEntry {
 754                            work_directory_id: db_repository.work_directory_id as u64,
 755                            branch: db_repository.branch,
 756                            updated_statuses,
 757                            removed_statuses,
 758                            current_merge_conflicts,
 759                            branch_summary,
 760                        });
 761                    }
 762                }
 763            }
 764
 765            worktrees.push(worktree);
 766        }
 767
 768        let language_servers = project
 769            .find_related(language_server::Entity)
 770            .all(tx)
 771            .await?
 772            .into_iter()
 773            .map(|language_server| proto::LanguageServer {
 774                id: language_server.id as u64,
 775                name: language_server.name,
 776                worktree_id: None,
 777            })
 778            .collect::<Vec<_>>();
 779
 780        {
 781            let mut db_settings_files = worktree_settings_file::Entity::find()
 782                .filter(worktree_settings_file::Column::ProjectId.eq(project_id))
 783                .stream(tx)
 784                .await?;
 785            while let Some(db_settings_file) = db_settings_files.next().await {
 786                let db_settings_file = db_settings_file?;
 787                if let Some(worktree) = worktrees
 788                    .iter_mut()
 789                    .find(|w| w.id == db_settings_file.worktree_id as u64)
 790                {
 791                    worktree.settings_files.push(WorktreeSettingsFile {
 792                        path: db_settings_file.path,
 793                        content: db_settings_file.content,
 794                        kind: db_settings_file.kind,
 795                    });
 796                }
 797            }
 798        }
 799
 800        let mut collaborators = project
 801            .find_related(project_collaborator::Entity)
 802            .all(tx)
 803            .await?;
 804        let self_collaborator = if let Some(self_collaborator_ix) = collaborators
 805            .iter()
 806            .position(|collaborator| collaborator.user_id == user_id)
 807        {
 808            collaborators.swap_remove(self_collaborator_ix)
 809        } else {
 810            return Ok(None);
 811        };
 812        let old_connection_id = self_collaborator.connection();
 813        project_collaborator::Entity::update(project_collaborator::ActiveModel {
 814            connection_id: ActiveValue::set(connection.id as i32),
 815            connection_server_id: ActiveValue::set(ServerId(connection.owner_id as i32)),
 816            ..self_collaborator.into_active_model()
 817        })
 818        .exec(tx)
 819        .await?;
 820
 821        let collaborators = collaborators
 822            .into_iter()
 823            .map(|collaborator| ProjectCollaborator {
 824                connection_id: collaborator.connection(),
 825                user_id: collaborator.user_id,
 826                replica_id: collaborator.replica_id,
 827                is_host: collaborator.is_host,
 828            })
 829            .collect::<Vec<_>>();
 830
 831        Ok(Some(RejoinedProject {
 832            id: project_id,
 833            old_connection_id,
 834            collaborators,
 835            worktrees,
 836            language_servers,
 837        }))
 838    }
 839
 840    pub async fn leave_room(
 841        &self,
 842        connection: ConnectionId,
 843    ) -> Result<Option<TransactionGuard<LeftRoom>>> {
 844        self.optional_room_transaction(|tx| async move {
 845            let leaving_participant = room_participant::Entity::find()
 846                .filter(
 847                    Condition::all()
 848                        .add(
 849                            room_participant::Column::AnsweringConnectionId
 850                                .eq(connection.id as i32),
 851                        )
 852                        .add(
 853                            room_participant::Column::AnsweringConnectionServerId
 854                                .eq(connection.owner_id as i32),
 855                        ),
 856                )
 857                .one(&*tx)
 858                .await?;
 859
 860            if let Some(leaving_participant) = leaving_participant {
 861                // Leave room.
 862                let room_id = leaving_participant.room_id;
 863                room_participant::Entity::delete_by_id(leaving_participant.id)
 864                    .exec(&*tx)
 865                    .await?;
 866
 867                // Cancel pending calls initiated by the leaving user.
 868                let called_participants = room_participant::Entity::find()
 869                    .filter(
 870                        Condition::all()
 871                            .add(
 872                                room_participant::Column::CallingUserId
 873                                    .eq(leaving_participant.user_id),
 874                            )
 875                            .add(room_participant::Column::AnsweringConnectionId.is_null()),
 876                    )
 877                    .all(&*tx)
 878                    .await?;
 879                room_participant::Entity::delete_many()
 880                    .filter(
 881                        room_participant::Column::Id
 882                            .is_in(called_participants.iter().map(|participant| participant.id)),
 883                    )
 884                    .exec(&*tx)
 885                    .await?;
 886                let canceled_calls_to_user_ids = called_participants
 887                    .into_iter()
 888                    .map(|participant| participant.user_id)
 889                    .collect();
 890
 891                // Detect left projects.
 892                #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
 893                enum QueryProjectIds {
 894                    ProjectId,
 895                }
 896                let project_ids: Vec<ProjectId> = project_collaborator::Entity::find()
 897                    .select_only()
 898                    .column_as(
 899                        project_collaborator::Column::ProjectId,
 900                        QueryProjectIds::ProjectId,
 901                    )
 902                    .filter(
 903                        Condition::all()
 904                            .add(
 905                                project_collaborator::Column::ConnectionId.eq(connection.id as i32),
 906                            )
 907                            .add(
 908                                project_collaborator::Column::ConnectionServerId
 909                                    .eq(connection.owner_id as i32),
 910                            ),
 911                    )
 912                    .into_values::<_, QueryProjectIds>()
 913                    .all(&*tx)
 914                    .await?;
 915
 916                let mut left_projects = HashMap::default();
 917                let mut collaborators = project_collaborator::Entity::find()
 918                    .filter(project_collaborator::Column::ProjectId.is_in(project_ids))
 919                    .stream(&*tx)
 920                    .await?;
 921
 922                while let Some(collaborator) = collaborators.next().await {
 923                    let collaborator = collaborator?;
 924                    let left_project =
 925                        left_projects
 926                            .entry(collaborator.project_id)
 927                            .or_insert(LeftProject {
 928                                id: collaborator.project_id,
 929                                connection_ids: Default::default(),
 930                                should_unshare: false,
 931                            });
 932
 933                    let collaborator_connection_id = collaborator.connection();
 934                    if collaborator_connection_id != connection {
 935                        left_project.connection_ids.push(collaborator_connection_id);
 936                    }
 937
 938                    if collaborator.is_host && collaborator.connection() == connection {
 939                        left_project.should_unshare = true;
 940                    }
 941                }
 942                drop(collaborators);
 943
 944                // Leave projects.
 945                project_collaborator::Entity::delete_many()
 946                    .filter(
 947                        Condition::all()
 948                            .add(
 949                                project_collaborator::Column::ConnectionId.eq(connection.id as i32),
 950                            )
 951                            .add(
 952                                project_collaborator::Column::ConnectionServerId
 953                                    .eq(connection.owner_id as i32),
 954                            ),
 955                    )
 956                    .exec(&*tx)
 957                    .await?;
 958
 959                follower::Entity::delete_many()
 960                    .filter(
 961                        Condition::all()
 962                            .add(follower::Column::FollowerConnectionId.eq(connection.id as i32)),
 963                    )
 964                    .exec(&*tx)
 965                    .await?;
 966
 967                // Unshare projects.
 968                project::Entity::delete_many()
 969                    .filter(
 970                        Condition::all()
 971                            .add(project::Column::RoomId.eq(room_id))
 972                            .add(project::Column::HostConnectionId.eq(connection.id as i32))
 973                            .add(
 974                                project::Column::HostConnectionServerId
 975                                    .eq(connection.owner_id as i32),
 976                            ),
 977                    )
 978                    .exec(&*tx)
 979                    .await?;
 980
 981                let (channel, room) = self.get_channel_room(room_id, &tx).await?;
 982                let deleted = if room.participants.is_empty() {
 983                    let result = room::Entity::delete_by_id(room_id).exec(&*tx).await?;
 984                    result.rows_affected > 0
 985                } else {
 986                    false
 987                };
 988
 989                let left_room = LeftRoom {
 990                    room,
 991                    channel,
 992                    left_projects,
 993                    canceled_calls_to_user_ids,
 994                    deleted,
 995                };
 996
 997                if left_room.room.participants.is_empty() {
 998                    self.rooms.remove(&room_id);
 999                }
1000
1001                Ok(Some((room_id, left_room)))
1002            } else {
1003                Ok(None)
1004            }
1005        })
1006        .await
1007    }
1008
1009    /// Updates the location of a participant in the given room.
1010    pub async fn update_room_participant_location(
1011        &self,
1012        room_id: RoomId,
1013        connection: ConnectionId,
1014        location: proto::ParticipantLocation,
1015    ) -> Result<TransactionGuard<proto::Room>> {
1016        self.room_transaction(room_id, |tx| async {
1017            let tx = tx;
1018            let location_kind;
1019            let location_project_id;
1020            match location
1021                .variant
1022                .as_ref()
1023                .ok_or_else(|| anyhow!("invalid location"))?
1024            {
1025                proto::participant_location::Variant::SharedProject(project) => {
1026                    location_kind = 0;
1027                    location_project_id = Some(ProjectId::from_proto(project.id));
1028                }
1029                proto::participant_location::Variant::UnsharedProject(_) => {
1030                    location_kind = 1;
1031                    location_project_id = None;
1032                }
1033                proto::participant_location::Variant::External(_) => {
1034                    location_kind = 2;
1035                    location_project_id = None;
1036                }
1037            }
1038
1039            let result = room_participant::Entity::update_many()
1040                .filter(
1041                    Condition::all()
1042                        .add(room_participant::Column::RoomId.eq(room_id))
1043                        .add(
1044                            room_participant::Column::AnsweringConnectionId
1045                                .eq(connection.id as i32),
1046                        )
1047                        .add(
1048                            room_participant::Column::AnsweringConnectionServerId
1049                                .eq(connection.owner_id as i32),
1050                        ),
1051                )
1052                .set(room_participant::ActiveModel {
1053                    location_kind: ActiveValue::set(Some(location_kind)),
1054                    location_project_id: ActiveValue::set(location_project_id),
1055                    ..Default::default()
1056                })
1057                .exec(&*tx)
1058                .await?;
1059
1060            if result.rows_affected == 1 {
1061                let room = self.get_room(room_id, &tx).await?;
1062                Ok(room)
1063            } else {
1064                Err(anyhow!("could not update room participant location"))?
1065            }
1066        })
1067        .await
1068    }
1069
1070    /// Sets the role of a participant in the given room.
1071    pub async fn set_room_participant_role(
1072        &self,
1073        admin_id: UserId,
1074        room_id: RoomId,
1075        user_id: UserId,
1076        role: ChannelRole,
1077    ) -> Result<TransactionGuard<proto::Room>> {
1078        self.room_transaction(room_id, |tx| async move {
1079            room_participant::Entity::find()
1080                .filter(
1081                    Condition::all()
1082                        .add(room_participant::Column::RoomId.eq(room_id))
1083                        .add(room_participant::Column::UserId.eq(admin_id))
1084                        .add(room_participant::Column::Role.eq(ChannelRole::Admin)),
1085                )
1086                .one(&*tx)
1087                .await?
1088                .ok_or_else(|| anyhow!("only admins can set participant role"))?;
1089
1090            if role.requires_cla() {
1091                self.check_user_has_signed_cla(user_id, room_id, &tx)
1092                    .await?;
1093            }
1094
1095            let result = room_participant::Entity::update_many()
1096                .filter(
1097                    Condition::all()
1098                        .add(room_participant::Column::RoomId.eq(room_id))
1099                        .add(room_participant::Column::UserId.eq(user_id)),
1100                )
1101                .set(room_participant::ActiveModel {
1102                    role: ActiveValue::set(Some(role)),
1103                    ..Default::default()
1104                })
1105                .exec(&*tx)
1106                .await?;
1107
1108            if result.rows_affected != 1 {
1109                Err(anyhow!("could not update room participant role"))?;
1110            }
1111            self.get_room(room_id, &tx).await
1112        })
1113        .await
1114    }
1115
1116    async fn check_user_has_signed_cla(
1117        &self,
1118        user_id: UserId,
1119        room_id: RoomId,
1120        tx: &DatabaseTransaction,
1121    ) -> Result<()> {
1122        let channel = room::Entity::find_by_id(room_id)
1123            .one(tx)
1124            .await?
1125            .ok_or_else(|| anyhow!("could not find room"))?
1126            .find_related(channel::Entity)
1127            .one(tx)
1128            .await?;
1129
1130        if let Some(channel) = channel {
1131            let requires_zed_cla = channel.requires_zed_cla
1132                || channel::Entity::find()
1133                    .filter(
1134                        channel::Column::Id
1135                            .is_in(channel.ancestors())
1136                            .and(channel::Column::RequiresZedCla.eq(true)),
1137                    )
1138                    .count(tx)
1139                    .await?
1140                    > 0;
1141            if requires_zed_cla
1142                && contributor::Entity::find()
1143                    .filter(contributor::Column::UserId.eq(user_id))
1144                    .one(tx)
1145                    .await?
1146                    .is_none()
1147            {
1148                Err(anyhow!("user has not signed the Zed CLA"))?;
1149            }
1150        }
1151        Ok(())
1152    }
1153
1154    pub async fn connection_lost(&self, connection: ConnectionId) -> Result<()> {
1155        self.transaction(|tx| async move {
1156            self.room_connection_lost(connection, &tx).await?;
1157            self.channel_buffer_connection_lost(connection, &tx).await?;
1158            self.channel_chat_connection_lost(connection, &tx).await?;
1159            Ok(())
1160        })
1161        .await
1162    }
1163
1164    pub async fn room_connection_lost(
1165        &self,
1166        connection: ConnectionId,
1167        tx: &DatabaseTransaction,
1168    ) -> Result<()> {
1169        let participant = room_participant::Entity::find()
1170            .filter(
1171                Condition::all()
1172                    .add(room_participant::Column::AnsweringConnectionId.eq(connection.id as i32))
1173                    .add(
1174                        room_participant::Column::AnsweringConnectionServerId
1175                            .eq(connection.owner_id as i32),
1176                    ),
1177            )
1178            .one(tx)
1179            .await?;
1180
1181        if let Some(participant) = participant {
1182            room_participant::Entity::update(room_participant::ActiveModel {
1183                answering_connection_lost: ActiveValue::set(true),
1184                ..participant.into_active_model()
1185            })
1186            .exec(tx)
1187            .await?;
1188        }
1189        Ok(())
1190    }
1191
1192    fn build_incoming_call(
1193        room: &proto::Room,
1194        called_user_id: UserId,
1195    ) -> Option<proto::IncomingCall> {
1196        let pending_participant = room
1197            .pending_participants
1198            .iter()
1199            .find(|participant| participant.user_id == called_user_id.to_proto())?;
1200
1201        Some(proto::IncomingCall {
1202            room_id: room.id,
1203            calling_user_id: pending_participant.calling_user_id,
1204            participant_user_ids: room
1205                .participants
1206                .iter()
1207                .map(|participant| participant.user_id)
1208                .collect(),
1209            initial_project: room.participants.iter().find_map(|participant| {
1210                let initial_project_id = pending_participant.initial_project_id?;
1211                participant
1212                    .projects
1213                    .iter()
1214                    .find(|project| project.id == initial_project_id)
1215                    .cloned()
1216            }),
1217        })
1218    }
1219
1220    pub async fn get_room(&self, room_id: RoomId, tx: &DatabaseTransaction) -> Result<proto::Room> {
1221        let (_, room) = self.get_channel_room(room_id, tx).await?;
1222        Ok(room)
1223    }
1224
1225    pub async fn room_connection_ids(
1226        &self,
1227        room_id: RoomId,
1228        connection_id: ConnectionId,
1229    ) -> Result<TransactionGuard<HashSet<ConnectionId>>> {
1230        self.room_transaction(room_id, |tx| async move {
1231            let mut participants = room_participant::Entity::find()
1232                .filter(room_participant::Column::RoomId.eq(room_id))
1233                .stream(&*tx)
1234                .await?;
1235
1236            let mut is_participant = false;
1237            let mut connection_ids = HashSet::default();
1238            while let Some(participant) = participants.next().await {
1239                let participant = participant?;
1240                if let Some(answering_connection) = participant.answering_connection() {
1241                    if answering_connection == connection_id {
1242                        is_participant = true;
1243                    } else {
1244                        connection_ids.insert(answering_connection);
1245                    }
1246                }
1247            }
1248
1249            if !is_participant {
1250                Err(anyhow!("not a room participant"))?;
1251            }
1252
1253            Ok(connection_ids)
1254        })
1255        .await
1256    }
1257
1258    async fn get_channel_room(
1259        &self,
1260        room_id: RoomId,
1261        tx: &DatabaseTransaction,
1262    ) -> Result<(Option<channel::Model>, proto::Room)> {
1263        let db_room = room::Entity::find_by_id(room_id)
1264            .one(tx)
1265            .await?
1266            .ok_or_else(|| anyhow!("could not find room"))?;
1267
1268        let mut db_participants = db_room
1269            .find_related(room_participant::Entity)
1270            .stream(tx)
1271            .await?;
1272        let mut participants = HashMap::default();
1273        let mut pending_participants = Vec::new();
1274        while let Some(db_participant) = db_participants.next().await {
1275            let db_participant = db_participant?;
1276            if let (
1277                Some(answering_connection_id),
1278                Some(answering_connection_server_id),
1279                Some(participant_index),
1280            ) = (
1281                db_participant.answering_connection_id,
1282                db_participant.answering_connection_server_id,
1283                db_participant.participant_index,
1284            ) {
1285                let location = match (
1286                    db_participant.location_kind,
1287                    db_participant.location_project_id,
1288                ) {
1289                    (Some(0), Some(project_id)) => {
1290                        Some(proto::participant_location::Variant::SharedProject(
1291                            proto::participant_location::SharedProject {
1292                                id: project_id.to_proto(),
1293                            },
1294                        ))
1295                    }
1296                    (Some(1), _) => Some(proto::participant_location::Variant::UnsharedProject(
1297                        Default::default(),
1298                    )),
1299                    _ => Some(proto::participant_location::Variant::External(
1300                        Default::default(),
1301                    )),
1302                };
1303
1304                let answering_connection = ConnectionId {
1305                    owner_id: answering_connection_server_id.0 as u32,
1306                    id: answering_connection_id as u32,
1307                };
1308                participants.insert(
1309                    answering_connection,
1310                    proto::Participant {
1311                        user_id: db_participant.user_id.to_proto(),
1312                        peer_id: Some(answering_connection.into()),
1313                        projects: Default::default(),
1314                        location: Some(proto::ParticipantLocation { variant: location }),
1315                        participant_index: participant_index as u32,
1316                        role: db_participant.role.unwrap_or(ChannelRole::Member).into(),
1317                    },
1318                );
1319            } else {
1320                pending_participants.push(proto::PendingParticipant {
1321                    user_id: db_participant.user_id.to_proto(),
1322                    calling_user_id: db_participant.calling_user_id.to_proto(),
1323                    initial_project_id: db_participant.initial_project_id.map(|id| id.to_proto()),
1324                });
1325            }
1326        }
1327        drop(db_participants);
1328
1329        let db_projects = db_room
1330            .find_related(project::Entity)
1331            .find_with_related(worktree::Entity)
1332            .all(tx)
1333            .await?;
1334
1335        for (db_project, db_worktrees) in db_projects {
1336            let host_connection = db_project.host_connection()?;
1337            if let Some(participant) = participants.get_mut(&host_connection) {
1338                participant.projects.push(proto::ParticipantProject {
1339                    id: db_project.id.to_proto(),
1340                    worktree_root_names: Default::default(),
1341                });
1342                let project = participant.projects.last_mut().unwrap();
1343
1344                for db_worktree in db_worktrees {
1345                    if db_worktree.visible {
1346                        project.worktree_root_names.push(db_worktree.root_name);
1347                    }
1348                }
1349            }
1350        }
1351
1352        let mut db_followers = db_room.find_related(follower::Entity).stream(tx).await?;
1353        let mut followers = Vec::new();
1354        while let Some(db_follower) = db_followers.next().await {
1355            let db_follower = db_follower?;
1356            followers.push(proto::Follower {
1357                leader_id: Some(db_follower.leader_connection().into()),
1358                follower_id: Some(db_follower.follower_connection().into()),
1359                project_id: db_follower.project_id.to_proto(),
1360            });
1361        }
1362        drop(db_followers);
1363
1364        let channel = if let Some(channel_id) = db_room.channel_id {
1365            Some(self.get_channel_internal(channel_id, tx).await?)
1366        } else {
1367            None
1368        };
1369
1370        Ok((
1371            channel,
1372            proto::Room {
1373                id: db_room.id.to_proto(),
1374                livekit_room: db_room.live_kit_room,
1375                participants: participants.into_values().collect(),
1376                pending_participants,
1377                followers,
1378            },
1379        ))
1380    }
1381}