db.rs

  1mod ids;
  2mod queries;
  3mod tables;
  4#[cfg(test)]
  5pub mod tests;
  6
  7use crate::{Error, Result, executor::Executor};
  8use anyhow::{Context as _, anyhow};
  9use collections::{BTreeMap, BTreeSet, HashMap, HashSet};
 10use dashmap::DashMap;
 11use futures::StreamExt;
 12use project_repository_statuses::StatusKind;
 13use rand::{Rng, SeedableRng, prelude::StdRng};
 14use rpc::ExtensionProvides;
 15use rpc::{
 16    ConnectionId, ExtensionMetadata,
 17    proto::{self},
 18};
 19use sea_orm::{
 20    ActiveValue, Condition, ConnectionTrait, DatabaseConnection, DatabaseTransaction, DbErr,
 21    FromQueryResult, IntoActiveModel, IsolationLevel, JoinType, QueryOrder, QuerySelect, Statement,
 22    TransactionTrait,
 23    entity::prelude::*,
 24    sea_query::{Alias, Expr, OnConflict},
 25};
 26use semantic_version::SemanticVersion;
 27use serde::{Deserialize, Serialize};
 28use std::ops::RangeInclusive;
 29use std::{
 30    fmt::Write as _,
 31    future::Future,
 32    marker::PhantomData,
 33    ops::{Deref, DerefMut},
 34    rc::Rc,
 35    sync::Arc,
 36    time::Duration,
 37};
 38use time::PrimitiveDateTime;
 39use tokio::sync::{Mutex, OwnedMutexGuard};
 40use worktree_settings_file::LocalSettingsKind;
 41
 42#[cfg(test)]
 43pub use tests::TestDb;
 44
 45pub use ids::*;
 46pub use queries::billing_customers::{CreateBillingCustomerParams, UpdateBillingCustomerParams};
 47pub use queries::billing_preferences::{
 48    CreateBillingPreferencesParams, UpdateBillingPreferencesParams,
 49};
 50pub use queries::billing_subscriptions::{
 51    CreateBillingSubscriptionParams, UpdateBillingSubscriptionParams,
 52};
 53pub use queries::contributors::ContributorSelector;
 54pub use queries::processed_stripe_events::CreateProcessedStripeEventParams;
 55pub use sea_orm::ConnectOptions;
 56pub use tables::user::Model as User;
 57pub use tables::*;
 58
 59/// Database gives you a handle that lets you access the database.
 60/// It handles pooling internally.
 61pub struct Database {
 62    options: ConnectOptions,
 63    pool: DatabaseConnection,
 64    rooms: DashMap<RoomId, Arc<Mutex<()>>>,
 65    projects: DashMap<ProjectId, Arc<Mutex<()>>>,
 66    rng: Mutex<StdRng>,
 67    executor: Executor,
 68    notification_kinds_by_id: HashMap<NotificationKindId, &'static str>,
 69    notification_kinds_by_name: HashMap<String, NotificationKindId>,
 70    #[cfg(test)]
 71    runtime: Option<tokio::runtime::Runtime>,
 72}
 73
 74// The `Database` type has so many methods that its impl blocks are split into
 75// separate files in the `queries` folder.
 76impl Database {
 77    /// Connects to the database with the given options
 78    pub async fn new(options: ConnectOptions, executor: Executor) -> Result<Self> {
 79        sqlx::any::install_default_drivers();
 80        Ok(Self {
 81            options: options.clone(),
 82            pool: sea_orm::Database::connect(options).await?,
 83            rooms: DashMap::with_capacity(16384),
 84            projects: DashMap::with_capacity(16384),
 85            rng: Mutex::new(StdRng::seed_from_u64(0)),
 86            notification_kinds_by_id: HashMap::default(),
 87            notification_kinds_by_name: HashMap::default(),
 88            executor,
 89            #[cfg(test)]
 90            runtime: None,
 91        })
 92    }
 93
 94    pub fn options(&self) -> &ConnectOptions {
 95        &self.options
 96    }
 97
 98    #[cfg(test)]
 99    pub fn reset(&self) {
100        self.rooms.clear();
101        self.projects.clear();
102    }
103
104    /// Transaction runs things in a transaction. If you want to call other methods
105    /// and pass the transaction around you need to reborrow the transaction at each
106    /// call site with: `&*tx`.
107    pub async fn transaction<F, Fut, T>(&self, f: F) -> Result<T>
108    where
109        F: Send + Fn(TransactionHandle) -> Fut,
110        Fut: Send + Future<Output = Result<T>>,
111    {
112        let body = async {
113            let mut i = 0;
114            loop {
115                let (tx, result) = self.with_transaction(&f).await?;
116                match result {
117                    Ok(result) => match tx.commit().await.map_err(Into::into) {
118                        Ok(()) => return Ok(result),
119                        Err(error) => {
120                            if !self.retry_on_serialization_error(&error, i).await {
121                                return Err(error);
122                            }
123                        }
124                    },
125                    Err(error) => {
126                        tx.rollback().await?;
127                        if !self.retry_on_serialization_error(&error, i).await {
128                            return Err(error);
129                        }
130                    }
131                }
132                i += 1;
133            }
134        };
135
136        self.run(body).await
137    }
138
139    pub async fn weak_transaction<F, Fut, T>(&self, f: F) -> Result<T>
140    where
141        F: Send + Fn(TransactionHandle) -> Fut,
142        Fut: Send + Future<Output = Result<T>>,
143    {
144        let body = async {
145            let (tx, result) = self.with_weak_transaction(&f).await?;
146            match result {
147                Ok(result) => match tx.commit().await.map_err(Into::into) {
148                    Ok(()) => Ok(result),
149                    Err(error) => Err(error),
150                },
151                Err(error) => {
152                    tx.rollback().await?;
153                    Err(error)
154                }
155            }
156        };
157
158        self.run(body).await
159    }
160
161    /// The same as room_transaction, but if you need to only optionally return a Room.
162    async fn optional_room_transaction<F, Fut, T>(
163        &self,
164        f: F,
165    ) -> Result<Option<TransactionGuard<T>>>
166    where
167        F: Send + Fn(TransactionHandle) -> Fut,
168        Fut: Send + Future<Output = Result<Option<(RoomId, T)>>>,
169    {
170        let body = async {
171            let mut i = 0;
172            loop {
173                let (tx, result) = self.with_transaction(&f).await?;
174                match result {
175                    Ok(Some((room_id, data))) => {
176                        let lock = self.rooms.entry(room_id).or_default().clone();
177                        let _guard = lock.lock_owned().await;
178                        match tx.commit().await.map_err(Into::into) {
179                            Ok(()) => {
180                                return Ok(Some(TransactionGuard {
181                                    data,
182                                    _guard,
183                                    _not_send: PhantomData,
184                                }));
185                            }
186                            Err(error) => {
187                                if !self.retry_on_serialization_error(&error, i).await {
188                                    return Err(error);
189                                }
190                            }
191                        }
192                    }
193                    Ok(None) => match tx.commit().await.map_err(Into::into) {
194                        Ok(()) => return Ok(None),
195                        Err(error) => {
196                            if !self.retry_on_serialization_error(&error, i).await {
197                                return Err(error);
198                            }
199                        }
200                    },
201                    Err(error) => {
202                        tx.rollback().await?;
203                        if !self.retry_on_serialization_error(&error, i).await {
204                            return Err(error);
205                        }
206                    }
207                }
208                i += 1;
209            }
210        };
211
212        self.run(body).await
213    }
214
215    async fn project_transaction<F, Fut, T>(
216        &self,
217        project_id: ProjectId,
218        f: F,
219    ) -> Result<TransactionGuard<T>>
220    where
221        F: Send + Fn(TransactionHandle) -> Fut,
222        Fut: Send + Future<Output = Result<T>>,
223    {
224        let room_id = Database::room_id_for_project(self, project_id).await?;
225        let body = async {
226            let mut i = 0;
227            loop {
228                let lock = if let Some(room_id) = room_id {
229                    self.rooms.entry(room_id).or_default().clone()
230                } else {
231                    self.projects.entry(project_id).or_default().clone()
232                };
233                let _guard = lock.lock_owned().await;
234                let (tx, result) = self.with_transaction(&f).await?;
235                match result {
236                    Ok(data) => match tx.commit().await.map_err(Into::into) {
237                        Ok(()) => {
238                            return Ok(TransactionGuard {
239                                data,
240                                _guard,
241                                _not_send: PhantomData,
242                            });
243                        }
244                        Err(error) => {
245                            if !self.retry_on_serialization_error(&error, i).await {
246                                return Err(error);
247                            }
248                        }
249                    },
250                    Err(error) => {
251                        tx.rollback().await?;
252                        if !self.retry_on_serialization_error(&error, i).await {
253                            return Err(error);
254                        }
255                    }
256                }
257                i += 1;
258            }
259        };
260
261        self.run(body).await
262    }
263
264    /// room_transaction runs the block in a transaction. It returns a RoomGuard, that keeps
265    /// the database locked until it is dropped. This ensures that updates sent to clients are
266    /// properly serialized with respect to database changes.
267    async fn room_transaction<F, Fut, T>(
268        &self,
269        room_id: RoomId,
270        f: F,
271    ) -> Result<TransactionGuard<T>>
272    where
273        F: Send + Fn(TransactionHandle) -> Fut,
274        Fut: Send + Future<Output = Result<T>>,
275    {
276        let body = async {
277            let mut i = 0;
278            loop {
279                let lock = self.rooms.entry(room_id).or_default().clone();
280                let _guard = lock.lock_owned().await;
281                let (tx, result) = self.with_transaction(&f).await?;
282                match result {
283                    Ok(data) => match tx.commit().await.map_err(Into::into) {
284                        Ok(()) => {
285                            return Ok(TransactionGuard {
286                                data,
287                                _guard,
288                                _not_send: PhantomData,
289                            });
290                        }
291                        Err(error) => {
292                            if !self.retry_on_serialization_error(&error, i).await {
293                                return Err(error);
294                            }
295                        }
296                    },
297                    Err(error) => {
298                        tx.rollback().await?;
299                        if !self.retry_on_serialization_error(&error, i).await {
300                            return Err(error);
301                        }
302                    }
303                }
304                i += 1;
305            }
306        };
307
308        self.run(body).await
309    }
310
311    async fn with_transaction<F, Fut, T>(&self, f: &F) -> Result<(DatabaseTransaction, Result<T>)>
312    where
313        F: Send + Fn(TransactionHandle) -> Fut,
314        Fut: Send + Future<Output = Result<T>>,
315    {
316        let tx = self
317            .pool
318            .begin_with_config(Some(IsolationLevel::Serializable), None)
319            .await?;
320
321        let mut tx = Arc::new(Some(tx));
322        let result = f(TransactionHandle(tx.clone())).await;
323        let tx = Arc::get_mut(&mut tx)
324            .and_then(|tx| tx.take())
325            .context("couldn't complete transaction because it's still in use")?;
326
327        Ok((tx, result))
328    }
329
330    async fn with_weak_transaction<F, Fut, T>(
331        &self,
332        f: &F,
333    ) -> Result<(DatabaseTransaction, Result<T>)>
334    where
335        F: Send + Fn(TransactionHandle) -> Fut,
336        Fut: Send + Future<Output = Result<T>>,
337    {
338        let tx = self
339            .pool
340            .begin_with_config(Some(IsolationLevel::ReadCommitted), None)
341            .await?;
342
343        let mut tx = Arc::new(Some(tx));
344        let result = f(TransactionHandle(tx.clone())).await;
345        let tx = Arc::get_mut(&mut tx)
346            .and_then(|tx| tx.take())
347            .context("couldn't complete transaction because it's still in use")?;
348
349        Ok((tx, result))
350    }
351
352    async fn run<F, T>(&self, future: F) -> Result<T>
353    where
354        F: Future<Output = Result<T>>,
355    {
356        #[cfg(test)]
357        {
358            if let Executor::Deterministic(executor) = &self.executor {
359                executor.simulate_random_delay().await;
360            }
361
362            self.runtime.as_ref().unwrap().block_on(future)
363        }
364
365        #[cfg(not(test))]
366        {
367            future.await
368        }
369    }
370
371    async fn retry_on_serialization_error(&self, error: &Error, prev_attempt_count: usize) -> bool {
372        // If the error is due to a failure to serialize concurrent transactions, then retry
373        // this transaction after a delay. With each subsequent retry, double the delay duration.
374        // Also vary the delay randomly in order to ensure different database connections retry
375        // at different times.
376        const SLEEPS: [f32; 10] = [10., 20., 40., 80., 160., 320., 640., 1280., 2560., 5120.];
377        if is_serialization_error(error) && prev_attempt_count < SLEEPS.len() {
378            let base_delay = SLEEPS[prev_attempt_count];
379            let randomized_delay = base_delay * self.rng.lock().await.gen_range(0.5..=2.0);
380            log::warn!(
381                "retrying transaction after serialization error. delay: {} ms.",
382                randomized_delay
383            );
384            self.executor
385                .sleep(Duration::from_millis(randomized_delay as u64))
386                .await;
387            true
388        } else {
389            false
390        }
391    }
392}
393
394fn is_serialization_error(error: &Error) -> bool {
395    const SERIALIZATION_FAILURE_CODE: &str = "40001";
396    match error {
397        Error::Database(
398            DbErr::Exec(sea_orm::RuntimeErr::SqlxError(error))
399            | DbErr::Query(sea_orm::RuntimeErr::SqlxError(error)),
400        ) if error
401            .as_database_error()
402            .and_then(|error| error.code())
403            .as_deref()
404            == Some(SERIALIZATION_FAILURE_CODE) =>
405        {
406            true
407        }
408        _ => false,
409    }
410}
411
412/// A handle to a [`DatabaseTransaction`].
413pub struct TransactionHandle(pub(crate) Arc<Option<DatabaseTransaction>>);
414
415impl Deref for TransactionHandle {
416    type Target = DatabaseTransaction;
417
418    fn deref(&self) -> &Self::Target {
419        self.0.as_ref().as_ref().unwrap()
420    }
421}
422
423/// [`TransactionGuard`] keeps a database transaction alive until it is dropped.
424/// It wraps data that depends on the state of the database and prevents an additional
425/// transaction from starting that would invalidate that data.
426pub struct TransactionGuard<T> {
427    data: T,
428    _guard: OwnedMutexGuard<()>,
429    _not_send: PhantomData<Rc<()>>,
430}
431
432impl<T> Deref for TransactionGuard<T> {
433    type Target = T;
434
435    fn deref(&self) -> &T {
436        &self.data
437    }
438}
439
440impl<T> DerefMut for TransactionGuard<T> {
441    fn deref_mut(&mut self) -> &mut T {
442        &mut self.data
443    }
444}
445
446impl<T> TransactionGuard<T> {
447    /// Returns the inner value of the guard.
448    pub fn into_inner(self) -> T {
449        self.data
450    }
451}
452
453#[derive(Clone, Debug, PartialEq, Eq)]
454pub enum Contact {
455    Accepted { user_id: UserId, busy: bool },
456    Outgoing { user_id: UserId },
457    Incoming { user_id: UserId },
458}
459
460impl Contact {
461    pub fn user_id(&self) -> UserId {
462        match self {
463            Contact::Accepted { user_id, .. } => *user_id,
464            Contact::Outgoing { user_id } => *user_id,
465            Contact::Incoming { user_id, .. } => *user_id,
466        }
467    }
468}
469
470pub type NotificationBatch = Vec<(UserId, proto::Notification)>;
471
472pub struct CreatedChannelMessage {
473    pub message_id: MessageId,
474    pub participant_connection_ids: HashSet<ConnectionId>,
475    pub notifications: NotificationBatch,
476}
477
478pub struct UpdatedChannelMessage {
479    pub message_id: MessageId,
480    pub participant_connection_ids: Vec<ConnectionId>,
481    pub notifications: NotificationBatch,
482    pub reply_to_message_id: Option<MessageId>,
483    pub timestamp: PrimitiveDateTime,
484    pub deleted_mention_notification_ids: Vec<NotificationId>,
485    pub updated_mention_notifications: Vec<rpc::proto::Notification>,
486}
487
488#[derive(Clone, Debug, PartialEq, Eq, FromQueryResult, Serialize, Deserialize)]
489pub struct Invite {
490    pub email_address: String,
491    pub email_confirmation_code: String,
492}
493
494#[derive(Clone, Debug, Deserialize)]
495pub struct NewSignup {
496    pub email_address: String,
497    pub platform_mac: bool,
498    pub platform_windows: bool,
499    pub platform_linux: bool,
500    pub editor_features: Vec<String>,
501    pub programming_languages: Vec<String>,
502    pub device_id: Option<String>,
503    pub added_to_mailing_list: bool,
504    pub created_at: Option<DateTime>,
505}
506
507#[derive(Clone, Debug, PartialEq, Deserialize, Serialize, FromQueryResult)]
508pub struct WaitlistSummary {
509    pub count: i64,
510    pub linux_count: i64,
511    pub mac_count: i64,
512    pub windows_count: i64,
513    pub unknown_count: i64,
514}
515
516/// The parameters to create a new user.
517#[derive(Debug, Serialize, Deserialize)]
518pub struct NewUserParams {
519    pub github_login: String,
520    pub github_user_id: i32,
521}
522
523/// The result of creating a new user.
524#[derive(Debug)]
525pub struct NewUserResult {
526    pub user_id: UserId,
527    pub metrics_id: String,
528    pub inviting_user_id: Option<UserId>,
529    pub signup_device_id: Option<String>,
530}
531
532/// The result of updating a channel membership.
533#[derive(Debug)]
534pub struct MembershipUpdated {
535    pub channel_id: ChannelId,
536    pub new_channels: ChannelsForUser,
537    pub removed_channels: Vec<ChannelId>,
538}
539
540/// The result of setting a member's role.
541#[derive(Debug)]
542
543pub enum SetMemberRoleResult {
544    InviteUpdated(Channel),
545    MembershipUpdated(MembershipUpdated),
546}
547
548/// The result of inviting a member to a channel.
549#[derive(Debug)]
550pub struct InviteMemberResult {
551    pub channel: Channel,
552    pub notifications: NotificationBatch,
553}
554
555#[derive(Debug)]
556pub struct RespondToChannelInvite {
557    pub membership_update: Option<MembershipUpdated>,
558    pub notifications: NotificationBatch,
559}
560
561#[derive(Debug)]
562pub struct RemoveChannelMemberResult {
563    pub membership_update: MembershipUpdated,
564    pub notification_id: Option<NotificationId>,
565}
566
567#[derive(Debug, PartialEq, Eq, Hash)]
568pub struct Channel {
569    pub id: ChannelId,
570    pub name: String,
571    pub visibility: ChannelVisibility,
572    /// parent_path is the channel ids from the root to this one (not including this one)
573    pub parent_path: Vec<ChannelId>,
574}
575
576impl Channel {
577    pub fn from_model(value: channel::Model) -> Self {
578        Channel {
579            id: value.id,
580            visibility: value.visibility,
581            name: value.clone().name,
582            parent_path: value.ancestors().collect(),
583        }
584    }
585
586    pub fn to_proto(&self) -> proto::Channel {
587        proto::Channel {
588            id: self.id.to_proto(),
589            name: self.name.clone(),
590            visibility: self.visibility.into(),
591            parent_path: self.parent_path.iter().map(|c| c.to_proto()).collect(),
592        }
593    }
594}
595
596#[derive(Debug, PartialEq, Eq, Hash)]
597pub struct ChannelMember {
598    pub role: ChannelRole,
599    pub user_id: UserId,
600    pub kind: proto::channel_member::Kind,
601}
602
603impl ChannelMember {
604    pub fn to_proto(&self) -> proto::ChannelMember {
605        proto::ChannelMember {
606            role: self.role.into(),
607            user_id: self.user_id.to_proto(),
608            kind: self.kind.into(),
609        }
610    }
611}
612
613#[derive(Debug, PartialEq)]
614pub struct ChannelsForUser {
615    pub channels: Vec<Channel>,
616    pub channel_memberships: Vec<channel_member::Model>,
617    pub channel_participants: HashMap<ChannelId, Vec<UserId>>,
618    pub invited_channels: Vec<Channel>,
619
620    pub observed_buffer_versions: Vec<proto::ChannelBufferVersion>,
621    pub observed_channel_messages: Vec<proto::ChannelMessageId>,
622    pub latest_buffer_versions: Vec<proto::ChannelBufferVersion>,
623    pub latest_channel_messages: Vec<proto::ChannelMessageId>,
624}
625
626#[derive(Debug)]
627pub struct RejoinedChannelBuffer {
628    pub buffer: proto::RejoinedChannelBuffer,
629    pub old_connection_id: ConnectionId,
630}
631
632#[derive(Clone)]
633pub struct JoinRoom {
634    pub room: proto::Room,
635    pub channel: Option<channel::Model>,
636}
637
638pub struct RejoinedRoom {
639    pub room: proto::Room,
640    pub rejoined_projects: Vec<RejoinedProject>,
641    pub reshared_projects: Vec<ResharedProject>,
642    pub channel: Option<channel::Model>,
643}
644
645pub struct ResharedProject {
646    pub id: ProjectId,
647    pub old_connection_id: ConnectionId,
648    pub collaborators: Vec<ProjectCollaborator>,
649    pub worktrees: Vec<proto::WorktreeMetadata>,
650}
651
652pub struct RejoinedProject {
653    pub id: ProjectId,
654    pub old_connection_id: ConnectionId,
655    pub collaborators: Vec<ProjectCollaborator>,
656    pub worktrees: Vec<RejoinedWorktree>,
657    pub updated_repositories: Vec<proto::UpdateRepository>,
658    pub removed_repositories: Vec<u64>,
659    pub language_servers: Vec<proto::LanguageServer>,
660}
661
662impl RejoinedProject {
663    pub fn to_proto(&self) -> proto::RejoinedProject {
664        proto::RejoinedProject {
665            id: self.id.to_proto(),
666            worktrees: self
667                .worktrees
668                .iter()
669                .map(|worktree| proto::WorktreeMetadata {
670                    id: worktree.id,
671                    root_name: worktree.root_name.clone(),
672                    visible: worktree.visible,
673                    abs_path: worktree.abs_path.clone(),
674                })
675                .collect(),
676            collaborators: self
677                .collaborators
678                .iter()
679                .map(|collaborator| collaborator.to_proto())
680                .collect(),
681            language_servers: self.language_servers.clone(),
682        }
683    }
684}
685
686#[derive(Debug)]
687pub struct RejoinedWorktree {
688    pub id: u64,
689    pub abs_path: String,
690    pub root_name: String,
691    pub visible: bool,
692    pub updated_entries: Vec<proto::Entry>,
693    pub removed_entries: Vec<u64>,
694    pub updated_repositories: Vec<proto::RepositoryEntry>,
695    pub removed_repositories: Vec<u64>,
696    pub diagnostic_summaries: Vec<proto::DiagnosticSummary>,
697    pub settings_files: Vec<WorktreeSettingsFile>,
698    pub scan_id: u64,
699    pub completed_scan_id: u64,
700}
701
702pub struct LeftRoom {
703    pub room: proto::Room,
704    pub channel: Option<channel::Model>,
705    pub left_projects: HashMap<ProjectId, LeftProject>,
706    pub canceled_calls_to_user_ids: Vec<UserId>,
707    pub deleted: bool,
708}
709
710pub struct RefreshedRoom {
711    pub room: proto::Room,
712    pub channel: Option<channel::Model>,
713    pub stale_participant_user_ids: Vec<UserId>,
714    pub canceled_calls_to_user_ids: Vec<UserId>,
715}
716
717pub struct RefreshedChannelBuffer {
718    pub connection_ids: Vec<ConnectionId>,
719    pub collaborators: Vec<proto::Collaborator>,
720}
721
722pub struct Project {
723    pub id: ProjectId,
724    pub role: ChannelRole,
725    pub collaborators: Vec<ProjectCollaborator>,
726    pub worktrees: BTreeMap<u64, Worktree>,
727    pub repositories: Vec<proto::UpdateRepository>,
728    pub language_servers: Vec<proto::LanguageServer>,
729}
730
731pub struct ProjectCollaborator {
732    pub connection_id: ConnectionId,
733    pub user_id: UserId,
734    pub replica_id: ReplicaId,
735    pub is_host: bool,
736}
737
738impl ProjectCollaborator {
739    pub fn to_proto(&self) -> proto::Collaborator {
740        proto::Collaborator {
741            peer_id: Some(self.connection_id.into()),
742            replica_id: self.replica_id.0 as u32,
743            user_id: self.user_id.to_proto(),
744            is_host: self.is_host,
745        }
746    }
747}
748
749#[derive(Debug)]
750pub struct LeftProject {
751    pub id: ProjectId,
752    pub should_unshare: bool,
753    pub connection_ids: Vec<ConnectionId>,
754}
755
756pub struct Worktree {
757    pub id: u64,
758    pub abs_path: String,
759    pub root_name: String,
760    pub visible: bool,
761    pub entries: Vec<proto::Entry>,
762    pub legacy_repository_entries: BTreeMap<u64, proto::RepositoryEntry>,
763    pub diagnostic_summaries: Vec<proto::DiagnosticSummary>,
764    pub settings_files: Vec<WorktreeSettingsFile>,
765    pub scan_id: u64,
766    pub completed_scan_id: u64,
767}
768
769#[derive(Debug)]
770pub struct WorktreeSettingsFile {
771    pub path: String,
772    pub content: String,
773    pub kind: LocalSettingsKind,
774}
775
776pub struct NewExtensionVersion {
777    pub name: String,
778    pub version: semver::Version,
779    pub description: String,
780    pub authors: Vec<String>,
781    pub repository: String,
782    pub schema_version: i32,
783    pub wasm_api_version: Option<String>,
784    pub provides: BTreeSet<ExtensionProvides>,
785    pub published_at: PrimitiveDateTime,
786}
787
788pub struct ExtensionVersionConstraints {
789    pub schema_versions: RangeInclusive<i32>,
790    pub wasm_api_versions: RangeInclusive<SemanticVersion>,
791}
792
793impl LocalSettingsKind {
794    pub fn from_proto(proto_kind: proto::LocalSettingsKind) -> Self {
795        match proto_kind {
796            proto::LocalSettingsKind::Settings => Self::Settings,
797            proto::LocalSettingsKind::Tasks => Self::Tasks,
798            proto::LocalSettingsKind::Editorconfig => Self::Editorconfig,
799            proto::LocalSettingsKind::Debug => Self::Debug,
800        }
801    }
802
803    pub fn to_proto(&self) -> proto::LocalSettingsKind {
804        match self {
805            Self::Settings => proto::LocalSettingsKind::Settings,
806            Self::Tasks => proto::LocalSettingsKind::Tasks,
807            Self::Editorconfig => proto::LocalSettingsKind::Editorconfig,
808            Self::Debug => proto::LocalSettingsKind::Debug,
809        }
810    }
811}
812
813fn db_status_to_proto(
814    entry: project_repository_statuses::Model,
815) -> anyhow::Result<proto::StatusEntry> {
816    use proto::git_file_status::{Tracked, Unmerged, Variant};
817
818    let (simple_status, variant) =
819        match (entry.status_kind, entry.first_status, entry.second_status) {
820            (StatusKind::Untracked, None, None) => (
821                proto::GitStatus::Added as i32,
822                Variant::Untracked(Default::default()),
823            ),
824            (StatusKind::Ignored, None, None) => (
825                proto::GitStatus::Added as i32,
826                Variant::Ignored(Default::default()),
827            ),
828            (StatusKind::Unmerged, Some(first_head), Some(second_head)) => (
829                proto::GitStatus::Conflict as i32,
830                Variant::Unmerged(Unmerged {
831                    first_head,
832                    second_head,
833                }),
834            ),
835            (StatusKind::Tracked, Some(index_status), Some(worktree_status)) => {
836                let simple_status = if worktree_status != proto::GitStatus::Unmodified as i32 {
837                    worktree_status
838                } else if index_status != proto::GitStatus::Unmodified as i32 {
839                    index_status
840                } else {
841                    proto::GitStatus::Unmodified as i32
842                };
843                (
844                    simple_status,
845                    Variant::Tracked(Tracked {
846                        index_status,
847                        worktree_status,
848                    }),
849                )
850            }
851            _ => {
852                anyhow::bail!("Unexpected combination of status fields: {entry:?}");
853            }
854        };
855    Ok(proto::StatusEntry {
856        repo_path: entry.repo_path,
857        simple_status,
858        status: Some(proto::GitFileStatus {
859            variant: Some(variant),
860        }),
861    })
862}
863
864fn proto_status_to_db(
865    status_entry: proto::StatusEntry,
866) -> (String, StatusKind, Option<i32>, Option<i32>) {
867    use proto::git_file_status::{Tracked, Unmerged, Variant};
868
869    let (status_kind, first_status, second_status) = status_entry
870        .status
871        .clone()
872        .and_then(|status| status.variant)
873        .map_or(
874            (StatusKind::Untracked, None, None),
875            |variant| match variant {
876                Variant::Untracked(_) => (StatusKind::Untracked, None, None),
877                Variant::Ignored(_) => (StatusKind::Ignored, None, None),
878                Variant::Unmerged(Unmerged {
879                    first_head,
880                    second_head,
881                }) => (StatusKind::Unmerged, Some(first_head), Some(second_head)),
882                Variant::Tracked(Tracked {
883                    index_status,
884                    worktree_status,
885                }) => (
886                    StatusKind::Tracked,
887                    Some(index_status),
888                    Some(worktree_status),
889                ),
890            },
891        );
892    (
893        status_entry.repo_path,
894        status_kind,
895        first_status,
896        second_status,
897    )
898}