db.rs

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