projects.rs

   1use anyhow::Context as _;
   2use collections::HashSet;
   3use util::ResultExt;
   4
   5use super::*;
   6
   7impl Database {
   8    /// Returns the count of all projects, excluding ones marked as admin.
   9    pub async fn project_count_excluding_admins(&self) -> Result<usize> {
  10        #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
  11        enum QueryAs {
  12            Count,
  13        }
  14
  15        self.transaction(|tx| async move {
  16            Ok(project::Entity::find()
  17                .select_only()
  18                .column_as(project::Column::Id.count(), QueryAs::Count)
  19                .inner_join(user::Entity)
  20                .filter(user::Column::Admin.eq(false))
  21                .into_values::<_, QueryAs>()
  22                .one(&*tx)
  23                .await?
  24                .unwrap_or(0i64) as usize)
  25        })
  26        .await
  27    }
  28
  29    /// Shares a project with the given room.
  30    pub async fn share_project(
  31        &self,
  32        room_id: RoomId,
  33        connection: ConnectionId,
  34        worktrees: &[proto::WorktreeMetadata],
  35        is_ssh_project: bool,
  36    ) -> Result<TransactionGuard<(ProjectId, proto::Room)>> {
  37        self.room_transaction(room_id, |tx| async move {
  38            let participant = room_participant::Entity::find()
  39                .filter(
  40                    Condition::all()
  41                        .add(
  42                            room_participant::Column::AnsweringConnectionId
  43                                .eq(connection.id as i32),
  44                        )
  45                        .add(
  46                            room_participant::Column::AnsweringConnectionServerId
  47                                .eq(connection.owner_id as i32),
  48                        ),
  49                )
  50                .one(&*tx)
  51                .await?
  52                .context("could not find participant")?;
  53            if participant.room_id != room_id {
  54                return Err(anyhow!("shared project on unexpected room"))?;
  55            }
  56            if !participant
  57                .role
  58                .unwrap_or(ChannelRole::Member)
  59                .can_edit_projects()
  60            {
  61                return Err(anyhow!("guests cannot share projects"))?;
  62            }
  63
  64            let project = project::ActiveModel {
  65                room_id: ActiveValue::set(Some(participant.room_id)),
  66                host_user_id: ActiveValue::set(Some(participant.user_id)),
  67                host_connection_id: ActiveValue::set(Some(connection.id as i32)),
  68                host_connection_server_id: ActiveValue::set(Some(ServerId(
  69                    connection.owner_id as i32,
  70                ))),
  71                id: ActiveValue::NotSet,
  72            }
  73            .insert(&*tx)
  74            .await?;
  75
  76            if !worktrees.is_empty() {
  77                worktree::Entity::insert_many(worktrees.iter().map(|worktree| {
  78                    worktree::ActiveModel {
  79                        id: ActiveValue::set(worktree.id as i64),
  80                        project_id: ActiveValue::set(project.id),
  81                        abs_path: ActiveValue::set(worktree.abs_path.clone()),
  82                        root_name: ActiveValue::set(worktree.root_name.clone()),
  83                        visible: ActiveValue::set(worktree.visible),
  84                        scan_id: ActiveValue::set(0),
  85                        completed_scan_id: ActiveValue::set(0),
  86                    }
  87                }))
  88                .exec(&*tx)
  89                .await?;
  90            }
  91
  92            let replica_id = if is_ssh_project { 1 } else { 0 };
  93
  94            project_collaborator::ActiveModel {
  95                project_id: ActiveValue::set(project.id),
  96                connection_id: ActiveValue::set(connection.id as i32),
  97                connection_server_id: ActiveValue::set(ServerId(connection.owner_id as i32)),
  98                user_id: ActiveValue::set(participant.user_id),
  99                replica_id: ActiveValue::set(ReplicaId(replica_id)),
 100                is_host: ActiveValue::set(true),
 101                id: ActiveValue::NotSet,
 102                committer_name: ActiveValue::Set(None),
 103                committer_email: ActiveValue::Set(None),
 104            }
 105            .insert(&*tx)
 106            .await?;
 107
 108            let room = self.get_room(room_id, &tx).await?;
 109            Ok((project.id, room))
 110        })
 111        .await
 112    }
 113
 114    pub async fn delete_project(&self, project_id: ProjectId) -> Result<()> {
 115        self.transaction(|tx| async move {
 116            project::Entity::delete_by_id(project_id).exec(&*tx).await?;
 117            Ok(())
 118        })
 119        .await
 120    }
 121
 122    /// Unshares the given project.
 123    pub async fn unshare_project(
 124        &self,
 125        project_id: ProjectId,
 126        connection: ConnectionId,
 127    ) -> Result<TransactionGuard<(bool, Option<proto::Room>, Vec<ConnectionId>)>> {
 128        self.project_transaction(project_id, |tx| async move {
 129            let guest_connection_ids = self.project_guest_connection_ids(project_id, &tx).await?;
 130            let project = project::Entity::find_by_id(project_id)
 131                .one(&*tx)
 132                .await?
 133                .context("project not found")?;
 134            let room = if let Some(room_id) = project.room_id {
 135                Some(self.get_room(room_id, &tx).await?)
 136            } else {
 137                None
 138            };
 139            if project.host_connection()? == connection {
 140                return Ok((true, room, guest_connection_ids));
 141            }
 142            Err(anyhow!("cannot unshare a project hosted by another user"))?
 143        })
 144        .await
 145    }
 146
 147    /// Updates the worktrees associated with the given project.
 148    pub async fn update_project(
 149        &self,
 150        project_id: ProjectId,
 151        connection: ConnectionId,
 152        worktrees: &[proto::WorktreeMetadata],
 153    ) -> Result<TransactionGuard<(Option<proto::Room>, Vec<ConnectionId>)>> {
 154        self.project_transaction(project_id, |tx| async move {
 155            let project = project::Entity::find_by_id(project_id)
 156                .filter(
 157                    Condition::all()
 158                        .add(project::Column::HostConnectionId.eq(connection.id as i32))
 159                        .add(
 160                            project::Column::HostConnectionServerId.eq(connection.owner_id as i32),
 161                        ),
 162                )
 163                .one(&*tx)
 164                .await?
 165                .context("no such project")?;
 166
 167            self.update_project_worktrees(project.id, worktrees, &tx)
 168                .await?;
 169
 170            let guest_connection_ids = self.project_guest_connection_ids(project.id, &tx).await?;
 171
 172            let room = if let Some(room_id) = project.room_id {
 173                Some(self.get_room(room_id, &tx).await?)
 174            } else {
 175                None
 176            };
 177
 178            Ok((room, guest_connection_ids))
 179        })
 180        .await
 181    }
 182
 183    pub(in crate::db) async fn update_project_worktrees(
 184        &self,
 185        project_id: ProjectId,
 186        worktrees: &[proto::WorktreeMetadata],
 187        tx: &DatabaseTransaction,
 188    ) -> Result<()> {
 189        if !worktrees.is_empty() {
 190            worktree::Entity::insert_many(worktrees.iter().map(|worktree| worktree::ActiveModel {
 191                id: ActiveValue::set(worktree.id as i64),
 192                project_id: ActiveValue::set(project_id),
 193                abs_path: ActiveValue::set(worktree.abs_path.clone()),
 194                root_name: ActiveValue::set(worktree.root_name.clone()),
 195                visible: ActiveValue::set(worktree.visible),
 196                scan_id: ActiveValue::set(0),
 197                completed_scan_id: ActiveValue::set(0),
 198            }))
 199            .on_conflict(
 200                OnConflict::columns([worktree::Column::ProjectId, worktree::Column::Id])
 201                    .update_column(worktree::Column::RootName)
 202                    .to_owned(),
 203            )
 204            .exec(tx)
 205            .await?;
 206        }
 207
 208        worktree::Entity::delete_many()
 209            .filter(worktree::Column::ProjectId.eq(project_id).and(
 210                worktree::Column::Id.is_not_in(worktrees.iter().map(|worktree| worktree.id as i64)),
 211            ))
 212            .exec(tx)
 213            .await?;
 214
 215        Ok(())
 216    }
 217
 218    pub async fn update_worktree(
 219        &self,
 220        update: &proto::UpdateWorktree,
 221        connection: ConnectionId,
 222    ) -> Result<TransactionGuard<Vec<ConnectionId>>> {
 223        if update.removed_entries.len() > proto::MAX_WORKTREE_UPDATE_MAX_CHUNK_SIZE
 224            || update.updated_entries.len() > proto::MAX_WORKTREE_UPDATE_MAX_CHUNK_SIZE
 225        {
 226            return Err(anyhow!(
 227                "invalid worktree update. removed entries: {}, updated entries: {}",
 228                update.removed_entries.len(),
 229                update.updated_entries.len()
 230            ))?;
 231        }
 232
 233        let project_id = ProjectId::from_proto(update.project_id);
 234        let worktree_id = update.worktree_id as i64;
 235        self.project_transaction(project_id, |tx| async move {
 236            // Ensure the update comes from the host.
 237            let _project = project::Entity::find_by_id(project_id)
 238                .filter(
 239                    Condition::all()
 240                        .add(project::Column::HostConnectionId.eq(connection.id as i32))
 241                        .add(
 242                            project::Column::HostConnectionServerId.eq(connection.owner_id as i32),
 243                        ),
 244                )
 245                .one(&*tx)
 246                .await?
 247                .with_context(|| format!("no such project: {project_id}"))?;
 248
 249            // Update metadata.
 250            worktree::Entity::update(worktree::ActiveModel {
 251                id: ActiveValue::set(worktree_id),
 252                project_id: ActiveValue::set(project_id),
 253                root_name: ActiveValue::set(update.root_name.clone()),
 254                scan_id: ActiveValue::set(update.scan_id as i64),
 255                completed_scan_id: if update.is_last_update {
 256                    ActiveValue::set(update.scan_id as i64)
 257                } else {
 258                    ActiveValue::default()
 259                },
 260                abs_path: ActiveValue::set(update.abs_path.clone()),
 261                ..Default::default()
 262            })
 263            .exec(&*tx)
 264            .await?;
 265
 266            if !update.updated_entries.is_empty() {
 267                worktree_entry::Entity::insert_many(update.updated_entries.iter().map(|entry| {
 268                    let mtime = entry.mtime.clone().unwrap_or_default();
 269                    worktree_entry::ActiveModel {
 270                        project_id: ActiveValue::set(project_id),
 271                        worktree_id: ActiveValue::set(worktree_id),
 272                        id: ActiveValue::set(entry.id as i64),
 273                        is_dir: ActiveValue::set(entry.is_dir),
 274                        path: ActiveValue::set(entry.path.clone()),
 275                        inode: ActiveValue::set(entry.inode as i64),
 276                        mtime_seconds: ActiveValue::set(mtime.seconds as i64),
 277                        mtime_nanos: ActiveValue::set(mtime.nanos as i32),
 278                        canonical_path: ActiveValue::set(entry.canonical_path.clone()),
 279                        is_ignored: ActiveValue::set(entry.is_ignored),
 280                        git_status: ActiveValue::set(None),
 281                        is_external: ActiveValue::set(entry.is_external),
 282                        is_deleted: ActiveValue::set(false),
 283                        scan_id: ActiveValue::set(update.scan_id as i64),
 284                        is_fifo: ActiveValue::set(entry.is_fifo),
 285                    }
 286                }))
 287                .on_conflict(
 288                    OnConflict::columns([
 289                        worktree_entry::Column::ProjectId,
 290                        worktree_entry::Column::WorktreeId,
 291                        worktree_entry::Column::Id,
 292                    ])
 293                    .update_columns([
 294                        worktree_entry::Column::IsDir,
 295                        worktree_entry::Column::Path,
 296                        worktree_entry::Column::Inode,
 297                        worktree_entry::Column::MtimeSeconds,
 298                        worktree_entry::Column::MtimeNanos,
 299                        worktree_entry::Column::CanonicalPath,
 300                        worktree_entry::Column::IsIgnored,
 301                        worktree_entry::Column::ScanId,
 302                    ])
 303                    .to_owned(),
 304                )
 305                .exec(&*tx)
 306                .await?;
 307            }
 308
 309            if !update.removed_entries.is_empty() {
 310                worktree_entry::Entity::update_many()
 311                    .filter(
 312                        worktree_entry::Column::ProjectId
 313                            .eq(project_id)
 314                            .and(worktree_entry::Column::WorktreeId.eq(worktree_id))
 315                            .and(
 316                                worktree_entry::Column::Id
 317                                    .is_in(update.removed_entries.iter().map(|id| *id as i64)),
 318                            ),
 319                    )
 320                    .set(worktree_entry::ActiveModel {
 321                        is_deleted: ActiveValue::Set(true),
 322                        scan_id: ActiveValue::Set(update.scan_id as i64),
 323                        ..Default::default()
 324                    })
 325                    .exec(&*tx)
 326                    .await?;
 327            }
 328
 329            // Backward-compatibility for old Zed clients.
 330            //
 331            // Remove this block when Zed 1.80 stable has been out for a week.
 332            {
 333                if !update.updated_repositories.is_empty() {
 334                    project_repository::Entity::insert_many(
 335                        update.updated_repositories.iter().map(|repository| {
 336                            project_repository::ActiveModel {
 337                                project_id: ActiveValue::set(project_id),
 338                                legacy_worktree_id: ActiveValue::set(Some(worktree_id)),
 339                                id: ActiveValue::set(repository.repository_id as i64),
 340                                scan_id: ActiveValue::set(update.scan_id as i64),
 341                                is_deleted: ActiveValue::set(false),
 342                                branch_summary: ActiveValue::Set(
 343                                    repository
 344                                        .branch_summary
 345                                        .as_ref()
 346                                        .map(|summary| serde_json::to_string(summary).unwrap()),
 347                                ),
 348                                current_merge_conflicts: ActiveValue::Set(Some(
 349                                    serde_json::to_string(&repository.current_merge_conflicts)
 350                                        .unwrap(),
 351                                )),
 352
 353                                // Old clients do not use abs path, entry ids or head_commit_details.
 354                                abs_path: ActiveValue::set(String::new()),
 355                                entry_ids: ActiveValue::set("[]".into()),
 356                                head_commit_details: ActiveValue::set(None),
 357                            }
 358                        }),
 359                    )
 360                    .on_conflict(
 361                        OnConflict::columns([
 362                            project_repository::Column::ProjectId,
 363                            project_repository::Column::Id,
 364                        ])
 365                        .update_columns([
 366                            project_repository::Column::ScanId,
 367                            project_repository::Column::BranchSummary,
 368                            project_repository::Column::CurrentMergeConflicts,
 369                        ])
 370                        .to_owned(),
 371                    )
 372                    .exec(&*tx)
 373                    .await?;
 374
 375                    let has_any_statuses = update
 376                        .updated_repositories
 377                        .iter()
 378                        .any(|repository| !repository.updated_statuses.is_empty());
 379
 380                    if has_any_statuses {
 381                        project_repository_statuses::Entity::insert_many(
 382                            update.updated_repositories.iter().flat_map(
 383                                |repository: &proto::RepositoryEntry| {
 384                                    repository.updated_statuses.iter().map(|status_entry| {
 385                                        let (repo_path, status_kind, first_status, second_status) =
 386                                            proto_status_to_db(status_entry.clone());
 387                                        project_repository_statuses::ActiveModel {
 388                                            project_id: ActiveValue::set(project_id),
 389                                            repository_id: ActiveValue::set(
 390                                                repository.repository_id as i64,
 391                                            ),
 392                                            scan_id: ActiveValue::set(update.scan_id as i64),
 393                                            is_deleted: ActiveValue::set(false),
 394                                            repo_path: ActiveValue::set(repo_path),
 395                                            status: ActiveValue::set(0),
 396                                            status_kind: ActiveValue::set(status_kind),
 397                                            first_status: ActiveValue::set(first_status),
 398                                            second_status: ActiveValue::set(second_status),
 399                                        }
 400                                    })
 401                                },
 402                            ),
 403                        )
 404                        .on_conflict(
 405                            OnConflict::columns([
 406                                project_repository_statuses::Column::ProjectId,
 407                                project_repository_statuses::Column::RepositoryId,
 408                                project_repository_statuses::Column::RepoPath,
 409                            ])
 410                            .update_columns([
 411                                project_repository_statuses::Column::ScanId,
 412                                project_repository_statuses::Column::StatusKind,
 413                                project_repository_statuses::Column::FirstStatus,
 414                                project_repository_statuses::Column::SecondStatus,
 415                            ])
 416                            .to_owned(),
 417                        )
 418                        .exec(&*tx)
 419                        .await?;
 420                    }
 421
 422                    for repo in &update.updated_repositories {
 423                        if !repo.removed_statuses.is_empty() {
 424                            project_repository_statuses::Entity::update_many()
 425                                .filter(
 426                                    project_repository_statuses::Column::ProjectId
 427                                        .eq(project_id)
 428                                        .and(
 429                                            project_repository_statuses::Column::RepositoryId
 430                                                .eq(repo.repository_id),
 431                                        )
 432                                        .and(
 433                                            project_repository_statuses::Column::RepoPath
 434                                                .is_in(repo.removed_statuses.iter()),
 435                                        ),
 436                                )
 437                                .set(project_repository_statuses::ActiveModel {
 438                                    is_deleted: ActiveValue::Set(true),
 439                                    scan_id: ActiveValue::Set(update.scan_id as i64),
 440                                    ..Default::default()
 441                                })
 442                                .exec(&*tx)
 443                                .await?;
 444                        }
 445                    }
 446                }
 447
 448                if !update.removed_repositories.is_empty() {
 449                    project_repository::Entity::update_many()
 450                        .filter(
 451                            project_repository::Column::ProjectId
 452                                .eq(project_id)
 453                                .and(project_repository::Column::LegacyWorktreeId.eq(worktree_id))
 454                                .and(project_repository::Column::Id.is_in(
 455                                    update.removed_repositories.iter().map(|id| *id as i64),
 456                                )),
 457                        )
 458                        .set(project_repository::ActiveModel {
 459                            is_deleted: ActiveValue::Set(true),
 460                            scan_id: ActiveValue::Set(update.scan_id as i64),
 461                            ..Default::default()
 462                        })
 463                        .exec(&*tx)
 464                        .await?;
 465                }
 466            }
 467
 468            let connection_ids = self.project_guest_connection_ids(project_id, &tx).await?;
 469            Ok(connection_ids)
 470        })
 471        .await
 472    }
 473
 474    pub async fn update_repository(
 475        &self,
 476        update: &proto::UpdateRepository,
 477        _connection: ConnectionId,
 478    ) -> Result<TransactionGuard<Vec<ConnectionId>>> {
 479        let project_id = ProjectId::from_proto(update.project_id);
 480        let repository_id = update.id as i64;
 481        self.project_transaction(project_id, |tx| async move {
 482            project_repository::Entity::insert(project_repository::ActiveModel {
 483                project_id: ActiveValue::set(project_id),
 484                id: ActiveValue::set(repository_id),
 485                legacy_worktree_id: ActiveValue::set(None),
 486                abs_path: ActiveValue::set(update.abs_path.clone()),
 487                entry_ids: ActiveValue::Set(serde_json::to_string(&update.entry_ids).unwrap()),
 488                scan_id: ActiveValue::set(update.scan_id as i64),
 489                is_deleted: ActiveValue::set(false),
 490                branch_summary: ActiveValue::Set(
 491                    update
 492                        .branch_summary
 493                        .as_ref()
 494                        .map(|summary| serde_json::to_string(summary).unwrap()),
 495                ),
 496                head_commit_details: ActiveValue::Set(
 497                    update
 498                        .head_commit_details
 499                        .as_ref()
 500                        .map(|details| serde_json::to_string(details).unwrap()),
 501                ),
 502                current_merge_conflicts: ActiveValue::Set(Some(
 503                    serde_json::to_string(&update.current_merge_conflicts).unwrap(),
 504                )),
 505            })
 506            .on_conflict(
 507                OnConflict::columns([
 508                    project_repository::Column::ProjectId,
 509                    project_repository::Column::Id,
 510                ])
 511                .update_columns([
 512                    project_repository::Column::ScanId,
 513                    project_repository::Column::BranchSummary,
 514                    project_repository::Column::EntryIds,
 515                    project_repository::Column::AbsPath,
 516                    project_repository::Column::CurrentMergeConflicts,
 517                    project_repository::Column::HeadCommitDetails,
 518                ])
 519                .to_owned(),
 520            )
 521            .exec(&*tx)
 522            .await?;
 523
 524            let has_any_statuses = !update.updated_statuses.is_empty();
 525
 526            if has_any_statuses {
 527                project_repository_statuses::Entity::insert_many(
 528                    update.updated_statuses.iter().map(|status_entry| {
 529                        let (repo_path, status_kind, first_status, second_status) =
 530                            proto_status_to_db(status_entry.clone());
 531                        project_repository_statuses::ActiveModel {
 532                            project_id: ActiveValue::set(project_id),
 533                            repository_id: ActiveValue::set(repository_id),
 534                            scan_id: ActiveValue::set(update.scan_id as i64),
 535                            is_deleted: ActiveValue::set(false),
 536                            repo_path: ActiveValue::set(repo_path),
 537                            status: ActiveValue::set(0),
 538                            status_kind: ActiveValue::set(status_kind),
 539                            first_status: ActiveValue::set(first_status),
 540                            second_status: ActiveValue::set(second_status),
 541                        }
 542                    }),
 543                )
 544                .on_conflict(
 545                    OnConflict::columns([
 546                        project_repository_statuses::Column::ProjectId,
 547                        project_repository_statuses::Column::RepositoryId,
 548                        project_repository_statuses::Column::RepoPath,
 549                    ])
 550                    .update_columns([
 551                        project_repository_statuses::Column::ScanId,
 552                        project_repository_statuses::Column::StatusKind,
 553                        project_repository_statuses::Column::FirstStatus,
 554                        project_repository_statuses::Column::SecondStatus,
 555                    ])
 556                    .to_owned(),
 557                )
 558                .exec(&*tx)
 559                .await?;
 560            }
 561
 562            let has_any_removed_statuses = !update.removed_statuses.is_empty();
 563
 564            if has_any_removed_statuses {
 565                project_repository_statuses::Entity::update_many()
 566                    .filter(
 567                        project_repository_statuses::Column::ProjectId
 568                            .eq(project_id)
 569                            .and(
 570                                project_repository_statuses::Column::RepositoryId.eq(repository_id),
 571                            )
 572                            .and(
 573                                project_repository_statuses::Column::RepoPath
 574                                    .is_in(update.removed_statuses.iter()),
 575                            ),
 576                    )
 577                    .set(project_repository_statuses::ActiveModel {
 578                        is_deleted: ActiveValue::Set(true),
 579                        scan_id: ActiveValue::Set(update.scan_id as i64),
 580                        ..Default::default()
 581                    })
 582                    .exec(&*tx)
 583                    .await?;
 584            }
 585
 586            let connection_ids = self.project_guest_connection_ids(project_id, &tx).await?;
 587            Ok(connection_ids)
 588        })
 589        .await
 590    }
 591
 592    pub async fn remove_repository(
 593        &self,
 594        remove: &proto::RemoveRepository,
 595        _connection: ConnectionId,
 596    ) -> Result<TransactionGuard<Vec<ConnectionId>>> {
 597        let project_id = ProjectId::from_proto(remove.project_id);
 598        let repository_id = remove.id as i64;
 599        self.project_transaction(project_id, |tx| async move {
 600            project_repository::Entity::update_many()
 601                .filter(
 602                    project_repository::Column::ProjectId
 603                        .eq(project_id)
 604                        .and(project_repository::Column::Id.eq(repository_id)),
 605                )
 606                .set(project_repository::ActiveModel {
 607                    is_deleted: ActiveValue::Set(true),
 608                    // scan_id: ActiveValue::Set(update.scan_id as i64),
 609                    ..Default::default()
 610                })
 611                .exec(&*tx)
 612                .await?;
 613
 614            let connection_ids = self.project_guest_connection_ids(project_id, &tx).await?;
 615            Ok(connection_ids)
 616        })
 617        .await
 618    }
 619
 620    /// Updates the diagnostic summary for the given connection.
 621    pub async fn update_diagnostic_summary(
 622        &self,
 623        update: &proto::UpdateDiagnosticSummary,
 624        connection: ConnectionId,
 625    ) -> Result<TransactionGuard<Vec<ConnectionId>>> {
 626        let project_id = ProjectId::from_proto(update.project_id);
 627        let worktree_id = update.worktree_id as i64;
 628        self.project_transaction(project_id, |tx| async move {
 629            let summary = update.summary.as_ref().context("invalid summary")?;
 630
 631            // Ensure the update comes from the host.
 632            let project = project::Entity::find_by_id(project_id)
 633                .one(&*tx)
 634                .await?
 635                .context("no such project")?;
 636            if project.host_connection()? != connection {
 637                return Err(anyhow!("can't update a project hosted by someone else"))?;
 638            }
 639
 640            // Update summary.
 641            worktree_diagnostic_summary::Entity::insert(worktree_diagnostic_summary::ActiveModel {
 642                project_id: ActiveValue::set(project_id),
 643                worktree_id: ActiveValue::set(worktree_id),
 644                path: ActiveValue::set(summary.path.clone()),
 645                language_server_id: ActiveValue::set(summary.language_server_id as i64),
 646                error_count: ActiveValue::set(summary.error_count as i32),
 647                warning_count: ActiveValue::set(summary.warning_count as i32),
 648            })
 649            .on_conflict(
 650                OnConflict::columns([
 651                    worktree_diagnostic_summary::Column::ProjectId,
 652                    worktree_diagnostic_summary::Column::WorktreeId,
 653                    worktree_diagnostic_summary::Column::Path,
 654                ])
 655                .update_columns([
 656                    worktree_diagnostic_summary::Column::LanguageServerId,
 657                    worktree_diagnostic_summary::Column::ErrorCount,
 658                    worktree_diagnostic_summary::Column::WarningCount,
 659                ])
 660                .to_owned(),
 661            )
 662            .exec(&*tx)
 663            .await?;
 664
 665            let connection_ids = self.project_guest_connection_ids(project_id, &tx).await?;
 666            Ok(connection_ids)
 667        })
 668        .await
 669    }
 670
 671    /// Starts the language server for the given connection.
 672    pub async fn start_language_server(
 673        &self,
 674        update: &proto::StartLanguageServer,
 675        connection: ConnectionId,
 676    ) -> Result<TransactionGuard<Vec<ConnectionId>>> {
 677        let project_id = ProjectId::from_proto(update.project_id);
 678        self.project_transaction(project_id, |tx| async move {
 679            let server = update.server.as_ref().context("invalid language server")?;
 680
 681            // Ensure the update comes from the host.
 682            let project = project::Entity::find_by_id(project_id)
 683                .one(&*tx)
 684                .await?
 685                .context("no such project")?;
 686            if project.host_connection()? != connection {
 687                return Err(anyhow!("can't update a project hosted by someone else"))?;
 688            }
 689
 690            // Add the newly-started language server.
 691            language_server::Entity::insert(language_server::ActiveModel {
 692                project_id: ActiveValue::set(project_id),
 693                id: ActiveValue::set(server.id as i64),
 694                name: ActiveValue::set(server.name.clone()),
 695                capabilities: ActiveValue::set(update.capabilities.clone()),
 696            })
 697            .on_conflict(
 698                OnConflict::columns([
 699                    language_server::Column::ProjectId,
 700                    language_server::Column::Id,
 701                ])
 702                .update_columns([
 703                    language_server::Column::Name,
 704                    language_server::Column::Capabilities,
 705                ])
 706                .to_owned(),
 707            )
 708            .exec(&*tx)
 709            .await?;
 710
 711            let connection_ids = self.project_guest_connection_ids(project_id, &tx).await?;
 712            Ok(connection_ids)
 713        })
 714        .await
 715    }
 716
 717    /// Updates the worktree settings for the given connection.
 718    pub async fn update_worktree_settings(
 719        &self,
 720        update: &proto::UpdateWorktreeSettings,
 721        connection: ConnectionId,
 722    ) -> Result<TransactionGuard<Vec<ConnectionId>>> {
 723        let project_id = ProjectId::from_proto(update.project_id);
 724        let kind = match update.kind {
 725            Some(kind) => proto::LocalSettingsKind::from_i32(kind)
 726                .with_context(|| format!("unknown worktree settings kind: {kind}"))?,
 727            None => proto::LocalSettingsKind::Settings,
 728        };
 729        let kind = LocalSettingsKind::from_proto(kind);
 730        self.project_transaction(project_id, |tx| async move {
 731            // Ensure the update comes from the host.
 732            let project = project::Entity::find_by_id(project_id)
 733                .one(&*tx)
 734                .await?
 735                .context("no such project")?;
 736            if project.host_connection()? != connection {
 737                return Err(anyhow!("can't update a project hosted by someone else"))?;
 738            }
 739
 740            if let Some(content) = &update.content {
 741                worktree_settings_file::Entity::insert(worktree_settings_file::ActiveModel {
 742                    project_id: ActiveValue::Set(project_id),
 743                    worktree_id: ActiveValue::Set(update.worktree_id as i64),
 744                    path: ActiveValue::Set(update.path.clone()),
 745                    content: ActiveValue::Set(content.clone()),
 746                    kind: ActiveValue::Set(kind),
 747                })
 748                .on_conflict(
 749                    OnConflict::columns([
 750                        worktree_settings_file::Column::ProjectId,
 751                        worktree_settings_file::Column::WorktreeId,
 752                        worktree_settings_file::Column::Path,
 753                    ])
 754                    .update_column(worktree_settings_file::Column::Content)
 755                    .to_owned(),
 756                )
 757                .exec(&*tx)
 758                .await?;
 759            } else {
 760                worktree_settings_file::Entity::delete(worktree_settings_file::ActiveModel {
 761                    project_id: ActiveValue::Set(project_id),
 762                    worktree_id: ActiveValue::Set(update.worktree_id as i64),
 763                    path: ActiveValue::Set(update.path.clone()),
 764                    ..Default::default()
 765                })
 766                .exec(&*tx)
 767                .await?;
 768            }
 769
 770            let connection_ids = self.project_guest_connection_ids(project_id, &tx).await?;
 771            Ok(connection_ids)
 772        })
 773        .await
 774    }
 775
 776    pub async fn get_project(&self, id: ProjectId) -> Result<project::Model> {
 777        self.transaction(|tx| async move {
 778            Ok(project::Entity::find_by_id(id)
 779                .one(&*tx)
 780                .await?
 781                .context("no such project")?)
 782        })
 783        .await
 784    }
 785
 786    /// Adds the given connection to the specified project
 787    /// in the current room.
 788    pub async fn join_project(
 789        &self,
 790        project_id: ProjectId,
 791        connection: ConnectionId,
 792        user_id: UserId,
 793        committer_name: Option<String>,
 794        committer_email: Option<String>,
 795    ) -> Result<TransactionGuard<(Project, ReplicaId)>> {
 796        self.project_transaction(project_id, move |tx| {
 797            let committer_name = committer_name.clone();
 798            let committer_email = committer_email.clone();
 799            async move {
 800                let (project, role) = self
 801                    .access_project(project_id, connection, Capability::ReadOnly, &tx)
 802                    .await?;
 803                self.join_project_internal(
 804                    project,
 805                    user_id,
 806                    committer_name,
 807                    committer_email,
 808                    connection,
 809                    role,
 810                    &tx,
 811                )
 812                .await
 813            }
 814        })
 815        .await
 816    }
 817
 818    async fn join_project_internal(
 819        &self,
 820        project: project::Model,
 821        user_id: UserId,
 822        committer_name: Option<String>,
 823        committer_email: Option<String>,
 824        connection: ConnectionId,
 825        role: ChannelRole,
 826        tx: &DatabaseTransaction,
 827    ) -> Result<(Project, ReplicaId)> {
 828        let mut collaborators = project
 829            .find_related(project_collaborator::Entity)
 830            .all(tx)
 831            .await?;
 832        let replica_ids = collaborators
 833            .iter()
 834            .map(|c| c.replica_id)
 835            .collect::<HashSet<_>>();
 836        let mut replica_id = ReplicaId(1);
 837        while replica_ids.contains(&replica_id) {
 838            replica_id.0 += 1;
 839        }
 840        let new_collaborator = project_collaborator::ActiveModel {
 841            project_id: ActiveValue::set(project.id),
 842            connection_id: ActiveValue::set(connection.id as i32),
 843            connection_server_id: ActiveValue::set(ServerId(connection.owner_id as i32)),
 844            user_id: ActiveValue::set(user_id),
 845            replica_id: ActiveValue::set(replica_id),
 846            is_host: ActiveValue::set(false),
 847            id: ActiveValue::NotSet,
 848            committer_name: ActiveValue::set(committer_name),
 849            committer_email: ActiveValue::set(committer_email),
 850        }
 851        .insert(tx)
 852        .await?;
 853        collaborators.push(new_collaborator);
 854
 855        let db_worktrees = project.find_related(worktree::Entity).all(tx).await?;
 856        let mut worktrees = db_worktrees
 857            .into_iter()
 858            .map(|db_worktree| {
 859                (
 860                    db_worktree.id as u64,
 861                    Worktree {
 862                        id: db_worktree.id as u64,
 863                        abs_path: db_worktree.abs_path,
 864                        root_name: db_worktree.root_name,
 865                        visible: db_worktree.visible,
 866                        entries: Default::default(),
 867                        diagnostic_summaries: Default::default(),
 868                        settings_files: Default::default(),
 869                        scan_id: db_worktree.scan_id as u64,
 870                        completed_scan_id: db_worktree.completed_scan_id as u64,
 871                        legacy_repository_entries: Default::default(),
 872                    },
 873                )
 874            })
 875            .collect::<BTreeMap<_, _>>();
 876
 877        // Populate worktree entries.
 878        {
 879            let mut db_entries = worktree_entry::Entity::find()
 880                .filter(
 881                    Condition::all()
 882                        .add(worktree_entry::Column::ProjectId.eq(project.id))
 883                        .add(worktree_entry::Column::IsDeleted.eq(false)),
 884                )
 885                .stream(tx)
 886                .await?;
 887            while let Some(db_entry) = db_entries.next().await {
 888                let db_entry = db_entry?;
 889                if let Some(worktree) = worktrees.get_mut(&(db_entry.worktree_id as u64)) {
 890                    worktree.entries.push(proto::Entry {
 891                        id: db_entry.id as u64,
 892                        is_dir: db_entry.is_dir,
 893                        path: db_entry.path,
 894                        inode: db_entry.inode as u64,
 895                        mtime: Some(proto::Timestamp {
 896                            seconds: db_entry.mtime_seconds as u64,
 897                            nanos: db_entry.mtime_nanos as u32,
 898                        }),
 899                        canonical_path: db_entry.canonical_path,
 900                        is_ignored: db_entry.is_ignored,
 901                        is_external: db_entry.is_external,
 902                        // This is only used in the summarization backlog, so if it's None,
 903                        // that just means we won't be able to detect when to resummarize
 904                        // based on total number of backlogged bytes - instead, we'd go
 905                        // on number of files only. That shouldn't be a huge deal in practice.
 906                        size: None,
 907                        is_fifo: db_entry.is_fifo,
 908                    });
 909                }
 910            }
 911        }
 912
 913        // Populate repository entries.
 914        let mut repositories = Vec::new();
 915        {
 916            let db_repository_entries = project_repository::Entity::find()
 917                .filter(
 918                    Condition::all()
 919                        .add(project_repository::Column::ProjectId.eq(project.id))
 920                        .add(project_repository::Column::IsDeleted.eq(false)),
 921                )
 922                .all(tx)
 923                .await?;
 924            for db_repository_entry in db_repository_entries {
 925                let mut repository_statuses = project_repository_statuses::Entity::find()
 926                    .filter(
 927                        Condition::all()
 928                            .add(project_repository_statuses::Column::ProjectId.eq(project.id))
 929                            .add(
 930                                project_repository_statuses::Column::RepositoryId
 931                                    .eq(db_repository_entry.id),
 932                            )
 933                            .add(project_repository_statuses::Column::IsDeleted.eq(false)),
 934                    )
 935                    .stream(tx)
 936                    .await?;
 937                let mut updated_statuses = Vec::new();
 938                while let Some(status_entry) = repository_statuses.next().await {
 939                    let status_entry = status_entry?;
 940                    updated_statuses.push(db_status_to_proto(status_entry)?);
 941                }
 942
 943                let current_merge_conflicts = db_repository_entry
 944                    .current_merge_conflicts
 945                    .as_ref()
 946                    .map(|conflicts| serde_json::from_str(conflicts))
 947                    .transpose()?
 948                    .unwrap_or_default();
 949
 950                let branch_summary = db_repository_entry
 951                    .branch_summary
 952                    .as_ref()
 953                    .map(|branch_summary| serde_json::from_str(branch_summary))
 954                    .transpose()?
 955                    .unwrap_or_default();
 956
 957                let head_commit_details = db_repository_entry
 958                    .head_commit_details
 959                    .as_ref()
 960                    .map(|head_commit_details| serde_json::from_str(head_commit_details))
 961                    .transpose()?
 962                    .unwrap_or_default();
 963
 964                let entry_ids = serde_json::from_str(&db_repository_entry.entry_ids)
 965                    .context("failed to deserialize repository's entry ids")?;
 966
 967                if let Some(worktree_id) = db_repository_entry.legacy_worktree_id {
 968                    if let Some(worktree) = worktrees.get_mut(&(worktree_id as u64)) {
 969                        worktree.legacy_repository_entries.insert(
 970                            db_repository_entry.id as u64,
 971                            proto::RepositoryEntry {
 972                                repository_id: db_repository_entry.id as u64,
 973                                updated_statuses,
 974                                removed_statuses: Vec::new(),
 975                                current_merge_conflicts,
 976                                branch_summary,
 977                            },
 978                        );
 979                    }
 980                } else {
 981                    repositories.push(proto::UpdateRepository {
 982                        project_id: db_repository_entry.project_id.0 as u64,
 983                        id: db_repository_entry.id as u64,
 984                        abs_path: db_repository_entry.abs_path,
 985                        entry_ids,
 986                        updated_statuses,
 987                        removed_statuses: Vec::new(),
 988                        current_merge_conflicts,
 989                        branch_summary,
 990                        head_commit_details,
 991                        scan_id: db_repository_entry.scan_id as u64,
 992                        is_last_update: true,
 993                    });
 994                }
 995            }
 996        }
 997
 998        // Populate worktree diagnostic summaries.
 999        {
1000            let mut db_summaries = worktree_diagnostic_summary::Entity::find()
1001                .filter(worktree_diagnostic_summary::Column::ProjectId.eq(project.id))
1002                .stream(tx)
1003                .await?;
1004            while let Some(db_summary) = db_summaries.next().await {
1005                let db_summary = db_summary?;
1006                if let Some(worktree) = worktrees.get_mut(&(db_summary.worktree_id as u64)) {
1007                    worktree
1008                        .diagnostic_summaries
1009                        .push(proto::DiagnosticSummary {
1010                            path: db_summary.path,
1011                            language_server_id: db_summary.language_server_id as u64,
1012                            error_count: db_summary.error_count as u32,
1013                            warning_count: db_summary.warning_count as u32,
1014                        });
1015                }
1016            }
1017        }
1018
1019        // Populate worktree settings files
1020        {
1021            let mut db_settings_files = worktree_settings_file::Entity::find()
1022                .filter(worktree_settings_file::Column::ProjectId.eq(project.id))
1023                .stream(tx)
1024                .await?;
1025            while let Some(db_settings_file) = db_settings_files.next().await {
1026                let db_settings_file = db_settings_file?;
1027                if let Some(worktree) = worktrees.get_mut(&(db_settings_file.worktree_id as u64)) {
1028                    worktree.settings_files.push(WorktreeSettingsFile {
1029                        path: db_settings_file.path,
1030                        content: db_settings_file.content,
1031                        kind: db_settings_file.kind,
1032                    });
1033                }
1034            }
1035        }
1036
1037        // Populate language servers.
1038        let language_servers = project
1039            .find_related(language_server::Entity)
1040            .all(tx)
1041            .await?;
1042
1043        let project = Project {
1044            id: project.id,
1045            role,
1046            collaborators: collaborators
1047                .into_iter()
1048                .map(|collaborator| ProjectCollaborator {
1049                    connection_id: collaborator.connection(),
1050                    user_id: collaborator.user_id,
1051                    replica_id: collaborator.replica_id,
1052                    is_host: collaborator.is_host,
1053                    committer_name: collaborator.committer_name,
1054                    committer_email: collaborator.committer_email,
1055                })
1056                .collect(),
1057            worktrees,
1058            repositories,
1059            language_servers: language_servers
1060                .into_iter()
1061                .map(|language_server| LanguageServer {
1062                    server: proto::LanguageServer {
1063                        id: language_server.id as u64,
1064                        name: language_server.name,
1065                        worktree_id: None,
1066                    },
1067                    capabilities: language_server.capabilities,
1068                })
1069                .collect(),
1070        };
1071        Ok((project, replica_id as ReplicaId))
1072    }
1073
1074    /// Removes the given connection from the specified project.
1075    pub async fn leave_project(
1076        &self,
1077        project_id: ProjectId,
1078        connection: ConnectionId,
1079    ) -> Result<TransactionGuard<(Option<proto::Room>, LeftProject)>> {
1080        self.project_transaction(project_id, |tx| async move {
1081            let result = project_collaborator::Entity::delete_many()
1082                .filter(
1083                    Condition::all()
1084                        .add(project_collaborator::Column::ProjectId.eq(project_id))
1085                        .add(project_collaborator::Column::ConnectionId.eq(connection.id as i32))
1086                        .add(
1087                            project_collaborator::Column::ConnectionServerId
1088                                .eq(connection.owner_id as i32),
1089                        ),
1090                )
1091                .exec(&*tx)
1092                .await?;
1093            if result.rows_affected == 0 {
1094                Err(anyhow!("not a collaborator on this project"))?;
1095            }
1096
1097            let project = project::Entity::find_by_id(project_id)
1098                .one(&*tx)
1099                .await?
1100                .context("no such project")?;
1101            let collaborators = project
1102                .find_related(project_collaborator::Entity)
1103                .all(&*tx)
1104                .await?;
1105            let connection_ids: Vec<ConnectionId> = collaborators
1106                .into_iter()
1107                .map(|collaborator| collaborator.connection())
1108                .collect();
1109
1110            follower::Entity::delete_many()
1111                .filter(
1112                    Condition::any()
1113                        .add(
1114                            Condition::all()
1115                                .add(follower::Column::ProjectId.eq(Some(project_id)))
1116                                .add(
1117                                    follower::Column::LeaderConnectionServerId
1118                                        .eq(connection.owner_id),
1119                                )
1120                                .add(follower::Column::LeaderConnectionId.eq(connection.id)),
1121                        )
1122                        .add(
1123                            Condition::all()
1124                                .add(follower::Column::ProjectId.eq(Some(project_id)))
1125                                .add(
1126                                    follower::Column::FollowerConnectionServerId
1127                                        .eq(connection.owner_id),
1128                                )
1129                                .add(follower::Column::FollowerConnectionId.eq(connection.id)),
1130                        ),
1131                )
1132                .exec(&*tx)
1133                .await?;
1134
1135            let room = if let Some(room_id) = project.room_id {
1136                Some(self.get_room(room_id, &tx).await?)
1137            } else {
1138                None
1139            };
1140
1141            let left_project = LeftProject {
1142                id: project_id,
1143                should_unshare: connection == project.host_connection()?,
1144                connection_ids,
1145            };
1146            Ok((room, left_project))
1147        })
1148        .await
1149    }
1150
1151    pub async fn check_user_is_project_host(
1152        &self,
1153        project_id: ProjectId,
1154        connection_id: ConnectionId,
1155    ) -> Result<()> {
1156        self.project_transaction(project_id, |tx| async move {
1157            project::Entity::find()
1158                .filter(
1159                    Condition::all()
1160                        .add(project::Column::Id.eq(project_id))
1161                        .add(project::Column::HostConnectionId.eq(Some(connection_id.id as i32)))
1162                        .add(
1163                            project::Column::HostConnectionServerId
1164                                .eq(Some(connection_id.owner_id as i32)),
1165                        ),
1166                )
1167                .one(&*tx)
1168                .await?
1169                .context("failed to read project host")?;
1170
1171            Ok(())
1172        })
1173        .await
1174        .map(|guard| guard.into_inner())
1175    }
1176
1177    /// Returns the current project if the given user is authorized to access it with the specified capability.
1178    pub async fn access_project(
1179        &self,
1180        project_id: ProjectId,
1181        connection_id: ConnectionId,
1182        capability: Capability,
1183        tx: &DatabaseTransaction,
1184    ) -> Result<(project::Model, ChannelRole)> {
1185        let project = project::Entity::find_by_id(project_id)
1186            .one(tx)
1187            .await?
1188            .context("no such project")?;
1189
1190        let role_from_room = if let Some(room_id) = project.room_id {
1191            room_participant::Entity::find()
1192                .filter(room_participant::Column::RoomId.eq(room_id))
1193                .filter(room_participant::Column::AnsweringConnectionId.eq(connection_id.id))
1194                .one(tx)
1195                .await?
1196                .and_then(|participant| participant.role)
1197        } else {
1198            None
1199        };
1200
1201        let role = role_from_room.unwrap_or(ChannelRole::Banned);
1202
1203        match capability {
1204            Capability::ReadWrite => {
1205                if !role.can_edit_projects() {
1206                    return Err(anyhow!("not authorized to edit projects"))?;
1207                }
1208            }
1209            Capability::ReadOnly => {
1210                if !role.can_read_projects() {
1211                    return Err(anyhow!("not authorized to read projects"))?;
1212                }
1213            }
1214        }
1215
1216        Ok((project, role))
1217    }
1218
1219    /// Returns the host connection for a read-only request to join a shared project.
1220    pub async fn host_for_read_only_project_request(
1221        &self,
1222        project_id: ProjectId,
1223        connection_id: ConnectionId,
1224    ) -> Result<ConnectionId> {
1225        self.project_transaction(project_id, |tx| async move {
1226            let (project, _) = self
1227                .access_project(project_id, connection_id, Capability::ReadOnly, &tx)
1228                .await?;
1229            project.host_connection()
1230        })
1231        .await
1232        .map(|guard| guard.into_inner())
1233    }
1234
1235    /// Returns the host connection for a request to join a shared project.
1236    pub async fn host_for_mutating_project_request(
1237        &self,
1238        project_id: ProjectId,
1239        connection_id: ConnectionId,
1240    ) -> Result<ConnectionId> {
1241        self.project_transaction(project_id, |tx| async move {
1242            let (project, _) = self
1243                .access_project(project_id, connection_id, Capability::ReadWrite, &tx)
1244                .await?;
1245            project.host_connection()
1246        })
1247        .await
1248        .map(|guard| guard.into_inner())
1249    }
1250
1251    pub async fn connections_for_buffer_update(
1252        &self,
1253        project_id: ProjectId,
1254        connection_id: ConnectionId,
1255        capability: Capability,
1256    ) -> Result<TransactionGuard<(ConnectionId, Vec<ConnectionId>)>> {
1257        self.project_transaction(project_id, |tx| async move {
1258            // Authorize
1259            let (project, _) = self
1260                .access_project(project_id, connection_id, capability, &tx)
1261                .await?;
1262
1263            let host_connection_id = project.host_connection()?;
1264
1265            let collaborators = project_collaborator::Entity::find()
1266                .filter(project_collaborator::Column::ProjectId.eq(project_id))
1267                .all(&*tx)
1268                .await?;
1269
1270            let guest_connection_ids = collaborators
1271                .into_iter()
1272                .filter_map(|collaborator| {
1273                    if collaborator.is_host {
1274                        None
1275                    } else {
1276                        Some(collaborator.connection())
1277                    }
1278                })
1279                .collect();
1280
1281            Ok((host_connection_id, guest_connection_ids))
1282        })
1283        .await
1284    }
1285
1286    /// Returns the connection IDs in the given project.
1287    ///
1288    /// The provided `connection_id` must also be a collaborator in the project,
1289    /// otherwise an error will be returned.
1290    pub async fn project_connection_ids(
1291        &self,
1292        project_id: ProjectId,
1293        connection_id: ConnectionId,
1294        exclude_dev_server: bool,
1295    ) -> Result<TransactionGuard<HashSet<ConnectionId>>> {
1296        self.project_transaction(project_id, |tx| async move {
1297            self.internal_project_connection_ids(project_id, connection_id, exclude_dev_server, &tx)
1298                .await
1299        })
1300        .await
1301    }
1302
1303    async fn internal_project_connection_ids(
1304        &self,
1305        project_id: ProjectId,
1306        connection_id: ConnectionId,
1307        exclude_dev_server: bool,
1308        tx: &DatabaseTransaction,
1309    ) -> Result<HashSet<ConnectionId>> {
1310        let project = project::Entity::find_by_id(project_id)
1311            .one(tx)
1312            .await?
1313            .context("no such project")?;
1314
1315        let mut collaborators = project_collaborator::Entity::find()
1316            .filter(project_collaborator::Column::ProjectId.eq(project_id))
1317            .stream(tx)
1318            .await?;
1319
1320        let mut connection_ids = HashSet::default();
1321        if let Some(host_connection) = project.host_connection().log_err() {
1322            if !exclude_dev_server {
1323                connection_ids.insert(host_connection);
1324            }
1325        }
1326
1327        while let Some(collaborator) = collaborators.next().await {
1328            let collaborator = collaborator?;
1329            connection_ids.insert(collaborator.connection());
1330        }
1331
1332        if connection_ids.contains(&connection_id)
1333            || Some(connection_id) == project.host_connection().ok()
1334        {
1335            Ok(connection_ids)
1336        } else {
1337            Err(anyhow!(
1338                "can only send project updates to a project you're in"
1339            ))?
1340        }
1341    }
1342
1343    async fn project_guest_connection_ids(
1344        &self,
1345        project_id: ProjectId,
1346        tx: &DatabaseTransaction,
1347    ) -> Result<Vec<ConnectionId>> {
1348        let mut collaborators = project_collaborator::Entity::find()
1349            .filter(
1350                project_collaborator::Column::ProjectId
1351                    .eq(project_id)
1352                    .and(project_collaborator::Column::IsHost.eq(false)),
1353            )
1354            .stream(tx)
1355            .await?;
1356
1357        let mut guest_connection_ids = Vec::new();
1358        while let Some(collaborator) = collaborators.next().await {
1359            let collaborator = collaborator?;
1360            guest_connection_ids.push(collaborator.connection());
1361        }
1362        Ok(guest_connection_ids)
1363    }
1364
1365    /// Returns the [`RoomId`] for the given project.
1366    pub async fn room_id_for_project(&self, project_id: ProjectId) -> Result<Option<RoomId>> {
1367        self.transaction(|tx| async move {
1368            Ok(project::Entity::find_by_id(project_id)
1369                .one(&*tx)
1370                .await?
1371                .and_then(|project| project.room_id))
1372        })
1373        .await
1374    }
1375
1376    pub async fn check_room_participants(
1377        &self,
1378        room_id: RoomId,
1379        leader_id: ConnectionId,
1380        follower_id: ConnectionId,
1381    ) -> Result<()> {
1382        self.transaction(|tx| async move {
1383            use room_participant::Column;
1384
1385            let count = room_participant::Entity::find()
1386                .filter(
1387                    Condition::all().add(Column::RoomId.eq(room_id)).add(
1388                        Condition::any()
1389                            .add(Column::AnsweringConnectionId.eq(leader_id.id as i32).and(
1390                                Column::AnsweringConnectionServerId.eq(leader_id.owner_id as i32),
1391                            ))
1392                            .add(Column::AnsweringConnectionId.eq(follower_id.id as i32).and(
1393                                Column::AnsweringConnectionServerId.eq(follower_id.owner_id as i32),
1394                            )),
1395                    ),
1396                )
1397                .count(&*tx)
1398                .await?;
1399
1400            if count < 2 {
1401                Err(anyhow!("not room participants"))?;
1402            }
1403
1404            Ok(())
1405        })
1406        .await
1407    }
1408
1409    /// Adds the given follower connection as a follower of the given leader connection.
1410    pub async fn follow(
1411        &self,
1412        room_id: RoomId,
1413        project_id: ProjectId,
1414        leader_connection: ConnectionId,
1415        follower_connection: ConnectionId,
1416    ) -> Result<TransactionGuard<proto::Room>> {
1417        self.room_transaction(room_id, |tx| async move {
1418            follower::ActiveModel {
1419                room_id: ActiveValue::set(room_id),
1420                project_id: ActiveValue::set(project_id),
1421                leader_connection_server_id: ActiveValue::set(ServerId(
1422                    leader_connection.owner_id as i32,
1423                )),
1424                leader_connection_id: ActiveValue::set(leader_connection.id as i32),
1425                follower_connection_server_id: ActiveValue::set(ServerId(
1426                    follower_connection.owner_id as i32,
1427                )),
1428                follower_connection_id: ActiveValue::set(follower_connection.id as i32),
1429                ..Default::default()
1430            }
1431            .insert(&*tx)
1432            .await?;
1433
1434            let room = self.get_room(room_id, &tx).await?;
1435            Ok(room)
1436        })
1437        .await
1438    }
1439
1440    /// Removes the given follower connection as a follower of the given leader connection.
1441    pub async fn unfollow(
1442        &self,
1443        room_id: RoomId,
1444        project_id: ProjectId,
1445        leader_connection: ConnectionId,
1446        follower_connection: ConnectionId,
1447    ) -> Result<TransactionGuard<proto::Room>> {
1448        self.room_transaction(room_id, |tx| async move {
1449            follower::Entity::delete_many()
1450                .filter(
1451                    Condition::all()
1452                        .add(follower::Column::RoomId.eq(room_id))
1453                        .add(follower::Column::ProjectId.eq(project_id))
1454                        .add(
1455                            follower::Column::LeaderConnectionServerId
1456                                .eq(leader_connection.owner_id),
1457                        )
1458                        .add(follower::Column::LeaderConnectionId.eq(leader_connection.id))
1459                        .add(
1460                            follower::Column::FollowerConnectionServerId
1461                                .eq(follower_connection.owner_id),
1462                        )
1463                        .add(follower::Column::FollowerConnectionId.eq(follower_connection.id)),
1464                )
1465                .exec(&*tx)
1466                .await?;
1467
1468            let room = self.get_room(room_id, &tx).await?;
1469            Ok(room)
1470        })
1471        .await
1472    }
1473}