db.rs

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