db.rs

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