db.rs

   1mod access_token;
   2mod contact;
   3mod language_server;
   4mod project;
   5mod project_collaborator;
   6mod room;
   7mod room_participant;
   8mod server;
   9mod signup;
  10#[cfg(test)]
  11mod tests;
  12mod user;
  13mod worktree;
  14mod worktree_diagnostic_summary;
  15mod worktree_entry;
  16
  17use crate::{Error, Result};
  18use anyhow::anyhow;
  19use collections::{BTreeMap, HashMap, HashSet};
  20pub use contact::Contact;
  21use dashmap::DashMap;
  22use futures::StreamExt;
  23use hyper::StatusCode;
  24use rpc::{proto, ConnectionId};
  25use sea_orm::Condition;
  26pub use sea_orm::ConnectOptions;
  27use sea_orm::{
  28    entity::prelude::*, ActiveValue, ConnectionTrait, DatabaseConnection, DatabaseTransaction,
  29    DbErr, FromQueryResult, IntoActiveModel, IsolationLevel, JoinType, QueryOrder, QuerySelect,
  30    Statement, TransactionTrait,
  31};
  32use sea_query::{Alias, Expr, OnConflict, Query};
  33use serde::{Deserialize, Serialize};
  34pub use signup::{Invite, NewSignup, WaitlistSummary};
  35use sqlx::migrate::{Migrate, Migration, MigrationSource};
  36use sqlx::Connection;
  37use std::ops::{Deref, DerefMut};
  38use std::path::Path;
  39use std::time::Duration;
  40use std::{future::Future, marker::PhantomData, rc::Rc, sync::Arc};
  41use tokio::sync::{Mutex, OwnedMutexGuard};
  42pub use user::Model as User;
  43
  44pub struct Database {
  45    options: ConnectOptions,
  46    pool: DatabaseConnection,
  47    rooms: DashMap<RoomId, Arc<Mutex<()>>>,
  48    #[cfg(test)]
  49    background: Option<std::sync::Arc<gpui::executor::Background>>,
  50    #[cfg(test)]
  51    runtime: Option<tokio::runtime::Runtime>,
  52}
  53
  54impl Database {
  55    pub async fn new(options: ConnectOptions) -> Result<Self> {
  56        Ok(Self {
  57            options: options.clone(),
  58            pool: sea_orm::Database::connect(options).await?,
  59            rooms: DashMap::with_capacity(16384),
  60            #[cfg(test)]
  61            background: None,
  62            #[cfg(test)]
  63            runtime: None,
  64        })
  65    }
  66
  67    #[cfg(test)]
  68    pub fn reset(&self) {
  69        self.rooms.clear();
  70    }
  71
  72    pub async fn migrate(
  73        &self,
  74        migrations_path: &Path,
  75        ignore_checksum_mismatch: bool,
  76    ) -> anyhow::Result<Vec<(Migration, Duration)>> {
  77        let migrations = MigrationSource::resolve(migrations_path)
  78            .await
  79            .map_err(|err| anyhow!("failed to load migrations: {err:?}"))?;
  80
  81        let mut connection = sqlx::AnyConnection::connect(self.options.get_url()).await?;
  82
  83        connection.ensure_migrations_table().await?;
  84        let applied_migrations: HashMap<_, _> = connection
  85            .list_applied_migrations()
  86            .await?
  87            .into_iter()
  88            .map(|m| (m.version, m))
  89            .collect();
  90
  91        let mut new_migrations = Vec::new();
  92        for migration in migrations {
  93            match applied_migrations.get(&migration.version) {
  94                Some(applied_migration) => {
  95                    if migration.checksum != applied_migration.checksum && !ignore_checksum_mismatch
  96                    {
  97                        Err(anyhow!(
  98                            "checksum mismatch for applied migration {}",
  99                            migration.description
 100                        ))?;
 101                    }
 102                }
 103                None => {
 104                    let elapsed = connection.apply(&migration).await?;
 105                    new_migrations.push((migration, elapsed));
 106                }
 107            }
 108        }
 109
 110        Ok(new_migrations)
 111    }
 112
 113    pub async fn create_server(&self, environment: &str) -> Result<ServerId> {
 114        self.transaction(|tx| async move {
 115            let server = server::ActiveModel {
 116                environment: ActiveValue::set(environment.into()),
 117                ..Default::default()
 118            }
 119            .insert(&*tx)
 120            .await?;
 121            Ok(server.id)
 122        })
 123        .await
 124    }
 125
 126    pub async fn delete_stale_projects(
 127        &self,
 128        environment: &str,
 129        new_server_id: ServerId,
 130    ) -> Result<()> {
 131        self.transaction(|tx| async move {
 132            let stale_server_epochs = self
 133                .stale_server_ids(environment, new_server_id, &tx)
 134                .await?;
 135            project_collaborator::Entity::delete_many()
 136                .filter(
 137                    project_collaborator::Column::ConnectionServerId
 138                        .is_in(stale_server_epochs.iter().copied()),
 139                )
 140                .exec(&*tx)
 141                .await?;
 142            project::Entity::delete_many()
 143                .filter(
 144                    project::Column::HostConnectionServerId
 145                        .is_in(stale_server_epochs.iter().copied()),
 146                )
 147                .exec(&*tx)
 148                .await?;
 149            Ok(())
 150        })
 151        .await
 152    }
 153
 154    pub async fn stale_room_ids(
 155        &self,
 156        environment: &str,
 157        new_server_id: ServerId,
 158    ) -> Result<Vec<RoomId>> {
 159        self.transaction(|tx| async move {
 160            #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
 161            enum QueryAs {
 162                RoomId,
 163            }
 164
 165            let stale_server_epochs = self
 166                .stale_server_ids(environment, new_server_id, &tx)
 167                .await?;
 168            Ok(room_participant::Entity::find()
 169                .select_only()
 170                .column(room_participant::Column::RoomId)
 171                .distinct()
 172                .filter(
 173                    room_participant::Column::AnsweringConnectionServerId
 174                        .is_in(stale_server_epochs),
 175                )
 176                .into_values::<_, QueryAs>()
 177                .all(&*tx)
 178                .await?)
 179        })
 180        .await
 181    }
 182
 183    pub async fn refresh_room(
 184        &self,
 185        room_id: RoomId,
 186        new_server_id: ServerId,
 187    ) -> Result<RoomGuard<RefreshedRoom>> {
 188        self.room_transaction(|tx| async move {
 189            let stale_participant_filter = Condition::all()
 190                .add(room_participant::Column::RoomId.eq(room_id))
 191                .add(room_participant::Column::AnsweringConnectionId.is_not_null())
 192                .add(room_participant::Column::AnsweringConnectionServerId.ne(new_server_id));
 193
 194            let stale_participant_user_ids = room_participant::Entity::find()
 195                .filter(stale_participant_filter.clone())
 196                .all(&*tx)
 197                .await?
 198                .into_iter()
 199                .map(|participant| participant.user_id)
 200                .collect::<Vec<_>>();
 201
 202            // Delete participants who failed to reconnect.
 203            room_participant::Entity::delete_many()
 204                .filter(stale_participant_filter)
 205                .exec(&*tx)
 206                .await?;
 207
 208            let room = self.get_room(room_id, &tx).await?;
 209            let mut canceled_calls_to_user_ids = Vec::new();
 210            // Delete the room if it becomes empty and cancel pending calls.
 211            if room.participants.is_empty() {
 212                canceled_calls_to_user_ids.extend(
 213                    room.pending_participants
 214                        .iter()
 215                        .map(|pending_participant| UserId::from_proto(pending_participant.user_id)),
 216                );
 217                room_participant::Entity::delete_many()
 218                    .filter(room_participant::Column::RoomId.eq(room_id))
 219                    .exec(&*tx)
 220                    .await?;
 221                room::Entity::delete_by_id(room_id).exec(&*tx).await?;
 222            }
 223
 224            Ok((
 225                room_id,
 226                RefreshedRoom {
 227                    room,
 228                    stale_participant_user_ids,
 229                    canceled_calls_to_user_ids,
 230                },
 231            ))
 232        })
 233        .await
 234    }
 235
 236    pub async fn delete_stale_servers(
 237        &self,
 238        new_server_id: ServerId,
 239        environment: &str,
 240    ) -> Result<()> {
 241        self.transaction(|tx| async move {
 242            server::Entity::delete_many()
 243                .filter(
 244                    Condition::all()
 245                        .add(server::Column::Environment.eq(environment))
 246                        .add(server::Column::Id.ne(new_server_id)),
 247                )
 248                .exec(&*tx)
 249                .await?;
 250            Ok(())
 251        })
 252        .await
 253    }
 254
 255    async fn stale_server_ids(
 256        &self,
 257        environment: &str,
 258        new_server_id: ServerId,
 259        tx: &DatabaseTransaction,
 260    ) -> Result<Vec<ServerId>> {
 261        let stale_servers = server::Entity::find()
 262            .filter(
 263                Condition::all()
 264                    .add(server::Column::Environment.eq(environment))
 265                    .add(server::Column::Id.ne(new_server_id)),
 266            )
 267            .all(&*tx)
 268            .await?;
 269        Ok(stale_servers.into_iter().map(|server| server.id).collect())
 270    }
 271
 272    // users
 273
 274    pub async fn create_user(
 275        &self,
 276        email_address: &str,
 277        admin: bool,
 278        params: NewUserParams,
 279    ) -> Result<NewUserResult> {
 280        self.transaction(|tx| async {
 281            let tx = tx;
 282            let user = user::Entity::insert(user::ActiveModel {
 283                email_address: ActiveValue::set(Some(email_address.into())),
 284                github_login: ActiveValue::set(params.github_login.clone()),
 285                github_user_id: ActiveValue::set(Some(params.github_user_id)),
 286                admin: ActiveValue::set(admin),
 287                metrics_id: ActiveValue::set(Uuid::new_v4()),
 288                ..Default::default()
 289            })
 290            .on_conflict(
 291                OnConflict::column(user::Column::GithubLogin)
 292                    .update_column(user::Column::GithubLogin)
 293                    .to_owned(),
 294            )
 295            .exec_with_returning(&*tx)
 296            .await?;
 297
 298            Ok(NewUserResult {
 299                user_id: user.id,
 300                metrics_id: user.metrics_id.to_string(),
 301                signup_device_id: None,
 302                inviting_user_id: None,
 303            })
 304        })
 305        .await
 306    }
 307
 308    pub async fn get_user_by_id(&self, id: UserId) -> Result<Option<user::Model>> {
 309        self.transaction(|tx| async move { Ok(user::Entity::find_by_id(id).one(&*tx).await?) })
 310            .await
 311    }
 312
 313    pub async fn get_users_by_ids(&self, ids: Vec<UserId>) -> Result<Vec<user::Model>> {
 314        self.transaction(|tx| async {
 315            let tx = tx;
 316            Ok(user::Entity::find()
 317                .filter(user::Column::Id.is_in(ids.iter().copied()))
 318                .all(&*tx)
 319                .await?)
 320        })
 321        .await
 322    }
 323
 324    pub async fn get_user_by_github_account(
 325        &self,
 326        github_login: &str,
 327        github_user_id: Option<i32>,
 328    ) -> Result<Option<User>> {
 329        self.transaction(|tx| async move {
 330            let tx = &*tx;
 331            if let Some(github_user_id) = github_user_id {
 332                if let Some(user_by_github_user_id) = user::Entity::find()
 333                    .filter(user::Column::GithubUserId.eq(github_user_id))
 334                    .one(tx)
 335                    .await?
 336                {
 337                    let mut user_by_github_user_id = user_by_github_user_id.into_active_model();
 338                    user_by_github_user_id.github_login = ActiveValue::set(github_login.into());
 339                    Ok(Some(user_by_github_user_id.update(tx).await?))
 340                } else if let Some(user_by_github_login) = user::Entity::find()
 341                    .filter(user::Column::GithubLogin.eq(github_login))
 342                    .one(tx)
 343                    .await?
 344                {
 345                    let mut user_by_github_login = user_by_github_login.into_active_model();
 346                    user_by_github_login.github_user_id = ActiveValue::set(Some(github_user_id));
 347                    Ok(Some(user_by_github_login.update(tx).await?))
 348                } else {
 349                    Ok(None)
 350                }
 351            } else {
 352                Ok(user::Entity::find()
 353                    .filter(user::Column::GithubLogin.eq(github_login))
 354                    .one(tx)
 355                    .await?)
 356            }
 357        })
 358        .await
 359    }
 360
 361    pub async fn get_all_users(&self, page: u32, limit: u32) -> Result<Vec<User>> {
 362        self.transaction(|tx| async move {
 363            Ok(user::Entity::find()
 364                .order_by_asc(user::Column::GithubLogin)
 365                .limit(limit as u64)
 366                .offset(page as u64 * limit as u64)
 367                .all(&*tx)
 368                .await?)
 369        })
 370        .await
 371    }
 372
 373    pub async fn get_users_with_no_invites(
 374        &self,
 375        invited_by_another_user: bool,
 376    ) -> Result<Vec<User>> {
 377        self.transaction(|tx| async move {
 378            Ok(user::Entity::find()
 379                .filter(
 380                    user::Column::InviteCount
 381                        .eq(0)
 382                        .and(if invited_by_another_user {
 383                            user::Column::InviterId.is_not_null()
 384                        } else {
 385                            user::Column::InviterId.is_null()
 386                        }),
 387                )
 388                .all(&*tx)
 389                .await?)
 390        })
 391        .await
 392    }
 393
 394    pub async fn get_user_metrics_id(&self, id: UserId) -> Result<String> {
 395        #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
 396        enum QueryAs {
 397            MetricsId,
 398        }
 399
 400        self.transaction(|tx| async move {
 401            let metrics_id: Uuid = user::Entity::find_by_id(id)
 402                .select_only()
 403                .column(user::Column::MetricsId)
 404                .into_values::<_, QueryAs>()
 405                .one(&*tx)
 406                .await?
 407                .ok_or_else(|| anyhow!("could not find user"))?;
 408            Ok(metrics_id.to_string())
 409        })
 410        .await
 411    }
 412
 413    pub async fn set_user_is_admin(&self, id: UserId, is_admin: bool) -> Result<()> {
 414        self.transaction(|tx| async move {
 415            user::Entity::update_many()
 416                .filter(user::Column::Id.eq(id))
 417                .set(user::ActiveModel {
 418                    admin: ActiveValue::set(is_admin),
 419                    ..Default::default()
 420                })
 421                .exec(&*tx)
 422                .await?;
 423            Ok(())
 424        })
 425        .await
 426    }
 427
 428    pub async fn set_user_connected_once(&self, id: UserId, connected_once: bool) -> Result<()> {
 429        self.transaction(|tx| async move {
 430            user::Entity::update_many()
 431                .filter(user::Column::Id.eq(id))
 432                .set(user::ActiveModel {
 433                    connected_once: ActiveValue::set(connected_once),
 434                    ..Default::default()
 435                })
 436                .exec(&*tx)
 437                .await?;
 438            Ok(())
 439        })
 440        .await
 441    }
 442
 443    pub async fn destroy_user(&self, id: UserId) -> Result<()> {
 444        self.transaction(|tx| async move {
 445            access_token::Entity::delete_many()
 446                .filter(access_token::Column::UserId.eq(id))
 447                .exec(&*tx)
 448                .await?;
 449            user::Entity::delete_by_id(id).exec(&*tx).await?;
 450            Ok(())
 451        })
 452        .await
 453    }
 454
 455    // contacts
 456
 457    pub async fn get_contacts(&self, user_id: UserId) -> Result<Vec<Contact>> {
 458        #[derive(Debug, FromQueryResult)]
 459        struct ContactWithUserBusyStatuses {
 460            user_id_a: UserId,
 461            user_id_b: UserId,
 462            a_to_b: bool,
 463            accepted: bool,
 464            should_notify: bool,
 465            user_a_busy: bool,
 466            user_b_busy: bool,
 467        }
 468
 469        self.transaction(|tx| async move {
 470            let user_a_participant = Alias::new("user_a_participant");
 471            let user_b_participant = Alias::new("user_b_participant");
 472            let mut db_contacts = contact::Entity::find()
 473                .column_as(
 474                    Expr::tbl(user_a_participant.clone(), room_participant::Column::Id)
 475                        .is_not_null(),
 476                    "user_a_busy",
 477                )
 478                .column_as(
 479                    Expr::tbl(user_b_participant.clone(), room_participant::Column::Id)
 480                        .is_not_null(),
 481                    "user_b_busy",
 482                )
 483                .filter(
 484                    contact::Column::UserIdA
 485                        .eq(user_id)
 486                        .or(contact::Column::UserIdB.eq(user_id)),
 487                )
 488                .join_as(
 489                    JoinType::LeftJoin,
 490                    contact::Relation::UserARoomParticipant.def(),
 491                    user_a_participant,
 492                )
 493                .join_as(
 494                    JoinType::LeftJoin,
 495                    contact::Relation::UserBRoomParticipant.def(),
 496                    user_b_participant,
 497                )
 498                .into_model::<ContactWithUserBusyStatuses>()
 499                .stream(&*tx)
 500                .await?;
 501
 502            let mut contacts = Vec::new();
 503            while let Some(db_contact) = db_contacts.next().await {
 504                let db_contact = db_contact?;
 505                if db_contact.user_id_a == user_id {
 506                    if db_contact.accepted {
 507                        contacts.push(Contact::Accepted {
 508                            user_id: db_contact.user_id_b,
 509                            should_notify: db_contact.should_notify && db_contact.a_to_b,
 510                            busy: db_contact.user_b_busy,
 511                        });
 512                    } else if db_contact.a_to_b {
 513                        contacts.push(Contact::Outgoing {
 514                            user_id: db_contact.user_id_b,
 515                        })
 516                    } else {
 517                        contacts.push(Contact::Incoming {
 518                            user_id: db_contact.user_id_b,
 519                            should_notify: db_contact.should_notify,
 520                        });
 521                    }
 522                } else if db_contact.accepted {
 523                    contacts.push(Contact::Accepted {
 524                        user_id: db_contact.user_id_a,
 525                        should_notify: db_contact.should_notify && !db_contact.a_to_b,
 526                        busy: db_contact.user_a_busy,
 527                    });
 528                } else if db_contact.a_to_b {
 529                    contacts.push(Contact::Incoming {
 530                        user_id: db_contact.user_id_a,
 531                        should_notify: db_contact.should_notify,
 532                    });
 533                } else {
 534                    contacts.push(Contact::Outgoing {
 535                        user_id: db_contact.user_id_a,
 536                    });
 537                }
 538            }
 539
 540            contacts.sort_unstable_by_key(|contact| contact.user_id());
 541
 542            Ok(contacts)
 543        })
 544        .await
 545    }
 546
 547    pub async fn is_user_busy(&self, user_id: UserId) -> Result<bool> {
 548        self.transaction(|tx| async move {
 549            let participant = room_participant::Entity::find()
 550                .filter(room_participant::Column::UserId.eq(user_id))
 551                .one(&*tx)
 552                .await?;
 553            Ok(participant.is_some())
 554        })
 555        .await
 556    }
 557
 558    pub async fn has_contact(&self, user_id_1: UserId, user_id_2: UserId) -> Result<bool> {
 559        self.transaction(|tx| async move {
 560            let (id_a, id_b) = if user_id_1 < user_id_2 {
 561                (user_id_1, user_id_2)
 562            } else {
 563                (user_id_2, user_id_1)
 564            };
 565
 566            Ok(contact::Entity::find()
 567                .filter(
 568                    contact::Column::UserIdA
 569                        .eq(id_a)
 570                        .and(contact::Column::UserIdB.eq(id_b))
 571                        .and(contact::Column::Accepted.eq(true)),
 572                )
 573                .one(&*tx)
 574                .await?
 575                .is_some())
 576        })
 577        .await
 578    }
 579
 580    pub async fn send_contact_request(&self, sender_id: UserId, receiver_id: UserId) -> Result<()> {
 581        self.transaction(|tx| async move {
 582            let (id_a, id_b, a_to_b) = if sender_id < receiver_id {
 583                (sender_id, receiver_id, true)
 584            } else {
 585                (receiver_id, sender_id, false)
 586            };
 587
 588            let rows_affected = contact::Entity::insert(contact::ActiveModel {
 589                user_id_a: ActiveValue::set(id_a),
 590                user_id_b: ActiveValue::set(id_b),
 591                a_to_b: ActiveValue::set(a_to_b),
 592                accepted: ActiveValue::set(false),
 593                should_notify: ActiveValue::set(true),
 594                ..Default::default()
 595            })
 596            .on_conflict(
 597                OnConflict::columns([contact::Column::UserIdA, contact::Column::UserIdB])
 598                    .values([
 599                        (contact::Column::Accepted, true.into()),
 600                        (contact::Column::ShouldNotify, false.into()),
 601                    ])
 602                    .action_and_where(
 603                        contact::Column::Accepted.eq(false).and(
 604                            contact::Column::AToB
 605                                .eq(a_to_b)
 606                                .and(contact::Column::UserIdA.eq(id_b))
 607                                .or(contact::Column::AToB
 608                                    .ne(a_to_b)
 609                                    .and(contact::Column::UserIdA.eq(id_a))),
 610                        ),
 611                    )
 612                    .to_owned(),
 613            )
 614            .exec_without_returning(&*tx)
 615            .await?;
 616
 617            if rows_affected == 1 {
 618                Ok(())
 619            } else {
 620                Err(anyhow!("contact already requested"))?
 621            }
 622        })
 623        .await
 624    }
 625
 626    pub async fn remove_contact(&self, requester_id: UserId, responder_id: UserId) -> Result<()> {
 627        self.transaction(|tx| async move {
 628            let (id_a, id_b) = if responder_id < requester_id {
 629                (responder_id, requester_id)
 630            } else {
 631                (requester_id, responder_id)
 632            };
 633
 634            let result = contact::Entity::delete_many()
 635                .filter(
 636                    contact::Column::UserIdA
 637                        .eq(id_a)
 638                        .and(contact::Column::UserIdB.eq(id_b)),
 639                )
 640                .exec(&*tx)
 641                .await?;
 642
 643            if result.rows_affected == 1 {
 644                Ok(())
 645            } else {
 646                Err(anyhow!("no such contact"))?
 647            }
 648        })
 649        .await
 650    }
 651
 652    pub async fn dismiss_contact_notification(
 653        &self,
 654        user_id: UserId,
 655        contact_user_id: UserId,
 656    ) -> Result<()> {
 657        self.transaction(|tx| async move {
 658            let (id_a, id_b, a_to_b) = if user_id < contact_user_id {
 659                (user_id, contact_user_id, true)
 660            } else {
 661                (contact_user_id, user_id, false)
 662            };
 663
 664            let result = contact::Entity::update_many()
 665                .set(contact::ActiveModel {
 666                    should_notify: ActiveValue::set(false),
 667                    ..Default::default()
 668                })
 669                .filter(
 670                    contact::Column::UserIdA
 671                        .eq(id_a)
 672                        .and(contact::Column::UserIdB.eq(id_b))
 673                        .and(
 674                            contact::Column::AToB
 675                                .eq(a_to_b)
 676                                .and(contact::Column::Accepted.eq(true))
 677                                .or(contact::Column::AToB
 678                                    .ne(a_to_b)
 679                                    .and(contact::Column::Accepted.eq(false))),
 680                        ),
 681                )
 682                .exec(&*tx)
 683                .await?;
 684            if result.rows_affected == 0 {
 685                Err(anyhow!("no such contact request"))?
 686            } else {
 687                Ok(())
 688            }
 689        })
 690        .await
 691    }
 692
 693    pub async fn respond_to_contact_request(
 694        &self,
 695        responder_id: UserId,
 696        requester_id: UserId,
 697        accept: bool,
 698    ) -> Result<()> {
 699        self.transaction(|tx| async move {
 700            let (id_a, id_b, a_to_b) = if responder_id < requester_id {
 701                (responder_id, requester_id, false)
 702            } else {
 703                (requester_id, responder_id, true)
 704            };
 705            let rows_affected = if accept {
 706                let result = contact::Entity::update_many()
 707                    .set(contact::ActiveModel {
 708                        accepted: ActiveValue::set(true),
 709                        should_notify: ActiveValue::set(true),
 710                        ..Default::default()
 711                    })
 712                    .filter(
 713                        contact::Column::UserIdA
 714                            .eq(id_a)
 715                            .and(contact::Column::UserIdB.eq(id_b))
 716                            .and(contact::Column::AToB.eq(a_to_b)),
 717                    )
 718                    .exec(&*tx)
 719                    .await?;
 720                result.rows_affected
 721            } else {
 722                let result = contact::Entity::delete_many()
 723                    .filter(
 724                        contact::Column::UserIdA
 725                            .eq(id_a)
 726                            .and(contact::Column::UserIdB.eq(id_b))
 727                            .and(contact::Column::AToB.eq(a_to_b))
 728                            .and(contact::Column::Accepted.eq(false)),
 729                    )
 730                    .exec(&*tx)
 731                    .await?;
 732
 733                result.rows_affected
 734            };
 735
 736            if rows_affected == 1 {
 737                Ok(())
 738            } else {
 739                Err(anyhow!("no such contact request"))?
 740            }
 741        })
 742        .await
 743    }
 744
 745    pub fn fuzzy_like_string(string: &str) -> String {
 746        let mut result = String::with_capacity(string.len() * 2 + 1);
 747        for c in string.chars() {
 748            if c.is_alphanumeric() {
 749                result.push('%');
 750                result.push(c);
 751            }
 752        }
 753        result.push('%');
 754        result
 755    }
 756
 757    pub async fn fuzzy_search_users(&self, name_query: &str, limit: u32) -> Result<Vec<User>> {
 758        self.transaction(|tx| async {
 759            let tx = tx;
 760            let like_string = Self::fuzzy_like_string(name_query);
 761            let query = "
 762                SELECT users.*
 763                FROM users
 764                WHERE github_login ILIKE $1
 765                ORDER BY github_login <-> $2
 766                LIMIT $3
 767            ";
 768
 769            Ok(user::Entity::find()
 770                .from_raw_sql(Statement::from_sql_and_values(
 771                    self.pool.get_database_backend(),
 772                    query.into(),
 773                    vec![like_string.into(), name_query.into(), limit.into()],
 774                ))
 775                .all(&*tx)
 776                .await?)
 777        })
 778        .await
 779    }
 780
 781    // signups
 782
 783    pub async fn create_signup(&self, signup: &NewSignup) -> Result<()> {
 784        self.transaction(|tx| async move {
 785            signup::Entity::insert(signup::ActiveModel {
 786                email_address: ActiveValue::set(signup.email_address.clone()),
 787                email_confirmation_code: ActiveValue::set(random_email_confirmation_code()),
 788                email_confirmation_sent: ActiveValue::set(false),
 789                platform_mac: ActiveValue::set(signup.platform_mac),
 790                platform_windows: ActiveValue::set(signup.platform_windows),
 791                platform_linux: ActiveValue::set(signup.platform_linux),
 792                platform_unknown: ActiveValue::set(false),
 793                editor_features: ActiveValue::set(Some(signup.editor_features.clone())),
 794                programming_languages: ActiveValue::set(Some(signup.programming_languages.clone())),
 795                device_id: ActiveValue::set(signup.device_id.clone()),
 796                added_to_mailing_list: ActiveValue::set(signup.added_to_mailing_list),
 797                ..Default::default()
 798            })
 799            .on_conflict(
 800                OnConflict::column(signup::Column::EmailAddress)
 801                    .update_columns([
 802                        signup::Column::PlatformMac,
 803                        signup::Column::PlatformWindows,
 804                        signup::Column::PlatformLinux,
 805                        signup::Column::EditorFeatures,
 806                        signup::Column::ProgrammingLanguages,
 807                        signup::Column::DeviceId,
 808                        signup::Column::AddedToMailingList,
 809                    ])
 810                    .to_owned(),
 811            )
 812            .exec(&*tx)
 813            .await?;
 814            Ok(())
 815        })
 816        .await
 817    }
 818
 819    pub async fn get_signup(&self, email_address: &str) -> Result<signup::Model> {
 820        self.transaction(|tx| async move {
 821            let signup = signup::Entity::find()
 822                .filter(signup::Column::EmailAddress.eq(email_address))
 823                .one(&*tx)
 824                .await?
 825                .ok_or_else(|| {
 826                    anyhow!("signup with email address {} doesn't exist", email_address)
 827                })?;
 828
 829            Ok(signup)
 830        })
 831        .await
 832    }
 833
 834    pub async fn get_waitlist_summary(&self) -> Result<WaitlistSummary> {
 835        self.transaction(|tx| async move {
 836            let query = "
 837                SELECT
 838                    COUNT(*) as count,
 839                    COALESCE(SUM(CASE WHEN platform_linux THEN 1 ELSE 0 END), 0) as linux_count,
 840                    COALESCE(SUM(CASE WHEN platform_mac THEN 1 ELSE 0 END), 0) as mac_count,
 841                    COALESCE(SUM(CASE WHEN platform_windows THEN 1 ELSE 0 END), 0) as windows_count,
 842                    COALESCE(SUM(CASE WHEN platform_unknown THEN 1 ELSE 0 END), 0) as unknown_count
 843                FROM (
 844                    SELECT *
 845                    FROM signups
 846                    WHERE
 847                        NOT email_confirmation_sent
 848                ) AS unsent
 849            ";
 850            Ok(
 851                WaitlistSummary::find_by_statement(Statement::from_sql_and_values(
 852                    self.pool.get_database_backend(),
 853                    query.into(),
 854                    vec![],
 855                ))
 856                .one(&*tx)
 857                .await?
 858                .ok_or_else(|| anyhow!("invalid result"))?,
 859            )
 860        })
 861        .await
 862    }
 863
 864    pub async fn record_sent_invites(&self, invites: &[Invite]) -> Result<()> {
 865        let emails = invites
 866            .iter()
 867            .map(|s| s.email_address.as_str())
 868            .collect::<Vec<_>>();
 869        self.transaction(|tx| async {
 870            let tx = tx;
 871            signup::Entity::update_many()
 872                .filter(signup::Column::EmailAddress.is_in(emails.iter().copied()))
 873                .set(signup::ActiveModel {
 874                    email_confirmation_sent: ActiveValue::set(true),
 875                    ..Default::default()
 876                })
 877                .exec(&*tx)
 878                .await?;
 879            Ok(())
 880        })
 881        .await
 882    }
 883
 884    pub async fn get_unsent_invites(&self, count: usize) -> Result<Vec<Invite>> {
 885        self.transaction(|tx| async move {
 886            Ok(signup::Entity::find()
 887                .select_only()
 888                .column(signup::Column::EmailAddress)
 889                .column(signup::Column::EmailConfirmationCode)
 890                .filter(
 891                    signup::Column::EmailConfirmationSent.eq(false).and(
 892                        signup::Column::PlatformMac
 893                            .eq(true)
 894                            .or(signup::Column::PlatformUnknown.eq(true)),
 895                    ),
 896                )
 897                .order_by_asc(signup::Column::CreatedAt)
 898                .limit(count as u64)
 899                .into_model()
 900                .all(&*tx)
 901                .await?)
 902        })
 903        .await
 904    }
 905
 906    // invite codes
 907
 908    pub async fn create_invite_from_code(
 909        &self,
 910        code: &str,
 911        email_address: &str,
 912        device_id: Option<&str>,
 913    ) -> Result<Invite> {
 914        self.transaction(|tx| async move {
 915            let existing_user = user::Entity::find()
 916                .filter(user::Column::EmailAddress.eq(email_address))
 917                .one(&*tx)
 918                .await?;
 919
 920            if existing_user.is_some() {
 921                Err(anyhow!("email address is already in use"))?;
 922            }
 923
 924            let inviting_user_with_invites = match user::Entity::find()
 925                .filter(
 926                    user::Column::InviteCode
 927                        .eq(code)
 928                        .and(user::Column::InviteCount.gt(0)),
 929                )
 930                .one(&*tx)
 931                .await?
 932            {
 933                Some(inviting_user) => inviting_user,
 934                None => {
 935                    return Err(Error::Http(
 936                        StatusCode::UNAUTHORIZED,
 937                        "unable to find an invite code with invites remaining".to_string(),
 938                    ))?
 939                }
 940            };
 941            user::Entity::update_many()
 942                .filter(
 943                    user::Column::Id
 944                        .eq(inviting_user_with_invites.id)
 945                        .and(user::Column::InviteCount.gt(0)),
 946                )
 947                .col_expr(
 948                    user::Column::InviteCount,
 949                    Expr::col(user::Column::InviteCount).sub(1),
 950                )
 951                .exec(&*tx)
 952                .await?;
 953
 954            let signup = signup::Entity::insert(signup::ActiveModel {
 955                email_address: ActiveValue::set(email_address.into()),
 956                email_confirmation_code: ActiveValue::set(random_email_confirmation_code()),
 957                email_confirmation_sent: ActiveValue::set(false),
 958                inviting_user_id: ActiveValue::set(Some(inviting_user_with_invites.id)),
 959                platform_linux: ActiveValue::set(false),
 960                platform_mac: ActiveValue::set(false),
 961                platform_windows: ActiveValue::set(false),
 962                platform_unknown: ActiveValue::set(true),
 963                device_id: ActiveValue::set(device_id.map(|device_id| device_id.into())),
 964                ..Default::default()
 965            })
 966            .on_conflict(
 967                OnConflict::column(signup::Column::EmailAddress)
 968                    .update_column(signup::Column::InvitingUserId)
 969                    .to_owned(),
 970            )
 971            .exec_with_returning(&*tx)
 972            .await?;
 973
 974            Ok(Invite {
 975                email_address: signup.email_address,
 976                email_confirmation_code: signup.email_confirmation_code,
 977            })
 978        })
 979        .await
 980    }
 981
 982    pub async fn create_user_from_invite(
 983        &self,
 984        invite: &Invite,
 985        user: NewUserParams,
 986    ) -> Result<Option<NewUserResult>> {
 987        self.transaction(|tx| async {
 988            let tx = tx;
 989            let signup = signup::Entity::find()
 990                .filter(
 991                    signup::Column::EmailAddress
 992                        .eq(invite.email_address.as_str())
 993                        .and(
 994                            signup::Column::EmailConfirmationCode
 995                                .eq(invite.email_confirmation_code.as_str()),
 996                        ),
 997                )
 998                .one(&*tx)
 999                .await?
1000                .ok_or_else(|| Error::Http(StatusCode::NOT_FOUND, "no such invite".to_string()))?;
1001
1002            if signup.user_id.is_some() {
1003                return Ok(None);
1004            }
1005
1006            let user = user::Entity::insert(user::ActiveModel {
1007                email_address: ActiveValue::set(Some(invite.email_address.clone())),
1008                github_login: ActiveValue::set(user.github_login.clone()),
1009                github_user_id: ActiveValue::set(Some(user.github_user_id)),
1010                admin: ActiveValue::set(false),
1011                invite_count: ActiveValue::set(user.invite_count),
1012                invite_code: ActiveValue::set(Some(random_invite_code())),
1013                metrics_id: ActiveValue::set(Uuid::new_v4()),
1014                ..Default::default()
1015            })
1016            .on_conflict(
1017                OnConflict::column(user::Column::GithubLogin)
1018                    .update_columns([
1019                        user::Column::EmailAddress,
1020                        user::Column::GithubUserId,
1021                        user::Column::Admin,
1022                    ])
1023                    .to_owned(),
1024            )
1025            .exec_with_returning(&*tx)
1026            .await?;
1027
1028            let mut signup = signup.into_active_model();
1029            signup.user_id = ActiveValue::set(Some(user.id));
1030            let signup = signup.update(&*tx).await?;
1031
1032            if let Some(inviting_user_id) = signup.inviting_user_id {
1033                let (user_id_a, user_id_b, a_to_b) = if inviting_user_id < user.id {
1034                    (inviting_user_id, user.id, true)
1035                } else {
1036                    (user.id, inviting_user_id, false)
1037                };
1038
1039                contact::Entity::insert(contact::ActiveModel {
1040                    user_id_a: ActiveValue::set(user_id_a),
1041                    user_id_b: ActiveValue::set(user_id_b),
1042                    a_to_b: ActiveValue::set(a_to_b),
1043                    should_notify: ActiveValue::set(true),
1044                    accepted: ActiveValue::set(true),
1045                    ..Default::default()
1046                })
1047                .on_conflict(OnConflict::new().do_nothing().to_owned())
1048                .exec_without_returning(&*tx)
1049                .await?;
1050            }
1051
1052            Ok(Some(NewUserResult {
1053                user_id: user.id,
1054                metrics_id: user.metrics_id.to_string(),
1055                inviting_user_id: signup.inviting_user_id,
1056                signup_device_id: signup.device_id,
1057            }))
1058        })
1059        .await
1060    }
1061
1062    pub async fn set_invite_count_for_user(&self, id: UserId, count: i32) -> Result<()> {
1063        self.transaction(|tx| async move {
1064            if count > 0 {
1065                user::Entity::update_many()
1066                    .filter(
1067                        user::Column::Id
1068                            .eq(id)
1069                            .and(user::Column::InviteCode.is_null()),
1070                    )
1071                    .set(user::ActiveModel {
1072                        invite_code: ActiveValue::set(Some(random_invite_code())),
1073                        ..Default::default()
1074                    })
1075                    .exec(&*tx)
1076                    .await?;
1077            }
1078
1079            user::Entity::update_many()
1080                .filter(user::Column::Id.eq(id))
1081                .set(user::ActiveModel {
1082                    invite_count: ActiveValue::set(count),
1083                    ..Default::default()
1084                })
1085                .exec(&*tx)
1086                .await?;
1087            Ok(())
1088        })
1089        .await
1090    }
1091
1092    pub async fn get_invite_code_for_user(&self, id: UserId) -> Result<Option<(String, i32)>> {
1093        self.transaction(|tx| async move {
1094            match user::Entity::find_by_id(id).one(&*tx).await? {
1095                Some(user) if user.invite_code.is_some() => {
1096                    Ok(Some((user.invite_code.unwrap(), user.invite_count)))
1097                }
1098                _ => Ok(None),
1099            }
1100        })
1101        .await
1102    }
1103
1104    pub async fn get_user_for_invite_code(&self, code: &str) -> Result<User> {
1105        self.transaction(|tx| async move {
1106            user::Entity::find()
1107                .filter(user::Column::InviteCode.eq(code))
1108                .one(&*tx)
1109                .await?
1110                .ok_or_else(|| {
1111                    Error::Http(
1112                        StatusCode::NOT_FOUND,
1113                        "that invite code does not exist".to_string(),
1114                    )
1115                })
1116        })
1117        .await
1118    }
1119
1120    // rooms
1121
1122    pub async fn incoming_call_for_user(
1123        &self,
1124        user_id: UserId,
1125    ) -> Result<Option<proto::IncomingCall>> {
1126        self.transaction(|tx| async move {
1127            let pending_participant = room_participant::Entity::find()
1128                .filter(
1129                    room_participant::Column::UserId
1130                        .eq(user_id)
1131                        .and(room_participant::Column::AnsweringConnectionId.is_null()),
1132                )
1133                .one(&*tx)
1134                .await?;
1135
1136            if let Some(pending_participant) = pending_participant {
1137                let room = self.get_room(pending_participant.room_id, &tx).await?;
1138                Ok(Self::build_incoming_call(&room, user_id))
1139            } else {
1140                Ok(None)
1141            }
1142        })
1143        .await
1144    }
1145
1146    pub async fn create_room(
1147        &self,
1148        user_id: UserId,
1149        connection: ConnectionId,
1150        live_kit_room: &str,
1151    ) -> Result<RoomGuard<proto::Room>> {
1152        self.room_transaction(|tx| async move {
1153            let room = room::ActiveModel {
1154                live_kit_room: ActiveValue::set(live_kit_room.into()),
1155                ..Default::default()
1156            }
1157            .insert(&*tx)
1158            .await?;
1159            let room_id = room.id;
1160
1161            room_participant::ActiveModel {
1162                room_id: ActiveValue::set(room_id),
1163                user_id: ActiveValue::set(user_id),
1164                answering_connection_id: ActiveValue::set(Some(connection.id as i32)),
1165                answering_connection_server_id: ActiveValue::set(Some(ServerId(
1166                    connection.owner_id as i32,
1167                ))),
1168                answering_connection_lost: ActiveValue::set(false),
1169                calling_user_id: ActiveValue::set(user_id),
1170                calling_connection_id: ActiveValue::set(connection.id as i32),
1171                calling_connection_server_id: ActiveValue::set(Some(ServerId(
1172                    connection.owner_id as i32,
1173                ))),
1174                ..Default::default()
1175            }
1176            .insert(&*tx)
1177            .await?;
1178
1179            let room = self.get_room(room_id, &tx).await?;
1180            Ok((room_id, room))
1181        })
1182        .await
1183    }
1184
1185    pub async fn call(
1186        &self,
1187        room_id: RoomId,
1188        calling_user_id: UserId,
1189        calling_connection: ConnectionId,
1190        called_user_id: UserId,
1191        initial_project_id: Option<ProjectId>,
1192    ) -> Result<RoomGuard<(proto::Room, proto::IncomingCall)>> {
1193        self.room_transaction(|tx| async move {
1194            room_participant::ActiveModel {
1195                room_id: ActiveValue::set(room_id),
1196                user_id: ActiveValue::set(called_user_id),
1197                answering_connection_lost: ActiveValue::set(false),
1198                calling_user_id: ActiveValue::set(calling_user_id),
1199                calling_connection_id: ActiveValue::set(calling_connection.id as i32),
1200                calling_connection_server_id: ActiveValue::set(Some(ServerId(
1201                    calling_connection.owner_id as i32,
1202                ))),
1203                initial_project_id: ActiveValue::set(initial_project_id),
1204                ..Default::default()
1205            }
1206            .insert(&*tx)
1207            .await?;
1208
1209            let room = self.get_room(room_id, &tx).await?;
1210            let incoming_call = Self::build_incoming_call(&room, called_user_id)
1211                .ok_or_else(|| anyhow!("failed to build incoming call"))?;
1212            Ok((room_id, (room, incoming_call)))
1213        })
1214        .await
1215    }
1216
1217    pub async fn call_failed(
1218        &self,
1219        room_id: RoomId,
1220        called_user_id: UserId,
1221    ) -> Result<RoomGuard<proto::Room>> {
1222        self.room_transaction(|tx| async move {
1223            room_participant::Entity::delete_many()
1224                .filter(
1225                    room_participant::Column::RoomId
1226                        .eq(room_id)
1227                        .and(room_participant::Column::UserId.eq(called_user_id)),
1228                )
1229                .exec(&*tx)
1230                .await?;
1231            let room = self.get_room(room_id, &tx).await?;
1232            Ok((room_id, room))
1233        })
1234        .await
1235    }
1236
1237    pub async fn decline_call(
1238        &self,
1239        expected_room_id: Option<RoomId>,
1240        user_id: UserId,
1241    ) -> Result<Option<RoomGuard<proto::Room>>> {
1242        self.optional_room_transaction(|tx| async move {
1243            let mut filter = Condition::all()
1244                .add(room_participant::Column::UserId.eq(user_id))
1245                .add(room_participant::Column::AnsweringConnectionId.is_null());
1246            if let Some(room_id) = expected_room_id {
1247                filter = filter.add(room_participant::Column::RoomId.eq(room_id));
1248            }
1249            let participant = room_participant::Entity::find()
1250                .filter(filter)
1251                .one(&*tx)
1252                .await?;
1253
1254            let participant = if let Some(participant) = participant {
1255                participant
1256            } else if expected_room_id.is_some() {
1257                return Err(anyhow!("could not find call to decline"))?;
1258            } else {
1259                return Ok(None);
1260            };
1261
1262            let room_id = participant.room_id;
1263            room_participant::Entity::delete(participant.into_active_model())
1264                .exec(&*tx)
1265                .await?;
1266
1267            let room = self.get_room(room_id, &tx).await?;
1268            Ok(Some((room_id, room)))
1269        })
1270        .await
1271    }
1272
1273    pub async fn cancel_call(
1274        &self,
1275        room_id: RoomId,
1276        calling_connection: ConnectionId,
1277        called_user_id: UserId,
1278    ) -> Result<RoomGuard<proto::Room>> {
1279        self.room_transaction(|tx| async move {
1280            let participant = room_participant::Entity::find()
1281                .filter(
1282                    Condition::all()
1283                        .add(room_participant::Column::UserId.eq(called_user_id))
1284                        .add(room_participant::Column::RoomId.eq(room_id))
1285                        .add(
1286                            room_participant::Column::CallingConnectionId
1287                                .eq(calling_connection.id as i32),
1288                        )
1289                        .add(
1290                            room_participant::Column::CallingConnectionServerId
1291                                .eq(calling_connection.owner_id as i32),
1292                        )
1293                        .add(room_participant::Column::AnsweringConnectionId.is_null()),
1294                )
1295                .one(&*tx)
1296                .await?
1297                .ok_or_else(|| anyhow!("no call to cancel"))?;
1298            let room_id = participant.room_id;
1299
1300            room_participant::Entity::delete(participant.into_active_model())
1301                .exec(&*tx)
1302                .await?;
1303
1304            let room = self.get_room(room_id, &tx).await?;
1305            Ok((room_id, room))
1306        })
1307        .await
1308    }
1309
1310    pub async fn join_room(
1311        &self,
1312        room_id: RoomId,
1313        user_id: UserId,
1314        connection: ConnectionId,
1315    ) -> Result<RoomGuard<proto::Room>> {
1316        self.room_transaction(|tx| async move {
1317            let result = room_participant::Entity::update_many()
1318                .filter(
1319                    Condition::all()
1320                        .add(room_participant::Column::RoomId.eq(room_id))
1321                        .add(room_participant::Column::UserId.eq(user_id))
1322                        .add(
1323                            Condition::any()
1324                                .add(room_participant::Column::AnsweringConnectionId.is_null())
1325                                .add(room_participant::Column::AnsweringConnectionLost.eq(true))
1326                                .add(
1327                                    room_participant::Column::AnsweringConnectionServerId
1328                                        .ne(connection.owner_id as i32),
1329                                ),
1330                        ),
1331                )
1332                .set(room_participant::ActiveModel {
1333                    answering_connection_id: ActiveValue::set(Some(connection.id as i32)),
1334                    answering_connection_server_id: ActiveValue::set(Some(ServerId(
1335                        connection.owner_id as i32,
1336                    ))),
1337                    answering_connection_lost: ActiveValue::set(false),
1338                    ..Default::default()
1339                })
1340                .exec(&*tx)
1341                .await?;
1342            if result.rows_affected == 0 {
1343                Err(anyhow!("room does not exist or was already joined"))?
1344            } else {
1345                let room = self.get_room(room_id, &tx).await?;
1346                Ok((room_id, room))
1347            }
1348        })
1349        .await
1350    }
1351
1352    pub async fn leave_room(
1353        &self,
1354        connection: ConnectionId,
1355    ) -> Result<Option<RoomGuard<LeftRoom>>> {
1356        self.optional_room_transaction(|tx| async move {
1357            let leaving_participant = room_participant::Entity::find()
1358                .filter(
1359                    Condition::all()
1360                        .add(
1361                            room_participant::Column::AnsweringConnectionId
1362                                .eq(connection.id as i32),
1363                        )
1364                        .add(
1365                            room_participant::Column::AnsweringConnectionServerId
1366                                .eq(connection.owner_id as i32),
1367                        ),
1368                )
1369                .one(&*tx)
1370                .await?;
1371
1372            if let Some(leaving_participant) = leaving_participant {
1373                // Leave room.
1374                let room_id = leaving_participant.room_id;
1375                room_participant::Entity::delete_by_id(leaving_participant.id)
1376                    .exec(&*tx)
1377                    .await?;
1378
1379                // Cancel pending calls initiated by the leaving user.
1380                let called_participants = room_participant::Entity::find()
1381                    .filter(
1382                        Condition::all()
1383                            .add(
1384                                room_participant::Column::CallingConnectionId
1385                                    .eq(connection.id as i32),
1386                            )
1387                            .add(
1388                                room_participant::Column::CallingConnectionServerId
1389                                    .eq(connection.owner_id as i32),
1390                            )
1391                            .add(room_participant::Column::AnsweringConnectionId.is_null()),
1392                    )
1393                    .all(&*tx)
1394                    .await?;
1395                room_participant::Entity::delete_many()
1396                    .filter(
1397                        room_participant::Column::Id
1398                            .is_in(called_participants.iter().map(|participant| participant.id)),
1399                    )
1400                    .exec(&*tx)
1401                    .await?;
1402                let canceled_calls_to_user_ids = called_participants
1403                    .into_iter()
1404                    .map(|participant| participant.user_id)
1405                    .collect();
1406
1407                // Detect left projects.
1408                #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
1409                enum QueryProjectIds {
1410                    ProjectId,
1411                }
1412                let project_ids: Vec<ProjectId> = project_collaborator::Entity::find()
1413                    .select_only()
1414                    .column_as(
1415                        project_collaborator::Column::ProjectId,
1416                        QueryProjectIds::ProjectId,
1417                    )
1418                    .filter(
1419                        Condition::all()
1420                            .add(
1421                                project_collaborator::Column::ConnectionId.eq(connection.id as i32),
1422                            )
1423                            .add(
1424                                project_collaborator::Column::ConnectionServerId
1425                                    .eq(connection.owner_id as i32),
1426                            ),
1427                    )
1428                    .into_values::<_, QueryProjectIds>()
1429                    .all(&*tx)
1430                    .await?;
1431                let mut left_projects = HashMap::default();
1432                let mut collaborators = project_collaborator::Entity::find()
1433                    .filter(project_collaborator::Column::ProjectId.is_in(project_ids))
1434                    .stream(&*tx)
1435                    .await?;
1436                while let Some(collaborator) = collaborators.next().await {
1437                    let collaborator = collaborator?;
1438                    let left_project =
1439                        left_projects
1440                            .entry(collaborator.project_id)
1441                            .or_insert(LeftProject {
1442                                id: collaborator.project_id,
1443                                host_user_id: Default::default(),
1444                                connection_ids: Default::default(),
1445                                host_connection_id: Default::default(),
1446                            });
1447
1448                    let collaborator_connection_id = ConnectionId {
1449                        owner_id: collaborator.connection_server_id.0 as u32,
1450                        id: collaborator.connection_id as u32,
1451                    };
1452                    if collaborator_connection_id != connection {
1453                        left_project.connection_ids.push(collaborator_connection_id);
1454                    }
1455
1456                    if collaborator.is_host {
1457                        left_project.host_user_id = collaborator.user_id;
1458                        left_project.host_connection_id = collaborator_connection_id;
1459                    }
1460                }
1461                drop(collaborators);
1462
1463                // Leave projects.
1464                project_collaborator::Entity::delete_many()
1465                    .filter(
1466                        Condition::all()
1467                            .add(
1468                                project_collaborator::Column::ConnectionId.eq(connection.id as i32),
1469                            )
1470                            .add(
1471                                project_collaborator::Column::ConnectionServerId
1472                                    .eq(connection.owner_id as i32),
1473                            ),
1474                    )
1475                    .exec(&*tx)
1476                    .await?;
1477
1478                // Unshare projects.
1479                project::Entity::delete_many()
1480                    .filter(
1481                        Condition::all()
1482                            .add(project::Column::RoomId.eq(room_id))
1483                            .add(project::Column::HostConnectionId.eq(connection.id as i32))
1484                            .add(
1485                                project::Column::HostConnectionServerId
1486                                    .eq(connection.owner_id as i32),
1487                            ),
1488                    )
1489                    .exec(&*tx)
1490                    .await?;
1491
1492                let room = self.get_room(room_id, &tx).await?;
1493                if room.participants.is_empty() {
1494                    room::Entity::delete_by_id(room_id).exec(&*tx).await?;
1495                }
1496
1497                let left_room = LeftRoom {
1498                    room,
1499                    left_projects,
1500                    canceled_calls_to_user_ids,
1501                };
1502
1503                if left_room.room.participants.is_empty() {
1504                    self.rooms.remove(&room_id);
1505                }
1506
1507                Ok(Some((room_id, left_room)))
1508            } else {
1509                Ok(None)
1510            }
1511        })
1512        .await
1513    }
1514
1515    pub async fn update_room_participant_location(
1516        &self,
1517        room_id: RoomId,
1518        connection: ConnectionId,
1519        location: proto::ParticipantLocation,
1520    ) -> Result<RoomGuard<proto::Room>> {
1521        self.room_transaction(|tx| async {
1522            let tx = tx;
1523            let location_kind;
1524            let location_project_id;
1525            match location
1526                .variant
1527                .as_ref()
1528                .ok_or_else(|| anyhow!("invalid location"))?
1529            {
1530                proto::participant_location::Variant::SharedProject(project) => {
1531                    location_kind = 0;
1532                    location_project_id = Some(ProjectId::from_proto(project.id));
1533                }
1534                proto::participant_location::Variant::UnsharedProject(_) => {
1535                    location_kind = 1;
1536                    location_project_id = None;
1537                }
1538                proto::participant_location::Variant::External(_) => {
1539                    location_kind = 2;
1540                    location_project_id = None;
1541                }
1542            }
1543
1544            let result = room_participant::Entity::update_many()
1545                .filter(
1546                    Condition::all()
1547                        .add(room_participant::Column::RoomId.eq(room_id))
1548                        .add(
1549                            room_participant::Column::AnsweringConnectionId
1550                                .eq(connection.id as i32),
1551                        )
1552                        .add(
1553                            room_participant::Column::AnsweringConnectionServerId
1554                                .eq(connection.owner_id as i32),
1555                        ),
1556                )
1557                .set(room_participant::ActiveModel {
1558                    location_kind: ActiveValue::set(Some(location_kind)),
1559                    location_project_id: ActiveValue::set(location_project_id),
1560                    ..Default::default()
1561                })
1562                .exec(&*tx)
1563                .await?;
1564
1565            if result.rows_affected == 1 {
1566                let room = self.get_room(room_id, &tx).await?;
1567                Ok((room_id, room))
1568            } else {
1569                Err(anyhow!("could not update room participant location"))?
1570            }
1571        })
1572        .await
1573    }
1574
1575    pub async fn connection_lost(
1576        &self,
1577        connection: ConnectionId,
1578    ) -> Result<RoomGuard<Vec<LeftProject>>> {
1579        self.room_transaction(|tx| async move {
1580            let participant = room_participant::Entity::find()
1581                .filter(
1582                    Condition::all()
1583                        .add(
1584                            room_participant::Column::AnsweringConnectionId
1585                                .eq(connection.id as i32),
1586                        )
1587                        .add(
1588                            room_participant::Column::AnsweringConnectionServerId
1589                                .eq(connection.owner_id as i32),
1590                        ),
1591                )
1592                .one(&*tx)
1593                .await?
1594                .ok_or_else(|| anyhow!("not a participant in any room"))?;
1595            let room_id = participant.room_id;
1596
1597            room_participant::Entity::update(room_participant::ActiveModel {
1598                answering_connection_lost: ActiveValue::set(true),
1599                ..participant.into_active_model()
1600            })
1601            .exec(&*tx)
1602            .await?;
1603
1604            let collaborator_on_projects = project_collaborator::Entity::find()
1605                .find_also_related(project::Entity)
1606                .filter(
1607                    Condition::all()
1608                        .add(project_collaborator::Column::ConnectionId.eq(connection.id as i32))
1609                        .add(
1610                            project_collaborator::Column::ConnectionServerId
1611                                .eq(connection.owner_id as i32),
1612                        ),
1613                )
1614                .all(&*tx)
1615                .await?;
1616            project_collaborator::Entity::delete_many()
1617                .filter(
1618                    Condition::all()
1619                        .add(project_collaborator::Column::ConnectionId.eq(connection.id as i32))
1620                        .add(
1621                            project_collaborator::Column::ConnectionServerId
1622                                .eq(connection.owner_id as i32),
1623                        ),
1624                )
1625                .exec(&*tx)
1626                .await?;
1627
1628            let mut left_projects = Vec::new();
1629            for (_, project) in collaborator_on_projects {
1630                if let Some(project) = project {
1631                    let collaborators = project
1632                        .find_related(project_collaborator::Entity)
1633                        .all(&*tx)
1634                        .await?;
1635                    let connection_ids = collaborators
1636                        .into_iter()
1637                        .map(|collaborator| ConnectionId {
1638                            id: collaborator.connection_id as u32,
1639                            owner_id: collaborator.connection_server_id.0 as u32,
1640                        })
1641                        .collect();
1642
1643                    left_projects.push(LeftProject {
1644                        id: project.id,
1645                        host_user_id: project.host_user_id,
1646                        host_connection_id: project.host_connection()?,
1647                        connection_ids,
1648                    });
1649                }
1650            }
1651
1652            project::Entity::delete_many()
1653                .filter(
1654                    Condition::all()
1655                        .add(project::Column::HostConnectionId.eq(connection.id as i32))
1656                        .add(
1657                            project::Column::HostConnectionServerId.eq(connection.owner_id as i32),
1658                        ),
1659                )
1660                .exec(&*tx)
1661                .await?;
1662
1663            Ok((room_id, left_projects))
1664        })
1665        .await
1666    }
1667
1668    fn build_incoming_call(
1669        room: &proto::Room,
1670        called_user_id: UserId,
1671    ) -> Option<proto::IncomingCall> {
1672        let pending_participant = room
1673            .pending_participants
1674            .iter()
1675            .find(|participant| participant.user_id == called_user_id.to_proto())?;
1676
1677        Some(proto::IncomingCall {
1678            room_id: room.id,
1679            calling_user_id: pending_participant.calling_user_id,
1680            participant_user_ids: room
1681                .participants
1682                .iter()
1683                .map(|participant| participant.user_id)
1684                .collect(),
1685            initial_project: room.participants.iter().find_map(|participant| {
1686                let initial_project_id = pending_participant.initial_project_id?;
1687                participant
1688                    .projects
1689                    .iter()
1690                    .find(|project| project.id == initial_project_id)
1691                    .cloned()
1692            }),
1693        })
1694    }
1695
1696    async fn get_room(&self, room_id: RoomId, tx: &DatabaseTransaction) -> Result<proto::Room> {
1697        let db_room = room::Entity::find_by_id(room_id)
1698            .one(tx)
1699            .await?
1700            .ok_or_else(|| anyhow!("could not find room"))?;
1701
1702        let mut db_participants = db_room
1703            .find_related(room_participant::Entity)
1704            .stream(tx)
1705            .await?;
1706        let mut participants = HashMap::default();
1707        let mut pending_participants = Vec::new();
1708        while let Some(db_participant) = db_participants.next().await {
1709            let db_participant = db_participant?;
1710            if let Some((answering_connection_id, answering_connection_server_id)) = db_participant
1711                .answering_connection_id
1712                .zip(db_participant.answering_connection_server_id)
1713            {
1714                let location = match (
1715                    db_participant.location_kind,
1716                    db_participant.location_project_id,
1717                ) {
1718                    (Some(0), Some(project_id)) => {
1719                        Some(proto::participant_location::Variant::SharedProject(
1720                            proto::participant_location::SharedProject {
1721                                id: project_id.to_proto(),
1722                            },
1723                        ))
1724                    }
1725                    (Some(1), _) => Some(proto::participant_location::Variant::UnsharedProject(
1726                        Default::default(),
1727                    )),
1728                    _ => Some(proto::participant_location::Variant::External(
1729                        Default::default(),
1730                    )),
1731                };
1732
1733                let answering_connection = ConnectionId {
1734                    owner_id: answering_connection_server_id.0 as u32,
1735                    id: answering_connection_id as u32,
1736                };
1737                participants.insert(
1738                    answering_connection,
1739                    proto::Participant {
1740                        user_id: db_participant.user_id.to_proto(),
1741                        peer_id: Some(answering_connection.into()),
1742                        projects: Default::default(),
1743                        location: Some(proto::ParticipantLocation { variant: location }),
1744                    },
1745                );
1746            } else {
1747                pending_participants.push(proto::PendingParticipant {
1748                    user_id: db_participant.user_id.to_proto(),
1749                    calling_user_id: db_participant.calling_user_id.to_proto(),
1750                    initial_project_id: db_participant.initial_project_id.map(|id| id.to_proto()),
1751                });
1752            }
1753        }
1754        drop(db_participants);
1755
1756        let mut db_projects = db_room
1757            .find_related(project::Entity)
1758            .find_with_related(worktree::Entity)
1759            .stream(tx)
1760            .await?;
1761
1762        while let Some(row) = db_projects.next().await {
1763            let (db_project, db_worktree) = row?;
1764            let host_connection = db_project.host_connection()?;
1765            if let Some(participant) = participants.get_mut(&host_connection) {
1766                let project = if let Some(project) = participant
1767                    .projects
1768                    .iter_mut()
1769                    .find(|project| project.id == db_project.id.to_proto())
1770                {
1771                    project
1772                } else {
1773                    participant.projects.push(proto::ParticipantProject {
1774                        id: db_project.id.to_proto(),
1775                        worktree_root_names: Default::default(),
1776                    });
1777                    participant.projects.last_mut().unwrap()
1778                };
1779
1780                if let Some(db_worktree) = db_worktree {
1781                    project.worktree_root_names.push(db_worktree.root_name);
1782                }
1783            }
1784        }
1785
1786        Ok(proto::Room {
1787            id: db_room.id.to_proto(),
1788            live_kit_room: db_room.live_kit_room,
1789            participants: participants.into_values().collect(),
1790            pending_participants,
1791        })
1792    }
1793
1794    // projects
1795
1796    pub async fn project_count_excluding_admins(&self) -> Result<usize> {
1797        #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
1798        enum QueryAs {
1799            Count,
1800        }
1801
1802        self.transaction(|tx| async move {
1803            Ok(project::Entity::find()
1804                .select_only()
1805                .column_as(project::Column::Id.count(), QueryAs::Count)
1806                .inner_join(user::Entity)
1807                .filter(user::Column::Admin.eq(false))
1808                .into_values::<_, QueryAs>()
1809                .one(&*tx)
1810                .await?
1811                .unwrap_or(0i64) as usize)
1812        })
1813        .await
1814    }
1815
1816    pub async fn share_project(
1817        &self,
1818        room_id: RoomId,
1819        connection: ConnectionId,
1820        worktrees: &[proto::WorktreeMetadata],
1821    ) -> Result<RoomGuard<(ProjectId, proto::Room)>> {
1822        self.room_transaction(|tx| async move {
1823            let participant = room_participant::Entity::find()
1824                .filter(
1825                    Condition::all()
1826                        .add(
1827                            room_participant::Column::AnsweringConnectionId
1828                                .eq(connection.id as i32),
1829                        )
1830                        .add(
1831                            room_participant::Column::AnsweringConnectionServerId
1832                                .eq(connection.owner_id as i32),
1833                        ),
1834                )
1835                .one(&*tx)
1836                .await?
1837                .ok_or_else(|| anyhow!("could not find participant"))?;
1838            if participant.room_id != room_id {
1839                return Err(anyhow!("shared project on unexpected room"))?;
1840            }
1841
1842            let project = project::ActiveModel {
1843                room_id: ActiveValue::set(participant.room_id),
1844                host_user_id: ActiveValue::set(participant.user_id),
1845                host_connection_id: ActiveValue::set(Some(connection.id as i32)),
1846                host_connection_server_id: ActiveValue::set(Some(ServerId(
1847                    connection.owner_id as i32,
1848                ))),
1849                ..Default::default()
1850            }
1851            .insert(&*tx)
1852            .await?;
1853
1854            if !worktrees.is_empty() {
1855                worktree::Entity::insert_many(worktrees.iter().map(|worktree| {
1856                    worktree::ActiveModel {
1857                        id: ActiveValue::set(worktree.id as i64),
1858                        project_id: ActiveValue::set(project.id),
1859                        abs_path: ActiveValue::set(worktree.abs_path.clone()),
1860                        root_name: ActiveValue::set(worktree.root_name.clone()),
1861                        visible: ActiveValue::set(worktree.visible),
1862                        scan_id: ActiveValue::set(0),
1863                        is_complete: ActiveValue::set(false),
1864                    }
1865                }))
1866                .exec(&*tx)
1867                .await?;
1868            }
1869
1870            project_collaborator::ActiveModel {
1871                project_id: ActiveValue::set(project.id),
1872                connection_id: ActiveValue::set(connection.id as i32),
1873                connection_server_id: ActiveValue::set(ServerId(connection.owner_id as i32)),
1874                user_id: ActiveValue::set(participant.user_id),
1875                replica_id: ActiveValue::set(ReplicaId(0)),
1876                is_host: ActiveValue::set(true),
1877                ..Default::default()
1878            }
1879            .insert(&*tx)
1880            .await?;
1881
1882            let room = self.get_room(room_id, &tx).await?;
1883            Ok((room_id, (project.id, room)))
1884        })
1885        .await
1886    }
1887
1888    pub async fn unshare_project(
1889        &self,
1890        project_id: ProjectId,
1891        connection: ConnectionId,
1892    ) -> Result<RoomGuard<(proto::Room, Vec<ConnectionId>)>> {
1893        self.room_transaction(|tx| async move {
1894            let guest_connection_ids = self.project_guest_connection_ids(project_id, &tx).await?;
1895
1896            let project = project::Entity::find_by_id(project_id)
1897                .one(&*tx)
1898                .await?
1899                .ok_or_else(|| anyhow!("project not found"))?;
1900            if project.host_connection()? == connection {
1901                let room_id = project.room_id;
1902                project::Entity::delete(project.into_active_model())
1903                    .exec(&*tx)
1904                    .await?;
1905                let room = self.get_room(room_id, &tx).await?;
1906                Ok((room_id, (room, guest_connection_ids)))
1907            } else {
1908                Err(anyhow!("cannot unshare a project hosted by another user"))?
1909            }
1910        })
1911        .await
1912    }
1913
1914    pub async fn update_project(
1915        &self,
1916        project_id: ProjectId,
1917        connection: ConnectionId,
1918        worktrees: &[proto::WorktreeMetadata],
1919    ) -> Result<RoomGuard<(proto::Room, Vec<ConnectionId>)>> {
1920        self.room_transaction(|tx| async move {
1921            let project = project::Entity::find_by_id(project_id)
1922                .filter(
1923                    Condition::all()
1924                        .add(project::Column::HostConnectionId.eq(connection.id as i32))
1925                        .add(
1926                            project::Column::HostConnectionServerId.eq(connection.owner_id as i32),
1927                        ),
1928                )
1929                .one(&*tx)
1930                .await?
1931                .ok_or_else(|| anyhow!("no such project"))?;
1932
1933            if !worktrees.is_empty() {
1934                worktree::Entity::insert_many(worktrees.iter().map(|worktree| {
1935                    worktree::ActiveModel {
1936                        id: ActiveValue::set(worktree.id as i64),
1937                        project_id: ActiveValue::set(project.id),
1938                        abs_path: ActiveValue::set(worktree.abs_path.clone()),
1939                        root_name: ActiveValue::set(worktree.root_name.clone()),
1940                        visible: ActiveValue::set(worktree.visible),
1941                        scan_id: ActiveValue::set(0),
1942                        is_complete: ActiveValue::set(false),
1943                    }
1944                }))
1945                .on_conflict(
1946                    OnConflict::columns([worktree::Column::ProjectId, worktree::Column::Id])
1947                        .update_column(worktree::Column::RootName)
1948                        .to_owned(),
1949                )
1950                .exec(&*tx)
1951                .await?;
1952            }
1953
1954            worktree::Entity::delete_many()
1955                .filter(
1956                    worktree::Column::ProjectId.eq(project.id).and(
1957                        worktree::Column::Id
1958                            .is_not_in(worktrees.iter().map(|worktree| worktree.id as i64)),
1959                    ),
1960                )
1961                .exec(&*tx)
1962                .await?;
1963
1964            let guest_connection_ids = self.project_guest_connection_ids(project.id, &tx).await?;
1965            let room = self.get_room(project.room_id, &tx).await?;
1966            Ok((project.room_id, (room, guest_connection_ids)))
1967        })
1968        .await
1969    }
1970
1971    pub async fn update_worktree(
1972        &self,
1973        update: &proto::UpdateWorktree,
1974        connection: ConnectionId,
1975    ) -> Result<RoomGuard<Vec<ConnectionId>>> {
1976        self.room_transaction(|tx| async move {
1977            let project_id = ProjectId::from_proto(update.project_id);
1978            let worktree_id = update.worktree_id as i64;
1979
1980            // Ensure the update comes from the host.
1981            let project = project::Entity::find_by_id(project_id)
1982                .filter(
1983                    Condition::all()
1984                        .add(project::Column::HostConnectionId.eq(connection.id as i32))
1985                        .add(
1986                            project::Column::HostConnectionServerId.eq(connection.owner_id as i32),
1987                        ),
1988                )
1989                .one(&*tx)
1990                .await?
1991                .ok_or_else(|| anyhow!("no such project"))?;
1992            let room_id = project.room_id;
1993
1994            // Update metadata.
1995            worktree::Entity::update(worktree::ActiveModel {
1996                id: ActiveValue::set(worktree_id),
1997                project_id: ActiveValue::set(project_id),
1998                root_name: ActiveValue::set(update.root_name.clone()),
1999                scan_id: ActiveValue::set(update.scan_id as i64),
2000                is_complete: ActiveValue::set(update.is_last_update),
2001                abs_path: ActiveValue::set(update.abs_path.clone()),
2002                ..Default::default()
2003            })
2004            .exec(&*tx)
2005            .await?;
2006
2007            if !update.updated_entries.is_empty() {
2008                worktree_entry::Entity::insert_many(update.updated_entries.iter().map(|entry| {
2009                    let mtime = entry.mtime.clone().unwrap_or_default();
2010                    worktree_entry::ActiveModel {
2011                        project_id: ActiveValue::set(project_id),
2012                        worktree_id: ActiveValue::set(worktree_id),
2013                        id: ActiveValue::set(entry.id as i64),
2014                        is_dir: ActiveValue::set(entry.is_dir),
2015                        path: ActiveValue::set(entry.path.clone()),
2016                        inode: ActiveValue::set(entry.inode as i64),
2017                        mtime_seconds: ActiveValue::set(mtime.seconds as i64),
2018                        mtime_nanos: ActiveValue::set(mtime.nanos as i32),
2019                        is_symlink: ActiveValue::set(entry.is_symlink),
2020                        is_ignored: ActiveValue::set(entry.is_ignored),
2021                    }
2022                }))
2023                .on_conflict(
2024                    OnConflict::columns([
2025                        worktree_entry::Column::ProjectId,
2026                        worktree_entry::Column::WorktreeId,
2027                        worktree_entry::Column::Id,
2028                    ])
2029                    .update_columns([
2030                        worktree_entry::Column::IsDir,
2031                        worktree_entry::Column::Path,
2032                        worktree_entry::Column::Inode,
2033                        worktree_entry::Column::MtimeSeconds,
2034                        worktree_entry::Column::MtimeNanos,
2035                        worktree_entry::Column::IsSymlink,
2036                        worktree_entry::Column::IsIgnored,
2037                    ])
2038                    .to_owned(),
2039                )
2040                .exec(&*tx)
2041                .await?;
2042            }
2043
2044            if !update.removed_entries.is_empty() {
2045                worktree_entry::Entity::delete_many()
2046                    .filter(
2047                        worktree_entry::Column::ProjectId
2048                            .eq(project_id)
2049                            .and(worktree_entry::Column::WorktreeId.eq(worktree_id))
2050                            .and(
2051                                worktree_entry::Column::Id
2052                                    .is_in(update.removed_entries.iter().map(|id| *id as i64)),
2053                            ),
2054                    )
2055                    .exec(&*tx)
2056                    .await?;
2057            }
2058
2059            let connection_ids = self.project_guest_connection_ids(project_id, &tx).await?;
2060            Ok((room_id, connection_ids))
2061        })
2062        .await
2063    }
2064
2065    pub async fn update_diagnostic_summary(
2066        &self,
2067        update: &proto::UpdateDiagnosticSummary,
2068        connection: ConnectionId,
2069    ) -> Result<RoomGuard<Vec<ConnectionId>>> {
2070        self.room_transaction(|tx| async move {
2071            let project_id = ProjectId::from_proto(update.project_id);
2072            let worktree_id = update.worktree_id as i64;
2073            let summary = update
2074                .summary
2075                .as_ref()
2076                .ok_or_else(|| anyhow!("invalid summary"))?;
2077
2078            // Ensure the update comes from the host.
2079            let project = project::Entity::find_by_id(project_id)
2080                .one(&*tx)
2081                .await?
2082                .ok_or_else(|| anyhow!("no such project"))?;
2083            if project.host_connection()? != connection {
2084                return Err(anyhow!("can't update a project hosted by someone else"))?;
2085            }
2086
2087            // Update summary.
2088            worktree_diagnostic_summary::Entity::insert(worktree_diagnostic_summary::ActiveModel {
2089                project_id: ActiveValue::set(project_id),
2090                worktree_id: ActiveValue::set(worktree_id),
2091                path: ActiveValue::set(summary.path.clone()),
2092                language_server_id: ActiveValue::set(summary.language_server_id as i64),
2093                error_count: ActiveValue::set(summary.error_count as i32),
2094                warning_count: ActiveValue::set(summary.warning_count as i32),
2095                ..Default::default()
2096            })
2097            .on_conflict(
2098                OnConflict::columns([
2099                    worktree_diagnostic_summary::Column::ProjectId,
2100                    worktree_diagnostic_summary::Column::WorktreeId,
2101                    worktree_diagnostic_summary::Column::Path,
2102                ])
2103                .update_columns([
2104                    worktree_diagnostic_summary::Column::LanguageServerId,
2105                    worktree_diagnostic_summary::Column::ErrorCount,
2106                    worktree_diagnostic_summary::Column::WarningCount,
2107                ])
2108                .to_owned(),
2109            )
2110            .exec(&*tx)
2111            .await?;
2112
2113            let connection_ids = self.project_guest_connection_ids(project_id, &tx).await?;
2114            Ok((project.room_id, connection_ids))
2115        })
2116        .await
2117    }
2118
2119    pub async fn start_language_server(
2120        &self,
2121        update: &proto::StartLanguageServer,
2122        connection: ConnectionId,
2123    ) -> Result<RoomGuard<Vec<ConnectionId>>> {
2124        self.room_transaction(|tx| async move {
2125            let project_id = ProjectId::from_proto(update.project_id);
2126            let server = update
2127                .server
2128                .as_ref()
2129                .ok_or_else(|| anyhow!("invalid language server"))?;
2130
2131            // Ensure the update comes from the host.
2132            let project = project::Entity::find_by_id(project_id)
2133                .one(&*tx)
2134                .await?
2135                .ok_or_else(|| anyhow!("no such project"))?;
2136            if project.host_connection()? != connection {
2137                return Err(anyhow!("can't update a project hosted by someone else"))?;
2138            }
2139
2140            // Add the newly-started language server.
2141            language_server::Entity::insert(language_server::ActiveModel {
2142                project_id: ActiveValue::set(project_id),
2143                id: ActiveValue::set(server.id as i64),
2144                name: ActiveValue::set(server.name.clone()),
2145                ..Default::default()
2146            })
2147            .on_conflict(
2148                OnConflict::columns([
2149                    language_server::Column::ProjectId,
2150                    language_server::Column::Id,
2151                ])
2152                .update_column(language_server::Column::Name)
2153                .to_owned(),
2154            )
2155            .exec(&*tx)
2156            .await?;
2157
2158            let connection_ids = self.project_guest_connection_ids(project_id, &tx).await?;
2159            Ok((project.room_id, connection_ids))
2160        })
2161        .await
2162    }
2163
2164    pub async fn join_project(
2165        &self,
2166        project_id: ProjectId,
2167        connection: ConnectionId,
2168    ) -> Result<RoomGuard<(Project, ReplicaId)>> {
2169        self.room_transaction(|tx| async move {
2170            let participant = room_participant::Entity::find()
2171                .filter(
2172                    Condition::all()
2173                        .add(
2174                            room_participant::Column::AnsweringConnectionId
2175                                .eq(connection.id as i32),
2176                        )
2177                        .add(
2178                            room_participant::Column::AnsweringConnectionServerId
2179                                .eq(connection.owner_id as i32),
2180                        ),
2181                )
2182                .one(&*tx)
2183                .await?
2184                .ok_or_else(|| anyhow!("must join a room first"))?;
2185
2186            let project = project::Entity::find_by_id(project_id)
2187                .one(&*tx)
2188                .await?
2189                .ok_or_else(|| anyhow!("no such project"))?;
2190            if project.room_id != participant.room_id {
2191                return Err(anyhow!("no such project"))?;
2192            }
2193
2194            let mut collaborators = project
2195                .find_related(project_collaborator::Entity)
2196                .all(&*tx)
2197                .await?;
2198            let replica_ids = collaborators
2199                .iter()
2200                .map(|c| c.replica_id)
2201                .collect::<HashSet<_>>();
2202            let mut replica_id = ReplicaId(1);
2203            while replica_ids.contains(&replica_id) {
2204                replica_id.0 += 1;
2205            }
2206            let new_collaborator = project_collaborator::ActiveModel {
2207                project_id: ActiveValue::set(project_id),
2208                connection_id: ActiveValue::set(connection.id as i32),
2209                connection_server_id: ActiveValue::set(ServerId(connection.owner_id as i32)),
2210                user_id: ActiveValue::set(participant.user_id),
2211                replica_id: ActiveValue::set(replica_id),
2212                is_host: ActiveValue::set(false),
2213                ..Default::default()
2214            }
2215            .insert(&*tx)
2216            .await?;
2217            collaborators.push(new_collaborator);
2218
2219            let db_worktrees = project.find_related(worktree::Entity).all(&*tx).await?;
2220            let mut worktrees = db_worktrees
2221                .into_iter()
2222                .map(|db_worktree| {
2223                    (
2224                        db_worktree.id as u64,
2225                        Worktree {
2226                            id: db_worktree.id as u64,
2227                            abs_path: db_worktree.abs_path,
2228                            root_name: db_worktree.root_name,
2229                            visible: db_worktree.visible,
2230                            entries: Default::default(),
2231                            diagnostic_summaries: Default::default(),
2232                            scan_id: db_worktree.scan_id as u64,
2233                            is_complete: db_worktree.is_complete,
2234                        },
2235                    )
2236                })
2237                .collect::<BTreeMap<_, _>>();
2238
2239            // Populate worktree entries.
2240            {
2241                let mut db_entries = worktree_entry::Entity::find()
2242                    .filter(worktree_entry::Column::ProjectId.eq(project_id))
2243                    .stream(&*tx)
2244                    .await?;
2245                while let Some(db_entry) = db_entries.next().await {
2246                    let db_entry = db_entry?;
2247                    if let Some(worktree) = worktrees.get_mut(&(db_entry.worktree_id as u64)) {
2248                        worktree.entries.push(proto::Entry {
2249                            id: db_entry.id as u64,
2250                            is_dir: db_entry.is_dir,
2251                            path: db_entry.path,
2252                            inode: db_entry.inode as u64,
2253                            mtime: Some(proto::Timestamp {
2254                                seconds: db_entry.mtime_seconds as u64,
2255                                nanos: db_entry.mtime_nanos as u32,
2256                            }),
2257                            is_symlink: db_entry.is_symlink,
2258                            is_ignored: db_entry.is_ignored,
2259                        });
2260                    }
2261                }
2262            }
2263
2264            // Populate worktree diagnostic summaries.
2265            {
2266                let mut db_summaries = worktree_diagnostic_summary::Entity::find()
2267                    .filter(worktree_diagnostic_summary::Column::ProjectId.eq(project_id))
2268                    .stream(&*tx)
2269                    .await?;
2270                while let Some(db_summary) = db_summaries.next().await {
2271                    let db_summary = db_summary?;
2272                    if let Some(worktree) = worktrees.get_mut(&(db_summary.worktree_id as u64)) {
2273                        worktree
2274                            .diagnostic_summaries
2275                            .push(proto::DiagnosticSummary {
2276                                path: db_summary.path,
2277                                language_server_id: db_summary.language_server_id as u64,
2278                                error_count: db_summary.error_count as u32,
2279                                warning_count: db_summary.warning_count as u32,
2280                            });
2281                    }
2282                }
2283            }
2284
2285            // Populate language servers.
2286            let language_servers = project
2287                .find_related(language_server::Entity)
2288                .all(&*tx)
2289                .await?;
2290
2291            let room_id = project.room_id;
2292            let project = Project {
2293                collaborators,
2294                worktrees,
2295                language_servers: language_servers
2296                    .into_iter()
2297                    .map(|language_server| proto::LanguageServer {
2298                        id: language_server.id as u64,
2299                        name: language_server.name,
2300                    })
2301                    .collect(),
2302            };
2303            Ok((room_id, (project, replica_id as ReplicaId)))
2304        })
2305        .await
2306    }
2307
2308    pub async fn leave_project(
2309        &self,
2310        project_id: ProjectId,
2311        connection: ConnectionId,
2312    ) -> Result<RoomGuard<LeftProject>> {
2313        self.room_transaction(|tx| async move {
2314            let result = project_collaborator::Entity::delete_many()
2315                .filter(
2316                    Condition::all()
2317                        .add(project_collaborator::Column::ProjectId.eq(project_id))
2318                        .add(project_collaborator::Column::ConnectionId.eq(connection.id as i32))
2319                        .add(
2320                            project_collaborator::Column::ConnectionServerId
2321                                .eq(connection.owner_id as i32),
2322                        ),
2323                )
2324                .exec(&*tx)
2325                .await?;
2326            if result.rows_affected == 0 {
2327                Err(anyhow!("not a collaborator on this project"))?;
2328            }
2329
2330            let project = project::Entity::find_by_id(project_id)
2331                .one(&*tx)
2332                .await?
2333                .ok_or_else(|| anyhow!("no such project"))?;
2334            let collaborators = project
2335                .find_related(project_collaborator::Entity)
2336                .all(&*tx)
2337                .await?;
2338            let connection_ids = collaborators
2339                .into_iter()
2340                .map(|collaborator| ConnectionId {
2341                    owner_id: collaborator.connection_server_id.0 as u32,
2342                    id: collaborator.connection_id as u32,
2343                })
2344                .collect();
2345
2346            let left_project = LeftProject {
2347                id: project_id,
2348                host_user_id: project.host_user_id,
2349                host_connection_id: project.host_connection()?,
2350                connection_ids,
2351            };
2352            Ok((project.room_id, left_project))
2353        })
2354        .await
2355    }
2356
2357    pub async fn project_collaborators(
2358        &self,
2359        project_id: ProjectId,
2360        connection: ConnectionId,
2361    ) -> Result<RoomGuard<Vec<project_collaborator::Model>>> {
2362        self.room_transaction(|tx| async move {
2363            let project = project::Entity::find_by_id(project_id)
2364                .one(&*tx)
2365                .await?
2366                .ok_or_else(|| anyhow!("no such project"))?;
2367            let collaborators = project_collaborator::Entity::find()
2368                .filter(project_collaborator::Column::ProjectId.eq(project_id))
2369                .all(&*tx)
2370                .await?;
2371
2372            if collaborators.iter().any(|collaborator| {
2373                let collaborator_connection = ConnectionId {
2374                    owner_id: collaborator.connection_server_id.0 as u32,
2375                    id: collaborator.connection_id as u32,
2376                };
2377                collaborator_connection == connection
2378            }) {
2379                Ok((project.room_id, collaborators))
2380            } else {
2381                Err(anyhow!("no such project"))?
2382            }
2383        })
2384        .await
2385    }
2386
2387    pub async fn project_connection_ids(
2388        &self,
2389        project_id: ProjectId,
2390        connection_id: ConnectionId,
2391    ) -> Result<RoomGuard<HashSet<ConnectionId>>> {
2392        self.room_transaction(|tx| async move {
2393            let project = project::Entity::find_by_id(project_id)
2394                .one(&*tx)
2395                .await?
2396                .ok_or_else(|| anyhow!("no such project"))?;
2397            let mut participants = project_collaborator::Entity::find()
2398                .filter(project_collaborator::Column::ProjectId.eq(project_id))
2399                .stream(&*tx)
2400                .await?;
2401
2402            let mut connection_ids = HashSet::default();
2403            while let Some(participant) = participants.next().await {
2404                let participant = participant?;
2405                connection_ids.insert(ConnectionId {
2406                    owner_id: participant.connection_server_id.0 as u32,
2407                    id: participant.connection_id as u32,
2408                });
2409            }
2410
2411            if connection_ids.contains(&connection_id) {
2412                Ok((project.room_id, connection_ids))
2413            } else {
2414                Err(anyhow!("no such project"))?
2415            }
2416        })
2417        .await
2418    }
2419
2420    async fn project_guest_connection_ids(
2421        &self,
2422        project_id: ProjectId,
2423        tx: &DatabaseTransaction,
2424    ) -> Result<Vec<ConnectionId>> {
2425        let mut participants = project_collaborator::Entity::find()
2426            .filter(
2427                project_collaborator::Column::ProjectId
2428                    .eq(project_id)
2429                    .and(project_collaborator::Column::IsHost.eq(false)),
2430            )
2431            .stream(tx)
2432            .await?;
2433
2434        let mut guest_connection_ids = Vec::new();
2435        while let Some(participant) = participants.next().await {
2436            let participant = participant?;
2437            guest_connection_ids.push(ConnectionId {
2438                owner_id: participant.connection_server_id.0 as u32,
2439                id: participant.connection_id as u32,
2440            });
2441        }
2442        Ok(guest_connection_ids)
2443    }
2444
2445    // access tokens
2446
2447    pub async fn create_access_token_hash(
2448        &self,
2449        user_id: UserId,
2450        access_token_hash: &str,
2451        max_access_token_count: usize,
2452    ) -> Result<()> {
2453        self.transaction(|tx| async {
2454            let tx = tx;
2455
2456            access_token::ActiveModel {
2457                user_id: ActiveValue::set(user_id),
2458                hash: ActiveValue::set(access_token_hash.into()),
2459                ..Default::default()
2460            }
2461            .insert(&*tx)
2462            .await?;
2463
2464            access_token::Entity::delete_many()
2465                .filter(
2466                    access_token::Column::Id.in_subquery(
2467                        Query::select()
2468                            .column(access_token::Column::Id)
2469                            .from(access_token::Entity)
2470                            .and_where(access_token::Column::UserId.eq(user_id))
2471                            .order_by(access_token::Column::Id, sea_orm::Order::Desc)
2472                            .limit(10000)
2473                            .offset(max_access_token_count as u64)
2474                            .to_owned(),
2475                    ),
2476                )
2477                .exec(&*tx)
2478                .await?;
2479            Ok(())
2480        })
2481        .await
2482    }
2483
2484    pub async fn get_access_token_hashes(&self, user_id: UserId) -> Result<Vec<String>> {
2485        #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
2486        enum QueryAs {
2487            Hash,
2488        }
2489
2490        self.transaction(|tx| async move {
2491            Ok(access_token::Entity::find()
2492                .select_only()
2493                .column(access_token::Column::Hash)
2494                .filter(access_token::Column::UserId.eq(user_id))
2495                .order_by_desc(access_token::Column::Id)
2496                .into_values::<_, QueryAs>()
2497                .all(&*tx)
2498                .await?)
2499        })
2500        .await
2501    }
2502
2503    async fn transaction<F, Fut, T>(&self, f: F) -> Result<T>
2504    where
2505        F: Send + Fn(TransactionHandle) -> Fut,
2506        Fut: Send + Future<Output = Result<T>>,
2507    {
2508        let body = async {
2509            loop {
2510                let (tx, result) = self.with_transaction(&f).await?;
2511                match result {
2512                    Ok(result) => {
2513                        match tx.commit().await.map_err(Into::into) {
2514                            Ok(()) => return Ok(result),
2515                            Err(error) => {
2516                                if is_serialization_error(&error) {
2517                                    // Retry (don't break the loop)
2518                                } else {
2519                                    return Err(error);
2520                                }
2521                            }
2522                        }
2523                    }
2524                    Err(error) => {
2525                        tx.rollback().await?;
2526                        if is_serialization_error(&error) {
2527                            // Retry (don't break the loop)
2528                        } else {
2529                            return Err(error);
2530                        }
2531                    }
2532                }
2533            }
2534        };
2535
2536        self.run(body).await
2537    }
2538
2539    async fn optional_room_transaction<F, Fut, T>(&self, f: F) -> Result<Option<RoomGuard<T>>>
2540    where
2541        F: Send + Fn(TransactionHandle) -> Fut,
2542        Fut: Send + Future<Output = Result<Option<(RoomId, T)>>>,
2543    {
2544        let body = async {
2545            loop {
2546                let (tx, result) = self.with_transaction(&f).await?;
2547                match result {
2548                    Ok(Some((room_id, data))) => {
2549                        let lock = self.rooms.entry(room_id).or_default().clone();
2550                        let _guard = lock.lock_owned().await;
2551                        match tx.commit().await.map_err(Into::into) {
2552                            Ok(()) => {
2553                                return Ok(Some(RoomGuard {
2554                                    data,
2555                                    _guard,
2556                                    _not_send: PhantomData,
2557                                }));
2558                            }
2559                            Err(error) => {
2560                                if is_serialization_error(&error) {
2561                                    // Retry (don't break the loop)
2562                                } else {
2563                                    return Err(error);
2564                                }
2565                            }
2566                        }
2567                    }
2568                    Ok(None) => {
2569                        match tx.commit().await.map_err(Into::into) {
2570                            Ok(()) => return Ok(None),
2571                            Err(error) => {
2572                                if is_serialization_error(&error) {
2573                                    // Retry (don't break the loop)
2574                                } else {
2575                                    return Err(error);
2576                                }
2577                            }
2578                        }
2579                    }
2580                    Err(error) => {
2581                        tx.rollback().await?;
2582                        if is_serialization_error(&error) {
2583                            // Retry (don't break the loop)
2584                        } else {
2585                            return Err(error);
2586                        }
2587                    }
2588                }
2589            }
2590        };
2591
2592        self.run(body).await
2593    }
2594
2595    async fn room_transaction<F, Fut, T>(&self, f: F) -> Result<RoomGuard<T>>
2596    where
2597        F: Send + Fn(TransactionHandle) -> Fut,
2598        Fut: Send + Future<Output = Result<(RoomId, T)>>,
2599    {
2600        let data = self
2601            .optional_room_transaction(move |tx| {
2602                let future = f(tx);
2603                async {
2604                    let data = future.await?;
2605                    Ok(Some(data))
2606                }
2607            })
2608            .await?;
2609        Ok(data.unwrap())
2610    }
2611
2612    async fn with_transaction<F, Fut, T>(&self, f: &F) -> Result<(DatabaseTransaction, Result<T>)>
2613    where
2614        F: Send + Fn(TransactionHandle) -> Fut,
2615        Fut: Send + Future<Output = Result<T>>,
2616    {
2617        let tx = self
2618            .pool
2619            .begin_with_config(Some(IsolationLevel::Serializable), None)
2620            .await?;
2621
2622        let mut tx = Arc::new(Some(tx));
2623        let result = f(TransactionHandle(tx.clone())).await;
2624        let Some(tx) = Arc::get_mut(&mut tx).and_then(|tx| tx.take()) else {
2625            return Err(anyhow!("couldn't complete transaction because it's still in use"))?;
2626        };
2627
2628        Ok((tx, result))
2629    }
2630
2631    async fn run<F, T>(&self, future: F) -> T
2632    where
2633        F: Future<Output = T>,
2634    {
2635        #[cfg(test)]
2636        {
2637            if let Some(background) = self.background.as_ref() {
2638                background.simulate_random_delay().await;
2639            }
2640
2641            self.runtime.as_ref().unwrap().block_on(future)
2642        }
2643
2644        #[cfg(not(test))]
2645        {
2646            future.await
2647        }
2648    }
2649}
2650
2651fn is_serialization_error(error: &Error) -> bool {
2652    const SERIALIZATION_FAILURE_CODE: &'static str = "40001";
2653    match error {
2654        Error::Database(
2655            DbErr::Exec(sea_orm::RuntimeErr::SqlxError(error))
2656            | DbErr::Query(sea_orm::RuntimeErr::SqlxError(error)),
2657        ) if error
2658            .as_database_error()
2659            .and_then(|error| error.code())
2660            .as_deref()
2661            == Some(SERIALIZATION_FAILURE_CODE) =>
2662        {
2663            true
2664        }
2665        _ => false,
2666    }
2667}
2668
2669struct TransactionHandle(Arc<Option<DatabaseTransaction>>);
2670
2671impl Deref for TransactionHandle {
2672    type Target = DatabaseTransaction;
2673
2674    fn deref(&self) -> &Self::Target {
2675        self.0.as_ref().as_ref().unwrap()
2676    }
2677}
2678
2679pub struct RoomGuard<T> {
2680    data: T,
2681    _guard: OwnedMutexGuard<()>,
2682    _not_send: PhantomData<Rc<()>>,
2683}
2684
2685impl<T> Deref for RoomGuard<T> {
2686    type Target = T;
2687
2688    fn deref(&self) -> &T {
2689        &self.data
2690    }
2691}
2692
2693impl<T> DerefMut for RoomGuard<T> {
2694    fn deref_mut(&mut self) -> &mut T {
2695        &mut self.data
2696    }
2697}
2698
2699#[derive(Debug, Serialize, Deserialize)]
2700pub struct NewUserParams {
2701    pub github_login: String,
2702    pub github_user_id: i32,
2703    pub invite_count: i32,
2704}
2705
2706#[derive(Debug)]
2707pub struct NewUserResult {
2708    pub user_id: UserId,
2709    pub metrics_id: String,
2710    pub inviting_user_id: Option<UserId>,
2711    pub signup_device_id: Option<String>,
2712}
2713
2714fn random_invite_code() -> String {
2715    nanoid::nanoid!(16)
2716}
2717
2718fn random_email_confirmation_code() -> String {
2719    nanoid::nanoid!(64)
2720}
2721
2722macro_rules! id_type {
2723    ($name:ident) => {
2724        #[derive(
2725            Clone,
2726            Copy,
2727            Debug,
2728            Default,
2729            PartialEq,
2730            Eq,
2731            PartialOrd,
2732            Ord,
2733            Hash,
2734            Serialize,
2735            Deserialize,
2736        )]
2737        #[serde(transparent)]
2738        pub struct $name(pub i32);
2739
2740        impl $name {
2741            #[allow(unused)]
2742            pub const MAX: Self = Self(i32::MAX);
2743
2744            #[allow(unused)]
2745            pub fn from_proto(value: u64) -> Self {
2746                Self(value as i32)
2747            }
2748
2749            #[allow(unused)]
2750            pub fn to_proto(self) -> u64 {
2751                self.0 as u64
2752            }
2753        }
2754
2755        impl std::fmt::Display for $name {
2756            fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
2757                self.0.fmt(f)
2758            }
2759        }
2760
2761        impl From<$name> for sea_query::Value {
2762            fn from(value: $name) -> Self {
2763                sea_query::Value::Int(Some(value.0))
2764            }
2765        }
2766
2767        impl sea_orm::TryGetable for $name {
2768            fn try_get(
2769                res: &sea_orm::QueryResult,
2770                pre: &str,
2771                col: &str,
2772            ) -> Result<Self, sea_orm::TryGetError> {
2773                Ok(Self(i32::try_get(res, pre, col)?))
2774            }
2775        }
2776
2777        impl sea_query::ValueType for $name {
2778            fn try_from(v: Value) -> Result<Self, sea_query::ValueTypeErr> {
2779                match v {
2780                    Value::TinyInt(Some(int)) => {
2781                        Ok(Self(int.try_into().map_err(|_| sea_query::ValueTypeErr)?))
2782                    }
2783                    Value::SmallInt(Some(int)) => {
2784                        Ok(Self(int.try_into().map_err(|_| sea_query::ValueTypeErr)?))
2785                    }
2786                    Value::Int(Some(int)) => {
2787                        Ok(Self(int.try_into().map_err(|_| sea_query::ValueTypeErr)?))
2788                    }
2789                    Value::BigInt(Some(int)) => {
2790                        Ok(Self(int.try_into().map_err(|_| sea_query::ValueTypeErr)?))
2791                    }
2792                    Value::TinyUnsigned(Some(int)) => {
2793                        Ok(Self(int.try_into().map_err(|_| sea_query::ValueTypeErr)?))
2794                    }
2795                    Value::SmallUnsigned(Some(int)) => {
2796                        Ok(Self(int.try_into().map_err(|_| sea_query::ValueTypeErr)?))
2797                    }
2798                    Value::Unsigned(Some(int)) => {
2799                        Ok(Self(int.try_into().map_err(|_| sea_query::ValueTypeErr)?))
2800                    }
2801                    Value::BigUnsigned(Some(int)) => {
2802                        Ok(Self(int.try_into().map_err(|_| sea_query::ValueTypeErr)?))
2803                    }
2804                    _ => Err(sea_query::ValueTypeErr),
2805                }
2806            }
2807
2808            fn type_name() -> String {
2809                stringify!($name).into()
2810            }
2811
2812            fn array_type() -> sea_query::ArrayType {
2813                sea_query::ArrayType::Int
2814            }
2815
2816            fn column_type() -> sea_query::ColumnType {
2817                sea_query::ColumnType::Integer(None)
2818            }
2819        }
2820
2821        impl sea_orm::TryFromU64 for $name {
2822            fn try_from_u64(n: u64) -> Result<Self, DbErr> {
2823                Ok(Self(n.try_into().map_err(|_| {
2824                    DbErr::ConvertFromU64(concat!(
2825                        "error converting ",
2826                        stringify!($name),
2827                        " to u64"
2828                    ))
2829                })?))
2830            }
2831        }
2832
2833        impl sea_query::Nullable for $name {
2834            fn null() -> Value {
2835                Value::Int(None)
2836            }
2837        }
2838    };
2839}
2840
2841id_type!(AccessTokenId);
2842id_type!(ContactId);
2843id_type!(RoomId);
2844id_type!(RoomParticipantId);
2845id_type!(ProjectId);
2846id_type!(ProjectCollaboratorId);
2847id_type!(ReplicaId);
2848id_type!(ServerId);
2849id_type!(SignupId);
2850id_type!(UserId);
2851
2852pub struct LeftRoom {
2853    pub room: proto::Room,
2854    pub left_projects: HashMap<ProjectId, LeftProject>,
2855    pub canceled_calls_to_user_ids: Vec<UserId>,
2856}
2857
2858pub struct RefreshedRoom {
2859    pub room: proto::Room,
2860    pub stale_participant_user_ids: Vec<UserId>,
2861    pub canceled_calls_to_user_ids: Vec<UserId>,
2862}
2863
2864pub struct Project {
2865    pub collaborators: Vec<project_collaborator::Model>,
2866    pub worktrees: BTreeMap<u64, Worktree>,
2867    pub language_servers: Vec<proto::LanguageServer>,
2868}
2869
2870pub struct LeftProject {
2871    pub id: ProjectId,
2872    pub host_user_id: UserId,
2873    pub host_connection_id: ConnectionId,
2874    pub connection_ids: Vec<ConnectionId>,
2875}
2876
2877pub struct Worktree {
2878    pub id: u64,
2879    pub abs_path: String,
2880    pub root_name: String,
2881    pub visible: bool,
2882    pub entries: Vec<proto::Entry>,
2883    pub diagnostic_summaries: Vec<proto::DiagnosticSummary>,
2884    pub scan_id: u64,
2885    pub is_complete: bool,
2886}
2887
2888#[cfg(test)]
2889pub use test::*;
2890
2891#[cfg(test)]
2892mod test {
2893    use super::*;
2894    use gpui::executor::Background;
2895    use lazy_static::lazy_static;
2896    use parking_lot::Mutex;
2897    use rand::prelude::*;
2898    use sea_orm::ConnectionTrait;
2899    use sqlx::migrate::MigrateDatabase;
2900    use std::sync::Arc;
2901
2902    pub struct TestDb {
2903        pub db: Option<Arc<Database>>,
2904        pub connection: Option<sqlx::AnyConnection>,
2905    }
2906
2907    impl TestDb {
2908        pub fn sqlite(background: Arc<Background>) -> Self {
2909            let url = format!("sqlite::memory:");
2910            let runtime = tokio::runtime::Builder::new_current_thread()
2911                .enable_io()
2912                .enable_time()
2913                .build()
2914                .unwrap();
2915
2916            let mut db = runtime.block_on(async {
2917                let mut options = ConnectOptions::new(url);
2918                options.max_connections(5);
2919                let db = Database::new(options).await.unwrap();
2920                let sql = include_str!(concat!(
2921                    env!("CARGO_MANIFEST_DIR"),
2922                    "/migrations.sqlite/20221109000000_test_schema.sql"
2923                ));
2924                db.pool
2925                    .execute(sea_orm::Statement::from_string(
2926                        db.pool.get_database_backend(),
2927                        sql.into(),
2928                    ))
2929                    .await
2930                    .unwrap();
2931                db
2932            });
2933
2934            db.background = Some(background);
2935            db.runtime = Some(runtime);
2936
2937            Self {
2938                db: Some(Arc::new(db)),
2939                connection: None,
2940            }
2941        }
2942
2943        pub fn postgres(background: Arc<Background>) -> Self {
2944            lazy_static! {
2945                static ref LOCK: Mutex<()> = Mutex::new(());
2946            }
2947
2948            let _guard = LOCK.lock();
2949            let mut rng = StdRng::from_entropy();
2950            let url = format!(
2951                "postgres://postgres@localhost/zed-test-{}",
2952                rng.gen::<u128>()
2953            );
2954            let runtime = tokio::runtime::Builder::new_current_thread()
2955                .enable_io()
2956                .enable_time()
2957                .build()
2958                .unwrap();
2959
2960            let mut db = runtime.block_on(async {
2961                sqlx::Postgres::create_database(&url)
2962                    .await
2963                    .expect("failed to create test db");
2964                let mut options = ConnectOptions::new(url);
2965                options
2966                    .max_connections(5)
2967                    .idle_timeout(Duration::from_secs(0));
2968                let db = Database::new(options).await.unwrap();
2969                let migrations_path = concat!(env!("CARGO_MANIFEST_DIR"), "/migrations");
2970                db.migrate(Path::new(migrations_path), false).await.unwrap();
2971                db
2972            });
2973
2974            db.background = Some(background);
2975            db.runtime = Some(runtime);
2976
2977            Self {
2978                db: Some(Arc::new(db)),
2979                connection: None,
2980            }
2981        }
2982
2983        pub fn db(&self) -> &Arc<Database> {
2984            self.db.as_ref().unwrap()
2985        }
2986    }
2987
2988    impl Drop for TestDb {
2989        fn drop(&mut self) {
2990            let db = self.db.take().unwrap();
2991            if let sea_orm::DatabaseBackend::Postgres = db.pool.get_database_backend() {
2992                db.runtime.as_ref().unwrap().block_on(async {
2993                    use util::ResultExt;
2994                    let query = "
2995                        SELECT pg_terminate_backend(pg_stat_activity.pid)
2996                        FROM pg_stat_activity
2997                        WHERE
2998                            pg_stat_activity.datname = current_database() AND
2999                            pid <> pg_backend_pid();
3000                    ";
3001                    db.pool
3002                        .execute(sea_orm::Statement::from_string(
3003                            db.pool.get_database_backend(),
3004                            query.into(),
3005                        ))
3006                        .await
3007                        .log_err();
3008                    sqlx::Postgres::drop_database(db.options.get_url())
3009                        .await
3010                        .log_err();
3011                })
3012            }
3013        }
3014    }
3015}