db.rs

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