db.rs

  1#[cfg(test)]
  2pub mod tests;
  3
  4#[cfg(test)]
  5pub use tests::TestDb;
  6
  7mod ids;
  8mod queries;
  9mod tables;
 10
 11use crate::{executor::Executor, Error, Result};
 12use anyhow::anyhow;
 13use collections::{BTreeMap, HashMap, HashSet};
 14use dashmap::DashMap;
 15use futures::StreamExt;
 16use rand::{prelude::StdRng, Rng, SeedableRng};
 17use rpc::{
 18    proto::{self},
 19    ConnectionId,
 20};
 21use sea_orm::{
 22    entity::prelude::*,
 23    sea_query::{Alias, Expr, OnConflict},
 24    ActiveValue, Condition, ConnectionTrait, DatabaseConnection, DatabaseTransaction, DbErr,
 25    FromQueryResult, IntoActiveModel, IsolationLevel, JoinType, QueryOrder, QuerySelect, Statement,
 26    TransactionTrait,
 27};
 28use serde::{Deserialize, Serialize};
 29use sqlx::{
 30    migrate::{Migrate, Migration, MigrationSource},
 31    Connection,
 32};
 33use std::{
 34    fmt::Write as _,
 35    future::Future,
 36    marker::PhantomData,
 37    ops::{Deref, DerefMut},
 38    path::Path,
 39    rc::Rc,
 40    sync::Arc,
 41    time::Duration,
 42};
 43use tables::*;
 44use tokio::sync::{Mutex, OwnedMutexGuard};
 45
 46pub use ids::*;
 47pub use queries::contributors::ContributorSelector;
 48pub use sea_orm::ConnectOptions;
 49pub use tables::user::Model as User;
 50
 51/// Database gives you a handle that lets you access the database.
 52/// It handles pooling internally.
 53pub struct Database {
 54    options: ConnectOptions,
 55    pool: DatabaseConnection,
 56    rooms: DashMap<RoomId, Arc<Mutex<()>>>,
 57    rng: Mutex<StdRng>,
 58    executor: Executor,
 59    notification_kinds_by_id: HashMap<NotificationKindId, &'static str>,
 60    notification_kinds_by_name: HashMap<String, NotificationKindId>,
 61    #[cfg(test)]
 62    runtime: Option<tokio::runtime::Runtime>,
 63}
 64
 65// The `Database` type has so many methods that its impl blocks are split into
 66// separate files in the `queries` folder.
 67impl Database {
 68    /// Connects to the database with the given options
 69    pub async fn new(options: ConnectOptions, executor: Executor) -> Result<Self> {
 70        sqlx::any::install_default_drivers();
 71        Ok(Self {
 72            options: options.clone(),
 73            pool: sea_orm::Database::connect(options).await?,
 74            rooms: DashMap::with_capacity(16384),
 75            rng: Mutex::new(StdRng::seed_from_u64(0)),
 76            notification_kinds_by_id: HashMap::default(),
 77            notification_kinds_by_name: HashMap::default(),
 78            executor,
 79            #[cfg(test)]
 80            runtime: None,
 81        })
 82    }
 83
 84    #[cfg(test)]
 85    pub fn reset(&self) {
 86        self.rooms.clear();
 87    }
 88
 89    /// Runs the database migrations.
 90    pub async fn migrate(
 91        &self,
 92        migrations_path: &Path,
 93        ignore_checksum_mismatch: bool,
 94    ) -> anyhow::Result<Vec<(Migration, Duration)>> {
 95        let migrations = MigrationSource::resolve(migrations_path)
 96            .await
 97            .map_err(|err| anyhow!("failed to load migrations: {err:?}"))?;
 98
 99        let mut connection = sqlx::AnyConnection::connect(self.options.get_url()).await?;
100
101        connection.ensure_migrations_table().await?;
102        let applied_migrations: HashMap<_, _> = connection
103            .list_applied_migrations()
104            .await?
105            .into_iter()
106            .map(|m| (m.version, m))
107            .collect();
108
109        let mut new_migrations = Vec::new();
110        for migration in migrations {
111            match applied_migrations.get(&migration.version) {
112                Some(applied_migration) => {
113                    if migration.checksum != applied_migration.checksum && !ignore_checksum_mismatch
114                    {
115                        Err(anyhow!(
116                            "checksum mismatch for applied migration {}",
117                            migration.description
118                        ))?;
119                    }
120                }
121                None => {
122                    let elapsed = connection.apply(&migration).await?;
123                    new_migrations.push((migration, elapsed));
124                }
125            }
126        }
127
128        Ok(new_migrations)
129    }
130
131    /// Initializes static data that resides in the database by upserting it.
132    pub async fn initialize_static_data(&mut self) -> Result<()> {
133        self.initialize_notification_kinds().await?;
134        Ok(())
135    }
136
137    /// Transaction runs things in a transaction. If you want to call other methods
138    /// and pass the transaction around you need to reborrow the transaction at each
139    /// call site with: `&*tx`.
140    pub async fn transaction<F, Fut, T>(&self, f: F) -> Result<T>
141    where
142        F: Send + Fn(TransactionHandle) -> Fut,
143        Fut: Send + Future<Output = Result<T>>,
144    {
145        let body = async {
146            let mut i = 0;
147            loop {
148                let (tx, result) = self.with_transaction(&f).await?;
149                match result {
150                    Ok(result) => match tx.commit().await.map_err(Into::into) {
151                        Ok(()) => return Ok(result),
152                        Err(error) => {
153                            if !self.retry_on_serialization_error(&error, i).await {
154                                return Err(error);
155                            }
156                        }
157                    },
158                    Err(error) => {
159                        tx.rollback().await?;
160                        if !self.retry_on_serialization_error(&error, i).await {
161                            return Err(error);
162                        }
163                    }
164                }
165                i += 1;
166            }
167        };
168
169        self.run(body).await
170    }
171
172    /// The same as room_transaction, but if you need to only optionally return a Room.
173    async fn optional_room_transaction<F, Fut, T>(&self, f: F) -> Result<Option<RoomGuard<T>>>
174    where
175        F: Send + Fn(TransactionHandle) -> Fut,
176        Fut: Send + Future<Output = Result<Option<(RoomId, T)>>>,
177    {
178        let body = async {
179            let mut i = 0;
180            loop {
181                let (tx, result) = self.with_transaction(&f).await?;
182                match result {
183                    Ok(Some((room_id, data))) => {
184                        let lock = self.rooms.entry(room_id).or_default().clone();
185                        let _guard = lock.lock_owned().await;
186                        match tx.commit().await.map_err(Into::into) {
187                            Ok(()) => {
188                                return Ok(Some(RoomGuard {
189                                    data,
190                                    _guard,
191                                    _not_send: PhantomData,
192                                }));
193                            }
194                            Err(error) => {
195                                if !self.retry_on_serialization_error(&error, i).await {
196                                    return Err(error);
197                                }
198                            }
199                        }
200                    }
201                    Ok(None) => match tx.commit().await.map_err(Into::into) {
202                        Ok(()) => return Ok(None),
203                        Err(error) => {
204                            if !self.retry_on_serialization_error(&error, i).await {
205                                return Err(error);
206                            }
207                        }
208                    },
209                    Err(error) => {
210                        tx.rollback().await?;
211                        if !self.retry_on_serialization_error(&error, i).await {
212                            return Err(error);
213                        }
214                    }
215                }
216                i += 1;
217            }
218        };
219
220        self.run(body).await
221    }
222
223    /// room_transaction runs the block in a transaction. It returns a RoomGuard, that keeps
224    /// the database locked until it is dropped. This ensures that updates sent to clients are
225    /// properly serialized with respect to database changes.
226    async fn room_transaction<F, Fut, T>(&self, room_id: RoomId, f: F) -> Result<RoomGuard<T>>
227    where
228        F: Send + Fn(TransactionHandle) -> Fut,
229        Fut: Send + Future<Output = Result<T>>,
230    {
231        let body = async {
232            let mut i = 0;
233            loop {
234                let lock = self.rooms.entry(room_id).or_default().clone();
235                let _guard = lock.lock_owned().await;
236                let (tx, result) = self.with_transaction(&f).await?;
237                match result {
238                    Ok(data) => match tx.commit().await.map_err(Into::into) {
239                        Ok(()) => {
240                            return Ok(RoomGuard {
241                                data,
242                                _guard,
243                                _not_send: PhantomData,
244                            });
245                        }
246                        Err(error) => {
247                            if !self.retry_on_serialization_error(&error, i).await {
248                                return Err(error);
249                            }
250                        }
251                    },
252                    Err(error) => {
253                        tx.rollback().await?;
254                        if !self.retry_on_serialization_error(&error, i).await {
255                            return Err(error);
256                        }
257                    }
258                }
259                i += 1;
260            }
261        };
262
263        self.run(body).await
264    }
265
266    async fn with_transaction<F, Fut, T>(&self, f: &F) -> Result<(DatabaseTransaction, Result<T>)>
267    where
268        F: Send + Fn(TransactionHandle) -> Fut,
269        Fut: Send + Future<Output = Result<T>>,
270    {
271        let tx = self
272            .pool
273            .begin_with_config(Some(IsolationLevel::Serializable), None)
274            .await?;
275
276        let mut tx = Arc::new(Some(tx));
277        let result = f(TransactionHandle(tx.clone())).await;
278        let Some(tx) = Arc::get_mut(&mut tx).and_then(|tx| tx.take()) else {
279            return Err(anyhow!(
280                "couldn't complete transaction because it's still in use"
281            ))?;
282        };
283
284        Ok((tx, result))
285    }
286
287    async fn run<F, T>(&self, future: F) -> Result<T>
288    where
289        F: Future<Output = Result<T>>,
290    {
291        #[cfg(test)]
292        {
293            if let Executor::Deterministic(executor) = &self.executor {
294                executor.simulate_random_delay().await;
295            }
296
297            self.runtime.as_ref().unwrap().block_on(future)
298        }
299
300        #[cfg(not(test))]
301        {
302            future.await
303        }
304    }
305
306    async fn retry_on_serialization_error(&self, error: &Error, prev_attempt_count: u32) -> bool {
307        // If the error is due to a failure to serialize concurrent transactions, then retry
308        // this transaction after a delay. With each subsequent retry, double the delay duration.
309        // Also vary the delay randomly in order to ensure different database connections retry
310        // at different times.
311        if is_serialization_error(error) {
312            let base_delay = 4_u64 << prev_attempt_count.min(16);
313            let randomized_delay = base_delay as f32 * self.rng.lock().await.gen_range(0.5..=2.0);
314            log::info!(
315                "retrying transaction after serialization error. delay: {} ms.",
316                randomized_delay
317            );
318            self.executor
319                .sleep(Duration::from_millis(randomized_delay as u64))
320                .await;
321            true
322        } else {
323            false
324        }
325    }
326}
327
328fn is_serialization_error(error: &Error) -> bool {
329    const SERIALIZATION_FAILURE_CODE: &'static str = "40001";
330    match error {
331        Error::Database(
332            DbErr::Exec(sea_orm::RuntimeErr::SqlxError(error))
333            | DbErr::Query(sea_orm::RuntimeErr::SqlxError(error)),
334        ) if error
335            .as_database_error()
336            .and_then(|error| error.code())
337            .as_deref()
338            == Some(SERIALIZATION_FAILURE_CODE) =>
339        {
340            true
341        }
342        _ => false,
343    }
344}
345
346/// A handle to a [`DatabaseTransaction`].
347pub struct TransactionHandle(Arc<Option<DatabaseTransaction>>);
348
349impl Deref for TransactionHandle {
350    type Target = DatabaseTransaction;
351
352    fn deref(&self) -> &Self::Target {
353        self.0.as_ref().as_ref().unwrap()
354    }
355}
356
357/// [`RoomGuard`] keeps a database transaction alive until it is dropped.
358/// so that updates to rooms are serialized.
359pub struct RoomGuard<T> {
360    data: T,
361    _guard: OwnedMutexGuard<()>,
362    _not_send: PhantomData<Rc<()>>,
363}
364
365impl<T> Deref for RoomGuard<T> {
366    type Target = T;
367
368    fn deref(&self) -> &T {
369        &self.data
370    }
371}
372
373impl<T> DerefMut for RoomGuard<T> {
374    fn deref_mut(&mut self) -> &mut T {
375        &mut self.data
376    }
377}
378
379impl<T> RoomGuard<T> {
380    /// Returns the inner value of the guard.
381    pub fn into_inner(self) -> T {
382        self.data
383    }
384}
385
386#[derive(Clone, Debug, PartialEq, Eq)]
387pub enum Contact {
388    Accepted { user_id: UserId, busy: bool },
389    Outgoing { user_id: UserId },
390    Incoming { user_id: UserId },
391}
392
393impl Contact {
394    pub fn user_id(&self) -> UserId {
395        match self {
396            Contact::Accepted { user_id, .. } => *user_id,
397            Contact::Outgoing { user_id } => *user_id,
398            Contact::Incoming { user_id, .. } => *user_id,
399        }
400    }
401}
402
403pub type NotificationBatch = Vec<(UserId, proto::Notification)>;
404
405pub struct CreatedChannelMessage {
406    pub message_id: MessageId,
407    pub participant_connection_ids: Vec<ConnectionId>,
408    pub channel_members: Vec<UserId>,
409    pub notifications: NotificationBatch,
410}
411
412#[derive(Clone, Debug, PartialEq, Eq, FromQueryResult, Serialize, Deserialize)]
413pub struct Invite {
414    pub email_address: String,
415    pub email_confirmation_code: String,
416}
417
418#[derive(Clone, Debug, Deserialize)]
419pub struct NewSignup {
420    pub email_address: String,
421    pub platform_mac: bool,
422    pub platform_windows: bool,
423    pub platform_linux: bool,
424    pub editor_features: Vec<String>,
425    pub programming_languages: Vec<String>,
426    pub device_id: Option<String>,
427    pub added_to_mailing_list: bool,
428    pub created_at: Option<DateTime>,
429}
430
431#[derive(Clone, Debug, PartialEq, Deserialize, Serialize, FromQueryResult)]
432pub struct WaitlistSummary {
433    pub count: i64,
434    pub linux_count: i64,
435    pub mac_count: i64,
436    pub windows_count: i64,
437    pub unknown_count: i64,
438}
439
440/// The parameters to create a new user.
441#[derive(Debug, Serialize, Deserialize)]
442pub struct NewUserParams {
443    pub github_login: String,
444    pub github_user_id: i32,
445}
446
447/// The result of creating a new user.
448#[derive(Debug)]
449pub struct NewUserResult {
450    pub user_id: UserId,
451    pub metrics_id: String,
452    pub inviting_user_id: Option<UserId>,
453    pub signup_device_id: Option<String>,
454}
455
456/// The result of moving a channel.
457#[derive(Debug)]
458pub struct MoveChannelResult {
459    pub participants_to_update: HashMap<UserId, ChannelsForUser>,
460    pub participants_to_remove: HashSet<UserId>,
461    pub moved_channels: HashSet<ChannelId>,
462}
463
464/// The result of renaming a channel.
465#[derive(Debug)]
466pub struct RenameChannelResult {
467    pub channel: Channel,
468    pub participants_to_update: HashMap<UserId, Channel>,
469}
470
471/// The result of creating a channel.
472#[derive(Debug)]
473pub struct CreateChannelResult {
474    pub channel: Channel,
475    pub participants_to_update: Vec<(UserId, ChannelsForUser)>,
476}
477
478/// The result of setting a channel's visibility.
479#[derive(Debug)]
480pub struct SetChannelVisibilityResult {
481    pub participants_to_update: HashMap<UserId, ChannelsForUser>,
482    pub participants_to_remove: HashSet<UserId>,
483    pub channels_to_remove: Vec<ChannelId>,
484}
485
486/// The result of updating a channel membership.
487#[derive(Debug)]
488pub struct MembershipUpdated {
489    pub channel_id: ChannelId,
490    pub new_channels: ChannelsForUser,
491    pub removed_channels: Vec<ChannelId>,
492}
493
494/// The result of setting a member's role.
495#[derive(Debug)]
496pub enum SetMemberRoleResult {
497    InviteUpdated(Channel),
498    MembershipUpdated(MembershipUpdated),
499}
500
501/// The result of inviting a member to a channel.
502#[derive(Debug)]
503pub struct InviteMemberResult {
504    pub channel: Channel,
505    pub notifications: NotificationBatch,
506}
507
508#[derive(Debug)]
509pub struct RespondToChannelInvite {
510    pub membership_update: Option<MembershipUpdated>,
511    pub notifications: NotificationBatch,
512}
513
514#[derive(Debug)]
515pub struct RemoveChannelMemberResult {
516    pub membership_update: MembershipUpdated,
517    pub notification_id: Option<NotificationId>,
518}
519
520#[derive(Debug, PartialEq, Eq, Hash)]
521pub struct Channel {
522    pub id: ChannelId,
523    pub name: String,
524    pub visibility: ChannelVisibility,
525    pub role: ChannelRole,
526    /// parent_path is the channel ids from the root to this one (not including this one)
527    pub parent_path: Vec<ChannelId>,
528}
529
530impl Channel {
531    fn from_model(value: channel::Model, role: ChannelRole) -> Self {
532        Channel {
533            id: value.id,
534            visibility: value.visibility,
535            name: value.clone().name,
536            role,
537            parent_path: value.ancestors().collect(),
538        }
539    }
540
541    pub fn to_proto(&self) -> proto::Channel {
542        proto::Channel {
543            id: self.id.to_proto(),
544            name: self.name.clone(),
545            visibility: self.visibility.into(),
546            role: self.role.into(),
547            parent_path: self.parent_path.iter().map(|c| c.to_proto()).collect(),
548        }
549    }
550}
551
552#[derive(Debug, PartialEq, Eq, Hash)]
553pub struct ChannelMember {
554    pub role: ChannelRole,
555    pub user_id: UserId,
556    pub kind: proto::channel_member::Kind,
557}
558
559impl ChannelMember {
560    pub fn to_proto(&self) -> proto::ChannelMember {
561        proto::ChannelMember {
562            role: self.role.into(),
563            user_id: self.user_id.to_proto(),
564            kind: self.kind.into(),
565        }
566    }
567}
568
569#[derive(Debug, PartialEq)]
570pub struct ChannelsForUser {
571    pub channels: Vec<Channel>,
572    pub channel_participants: HashMap<ChannelId, Vec<UserId>>,
573    pub unseen_buffer_changes: Vec<proto::UnseenChannelBufferChange>,
574    pub channel_messages: Vec<proto::UnseenChannelMessage>,
575}
576
577#[derive(Debug)]
578pub struct RejoinedChannelBuffer {
579    pub buffer: proto::RejoinedChannelBuffer,
580    pub old_connection_id: ConnectionId,
581}
582
583#[derive(Clone)]
584pub struct JoinRoom {
585    pub room: proto::Room,
586    pub channel_id: Option<ChannelId>,
587    pub channel_members: Vec<UserId>,
588}
589
590pub struct RejoinedRoom {
591    pub room: proto::Room,
592    pub rejoined_projects: Vec<RejoinedProject>,
593    pub reshared_projects: Vec<ResharedProject>,
594    pub channel_id: Option<ChannelId>,
595    pub channel_members: Vec<UserId>,
596}
597
598pub struct ResharedProject {
599    pub id: ProjectId,
600    pub old_connection_id: ConnectionId,
601    pub collaborators: Vec<ProjectCollaborator>,
602    pub worktrees: Vec<proto::WorktreeMetadata>,
603}
604
605pub struct RejoinedProject {
606    pub id: ProjectId,
607    pub old_connection_id: ConnectionId,
608    pub collaborators: Vec<ProjectCollaborator>,
609    pub worktrees: Vec<RejoinedWorktree>,
610    pub language_servers: Vec<proto::LanguageServer>,
611}
612
613#[derive(Debug)]
614pub struct RejoinedWorktree {
615    pub id: u64,
616    pub abs_path: String,
617    pub root_name: String,
618    pub visible: bool,
619    pub updated_entries: Vec<proto::Entry>,
620    pub removed_entries: Vec<u64>,
621    pub updated_repositories: Vec<proto::RepositoryEntry>,
622    pub removed_repositories: Vec<u64>,
623    pub diagnostic_summaries: Vec<proto::DiagnosticSummary>,
624    pub settings_files: Vec<WorktreeSettingsFile>,
625    pub scan_id: u64,
626    pub completed_scan_id: u64,
627}
628
629pub struct LeftRoom {
630    pub room: proto::Room,
631    pub channel_id: Option<ChannelId>,
632    pub channel_members: Vec<UserId>,
633    pub left_projects: HashMap<ProjectId, LeftProject>,
634    pub canceled_calls_to_user_ids: Vec<UserId>,
635    pub deleted: bool,
636}
637
638pub struct RefreshedRoom {
639    pub room: proto::Room,
640    pub channel_id: Option<ChannelId>,
641    pub channel_members: Vec<UserId>,
642    pub stale_participant_user_ids: Vec<UserId>,
643    pub canceled_calls_to_user_ids: Vec<UserId>,
644}
645
646pub struct RefreshedChannelBuffer {
647    pub connection_ids: Vec<ConnectionId>,
648    pub collaborators: Vec<proto::Collaborator>,
649}
650
651pub struct Project {
652    pub collaborators: Vec<ProjectCollaborator>,
653    pub worktrees: BTreeMap<u64, Worktree>,
654    pub language_servers: Vec<proto::LanguageServer>,
655}
656
657pub struct ProjectCollaborator {
658    pub connection_id: ConnectionId,
659    pub user_id: UserId,
660    pub replica_id: ReplicaId,
661    pub is_host: bool,
662}
663
664impl ProjectCollaborator {
665    pub fn to_proto(&self) -> proto::Collaborator {
666        proto::Collaborator {
667            peer_id: Some(self.connection_id.into()),
668            replica_id: self.replica_id.0 as u32,
669            user_id: self.user_id.to_proto(),
670        }
671    }
672}
673
674#[derive(Debug)]
675pub struct LeftProject {
676    pub id: ProjectId,
677    pub host_user_id: UserId,
678    pub host_connection_id: ConnectionId,
679    pub connection_ids: Vec<ConnectionId>,
680}
681
682pub struct Worktree {
683    pub id: u64,
684    pub abs_path: String,
685    pub root_name: String,
686    pub visible: bool,
687    pub entries: Vec<proto::Entry>,
688    pub repository_entries: BTreeMap<u64, proto::RepositoryEntry>,
689    pub diagnostic_summaries: Vec<proto::DiagnosticSummary>,
690    pub settings_files: Vec<WorktreeSettingsFile>,
691    pub scan_id: u64,
692    pub completed_scan_id: u64,
693}
694
695#[derive(Debug)]
696pub struct WorktreeSettingsFile {
697    pub path: String,
698    pub content: String,
699}