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    ) -> Result<Invite> {
 886        self.transaction(|tx| async move {
 887            let existing_user = user::Entity::find()
 888                .filter(user::Column::EmailAddress.eq(email_address))
 889                .one(&*tx)
 890                .await?;
 891
 892            if existing_user.is_some() {
 893                Err(anyhow!("email address is already in use"))?;
 894            }
 895
 896            let inviting_user_with_invites = match user::Entity::find()
 897                .filter(
 898                    user::Column::InviteCode
 899                        .eq(code)
 900                        .and(user::Column::InviteCount.gt(0)),
 901                )
 902                .one(&*tx)
 903                .await?
 904            {
 905                Some(inviting_user) => inviting_user,
 906                None => {
 907                    return Err(Error::Http(
 908                        StatusCode::UNAUTHORIZED,
 909                        "unable to find an invite code with invites remaining".to_string(),
 910                    ))?
 911                }
 912            };
 913            user::Entity::update_many()
 914                .filter(
 915                    user::Column::Id
 916                        .eq(inviting_user_with_invites.id)
 917                        .and(user::Column::InviteCount.gt(0)),
 918                )
 919                .col_expr(
 920                    user::Column::InviteCount,
 921                    Expr::col(user::Column::InviteCount).sub(1),
 922                )
 923                .exec(&*tx)
 924                .await?;
 925
 926            let signup = signup::Entity::insert(signup::ActiveModel {
 927                email_address: ActiveValue::set(email_address.into()),
 928                email_confirmation_code: ActiveValue::set(random_email_confirmation_code()),
 929                email_confirmation_sent: ActiveValue::set(false),
 930                inviting_user_id: ActiveValue::set(Some(inviting_user_with_invites.id)),
 931                platform_linux: ActiveValue::set(false),
 932                platform_mac: ActiveValue::set(false),
 933                platform_windows: ActiveValue::set(false),
 934                platform_unknown: ActiveValue::set(true),
 935                device_id: ActiveValue::set(device_id.map(|device_id| device_id.into())),
 936                ..Default::default()
 937            })
 938            .on_conflict(
 939                OnConflict::column(signup::Column::EmailAddress)
 940                    .update_column(signup::Column::InvitingUserId)
 941                    .to_owned(),
 942            )
 943            .exec_with_returning(&*tx)
 944            .await?;
 945
 946            Ok(Invite {
 947                email_address: signup.email_address,
 948                email_confirmation_code: signup.email_confirmation_code,
 949            })
 950        })
 951        .await
 952    }
 953
 954    pub async fn create_user_from_invite(
 955        &self,
 956        invite: &Invite,
 957        user: NewUserParams,
 958    ) -> Result<Option<NewUserResult>> {
 959        self.transaction(|tx| async {
 960            let tx = tx;
 961            let signup = signup::Entity::find()
 962                .filter(
 963                    signup::Column::EmailAddress
 964                        .eq(invite.email_address.as_str())
 965                        .and(
 966                            signup::Column::EmailConfirmationCode
 967                                .eq(invite.email_confirmation_code.as_str()),
 968                        ),
 969                )
 970                .one(&*tx)
 971                .await?
 972                .ok_or_else(|| Error::Http(StatusCode::NOT_FOUND, "no such invite".to_string()))?;
 973
 974            if signup.user_id.is_some() {
 975                return Ok(None);
 976            }
 977
 978            let user = user::Entity::insert(user::ActiveModel {
 979                email_address: ActiveValue::set(Some(invite.email_address.clone())),
 980                github_login: ActiveValue::set(user.github_login.clone()),
 981                github_user_id: ActiveValue::set(Some(user.github_user_id)),
 982                admin: ActiveValue::set(false),
 983                invite_count: ActiveValue::set(user.invite_count),
 984                invite_code: ActiveValue::set(Some(random_invite_code())),
 985                metrics_id: ActiveValue::set(Uuid::new_v4()),
 986                ..Default::default()
 987            })
 988            .on_conflict(
 989                OnConflict::column(user::Column::GithubLogin)
 990                    .update_columns([
 991                        user::Column::EmailAddress,
 992                        user::Column::GithubUserId,
 993                        user::Column::Admin,
 994                    ])
 995                    .to_owned(),
 996            )
 997            .exec_with_returning(&*tx)
 998            .await?;
 999
1000            let mut signup = signup.into_active_model();
1001            signup.user_id = ActiveValue::set(Some(user.id));
1002            let signup = signup.update(&*tx).await?;
1003
1004            if let Some(inviting_user_id) = signup.inviting_user_id {
1005                let (user_id_a, user_id_b, a_to_b) = if inviting_user_id < user.id {
1006                    (inviting_user_id, user.id, true)
1007                } else {
1008                    (user.id, inviting_user_id, false)
1009                };
1010
1011                contact::Entity::insert(contact::ActiveModel {
1012                    user_id_a: ActiveValue::set(user_id_a),
1013                    user_id_b: ActiveValue::set(user_id_b),
1014                    a_to_b: ActiveValue::set(a_to_b),
1015                    should_notify: ActiveValue::set(true),
1016                    accepted: ActiveValue::set(true),
1017                    ..Default::default()
1018                })
1019                .on_conflict(OnConflict::new().do_nothing().to_owned())
1020                .exec_without_returning(&*tx)
1021                .await?;
1022            }
1023
1024            Ok(Some(NewUserResult {
1025                user_id: user.id,
1026                metrics_id: user.metrics_id.to_string(),
1027                inviting_user_id: signup.inviting_user_id,
1028                signup_device_id: signup.device_id,
1029            }))
1030        })
1031        .await
1032    }
1033
1034    pub async fn set_invite_count_for_user(&self, id: UserId, count: i32) -> Result<()> {
1035        self.transaction(|tx| async move {
1036            if count > 0 {
1037                user::Entity::update_many()
1038                    .filter(
1039                        user::Column::Id
1040                            .eq(id)
1041                            .and(user::Column::InviteCode.is_null()),
1042                    )
1043                    .set(user::ActiveModel {
1044                        invite_code: ActiveValue::set(Some(random_invite_code())),
1045                        ..Default::default()
1046                    })
1047                    .exec(&*tx)
1048                    .await?;
1049            }
1050
1051            user::Entity::update_many()
1052                .filter(user::Column::Id.eq(id))
1053                .set(user::ActiveModel {
1054                    invite_count: ActiveValue::set(count),
1055                    ..Default::default()
1056                })
1057                .exec(&*tx)
1058                .await?;
1059            Ok(())
1060        })
1061        .await
1062    }
1063
1064    pub async fn get_invite_code_for_user(&self, id: UserId) -> Result<Option<(String, i32)>> {
1065        self.transaction(|tx| async move {
1066            match user::Entity::find_by_id(id).one(&*tx).await? {
1067                Some(user) if user.invite_code.is_some() => {
1068                    Ok(Some((user.invite_code.unwrap(), user.invite_count)))
1069                }
1070                _ => Ok(None),
1071            }
1072        })
1073        .await
1074    }
1075
1076    pub async fn get_user_for_invite_code(&self, code: &str) -> Result<User> {
1077        self.transaction(|tx| async move {
1078            user::Entity::find()
1079                .filter(user::Column::InviteCode.eq(code))
1080                .one(&*tx)
1081                .await?
1082                .ok_or_else(|| {
1083                    Error::Http(
1084                        StatusCode::NOT_FOUND,
1085                        "that invite code does not exist".to_string(),
1086                    )
1087                })
1088        })
1089        .await
1090    }
1091
1092    // rooms
1093
1094    pub async fn incoming_call_for_user(
1095        &self,
1096        user_id: UserId,
1097    ) -> Result<Option<proto::IncomingCall>> {
1098        self.transaction(|tx| async move {
1099            let pending_participant = room_participant::Entity::find()
1100                .filter(
1101                    room_participant::Column::UserId
1102                        .eq(user_id)
1103                        .and(room_participant::Column::AnsweringConnectionId.is_null()),
1104                )
1105                .one(&*tx)
1106                .await?;
1107
1108            if let Some(pending_participant) = pending_participant {
1109                let room = self.get_room(pending_participant.room_id, &tx).await?;
1110                Ok(Self::build_incoming_call(&room, user_id))
1111            } else {
1112                Ok(None)
1113            }
1114        })
1115        .await
1116    }
1117
1118    pub async fn create_room(
1119        &self,
1120        user_id: UserId,
1121        connection: ConnectionId,
1122        live_kit_room: &str,
1123    ) -> Result<RoomGuard<proto::Room>> {
1124        self.room_transaction(|tx| async move {
1125            let room = room::ActiveModel {
1126                live_kit_room: ActiveValue::set(live_kit_room.into()),
1127                ..Default::default()
1128            }
1129            .insert(&*tx)
1130            .await?;
1131            let room_id = room.id;
1132
1133            room_participant::ActiveModel {
1134                room_id: ActiveValue::set(room_id),
1135                user_id: ActiveValue::set(user_id),
1136                answering_connection_id: ActiveValue::set(Some(connection.id as i32)),
1137                answering_connection_server_id: ActiveValue::set(Some(ServerId(
1138                    connection.owner_id as i32,
1139                ))),
1140                answering_connection_lost: ActiveValue::set(false),
1141                calling_user_id: ActiveValue::set(user_id),
1142                calling_connection_id: ActiveValue::set(connection.id as i32),
1143                calling_connection_server_id: ActiveValue::set(Some(ServerId(
1144                    connection.owner_id as i32,
1145                ))),
1146                ..Default::default()
1147            }
1148            .insert(&*tx)
1149            .await?;
1150
1151            let room = self.get_room(room_id, &tx).await?;
1152            Ok((room_id, room))
1153        })
1154        .await
1155    }
1156
1157    pub async fn call(
1158        &self,
1159        room_id: RoomId,
1160        calling_user_id: UserId,
1161        calling_connection: ConnectionId,
1162        called_user_id: UserId,
1163        initial_project_id: Option<ProjectId>,
1164    ) -> Result<RoomGuard<(proto::Room, proto::IncomingCall)>> {
1165        self.room_transaction(|tx| async move {
1166            room_participant::ActiveModel {
1167                room_id: ActiveValue::set(room_id),
1168                user_id: ActiveValue::set(called_user_id),
1169                answering_connection_lost: ActiveValue::set(false),
1170                calling_user_id: ActiveValue::set(calling_user_id),
1171                calling_connection_id: ActiveValue::set(calling_connection.id as i32),
1172                calling_connection_server_id: ActiveValue::set(Some(ServerId(
1173                    calling_connection.owner_id as i32,
1174                ))),
1175                initial_project_id: ActiveValue::set(initial_project_id),
1176                ..Default::default()
1177            }
1178            .insert(&*tx)
1179            .await?;
1180
1181            let room = self.get_room(room_id, &tx).await?;
1182            let incoming_call = Self::build_incoming_call(&room, called_user_id)
1183                .ok_or_else(|| anyhow!("failed to build incoming call"))?;
1184            Ok((room_id, (room, incoming_call)))
1185        })
1186        .await
1187    }
1188
1189    pub async fn call_failed(
1190        &self,
1191        room_id: RoomId,
1192        called_user_id: UserId,
1193    ) -> Result<RoomGuard<proto::Room>> {
1194        self.room_transaction(|tx| async move {
1195            room_participant::Entity::delete_many()
1196                .filter(
1197                    room_participant::Column::RoomId
1198                        .eq(room_id)
1199                        .and(room_participant::Column::UserId.eq(called_user_id)),
1200                )
1201                .exec(&*tx)
1202                .await?;
1203            let room = self.get_room(room_id, &tx).await?;
1204            Ok((room_id, room))
1205        })
1206        .await
1207    }
1208
1209    pub async fn decline_call(
1210        &self,
1211        expected_room_id: Option<RoomId>,
1212        user_id: UserId,
1213    ) -> Result<Option<RoomGuard<proto::Room>>> {
1214        self.optional_room_transaction(|tx| async move {
1215            let mut filter = Condition::all()
1216                .add(room_participant::Column::UserId.eq(user_id))
1217                .add(room_participant::Column::AnsweringConnectionId.is_null());
1218            if let Some(room_id) = expected_room_id {
1219                filter = filter.add(room_participant::Column::RoomId.eq(room_id));
1220            }
1221            let participant = room_participant::Entity::find()
1222                .filter(filter)
1223                .one(&*tx)
1224                .await?;
1225
1226            let participant = if let Some(participant) = participant {
1227                participant
1228            } else if expected_room_id.is_some() {
1229                return Err(anyhow!("could not find call to decline"))?;
1230            } else {
1231                return Ok(None);
1232            };
1233
1234            let room_id = participant.room_id;
1235            room_participant::Entity::delete(participant.into_active_model())
1236                .exec(&*tx)
1237                .await?;
1238
1239            let room = self.get_room(room_id, &tx).await?;
1240            Ok(Some((room_id, room)))
1241        })
1242        .await
1243    }
1244
1245    pub async fn cancel_call(
1246        &self,
1247        room_id: RoomId,
1248        calling_connection: ConnectionId,
1249        called_user_id: UserId,
1250    ) -> Result<RoomGuard<proto::Room>> {
1251        self.room_transaction(|tx| async move {
1252            let participant = room_participant::Entity::find()
1253                .filter(
1254                    Condition::all()
1255                        .add(room_participant::Column::UserId.eq(called_user_id))
1256                        .add(room_participant::Column::RoomId.eq(room_id))
1257                        .add(
1258                            room_participant::Column::CallingConnectionId
1259                                .eq(calling_connection.id as i32),
1260                        )
1261                        .add(
1262                            room_participant::Column::CallingConnectionServerId
1263                                .eq(calling_connection.owner_id as i32),
1264                        )
1265                        .add(room_participant::Column::AnsweringConnectionId.is_null()),
1266                )
1267                .one(&*tx)
1268                .await?
1269                .ok_or_else(|| anyhow!("no call to cancel"))?;
1270            let room_id = participant.room_id;
1271
1272            room_participant::Entity::delete(participant.into_active_model())
1273                .exec(&*tx)
1274                .await?;
1275
1276            let room = self.get_room(room_id, &tx).await?;
1277            Ok((room_id, room))
1278        })
1279        .await
1280    }
1281
1282    pub async fn join_room(
1283        &self,
1284        room_id: RoomId,
1285        user_id: UserId,
1286        connection: ConnectionId,
1287    ) -> Result<RoomGuard<proto::Room>> {
1288        self.room_transaction(|tx| async move {
1289            let result = room_participant::Entity::update_many()
1290                .filter(
1291                    Condition::all()
1292                        .add(room_participant::Column::RoomId.eq(room_id))
1293                        .add(room_participant::Column::UserId.eq(user_id))
1294                        .add(room_participant::Column::AnsweringConnectionId.is_null()),
1295                )
1296                .set(room_participant::ActiveModel {
1297                    answering_connection_id: ActiveValue::set(Some(connection.id as i32)),
1298                    answering_connection_server_id: ActiveValue::set(Some(ServerId(
1299                        connection.owner_id as i32,
1300                    ))),
1301                    answering_connection_lost: ActiveValue::set(false),
1302                    ..Default::default()
1303                })
1304                .exec(&*tx)
1305                .await?;
1306            if result.rows_affected == 0 {
1307                Err(anyhow!("room does not exist or was already joined"))?
1308            } else {
1309                let room = self.get_room(room_id, &tx).await?;
1310                Ok((room_id, room))
1311            }
1312        })
1313        .await
1314    }
1315
1316    pub async fn rejoin_room(
1317        &self,
1318        rejoin_room: proto::RejoinRoom,
1319        user_id: UserId,
1320        connection: ConnectionId,
1321    ) -> Result<RoomGuard<RejoinedRoom>> {
1322        self.room_transaction(|tx| async {
1323            let tx = tx;
1324            let room_id = RoomId::from_proto(rejoin_room.id);
1325            let participant_update = room_participant::Entity::update_many()
1326                .filter(
1327                    Condition::all()
1328                        .add(room_participant::Column::RoomId.eq(room_id))
1329                        .add(room_participant::Column::UserId.eq(user_id))
1330                        .add(room_participant::Column::AnsweringConnectionId.is_not_null())
1331                        .add(
1332                            Condition::any()
1333                                .add(room_participant::Column::AnsweringConnectionLost.eq(true))
1334                                .add(
1335                                    room_participant::Column::AnsweringConnectionServerId
1336                                        .ne(connection.owner_id as i32),
1337                                ),
1338                        ),
1339                )
1340                .set(room_participant::ActiveModel {
1341                    answering_connection_id: ActiveValue::set(Some(connection.id as i32)),
1342                    answering_connection_server_id: ActiveValue::set(Some(ServerId(
1343                        connection.owner_id as i32,
1344                    ))),
1345                    answering_connection_lost: ActiveValue::set(false),
1346                    ..Default::default()
1347                })
1348                .exec(&*tx)
1349                .await?;
1350            if participant_update.rows_affected == 0 {
1351                return Err(anyhow!("room does not exist or was already joined"))?;
1352            }
1353
1354            let mut reshared_projects = Vec::new();
1355            for reshared_project in &rejoin_room.reshared_projects {
1356                let project_id = ProjectId::from_proto(reshared_project.project_id);
1357                let project = project::Entity::find_by_id(project_id)
1358                    .one(&*tx)
1359                    .await?
1360                    .ok_or_else(|| anyhow!("project does not exist"))?;
1361                if project.host_user_id != user_id {
1362                    return Err(anyhow!("no such project"))?;
1363                }
1364
1365                let mut collaborators = project
1366                    .find_related(project_collaborator::Entity)
1367                    .all(&*tx)
1368                    .await?;
1369                let host_ix = collaborators
1370                    .iter()
1371                    .position(|collaborator| {
1372                        collaborator.user_id == user_id && collaborator.is_host
1373                    })
1374                    .ok_or_else(|| anyhow!("host not found among collaborators"))?;
1375                let host = collaborators.swap_remove(host_ix);
1376                let old_connection_id = host.connection();
1377
1378                project::Entity::update(project::ActiveModel {
1379                    host_connection_id: ActiveValue::set(Some(connection.id as i32)),
1380                    host_connection_server_id: ActiveValue::set(Some(ServerId(
1381                        connection.owner_id as i32,
1382                    ))),
1383                    ..project.into_active_model()
1384                })
1385                .exec(&*tx)
1386                .await?;
1387                project_collaborator::Entity::update(project_collaborator::ActiveModel {
1388                    connection_id: ActiveValue::set(connection.id as i32),
1389                    connection_server_id: ActiveValue::set(ServerId(connection.owner_id as i32)),
1390                    ..host.into_active_model()
1391                })
1392                .exec(&*tx)
1393                .await?;
1394
1395                self.update_project_worktrees(project_id, &reshared_project.worktrees, &tx)
1396                    .await?;
1397
1398                reshared_projects.push(ResharedProject {
1399                    id: project_id,
1400                    old_connection_id,
1401                    collaborators: collaborators
1402                        .iter()
1403                        .map(|collaborator| ProjectCollaborator {
1404                            connection_id: collaborator.connection(),
1405                            user_id: collaborator.user_id,
1406                            replica_id: collaborator.replica_id,
1407                            is_host: collaborator.is_host,
1408                        })
1409                        .collect(),
1410                    worktrees: reshared_project.worktrees.clone(),
1411                });
1412            }
1413
1414            project::Entity::delete_many()
1415                .filter(
1416                    Condition::all()
1417                        .add(project::Column::RoomId.eq(room_id))
1418                        .add(project::Column::HostUserId.eq(user_id))
1419                        .add(
1420                            project::Column::Id
1421                                .is_not_in(reshared_projects.iter().map(|project| project.id)),
1422                        ),
1423                )
1424                .exec(&*tx)
1425                .await?;
1426
1427            let mut rejoined_projects = Vec::new();
1428            for rejoined_project in &rejoin_room.rejoined_projects {
1429                let project_id = ProjectId::from_proto(rejoined_project.id);
1430                let Some(project) = project::Entity::find_by_id(project_id)
1431                        .one(&*tx)
1432                        .await? else {
1433                            continue
1434                        };
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                        is_complete: db_worktree.is_complete,
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                    .into_iter()
1509                    .map(|collaborator| ProjectCollaborator {
1510                        connection_id: collaborator.connection(),
1511                        user_id: collaborator.user_id,
1512                        replica_id: collaborator.replica_id,
1513                        is_host: collaborator.is_host,
1514                    })
1515                    .collect::<Vec<_>>();
1516
1517                let old_connection_id = if let Some(self_collaborator_ix) = collaborators
1518                    .iter()
1519                    .position(|collaborator| collaborator.user_id == user_id)
1520                {
1521                    let self_collaborator = collaborators.swap_remove(self_collaborator_ix);
1522                    self_collaborator.connection_id
1523                } else {
1524                    continue;
1525                };
1526
1527                rejoined_projects.push(RejoinedProject {
1528                    id: project_id,
1529                    old_connection_id,
1530                    collaborators,
1531                    worktrees,
1532                    language_servers,
1533                });
1534            }
1535
1536            let room = self.get_room(room_id, &tx).await?;
1537            Ok((
1538                room_id,
1539                RejoinedRoom {
1540                    room,
1541                    rejoined_projects,
1542                    reshared_projects,
1543                },
1544            ))
1545        })
1546        .await
1547    }
1548
1549    pub async fn leave_room(
1550        &self,
1551        connection: ConnectionId,
1552    ) -> Result<Option<RoomGuard<LeftRoom>>> {
1553        self.optional_room_transaction(|tx| async move {
1554            let leaving_participant = room_participant::Entity::find()
1555                .filter(
1556                    Condition::all()
1557                        .add(
1558                            room_participant::Column::AnsweringConnectionId
1559                                .eq(connection.id as i32),
1560                        )
1561                        .add(
1562                            room_participant::Column::AnsweringConnectionServerId
1563                                .eq(connection.owner_id as i32),
1564                        ),
1565                )
1566                .one(&*tx)
1567                .await?;
1568
1569            if let Some(leaving_participant) = leaving_participant {
1570                // Leave room.
1571                let room_id = leaving_participant.room_id;
1572                room_participant::Entity::delete_by_id(leaving_participant.id)
1573                    .exec(&*tx)
1574                    .await?;
1575
1576                // Cancel pending calls initiated by the leaving user.
1577                let called_participants = room_participant::Entity::find()
1578                    .filter(
1579                        Condition::all()
1580                            .add(
1581                                room_participant::Column::CallingConnectionId
1582                                    .eq(connection.id as i32),
1583                            )
1584                            .add(
1585                                room_participant::Column::CallingConnectionServerId
1586                                    .eq(connection.owner_id as i32),
1587                            )
1588                            .add(room_participant::Column::AnsweringConnectionId.is_null()),
1589                    )
1590                    .all(&*tx)
1591                    .await?;
1592                room_participant::Entity::delete_many()
1593                    .filter(
1594                        room_participant::Column::Id
1595                            .is_in(called_participants.iter().map(|participant| participant.id)),
1596                    )
1597                    .exec(&*tx)
1598                    .await?;
1599                let canceled_calls_to_user_ids = called_participants
1600                    .into_iter()
1601                    .map(|participant| participant.user_id)
1602                    .collect();
1603
1604                // Detect left projects.
1605                #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
1606                enum QueryProjectIds {
1607                    ProjectId,
1608                }
1609                let project_ids: Vec<ProjectId> = project_collaborator::Entity::find()
1610                    .select_only()
1611                    .column_as(
1612                        project_collaborator::Column::ProjectId,
1613                        QueryProjectIds::ProjectId,
1614                    )
1615                    .filter(
1616                        Condition::all()
1617                            .add(
1618                                project_collaborator::Column::ConnectionId.eq(connection.id as i32),
1619                            )
1620                            .add(
1621                                project_collaborator::Column::ConnectionServerId
1622                                    .eq(connection.owner_id as i32),
1623                            ),
1624                    )
1625                    .into_values::<_, QueryProjectIds>()
1626                    .all(&*tx)
1627                    .await?;
1628                let mut left_projects = HashMap::default();
1629                let mut collaborators = project_collaborator::Entity::find()
1630                    .filter(project_collaborator::Column::ProjectId.is_in(project_ids))
1631                    .stream(&*tx)
1632                    .await?;
1633                while let Some(collaborator) = collaborators.next().await {
1634                    let collaborator = collaborator?;
1635                    let left_project =
1636                        left_projects
1637                            .entry(collaborator.project_id)
1638                            .or_insert(LeftProject {
1639                                id: collaborator.project_id,
1640                                host_user_id: Default::default(),
1641                                connection_ids: Default::default(),
1642                                host_connection_id: Default::default(),
1643                            });
1644
1645                    let collaborator_connection_id = collaborator.connection();
1646                    if collaborator_connection_id != connection {
1647                        left_project.connection_ids.push(collaborator_connection_id);
1648                    }
1649
1650                    if collaborator.is_host {
1651                        left_project.host_user_id = collaborator.user_id;
1652                        left_project.host_connection_id = collaborator_connection_id;
1653                    }
1654                }
1655                drop(collaborators);
1656
1657                // Leave projects.
1658                project_collaborator::Entity::delete_many()
1659                    .filter(
1660                        Condition::all()
1661                            .add(
1662                                project_collaborator::Column::ConnectionId.eq(connection.id as i32),
1663                            )
1664                            .add(
1665                                project_collaborator::Column::ConnectionServerId
1666                                    .eq(connection.owner_id as i32),
1667                            ),
1668                    )
1669                    .exec(&*tx)
1670                    .await?;
1671
1672                // Unshare projects.
1673                project::Entity::delete_many()
1674                    .filter(
1675                        Condition::all()
1676                            .add(project::Column::RoomId.eq(room_id))
1677                            .add(project::Column::HostConnectionId.eq(connection.id as i32))
1678                            .add(
1679                                project::Column::HostConnectionServerId
1680                                    .eq(connection.owner_id as i32),
1681                            ),
1682                    )
1683                    .exec(&*tx)
1684                    .await?;
1685
1686                let room = self.get_room(room_id, &tx).await?;
1687                if room.participants.is_empty() {
1688                    room::Entity::delete_by_id(room_id).exec(&*tx).await?;
1689                }
1690
1691                let left_room = LeftRoom {
1692                    room,
1693                    left_projects,
1694                    canceled_calls_to_user_ids,
1695                };
1696
1697                if left_room.room.participants.is_empty() {
1698                    self.rooms.remove(&room_id);
1699                }
1700
1701                Ok(Some((room_id, left_room)))
1702            } else {
1703                Ok(None)
1704            }
1705        })
1706        .await
1707    }
1708
1709    pub async fn update_room_participant_location(
1710        &self,
1711        room_id: RoomId,
1712        connection: ConnectionId,
1713        location: proto::ParticipantLocation,
1714    ) -> Result<RoomGuard<proto::Room>> {
1715        self.room_transaction(|tx| async {
1716            let tx = tx;
1717            let location_kind;
1718            let location_project_id;
1719            match location
1720                .variant
1721                .as_ref()
1722                .ok_or_else(|| anyhow!("invalid location"))?
1723            {
1724                proto::participant_location::Variant::SharedProject(project) => {
1725                    location_kind = 0;
1726                    location_project_id = Some(ProjectId::from_proto(project.id));
1727                }
1728                proto::participant_location::Variant::UnsharedProject(_) => {
1729                    location_kind = 1;
1730                    location_project_id = None;
1731                }
1732                proto::participant_location::Variant::External(_) => {
1733                    location_kind = 2;
1734                    location_project_id = None;
1735                }
1736            }
1737
1738            let result = room_participant::Entity::update_many()
1739                .filter(
1740                    Condition::all()
1741                        .add(room_participant::Column::RoomId.eq(room_id))
1742                        .add(
1743                            room_participant::Column::AnsweringConnectionId
1744                                .eq(connection.id as i32),
1745                        )
1746                        .add(
1747                            room_participant::Column::AnsweringConnectionServerId
1748                                .eq(connection.owner_id as i32),
1749                        ),
1750                )
1751                .set(room_participant::ActiveModel {
1752                    location_kind: ActiveValue::set(Some(location_kind)),
1753                    location_project_id: ActiveValue::set(location_project_id),
1754                    ..Default::default()
1755                })
1756                .exec(&*tx)
1757                .await?;
1758
1759            if result.rows_affected == 1 {
1760                let room = self.get_room(room_id, &tx).await?;
1761                Ok((room_id, room))
1762            } else {
1763                Err(anyhow!("could not update room participant location"))?
1764            }
1765        })
1766        .await
1767    }
1768
1769    pub async fn connection_lost(&self, connection: ConnectionId) -> Result<()> {
1770        self.transaction(|tx| async move {
1771            let participant = room_participant::Entity::find()
1772                .filter(
1773                    Condition::all()
1774                        .add(
1775                            room_participant::Column::AnsweringConnectionId
1776                                .eq(connection.id as i32),
1777                        )
1778                        .add(
1779                            room_participant::Column::AnsweringConnectionServerId
1780                                .eq(connection.owner_id as i32),
1781                        ),
1782                )
1783                .one(&*tx)
1784                .await?
1785                .ok_or_else(|| anyhow!("not a participant in any room"))?;
1786
1787            room_participant::Entity::update(room_participant::ActiveModel {
1788                answering_connection_lost: ActiveValue::set(true),
1789                ..participant.into_active_model()
1790            })
1791            .exec(&*tx)
1792            .await?;
1793
1794            Ok(())
1795        })
1796        .await
1797    }
1798
1799    fn build_incoming_call(
1800        room: &proto::Room,
1801        called_user_id: UserId,
1802    ) -> Option<proto::IncomingCall> {
1803        let pending_participant = room
1804            .pending_participants
1805            .iter()
1806            .find(|participant| participant.user_id == called_user_id.to_proto())?;
1807
1808        Some(proto::IncomingCall {
1809            room_id: room.id,
1810            calling_user_id: pending_participant.calling_user_id,
1811            participant_user_ids: room
1812                .participants
1813                .iter()
1814                .map(|participant| participant.user_id)
1815                .collect(),
1816            initial_project: room.participants.iter().find_map(|participant| {
1817                let initial_project_id = pending_participant.initial_project_id?;
1818                participant
1819                    .projects
1820                    .iter()
1821                    .find(|project| project.id == initial_project_id)
1822                    .cloned()
1823            }),
1824        })
1825    }
1826
1827    async fn get_room(&self, room_id: RoomId, tx: &DatabaseTransaction) -> Result<proto::Room> {
1828        let db_room = room::Entity::find_by_id(room_id)
1829            .one(tx)
1830            .await?
1831            .ok_or_else(|| anyhow!("could not find room"))?;
1832
1833        let mut db_participants = db_room
1834            .find_related(room_participant::Entity)
1835            .stream(tx)
1836            .await?;
1837        let mut participants = HashMap::default();
1838        let mut pending_participants = Vec::new();
1839        while let Some(db_participant) = db_participants.next().await {
1840            let db_participant = db_participant?;
1841            if let Some((answering_connection_id, answering_connection_server_id)) = db_participant
1842                .answering_connection_id
1843                .zip(db_participant.answering_connection_server_id)
1844            {
1845                let location = match (
1846                    db_participant.location_kind,
1847                    db_participant.location_project_id,
1848                ) {
1849                    (Some(0), Some(project_id)) => {
1850                        Some(proto::participant_location::Variant::SharedProject(
1851                            proto::participant_location::SharedProject {
1852                                id: project_id.to_proto(),
1853                            },
1854                        ))
1855                    }
1856                    (Some(1), _) => Some(proto::participant_location::Variant::UnsharedProject(
1857                        Default::default(),
1858                    )),
1859                    _ => Some(proto::participant_location::Variant::External(
1860                        Default::default(),
1861                    )),
1862                };
1863
1864                let answering_connection = ConnectionId {
1865                    owner_id: answering_connection_server_id.0 as u32,
1866                    id: answering_connection_id as u32,
1867                };
1868                participants.insert(
1869                    answering_connection,
1870                    proto::Participant {
1871                        user_id: db_participant.user_id.to_proto(),
1872                        peer_id: Some(answering_connection.into()),
1873                        projects: Default::default(),
1874                        location: Some(proto::ParticipantLocation { variant: location }),
1875                    },
1876                );
1877            } else {
1878                pending_participants.push(proto::PendingParticipant {
1879                    user_id: db_participant.user_id.to_proto(),
1880                    calling_user_id: db_participant.calling_user_id.to_proto(),
1881                    initial_project_id: db_participant.initial_project_id.map(|id| id.to_proto()),
1882                });
1883            }
1884        }
1885        drop(db_participants);
1886
1887        let mut db_projects = db_room
1888            .find_related(project::Entity)
1889            .find_with_related(worktree::Entity)
1890            .stream(tx)
1891            .await?;
1892
1893        while let Some(row) = db_projects.next().await {
1894            let (db_project, db_worktree) = row?;
1895            let host_connection = db_project.host_connection()?;
1896            if let Some(participant) = participants.get_mut(&host_connection) {
1897                let project = if let Some(project) = participant
1898                    .projects
1899                    .iter_mut()
1900                    .find(|project| project.id == db_project.id.to_proto())
1901                {
1902                    project
1903                } else {
1904                    participant.projects.push(proto::ParticipantProject {
1905                        id: db_project.id.to_proto(),
1906                        worktree_root_names: Default::default(),
1907                    });
1908                    participant.projects.last_mut().unwrap()
1909                };
1910
1911                if let Some(db_worktree) = db_worktree {
1912                    project.worktree_root_names.push(db_worktree.root_name);
1913                }
1914            }
1915        }
1916
1917        Ok(proto::Room {
1918            id: db_room.id.to_proto(),
1919            live_kit_room: db_room.live_kit_room,
1920            participants: participants.into_values().collect(),
1921            pending_participants,
1922        })
1923    }
1924
1925    // projects
1926
1927    pub async fn project_count_excluding_admins(&self) -> Result<usize> {
1928        #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
1929        enum QueryAs {
1930            Count,
1931        }
1932
1933        self.transaction(|tx| async move {
1934            Ok(project::Entity::find()
1935                .select_only()
1936                .column_as(project::Column::Id.count(), QueryAs::Count)
1937                .inner_join(user::Entity)
1938                .filter(user::Column::Admin.eq(false))
1939                .into_values::<_, QueryAs>()
1940                .one(&*tx)
1941                .await?
1942                .unwrap_or(0i64) as usize)
1943        })
1944        .await
1945    }
1946
1947    pub async fn share_project(
1948        &self,
1949        room_id: RoomId,
1950        connection: ConnectionId,
1951        worktrees: &[proto::WorktreeMetadata],
1952    ) -> Result<RoomGuard<(ProjectId, proto::Room)>> {
1953        self.room_transaction(|tx| async move {
1954            let participant = room_participant::Entity::find()
1955                .filter(
1956                    Condition::all()
1957                        .add(
1958                            room_participant::Column::AnsweringConnectionId
1959                                .eq(connection.id as i32),
1960                        )
1961                        .add(
1962                            room_participant::Column::AnsweringConnectionServerId
1963                                .eq(connection.owner_id as i32),
1964                        ),
1965                )
1966                .one(&*tx)
1967                .await?
1968                .ok_or_else(|| anyhow!("could not find participant"))?;
1969            if participant.room_id != room_id {
1970                return Err(anyhow!("shared project on unexpected room"))?;
1971            }
1972
1973            let project = project::ActiveModel {
1974                room_id: ActiveValue::set(participant.room_id),
1975                host_user_id: ActiveValue::set(participant.user_id),
1976                host_connection_id: ActiveValue::set(Some(connection.id as i32)),
1977                host_connection_server_id: ActiveValue::set(Some(ServerId(
1978                    connection.owner_id as i32,
1979                ))),
1980                ..Default::default()
1981            }
1982            .insert(&*tx)
1983            .await?;
1984
1985            if !worktrees.is_empty() {
1986                worktree::Entity::insert_many(worktrees.iter().map(|worktree| {
1987                    worktree::ActiveModel {
1988                        id: ActiveValue::set(worktree.id as i64),
1989                        project_id: ActiveValue::set(project.id),
1990                        abs_path: ActiveValue::set(worktree.abs_path.clone()),
1991                        root_name: ActiveValue::set(worktree.root_name.clone()),
1992                        visible: ActiveValue::set(worktree.visible),
1993                        scan_id: ActiveValue::set(0),
1994                        is_complete: ActiveValue::set(false),
1995                    }
1996                }))
1997                .exec(&*tx)
1998                .await?;
1999            }
2000
2001            project_collaborator::ActiveModel {
2002                project_id: ActiveValue::set(project.id),
2003                connection_id: ActiveValue::set(connection.id as i32),
2004                connection_server_id: ActiveValue::set(ServerId(connection.owner_id as i32)),
2005                user_id: ActiveValue::set(participant.user_id),
2006                replica_id: ActiveValue::set(ReplicaId(0)),
2007                is_host: ActiveValue::set(true),
2008                ..Default::default()
2009            }
2010            .insert(&*tx)
2011            .await?;
2012
2013            let room = self.get_room(room_id, &tx).await?;
2014            Ok((room_id, (project.id, room)))
2015        })
2016        .await
2017    }
2018
2019    pub async fn unshare_project(
2020        &self,
2021        project_id: ProjectId,
2022        connection: ConnectionId,
2023    ) -> Result<RoomGuard<(proto::Room, Vec<ConnectionId>)>> {
2024        self.room_transaction(|tx| async move {
2025            let guest_connection_ids = self.project_guest_connection_ids(project_id, &tx).await?;
2026
2027            let project = project::Entity::find_by_id(project_id)
2028                .one(&*tx)
2029                .await?
2030                .ok_or_else(|| anyhow!("project not found"))?;
2031            if project.host_connection()? == connection {
2032                let room_id = project.room_id;
2033                project::Entity::delete(project.into_active_model())
2034                    .exec(&*tx)
2035                    .await?;
2036                let room = self.get_room(room_id, &tx).await?;
2037                Ok((room_id, (room, guest_connection_ids)))
2038            } else {
2039                Err(anyhow!("cannot unshare a project hosted by another user"))?
2040            }
2041        })
2042        .await
2043    }
2044
2045    pub async fn update_project(
2046        &self,
2047        project_id: ProjectId,
2048        connection: ConnectionId,
2049        worktrees: &[proto::WorktreeMetadata],
2050    ) -> Result<RoomGuard<(proto::Room, Vec<ConnectionId>)>> {
2051        self.room_transaction(|tx| async move {
2052            let project = project::Entity::find_by_id(project_id)
2053                .filter(
2054                    Condition::all()
2055                        .add(project::Column::HostConnectionId.eq(connection.id as i32))
2056                        .add(
2057                            project::Column::HostConnectionServerId.eq(connection.owner_id as i32),
2058                        ),
2059                )
2060                .one(&*tx)
2061                .await?
2062                .ok_or_else(|| anyhow!("no such project"))?;
2063
2064            self.update_project_worktrees(project.id, worktrees, &tx)
2065                .await?;
2066
2067            let guest_connection_ids = self.project_guest_connection_ids(project.id, &tx).await?;
2068            let room = self.get_room(project.room_id, &tx).await?;
2069            Ok((project.room_id, (room, guest_connection_ids)))
2070        })
2071        .await
2072    }
2073
2074    async fn update_project_worktrees(
2075        &self,
2076        project_id: ProjectId,
2077        worktrees: &[proto::WorktreeMetadata],
2078        tx: &DatabaseTransaction,
2079    ) -> Result<()> {
2080        if !worktrees.is_empty() {
2081            worktree::Entity::insert_many(worktrees.iter().map(|worktree| worktree::ActiveModel {
2082                id: ActiveValue::set(worktree.id as i64),
2083                project_id: ActiveValue::set(project_id),
2084                abs_path: ActiveValue::set(worktree.abs_path.clone()),
2085                root_name: ActiveValue::set(worktree.root_name.clone()),
2086                visible: ActiveValue::set(worktree.visible),
2087                scan_id: ActiveValue::set(0),
2088                is_complete: ActiveValue::set(false),
2089            }))
2090            .on_conflict(
2091                OnConflict::columns([worktree::Column::ProjectId, worktree::Column::Id])
2092                    .update_column(worktree::Column::RootName)
2093                    .to_owned(),
2094            )
2095            .exec(&*tx)
2096            .await?;
2097        }
2098
2099        worktree::Entity::delete_many()
2100            .filter(worktree::Column::ProjectId.eq(project_id).and(
2101                worktree::Column::Id.is_not_in(worktrees.iter().map(|worktree| worktree.id as i64)),
2102            ))
2103            .exec(&*tx)
2104            .await?;
2105
2106        Ok(())
2107    }
2108
2109    pub async fn update_worktree(
2110        &self,
2111        update: &proto::UpdateWorktree,
2112        connection: ConnectionId,
2113    ) -> Result<RoomGuard<Vec<ConnectionId>>> {
2114        self.room_transaction(|tx| async move {
2115            let project_id = ProjectId::from_proto(update.project_id);
2116            let worktree_id = update.worktree_id as i64;
2117
2118            // Ensure the update comes from the host.
2119            let project = project::Entity::find_by_id(project_id)
2120                .filter(
2121                    Condition::all()
2122                        .add(project::Column::HostConnectionId.eq(connection.id as i32))
2123                        .add(
2124                            project::Column::HostConnectionServerId.eq(connection.owner_id as i32),
2125                        ),
2126                )
2127                .one(&*tx)
2128                .await?
2129                .ok_or_else(|| anyhow!("no such project"))?;
2130            let room_id = project.room_id;
2131
2132            // Update metadata.
2133            worktree::Entity::update(worktree::ActiveModel {
2134                id: ActiveValue::set(worktree_id),
2135                project_id: ActiveValue::set(project_id),
2136                root_name: ActiveValue::set(update.root_name.clone()),
2137                scan_id: ActiveValue::set(update.scan_id as i64),
2138                is_complete: ActiveValue::set(update.is_last_update),
2139                abs_path: ActiveValue::set(update.abs_path.clone()),
2140                ..Default::default()
2141            })
2142            .exec(&*tx)
2143            .await?;
2144
2145            if !update.updated_entries.is_empty() {
2146                worktree_entry::Entity::insert_many(update.updated_entries.iter().map(|entry| {
2147                    let mtime = entry.mtime.clone().unwrap_or_default();
2148                    worktree_entry::ActiveModel {
2149                        project_id: ActiveValue::set(project_id),
2150                        worktree_id: ActiveValue::set(worktree_id),
2151                        id: ActiveValue::set(entry.id as i64),
2152                        is_dir: ActiveValue::set(entry.is_dir),
2153                        path: ActiveValue::set(entry.path.clone()),
2154                        inode: ActiveValue::set(entry.inode as i64),
2155                        mtime_seconds: ActiveValue::set(mtime.seconds as i64),
2156                        mtime_nanos: ActiveValue::set(mtime.nanos as i32),
2157                        is_symlink: ActiveValue::set(entry.is_symlink),
2158                        is_ignored: ActiveValue::set(entry.is_ignored),
2159                        is_deleted: ActiveValue::set(false),
2160                        scan_id: ActiveValue::set(update.scan_id as i64),
2161                    }
2162                }))
2163                .on_conflict(
2164                    OnConflict::columns([
2165                        worktree_entry::Column::ProjectId,
2166                        worktree_entry::Column::WorktreeId,
2167                        worktree_entry::Column::Id,
2168                    ])
2169                    .update_columns([
2170                        worktree_entry::Column::IsDir,
2171                        worktree_entry::Column::Path,
2172                        worktree_entry::Column::Inode,
2173                        worktree_entry::Column::MtimeSeconds,
2174                        worktree_entry::Column::MtimeNanos,
2175                        worktree_entry::Column::IsSymlink,
2176                        worktree_entry::Column::IsIgnored,
2177                    ])
2178                    .to_owned(),
2179                )
2180                .exec(&*tx)
2181                .await?;
2182            }
2183
2184            if !update.removed_entries.is_empty() {
2185                worktree_entry::Entity::update_many()
2186                    .filter(
2187                        worktree_entry::Column::ProjectId
2188                            .eq(project_id)
2189                            .and(worktree_entry::Column::WorktreeId.eq(worktree_id))
2190                            .and(
2191                                worktree_entry::Column::Id
2192                                    .is_in(update.removed_entries.iter().map(|id| *id as i64)),
2193                            ),
2194                    )
2195                    .set(worktree_entry::ActiveModel {
2196                        is_deleted: ActiveValue::Set(true),
2197                        scan_id: ActiveValue::Set(update.scan_id as i64),
2198                        ..Default::default()
2199                    })
2200                    .exec(&*tx)
2201                    .await?;
2202            }
2203
2204            let connection_ids = self.project_guest_connection_ids(project_id, &tx).await?;
2205            Ok((room_id, connection_ids))
2206        })
2207        .await
2208    }
2209
2210    pub async fn update_diagnostic_summary(
2211        &self,
2212        update: &proto::UpdateDiagnosticSummary,
2213        connection: ConnectionId,
2214    ) -> Result<RoomGuard<Vec<ConnectionId>>> {
2215        self.room_transaction(|tx| async move {
2216            let project_id = ProjectId::from_proto(update.project_id);
2217            let worktree_id = update.worktree_id as i64;
2218            let summary = update
2219                .summary
2220                .as_ref()
2221                .ok_or_else(|| anyhow!("invalid summary"))?;
2222
2223            // Ensure the update comes from the host.
2224            let project = project::Entity::find_by_id(project_id)
2225                .one(&*tx)
2226                .await?
2227                .ok_or_else(|| anyhow!("no such project"))?;
2228            if project.host_connection()? != connection {
2229                return Err(anyhow!("can't update a project hosted by someone else"))?;
2230            }
2231
2232            // Update summary.
2233            worktree_diagnostic_summary::Entity::insert(worktree_diagnostic_summary::ActiveModel {
2234                project_id: ActiveValue::set(project_id),
2235                worktree_id: ActiveValue::set(worktree_id),
2236                path: ActiveValue::set(summary.path.clone()),
2237                language_server_id: ActiveValue::set(summary.language_server_id as i64),
2238                error_count: ActiveValue::set(summary.error_count as i32),
2239                warning_count: ActiveValue::set(summary.warning_count as i32),
2240                ..Default::default()
2241            })
2242            .on_conflict(
2243                OnConflict::columns([
2244                    worktree_diagnostic_summary::Column::ProjectId,
2245                    worktree_diagnostic_summary::Column::WorktreeId,
2246                    worktree_diagnostic_summary::Column::Path,
2247                ])
2248                .update_columns([
2249                    worktree_diagnostic_summary::Column::LanguageServerId,
2250                    worktree_diagnostic_summary::Column::ErrorCount,
2251                    worktree_diagnostic_summary::Column::WarningCount,
2252                ])
2253                .to_owned(),
2254            )
2255            .exec(&*tx)
2256            .await?;
2257
2258            let connection_ids = self.project_guest_connection_ids(project_id, &tx).await?;
2259            Ok((project.room_id, connection_ids))
2260        })
2261        .await
2262    }
2263
2264    pub async fn start_language_server(
2265        &self,
2266        update: &proto::StartLanguageServer,
2267        connection: ConnectionId,
2268    ) -> Result<RoomGuard<Vec<ConnectionId>>> {
2269        self.room_transaction(|tx| async move {
2270            let project_id = ProjectId::from_proto(update.project_id);
2271            let server = update
2272                .server
2273                .as_ref()
2274                .ok_or_else(|| anyhow!("invalid language server"))?;
2275
2276            // Ensure the update comes from the host.
2277            let project = project::Entity::find_by_id(project_id)
2278                .one(&*tx)
2279                .await?
2280                .ok_or_else(|| anyhow!("no such project"))?;
2281            if project.host_connection()? != connection {
2282                return Err(anyhow!("can't update a project hosted by someone else"))?;
2283            }
2284
2285            // Add the newly-started language server.
2286            language_server::Entity::insert(language_server::ActiveModel {
2287                project_id: ActiveValue::set(project_id),
2288                id: ActiveValue::set(server.id as i64),
2289                name: ActiveValue::set(server.name.clone()),
2290                ..Default::default()
2291            })
2292            .on_conflict(
2293                OnConflict::columns([
2294                    language_server::Column::ProjectId,
2295                    language_server::Column::Id,
2296                ])
2297                .update_column(language_server::Column::Name)
2298                .to_owned(),
2299            )
2300            .exec(&*tx)
2301            .await?;
2302
2303            let connection_ids = self.project_guest_connection_ids(project_id, &tx).await?;
2304            Ok((project.room_id, connection_ids))
2305        })
2306        .await
2307    }
2308
2309    pub async fn join_project(
2310        &self,
2311        project_id: ProjectId,
2312        connection: ConnectionId,
2313    ) -> Result<RoomGuard<(Project, ReplicaId)>> {
2314        self.room_transaction(|tx| async move {
2315            let participant = room_participant::Entity::find()
2316                .filter(
2317                    Condition::all()
2318                        .add(
2319                            room_participant::Column::AnsweringConnectionId
2320                                .eq(connection.id as i32),
2321                        )
2322                        .add(
2323                            room_participant::Column::AnsweringConnectionServerId
2324                                .eq(connection.owner_id as i32),
2325                        ),
2326                )
2327                .one(&*tx)
2328                .await?
2329                .ok_or_else(|| anyhow!("must join a room first"))?;
2330
2331            let project = project::Entity::find_by_id(project_id)
2332                .one(&*tx)
2333                .await?
2334                .ok_or_else(|| anyhow!("no such project"))?;
2335            if project.room_id != participant.room_id {
2336                return Err(anyhow!("no such project"))?;
2337            }
2338
2339            let mut collaborators = project
2340                .find_related(project_collaborator::Entity)
2341                .all(&*tx)
2342                .await?;
2343            let replica_ids = collaborators
2344                .iter()
2345                .map(|c| c.replica_id)
2346                .collect::<HashSet<_>>();
2347            let mut replica_id = ReplicaId(1);
2348            while replica_ids.contains(&replica_id) {
2349                replica_id.0 += 1;
2350            }
2351            let new_collaborator = project_collaborator::ActiveModel {
2352                project_id: ActiveValue::set(project_id),
2353                connection_id: ActiveValue::set(connection.id as i32),
2354                connection_server_id: ActiveValue::set(ServerId(connection.owner_id as i32)),
2355                user_id: ActiveValue::set(participant.user_id),
2356                replica_id: ActiveValue::set(replica_id),
2357                is_host: ActiveValue::set(false),
2358                ..Default::default()
2359            }
2360            .insert(&*tx)
2361            .await?;
2362            collaborators.push(new_collaborator);
2363
2364            let db_worktrees = project.find_related(worktree::Entity).all(&*tx).await?;
2365            let mut worktrees = db_worktrees
2366                .into_iter()
2367                .map(|db_worktree| {
2368                    (
2369                        db_worktree.id as u64,
2370                        Worktree {
2371                            id: db_worktree.id as u64,
2372                            abs_path: db_worktree.abs_path,
2373                            root_name: db_worktree.root_name,
2374                            visible: db_worktree.visible,
2375                            entries: Default::default(),
2376                            diagnostic_summaries: Default::default(),
2377                            scan_id: db_worktree.scan_id as u64,
2378                            is_complete: db_worktree.is_complete,
2379                        },
2380                    )
2381                })
2382                .collect::<BTreeMap<_, _>>();
2383
2384            // Populate worktree entries.
2385            {
2386                let mut db_entries = worktree_entry::Entity::find()
2387                    .filter(worktree_entry::Column::ProjectId.eq(project_id))
2388                    .stream(&*tx)
2389                    .await?;
2390                while let Some(db_entry) = db_entries.next().await {
2391                    let db_entry = db_entry?;
2392                    if let Some(worktree) = worktrees.get_mut(&(db_entry.worktree_id as u64)) {
2393                        worktree.entries.push(proto::Entry {
2394                            id: db_entry.id as u64,
2395                            is_dir: db_entry.is_dir,
2396                            path: db_entry.path,
2397                            inode: db_entry.inode as u64,
2398                            mtime: Some(proto::Timestamp {
2399                                seconds: db_entry.mtime_seconds as u64,
2400                                nanos: db_entry.mtime_nanos as u32,
2401                            }),
2402                            is_symlink: db_entry.is_symlink,
2403                            is_ignored: db_entry.is_ignored,
2404                        });
2405                    }
2406                }
2407            }
2408
2409            // Populate worktree diagnostic summaries.
2410            {
2411                let mut db_summaries = worktree_diagnostic_summary::Entity::find()
2412                    .filter(worktree_diagnostic_summary::Column::ProjectId.eq(project_id))
2413                    .stream(&*tx)
2414                    .await?;
2415                while let Some(db_summary) = db_summaries.next().await {
2416                    let db_summary = db_summary?;
2417                    if let Some(worktree) = worktrees.get_mut(&(db_summary.worktree_id as u64)) {
2418                        worktree
2419                            .diagnostic_summaries
2420                            .push(proto::DiagnosticSummary {
2421                                path: db_summary.path,
2422                                language_server_id: db_summary.language_server_id as u64,
2423                                error_count: db_summary.error_count as u32,
2424                                warning_count: db_summary.warning_count as u32,
2425                            });
2426                    }
2427                }
2428            }
2429
2430            // Populate language servers.
2431            let language_servers = project
2432                .find_related(language_server::Entity)
2433                .all(&*tx)
2434                .await?;
2435
2436            let room_id = project.room_id;
2437            let project = Project {
2438                collaborators: collaborators
2439                    .into_iter()
2440                    .map(|collaborator| ProjectCollaborator {
2441                        connection_id: collaborator.connection(),
2442                        user_id: collaborator.user_id,
2443                        replica_id: collaborator.replica_id,
2444                        is_host: collaborator.is_host,
2445                    })
2446                    .collect(),
2447                worktrees,
2448                language_servers: language_servers
2449                    .into_iter()
2450                    .map(|language_server| proto::LanguageServer {
2451                        id: language_server.id as u64,
2452                        name: language_server.name,
2453                    })
2454                    .collect(),
2455            };
2456            Ok((room_id, (project, replica_id as ReplicaId)))
2457        })
2458        .await
2459    }
2460
2461    pub async fn leave_project(
2462        &self,
2463        project_id: ProjectId,
2464        connection: ConnectionId,
2465    ) -> Result<RoomGuard<LeftProject>> {
2466        self.room_transaction(|tx| async move {
2467            let result = project_collaborator::Entity::delete_many()
2468                .filter(
2469                    Condition::all()
2470                        .add(project_collaborator::Column::ProjectId.eq(project_id))
2471                        .add(project_collaborator::Column::ConnectionId.eq(connection.id as i32))
2472                        .add(
2473                            project_collaborator::Column::ConnectionServerId
2474                                .eq(connection.owner_id as i32),
2475                        ),
2476                )
2477                .exec(&*tx)
2478                .await?;
2479            if result.rows_affected == 0 {
2480                Err(anyhow!("not a collaborator on this project"))?;
2481            }
2482
2483            let project = project::Entity::find_by_id(project_id)
2484                .one(&*tx)
2485                .await?
2486                .ok_or_else(|| anyhow!("no such project"))?;
2487            let collaborators = project
2488                .find_related(project_collaborator::Entity)
2489                .all(&*tx)
2490                .await?;
2491            let connection_ids = collaborators
2492                .into_iter()
2493                .map(|collaborator| collaborator.connection())
2494                .collect();
2495
2496            let left_project = LeftProject {
2497                id: project_id,
2498                host_user_id: project.host_user_id,
2499                host_connection_id: project.host_connection()?,
2500                connection_ids,
2501            };
2502            Ok((project.room_id, left_project))
2503        })
2504        .await
2505    }
2506
2507    pub async fn project_collaborators(
2508        &self,
2509        project_id: ProjectId,
2510        connection_id: ConnectionId,
2511    ) -> Result<RoomGuard<Vec<ProjectCollaborator>>> {
2512        self.room_transaction(|tx| async move {
2513            let project = project::Entity::find_by_id(project_id)
2514                .one(&*tx)
2515                .await?
2516                .ok_or_else(|| anyhow!("no such project"))?;
2517            let collaborators = project_collaborator::Entity::find()
2518                .filter(project_collaborator::Column::ProjectId.eq(project_id))
2519                .all(&*tx)
2520                .await?
2521                .into_iter()
2522                .map(|collaborator| ProjectCollaborator {
2523                    connection_id: collaborator.connection(),
2524                    user_id: collaborator.user_id,
2525                    replica_id: collaborator.replica_id,
2526                    is_host: collaborator.is_host,
2527                })
2528                .collect::<Vec<_>>();
2529
2530            if collaborators
2531                .iter()
2532                .any(|collaborator| collaborator.connection_id == connection_id)
2533            {
2534                Ok((project.room_id, collaborators))
2535            } else {
2536                Err(anyhow!("no such project"))?
2537            }
2538        })
2539        .await
2540    }
2541
2542    pub async fn project_connection_ids(
2543        &self,
2544        project_id: ProjectId,
2545        connection_id: ConnectionId,
2546    ) -> Result<RoomGuard<HashSet<ConnectionId>>> {
2547        self.room_transaction(|tx| async move {
2548            let project = project::Entity::find_by_id(project_id)
2549                .one(&*tx)
2550                .await?
2551                .ok_or_else(|| anyhow!("no such project"))?;
2552            let mut collaborators = project_collaborator::Entity::find()
2553                .filter(project_collaborator::Column::ProjectId.eq(project_id))
2554                .stream(&*tx)
2555                .await?;
2556
2557            let mut connection_ids = HashSet::default();
2558            while let Some(collaborator) = collaborators.next().await {
2559                let collaborator = collaborator?;
2560                connection_ids.insert(collaborator.connection());
2561            }
2562
2563            if connection_ids.contains(&connection_id) {
2564                Ok((project.room_id, connection_ids))
2565            } else {
2566                Err(anyhow!("no such project"))?
2567            }
2568        })
2569        .await
2570    }
2571
2572    async fn project_guest_connection_ids(
2573        &self,
2574        project_id: ProjectId,
2575        tx: &DatabaseTransaction,
2576    ) -> Result<Vec<ConnectionId>> {
2577        let mut collaborators = project_collaborator::Entity::find()
2578            .filter(
2579                project_collaborator::Column::ProjectId
2580                    .eq(project_id)
2581                    .and(project_collaborator::Column::IsHost.eq(false)),
2582            )
2583            .stream(tx)
2584            .await?;
2585
2586        let mut guest_connection_ids = Vec::new();
2587        while let Some(collaborator) = collaborators.next().await {
2588            let collaborator = collaborator?;
2589            guest_connection_ids.push(collaborator.connection());
2590        }
2591        Ok(guest_connection_ids)
2592    }
2593
2594    // access tokens
2595
2596    pub async fn create_access_token_hash(
2597        &self,
2598        user_id: UserId,
2599        access_token_hash: &str,
2600        max_access_token_count: usize,
2601    ) -> Result<()> {
2602        self.transaction(|tx| async {
2603            let tx = tx;
2604
2605            access_token::ActiveModel {
2606                user_id: ActiveValue::set(user_id),
2607                hash: ActiveValue::set(access_token_hash.into()),
2608                ..Default::default()
2609            }
2610            .insert(&*tx)
2611            .await?;
2612
2613            access_token::Entity::delete_many()
2614                .filter(
2615                    access_token::Column::Id.in_subquery(
2616                        Query::select()
2617                            .column(access_token::Column::Id)
2618                            .from(access_token::Entity)
2619                            .and_where(access_token::Column::UserId.eq(user_id))
2620                            .order_by(access_token::Column::Id, sea_orm::Order::Desc)
2621                            .limit(10000)
2622                            .offset(max_access_token_count as u64)
2623                            .to_owned(),
2624                    ),
2625                )
2626                .exec(&*tx)
2627                .await?;
2628            Ok(())
2629        })
2630        .await
2631    }
2632
2633    pub async fn get_access_token_hashes(&self, user_id: UserId) -> Result<Vec<String>> {
2634        #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
2635        enum QueryAs {
2636            Hash,
2637        }
2638
2639        self.transaction(|tx| async move {
2640            Ok(access_token::Entity::find()
2641                .select_only()
2642                .column(access_token::Column::Hash)
2643                .filter(access_token::Column::UserId.eq(user_id))
2644                .order_by_desc(access_token::Column::Id)
2645                .into_values::<_, QueryAs>()
2646                .all(&*tx)
2647                .await?)
2648        })
2649        .await
2650    }
2651
2652    async fn transaction<F, Fut, T>(&self, f: F) -> Result<T>
2653    where
2654        F: Send + Fn(TransactionHandle) -> Fut,
2655        Fut: Send + Future<Output = Result<T>>,
2656    {
2657        let body = async {
2658            loop {
2659                let (tx, result) = self.with_transaction(&f).await?;
2660                match result {
2661                    Ok(result) => {
2662                        match tx.commit().await.map_err(Into::into) {
2663                            Ok(()) => return Ok(result),
2664                            Err(error) => {
2665                                if is_serialization_error(&error) {
2666                                    // Retry (don't break the loop)
2667                                } else {
2668                                    return Err(error);
2669                                }
2670                            }
2671                        }
2672                    }
2673                    Err(error) => {
2674                        tx.rollback().await?;
2675                        if is_serialization_error(&error) {
2676                            // Retry (don't break the loop)
2677                        } else {
2678                            return Err(error);
2679                        }
2680                    }
2681                }
2682            }
2683        };
2684
2685        self.run(body).await
2686    }
2687
2688    async fn optional_room_transaction<F, Fut, T>(&self, f: F) -> Result<Option<RoomGuard<T>>>
2689    where
2690        F: Send + Fn(TransactionHandle) -> Fut,
2691        Fut: Send + Future<Output = Result<Option<(RoomId, T)>>>,
2692    {
2693        let body = async {
2694            loop {
2695                let (tx, result) = self.with_transaction(&f).await?;
2696                match result {
2697                    Ok(Some((room_id, data))) => {
2698                        let lock = self.rooms.entry(room_id).or_default().clone();
2699                        let _guard = lock.lock_owned().await;
2700                        match tx.commit().await.map_err(Into::into) {
2701                            Ok(()) => {
2702                                return Ok(Some(RoomGuard {
2703                                    data,
2704                                    _guard,
2705                                    _not_send: PhantomData,
2706                                }));
2707                            }
2708                            Err(error) => {
2709                                if is_serialization_error(&error) {
2710                                    // Retry (don't break the loop)
2711                                } else {
2712                                    return Err(error);
2713                                }
2714                            }
2715                        }
2716                    }
2717                    Ok(None) => {
2718                        match tx.commit().await.map_err(Into::into) {
2719                            Ok(()) => return Ok(None),
2720                            Err(error) => {
2721                                if is_serialization_error(&error) {
2722                                    // Retry (don't break the loop)
2723                                } else {
2724                                    return Err(error);
2725                                }
2726                            }
2727                        }
2728                    }
2729                    Err(error) => {
2730                        tx.rollback().await?;
2731                        if is_serialization_error(&error) {
2732                            // Retry (don't break the loop)
2733                        } else {
2734                            return Err(error);
2735                        }
2736                    }
2737                }
2738            }
2739        };
2740
2741        self.run(body).await
2742    }
2743
2744    async fn room_transaction<F, Fut, T>(&self, f: F) -> Result<RoomGuard<T>>
2745    where
2746        F: Send + Fn(TransactionHandle) -> Fut,
2747        Fut: Send + Future<Output = Result<(RoomId, T)>>,
2748    {
2749        let data = self
2750            .optional_room_transaction(move |tx| {
2751                let future = f(tx);
2752                async {
2753                    let data = future.await?;
2754                    Ok(Some(data))
2755                }
2756            })
2757            .await?;
2758        Ok(data.unwrap())
2759    }
2760
2761    async fn with_transaction<F, Fut, T>(&self, f: &F) -> Result<(DatabaseTransaction, Result<T>)>
2762    where
2763        F: Send + Fn(TransactionHandle) -> Fut,
2764        Fut: Send + Future<Output = Result<T>>,
2765    {
2766        let tx = self
2767            .pool
2768            .begin_with_config(Some(IsolationLevel::Serializable), None)
2769            .await?;
2770
2771        let mut tx = Arc::new(Some(tx));
2772        let result = f(TransactionHandle(tx.clone())).await;
2773        let Some(tx) = Arc::get_mut(&mut tx).and_then(|tx| tx.take()) else {
2774            return Err(anyhow!("couldn't complete transaction because it's still in use"))?;
2775        };
2776
2777        Ok((tx, result))
2778    }
2779
2780    async fn run<F, T>(&self, future: F) -> T
2781    where
2782        F: Future<Output = T>,
2783    {
2784        #[cfg(test)]
2785        {
2786            if let Some(background) = self.background.as_ref() {
2787                background.simulate_random_delay().await;
2788            }
2789
2790            self.runtime.as_ref().unwrap().block_on(future)
2791        }
2792
2793        #[cfg(not(test))]
2794        {
2795            future.await
2796        }
2797    }
2798}
2799
2800fn is_serialization_error(error: &Error) -> bool {
2801    const SERIALIZATION_FAILURE_CODE: &'static str = "40001";
2802    match error {
2803        Error::Database(
2804            DbErr::Exec(sea_orm::RuntimeErr::SqlxError(error))
2805            | DbErr::Query(sea_orm::RuntimeErr::SqlxError(error)),
2806        ) if error
2807            .as_database_error()
2808            .and_then(|error| error.code())
2809            .as_deref()
2810            == Some(SERIALIZATION_FAILURE_CODE) =>
2811        {
2812            true
2813        }
2814        _ => false,
2815    }
2816}
2817
2818struct TransactionHandle(Arc<Option<DatabaseTransaction>>);
2819
2820impl Deref for TransactionHandle {
2821    type Target = DatabaseTransaction;
2822
2823    fn deref(&self) -> &Self::Target {
2824        self.0.as_ref().as_ref().unwrap()
2825    }
2826}
2827
2828pub struct RoomGuard<T> {
2829    data: T,
2830    _guard: OwnedMutexGuard<()>,
2831    _not_send: PhantomData<Rc<()>>,
2832}
2833
2834impl<T> Deref for RoomGuard<T> {
2835    type Target = T;
2836
2837    fn deref(&self) -> &T {
2838        &self.data
2839    }
2840}
2841
2842impl<T> DerefMut for RoomGuard<T> {
2843    fn deref_mut(&mut self) -> &mut T {
2844        &mut self.data
2845    }
2846}
2847
2848#[derive(Debug, Serialize, Deserialize)]
2849pub struct NewUserParams {
2850    pub github_login: String,
2851    pub github_user_id: i32,
2852    pub invite_count: i32,
2853}
2854
2855#[derive(Debug)]
2856pub struct NewUserResult {
2857    pub user_id: UserId,
2858    pub metrics_id: String,
2859    pub inviting_user_id: Option<UserId>,
2860    pub signup_device_id: Option<String>,
2861}
2862
2863fn random_invite_code() -> String {
2864    nanoid::nanoid!(16)
2865}
2866
2867fn random_email_confirmation_code() -> String {
2868    nanoid::nanoid!(64)
2869}
2870
2871macro_rules! id_type {
2872    ($name:ident) => {
2873        #[derive(
2874            Clone,
2875            Copy,
2876            Debug,
2877            Default,
2878            PartialEq,
2879            Eq,
2880            PartialOrd,
2881            Ord,
2882            Hash,
2883            Serialize,
2884            Deserialize,
2885        )]
2886        #[serde(transparent)]
2887        pub struct $name(pub i32);
2888
2889        impl $name {
2890            #[allow(unused)]
2891            pub const MAX: Self = Self(i32::MAX);
2892
2893            #[allow(unused)]
2894            pub fn from_proto(value: u64) -> Self {
2895                Self(value as i32)
2896            }
2897
2898            #[allow(unused)]
2899            pub fn to_proto(self) -> u64 {
2900                self.0 as u64
2901            }
2902        }
2903
2904        impl std::fmt::Display for $name {
2905            fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
2906                self.0.fmt(f)
2907            }
2908        }
2909
2910        impl From<$name> for sea_query::Value {
2911            fn from(value: $name) -> Self {
2912                sea_query::Value::Int(Some(value.0))
2913            }
2914        }
2915
2916        impl sea_orm::TryGetable for $name {
2917            fn try_get(
2918                res: &sea_orm::QueryResult,
2919                pre: &str,
2920                col: &str,
2921            ) -> Result<Self, sea_orm::TryGetError> {
2922                Ok(Self(i32::try_get(res, pre, col)?))
2923            }
2924        }
2925
2926        impl sea_query::ValueType for $name {
2927            fn try_from(v: Value) -> Result<Self, sea_query::ValueTypeErr> {
2928                match v {
2929                    Value::TinyInt(Some(int)) => {
2930                        Ok(Self(int.try_into().map_err(|_| sea_query::ValueTypeErr)?))
2931                    }
2932                    Value::SmallInt(Some(int)) => {
2933                        Ok(Self(int.try_into().map_err(|_| sea_query::ValueTypeErr)?))
2934                    }
2935                    Value::Int(Some(int)) => {
2936                        Ok(Self(int.try_into().map_err(|_| sea_query::ValueTypeErr)?))
2937                    }
2938                    Value::BigInt(Some(int)) => {
2939                        Ok(Self(int.try_into().map_err(|_| sea_query::ValueTypeErr)?))
2940                    }
2941                    Value::TinyUnsigned(Some(int)) => {
2942                        Ok(Self(int.try_into().map_err(|_| sea_query::ValueTypeErr)?))
2943                    }
2944                    Value::SmallUnsigned(Some(int)) => {
2945                        Ok(Self(int.try_into().map_err(|_| sea_query::ValueTypeErr)?))
2946                    }
2947                    Value::Unsigned(Some(int)) => {
2948                        Ok(Self(int.try_into().map_err(|_| sea_query::ValueTypeErr)?))
2949                    }
2950                    Value::BigUnsigned(Some(int)) => {
2951                        Ok(Self(int.try_into().map_err(|_| sea_query::ValueTypeErr)?))
2952                    }
2953                    _ => Err(sea_query::ValueTypeErr),
2954                }
2955            }
2956
2957            fn type_name() -> String {
2958                stringify!($name).into()
2959            }
2960
2961            fn array_type() -> sea_query::ArrayType {
2962                sea_query::ArrayType::Int
2963            }
2964
2965            fn column_type() -> sea_query::ColumnType {
2966                sea_query::ColumnType::Integer(None)
2967            }
2968        }
2969
2970        impl sea_orm::TryFromU64 for $name {
2971            fn try_from_u64(n: u64) -> Result<Self, DbErr> {
2972                Ok(Self(n.try_into().map_err(|_| {
2973                    DbErr::ConvertFromU64(concat!(
2974                        "error converting ",
2975                        stringify!($name),
2976                        " to u64"
2977                    ))
2978                })?))
2979            }
2980        }
2981
2982        impl sea_query::Nullable for $name {
2983            fn null() -> Value {
2984                Value::Int(None)
2985            }
2986        }
2987    };
2988}
2989
2990id_type!(AccessTokenId);
2991id_type!(ContactId);
2992id_type!(RoomId);
2993id_type!(RoomParticipantId);
2994id_type!(ProjectId);
2995id_type!(ProjectCollaboratorId);
2996id_type!(ReplicaId);
2997id_type!(ServerId);
2998id_type!(SignupId);
2999id_type!(UserId);
3000
3001pub struct RejoinedRoom {
3002    pub room: proto::Room,
3003    pub rejoined_projects: Vec<RejoinedProject>,
3004    pub reshared_projects: Vec<ResharedProject>,
3005}
3006
3007pub struct ResharedProject {
3008    pub id: ProjectId,
3009    pub old_connection_id: ConnectionId,
3010    pub collaborators: Vec<ProjectCollaborator>,
3011    pub worktrees: Vec<proto::WorktreeMetadata>,
3012}
3013
3014pub struct RejoinedProject {
3015    pub id: ProjectId,
3016    pub old_connection_id: ConnectionId,
3017    pub collaborators: Vec<ProjectCollaborator>,
3018    pub worktrees: Vec<RejoinedWorktree>,
3019    pub language_servers: Vec<proto::LanguageServer>,
3020}
3021
3022#[derive(Debug)]
3023pub struct RejoinedWorktree {
3024    pub id: u64,
3025    pub abs_path: String,
3026    pub root_name: String,
3027    pub visible: bool,
3028    pub updated_entries: Vec<proto::Entry>,
3029    pub removed_entries: Vec<u64>,
3030    pub diagnostic_summaries: Vec<proto::DiagnosticSummary>,
3031    pub scan_id: u64,
3032    pub is_complete: bool,
3033}
3034
3035pub struct LeftRoom {
3036    pub room: proto::Room,
3037    pub left_projects: HashMap<ProjectId, LeftProject>,
3038    pub canceled_calls_to_user_ids: Vec<UserId>,
3039}
3040
3041pub struct RefreshedRoom {
3042    pub room: proto::Room,
3043    pub stale_participant_user_ids: Vec<UserId>,
3044    pub canceled_calls_to_user_ids: Vec<UserId>,
3045}
3046
3047pub struct Project {
3048    pub collaborators: Vec<ProjectCollaborator>,
3049    pub worktrees: BTreeMap<u64, Worktree>,
3050    pub language_servers: Vec<proto::LanguageServer>,
3051}
3052
3053pub struct ProjectCollaborator {
3054    pub connection_id: ConnectionId,
3055    pub user_id: UserId,
3056    pub replica_id: ReplicaId,
3057    pub is_host: bool,
3058}
3059
3060impl ProjectCollaborator {
3061    pub fn to_proto(&self) -> proto::Collaborator {
3062        proto::Collaborator {
3063            peer_id: Some(self.connection_id.into()),
3064            replica_id: self.replica_id.0 as u32,
3065            user_id: self.user_id.to_proto(),
3066        }
3067    }
3068}
3069
3070#[derive(Debug)]
3071pub struct LeftProject {
3072    pub id: ProjectId,
3073    pub host_user_id: UserId,
3074    pub host_connection_id: ConnectionId,
3075    pub connection_ids: Vec<ConnectionId>,
3076}
3077
3078pub struct Worktree {
3079    pub id: u64,
3080    pub abs_path: String,
3081    pub root_name: String,
3082    pub visible: bool,
3083    pub entries: Vec<proto::Entry>,
3084    pub diagnostic_summaries: Vec<proto::DiagnosticSummary>,
3085    pub scan_id: u64,
3086    pub is_complete: bool,
3087}
3088
3089#[cfg(test)]
3090pub use test::*;
3091
3092#[cfg(test)]
3093mod test {
3094    use super::*;
3095    use gpui::executor::Background;
3096    use lazy_static::lazy_static;
3097    use parking_lot::Mutex;
3098    use rand::prelude::*;
3099    use sea_orm::ConnectionTrait;
3100    use sqlx::migrate::MigrateDatabase;
3101    use std::sync::Arc;
3102
3103    pub struct TestDb {
3104        pub db: Option<Arc<Database>>,
3105        pub connection: Option<sqlx::AnyConnection>,
3106    }
3107
3108    impl TestDb {
3109        pub fn sqlite(background: Arc<Background>) -> Self {
3110            let url = format!("sqlite::memory:");
3111            let runtime = tokio::runtime::Builder::new_current_thread()
3112                .enable_io()
3113                .enable_time()
3114                .build()
3115                .unwrap();
3116
3117            let mut db = runtime.block_on(async {
3118                let mut options = ConnectOptions::new(url);
3119                options.max_connections(5);
3120                let db = Database::new(options).await.unwrap();
3121                let sql = include_str!(concat!(
3122                    env!("CARGO_MANIFEST_DIR"),
3123                    "/migrations.sqlite/20221109000000_test_schema.sql"
3124                ));
3125                db.pool
3126                    .execute(sea_orm::Statement::from_string(
3127                        db.pool.get_database_backend(),
3128                        sql.into(),
3129                    ))
3130                    .await
3131                    .unwrap();
3132                db
3133            });
3134
3135            db.background = Some(background);
3136            db.runtime = Some(runtime);
3137
3138            Self {
3139                db: Some(Arc::new(db)),
3140                connection: None,
3141            }
3142        }
3143
3144        pub fn postgres(background: Arc<Background>) -> Self {
3145            lazy_static! {
3146                static ref LOCK: Mutex<()> = Mutex::new(());
3147            }
3148
3149            let _guard = LOCK.lock();
3150            let mut rng = StdRng::from_entropy();
3151            let url = format!(
3152                "postgres://postgres@localhost/zed-test-{}",
3153                rng.gen::<u128>()
3154            );
3155            let runtime = tokio::runtime::Builder::new_current_thread()
3156                .enable_io()
3157                .enable_time()
3158                .build()
3159                .unwrap();
3160
3161            let mut db = runtime.block_on(async {
3162                sqlx::Postgres::create_database(&url)
3163                    .await
3164                    .expect("failed to create test db");
3165                let mut options = ConnectOptions::new(url);
3166                options
3167                    .max_connections(5)
3168                    .idle_timeout(Duration::from_secs(0));
3169                let db = Database::new(options).await.unwrap();
3170                let migrations_path = concat!(env!("CARGO_MANIFEST_DIR"), "/migrations");
3171                db.migrate(Path::new(migrations_path), false).await.unwrap();
3172                db
3173            });
3174
3175            db.background = Some(background);
3176            db.runtime = Some(runtime);
3177
3178            Self {
3179                db: Some(Arc::new(db)),
3180                connection: None,
3181            }
3182        }
3183
3184        pub fn db(&self) -> &Arc<Database> {
3185            self.db.as_ref().unwrap()
3186        }
3187    }
3188
3189    impl Drop for TestDb {
3190        fn drop(&mut self) {
3191            let db = self.db.take().unwrap();
3192            if let sea_orm::DatabaseBackend::Postgres = db.pool.get_database_backend() {
3193                db.runtime.as_ref().unwrap().block_on(async {
3194                    use util::ResultExt;
3195                    let query = "
3196                        SELECT pg_terminate_backend(pg_stat_activity.pid)
3197                        FROM pg_stat_activity
3198                        WHERE
3199                            pg_stat_activity.datname = current_database() AND
3200                            pid <> pg_backend_pid();
3201                    ";
3202                    db.pool
3203                        .execute(sea_orm::Statement::from_string(
3204                            db.pool.get_database_backend(),
3205                            query.into(),
3206                        ))
3207                        .await
3208                        .log_err();
3209                    sqlx::Postgres::drop_database(db.options.get_url())
3210                        .await
3211                        .log_err();
3212                })
3213            }
3214        }
3215    }
3216}