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