db.rs

  1mod ids;
  2mod queries;
  3mod tables;
  4#[cfg(test)]
  5pub mod tests;
  6
  7use crate::{Error, Result, executor::Executor};
  8use anyhow::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 Some(tx) = Arc::get_mut(&mut tx).and_then(|tx| tx.take()) else {
324            return Err(anyhow!(
325                "couldn't complete transaction because it's still in use"
326            ))?;
327        };
328
329        Ok((tx, result))
330    }
331
332    async fn with_weak_transaction<F, Fut, T>(
333        &self,
334        f: &F,
335    ) -> Result<(DatabaseTransaction, Result<T>)>
336    where
337        F: Send + Fn(TransactionHandle) -> Fut,
338        Fut: Send + Future<Output = Result<T>>,
339    {
340        let tx = self
341            .pool
342            .begin_with_config(Some(IsolationLevel::ReadCommitted), None)
343            .await?;
344
345        let mut tx = Arc::new(Some(tx));
346        let result = f(TransactionHandle(tx.clone())).await;
347        let Some(tx) = Arc::get_mut(&mut tx).and_then(|tx| tx.take()) else {
348            return Err(anyhow!(
349                "couldn't complete transaction because it's still in use"
350            ))?;
351        };
352
353        Ok((tx, result))
354    }
355
356    async fn run<F, T>(&self, future: F) -> Result<T>
357    where
358        F: Future<Output = Result<T>>,
359    {
360        #[cfg(test)]
361        {
362            if let Executor::Deterministic(executor) = &self.executor {
363                executor.simulate_random_delay().await;
364            }
365
366            self.runtime.as_ref().unwrap().block_on(future)
367        }
368
369        #[cfg(not(test))]
370        {
371            future.await
372        }
373    }
374
375    async fn retry_on_serialization_error(&self, error: &Error, prev_attempt_count: usize) -> bool {
376        // If the error is due to a failure to serialize concurrent transactions, then retry
377        // this transaction after a delay. With each subsequent retry, double the delay duration.
378        // Also vary the delay randomly in order to ensure different database connections retry
379        // at different times.
380        const SLEEPS: [f32; 10] = [10., 20., 40., 80., 160., 320., 640., 1280., 2560., 5120.];
381        if is_serialization_error(error) && prev_attempt_count < SLEEPS.len() {
382            let base_delay = SLEEPS[prev_attempt_count];
383            let randomized_delay = base_delay * self.rng.lock().await.gen_range(0.5..=2.0);
384            log::warn!(
385                "retrying transaction after serialization error. delay: {} ms.",
386                randomized_delay
387            );
388            self.executor
389                .sleep(Duration::from_millis(randomized_delay as u64))
390                .await;
391            true
392        } else {
393            false
394        }
395    }
396}
397
398fn is_serialization_error(error: &Error) -> bool {
399    const SERIALIZATION_FAILURE_CODE: &str = "40001";
400    match error {
401        Error::Database(
402            DbErr::Exec(sea_orm::RuntimeErr::SqlxError(error))
403            | DbErr::Query(sea_orm::RuntimeErr::SqlxError(error)),
404        ) if error
405            .as_database_error()
406            .and_then(|error| error.code())
407            .as_deref()
408            == Some(SERIALIZATION_FAILURE_CODE) =>
409        {
410            true
411        }
412        _ => false,
413    }
414}
415
416/// A handle to a [`DatabaseTransaction`].
417pub struct TransactionHandle(pub(crate) Arc<Option<DatabaseTransaction>>);
418
419impl Deref for TransactionHandle {
420    type Target = DatabaseTransaction;
421
422    fn deref(&self) -> &Self::Target {
423        self.0.as_ref().as_ref().unwrap()
424    }
425}
426
427/// [`TransactionGuard`] keeps a database transaction alive until it is dropped.
428/// It wraps data that depends on the state of the database and prevents an additional
429/// transaction from starting that would invalidate that data.
430pub struct TransactionGuard<T> {
431    data: T,
432    _guard: OwnedMutexGuard<()>,
433    _not_send: PhantomData<Rc<()>>,
434}
435
436impl<T> Deref for TransactionGuard<T> {
437    type Target = T;
438
439    fn deref(&self) -> &T {
440        &self.data
441    }
442}
443
444impl<T> DerefMut for TransactionGuard<T> {
445    fn deref_mut(&mut self) -> &mut T {
446        &mut self.data
447    }
448}
449
450impl<T> TransactionGuard<T> {
451    /// Returns the inner value of the guard.
452    pub fn into_inner(self) -> T {
453        self.data
454    }
455}
456
457#[derive(Clone, Debug, PartialEq, Eq)]
458pub enum Contact {
459    Accepted { user_id: UserId, busy: bool },
460    Outgoing { user_id: UserId },
461    Incoming { user_id: UserId },
462}
463
464impl Contact {
465    pub fn user_id(&self) -> UserId {
466        match self {
467            Contact::Accepted { user_id, .. } => *user_id,
468            Contact::Outgoing { user_id } => *user_id,
469            Contact::Incoming { user_id, .. } => *user_id,
470        }
471    }
472}
473
474pub type NotificationBatch = Vec<(UserId, proto::Notification)>;
475
476pub struct CreatedChannelMessage {
477    pub message_id: MessageId,
478    pub participant_connection_ids: HashSet<ConnectionId>,
479    pub notifications: NotificationBatch,
480}
481
482pub struct UpdatedChannelMessage {
483    pub message_id: MessageId,
484    pub participant_connection_ids: Vec<ConnectionId>,
485    pub notifications: NotificationBatch,
486    pub reply_to_message_id: Option<MessageId>,
487    pub timestamp: PrimitiveDateTime,
488    pub deleted_mention_notification_ids: Vec<NotificationId>,
489    pub updated_mention_notifications: Vec<rpc::proto::Notification>,
490}
491
492#[derive(Clone, Debug, PartialEq, Eq, FromQueryResult, Serialize, Deserialize)]
493pub struct Invite {
494    pub email_address: String,
495    pub email_confirmation_code: String,
496}
497
498#[derive(Clone, Debug, Deserialize)]
499pub struct NewSignup {
500    pub email_address: String,
501    pub platform_mac: bool,
502    pub platform_windows: bool,
503    pub platform_linux: bool,
504    pub editor_features: Vec<String>,
505    pub programming_languages: Vec<String>,
506    pub device_id: Option<String>,
507    pub added_to_mailing_list: bool,
508    pub created_at: Option<DateTime>,
509}
510
511#[derive(Clone, Debug, PartialEq, Deserialize, Serialize, FromQueryResult)]
512pub struct WaitlistSummary {
513    pub count: i64,
514    pub linux_count: i64,
515    pub mac_count: i64,
516    pub windows_count: i64,
517    pub unknown_count: i64,
518}
519
520/// The parameters to create a new user.
521#[derive(Debug, Serialize, Deserialize)]
522pub struct NewUserParams {
523    pub github_login: String,
524    pub github_user_id: i32,
525}
526
527/// The result of creating a new user.
528#[derive(Debug)]
529pub struct NewUserResult {
530    pub user_id: UserId,
531    pub metrics_id: String,
532    pub inviting_user_id: Option<UserId>,
533    pub signup_device_id: Option<String>,
534}
535
536/// The result of updating a channel membership.
537#[derive(Debug)]
538pub struct MembershipUpdated {
539    pub channel_id: ChannelId,
540    pub new_channels: ChannelsForUser,
541    pub removed_channels: Vec<ChannelId>,
542}
543
544/// The result of setting a member's role.
545#[derive(Debug)]
546
547pub enum SetMemberRoleResult {
548    InviteUpdated(Channel),
549    MembershipUpdated(MembershipUpdated),
550}
551
552/// The result of inviting a member to a channel.
553#[derive(Debug)]
554pub struct InviteMemberResult {
555    pub channel: Channel,
556    pub notifications: NotificationBatch,
557}
558
559#[derive(Debug)]
560pub struct RespondToChannelInvite {
561    pub membership_update: Option<MembershipUpdated>,
562    pub notifications: NotificationBatch,
563}
564
565#[derive(Debug)]
566pub struct RemoveChannelMemberResult {
567    pub membership_update: MembershipUpdated,
568    pub notification_id: Option<NotificationId>,
569}
570
571#[derive(Debug, PartialEq, Eq, Hash)]
572pub struct Channel {
573    pub id: ChannelId,
574    pub name: String,
575    pub visibility: ChannelVisibility,
576    /// parent_path is the channel ids from the root to this one (not including this one)
577    pub parent_path: Vec<ChannelId>,
578}
579
580impl Channel {
581    pub fn from_model(value: channel::Model) -> Self {
582        Channel {
583            id: value.id,
584            visibility: value.visibility,
585            name: value.clone().name,
586            parent_path: value.ancestors().collect(),
587        }
588    }
589
590    pub fn to_proto(&self) -> proto::Channel {
591        proto::Channel {
592            id: self.id.to_proto(),
593            name: self.name.clone(),
594            visibility: self.visibility.into(),
595            parent_path: self.parent_path.iter().map(|c| c.to_proto()).collect(),
596        }
597    }
598}
599
600#[derive(Debug, PartialEq, Eq, Hash)]
601pub struct ChannelMember {
602    pub role: ChannelRole,
603    pub user_id: UserId,
604    pub kind: proto::channel_member::Kind,
605}
606
607impl ChannelMember {
608    pub fn to_proto(&self) -> proto::ChannelMember {
609        proto::ChannelMember {
610            role: self.role.into(),
611            user_id: self.user_id.to_proto(),
612            kind: self.kind.into(),
613        }
614    }
615}
616
617#[derive(Debug, PartialEq)]
618pub struct ChannelsForUser {
619    pub channels: Vec<Channel>,
620    pub channel_memberships: Vec<channel_member::Model>,
621    pub channel_participants: HashMap<ChannelId, Vec<UserId>>,
622    pub invited_channels: Vec<Channel>,
623
624    pub observed_buffer_versions: Vec<proto::ChannelBufferVersion>,
625    pub observed_channel_messages: Vec<proto::ChannelMessageId>,
626    pub latest_buffer_versions: Vec<proto::ChannelBufferVersion>,
627    pub latest_channel_messages: Vec<proto::ChannelMessageId>,
628}
629
630#[derive(Debug)]
631pub struct RejoinedChannelBuffer {
632    pub buffer: proto::RejoinedChannelBuffer,
633    pub old_connection_id: ConnectionId,
634}
635
636#[derive(Clone)]
637pub struct JoinRoom {
638    pub room: proto::Room,
639    pub channel: Option<channel::Model>,
640}
641
642pub struct RejoinedRoom {
643    pub room: proto::Room,
644    pub rejoined_projects: Vec<RejoinedProject>,
645    pub reshared_projects: Vec<ResharedProject>,
646    pub channel: Option<channel::Model>,
647}
648
649pub struct ResharedProject {
650    pub id: ProjectId,
651    pub old_connection_id: ConnectionId,
652    pub collaborators: Vec<ProjectCollaborator>,
653    pub worktrees: Vec<proto::WorktreeMetadata>,
654}
655
656pub struct RejoinedProject {
657    pub id: ProjectId,
658    pub old_connection_id: ConnectionId,
659    pub collaborators: Vec<ProjectCollaborator>,
660    pub worktrees: Vec<RejoinedWorktree>,
661    pub updated_repositories: Vec<proto::UpdateRepository>,
662    pub removed_repositories: Vec<u64>,
663    pub language_servers: Vec<proto::LanguageServer>,
664}
665
666impl RejoinedProject {
667    pub fn to_proto(&self) -> proto::RejoinedProject {
668        proto::RejoinedProject {
669            id: self.id.to_proto(),
670            worktrees: self
671                .worktrees
672                .iter()
673                .map(|worktree| proto::WorktreeMetadata {
674                    id: worktree.id,
675                    root_name: worktree.root_name.clone(),
676                    visible: worktree.visible,
677                    abs_path: worktree.abs_path.clone(),
678                })
679                .collect(),
680            collaborators: self
681                .collaborators
682                .iter()
683                .map(|collaborator| collaborator.to_proto())
684                .collect(),
685            language_servers: self.language_servers.clone(),
686        }
687    }
688}
689
690#[derive(Debug)]
691pub struct RejoinedWorktree {
692    pub id: u64,
693    pub abs_path: String,
694    pub root_name: String,
695    pub visible: bool,
696    pub updated_entries: Vec<proto::Entry>,
697    pub removed_entries: Vec<u64>,
698    pub updated_repositories: Vec<proto::RepositoryEntry>,
699    pub removed_repositories: Vec<u64>,
700    pub diagnostic_summaries: Vec<proto::DiagnosticSummary>,
701    pub settings_files: Vec<WorktreeSettingsFile>,
702    pub scan_id: u64,
703    pub completed_scan_id: u64,
704}
705
706pub struct LeftRoom {
707    pub room: proto::Room,
708    pub channel: Option<channel::Model>,
709    pub left_projects: HashMap<ProjectId, LeftProject>,
710    pub canceled_calls_to_user_ids: Vec<UserId>,
711    pub deleted: bool,
712}
713
714pub struct RefreshedRoom {
715    pub room: proto::Room,
716    pub channel: Option<channel::Model>,
717    pub stale_participant_user_ids: Vec<UserId>,
718    pub canceled_calls_to_user_ids: Vec<UserId>,
719}
720
721pub struct RefreshedChannelBuffer {
722    pub connection_ids: Vec<ConnectionId>,
723    pub collaborators: Vec<proto::Collaborator>,
724}
725
726pub struct Project {
727    pub id: ProjectId,
728    pub role: ChannelRole,
729    pub collaborators: Vec<ProjectCollaborator>,
730    pub worktrees: BTreeMap<u64, Worktree>,
731    pub repositories: Vec<proto::UpdateRepository>,
732    pub language_servers: Vec<proto::LanguageServer>,
733}
734
735pub struct ProjectCollaborator {
736    pub connection_id: ConnectionId,
737    pub user_id: UserId,
738    pub replica_id: ReplicaId,
739    pub is_host: bool,
740}
741
742impl ProjectCollaborator {
743    pub fn to_proto(&self) -> proto::Collaborator {
744        proto::Collaborator {
745            peer_id: Some(self.connection_id.into()),
746            replica_id: self.replica_id.0 as u32,
747            user_id: self.user_id.to_proto(),
748            is_host: self.is_host,
749        }
750    }
751}
752
753#[derive(Debug)]
754pub struct LeftProject {
755    pub id: ProjectId,
756    pub should_unshare: bool,
757    pub connection_ids: Vec<ConnectionId>,
758}
759
760pub struct Worktree {
761    pub id: u64,
762    pub abs_path: String,
763    pub root_name: String,
764    pub visible: bool,
765    pub entries: Vec<proto::Entry>,
766    pub legacy_repository_entries: BTreeMap<u64, proto::RepositoryEntry>,
767    pub diagnostic_summaries: Vec<proto::DiagnosticSummary>,
768    pub settings_files: Vec<WorktreeSettingsFile>,
769    pub scan_id: u64,
770    pub completed_scan_id: u64,
771}
772
773#[derive(Debug)]
774pub struct WorktreeSettingsFile {
775    pub path: String,
776    pub content: String,
777    pub kind: LocalSettingsKind,
778}
779
780pub struct NewExtensionVersion {
781    pub name: String,
782    pub version: semver::Version,
783    pub description: String,
784    pub authors: Vec<String>,
785    pub repository: String,
786    pub schema_version: i32,
787    pub wasm_api_version: Option<String>,
788    pub provides: BTreeSet<ExtensionProvides>,
789    pub published_at: PrimitiveDateTime,
790}
791
792pub struct ExtensionVersionConstraints {
793    pub schema_versions: RangeInclusive<i32>,
794    pub wasm_api_versions: RangeInclusive<SemanticVersion>,
795}
796
797impl LocalSettingsKind {
798    pub fn from_proto(proto_kind: proto::LocalSettingsKind) -> Self {
799        match proto_kind {
800            proto::LocalSettingsKind::Settings => Self::Settings,
801            proto::LocalSettingsKind::Tasks => Self::Tasks,
802            proto::LocalSettingsKind::Editorconfig => Self::Editorconfig,
803            proto::LocalSettingsKind::Debug => Self::Debug,
804        }
805    }
806
807    pub fn to_proto(&self) -> proto::LocalSettingsKind {
808        match self {
809            Self::Settings => proto::LocalSettingsKind::Settings,
810            Self::Tasks => proto::LocalSettingsKind::Tasks,
811            Self::Editorconfig => proto::LocalSettingsKind::Editorconfig,
812            Self::Debug => proto::LocalSettingsKind::Debug,
813        }
814    }
815}
816
817fn db_status_to_proto(
818    entry: project_repository_statuses::Model,
819) -> anyhow::Result<proto::StatusEntry> {
820    use proto::git_file_status::{Tracked, Unmerged, Variant};
821
822    let (simple_status, variant) =
823        match (entry.status_kind, entry.first_status, entry.second_status) {
824            (StatusKind::Untracked, None, None) => (
825                proto::GitStatus::Added as i32,
826                Variant::Untracked(Default::default()),
827            ),
828            (StatusKind::Ignored, None, None) => (
829                proto::GitStatus::Added as i32,
830                Variant::Ignored(Default::default()),
831            ),
832            (StatusKind::Unmerged, Some(first_head), Some(second_head)) => (
833                proto::GitStatus::Conflict as i32,
834                Variant::Unmerged(Unmerged {
835                    first_head,
836                    second_head,
837                }),
838            ),
839            (StatusKind::Tracked, Some(index_status), Some(worktree_status)) => {
840                let simple_status = if worktree_status != proto::GitStatus::Unmodified as i32 {
841                    worktree_status
842                } else if index_status != proto::GitStatus::Unmodified as i32 {
843                    index_status
844                } else {
845                    proto::GitStatus::Unmodified as i32
846                };
847                (
848                    simple_status,
849                    Variant::Tracked(Tracked {
850                        index_status,
851                        worktree_status,
852                    }),
853                )
854            }
855            _ => {
856                return Err(anyhow!(
857                    "Unexpected combination of status fields: {entry:?}"
858                ));
859            }
860        };
861    Ok(proto::StatusEntry {
862        repo_path: entry.repo_path,
863        simple_status,
864        status: Some(proto::GitFileStatus {
865            variant: Some(variant),
866        }),
867    })
868}
869
870fn proto_status_to_db(
871    status_entry: proto::StatusEntry,
872) -> (String, StatusKind, Option<i32>, Option<i32>) {
873    use proto::git_file_status::{Tracked, Unmerged, Variant};
874
875    let (status_kind, first_status, second_status) = status_entry
876        .status
877        .clone()
878        .and_then(|status| status.variant)
879        .map_or(
880            (StatusKind::Untracked, None, None),
881            |variant| match variant {
882                Variant::Untracked(_) => (StatusKind::Untracked, None, None),
883                Variant::Ignored(_) => (StatusKind::Ignored, None, None),
884                Variant::Unmerged(Unmerged {
885                    first_head,
886                    second_head,
887                }) => (StatusKind::Unmerged, Some(first_head), Some(second_head)),
888                Variant::Tracked(Tracked {
889                    index_status,
890                    worktree_status,
891                }) => (
892                    StatusKind::Tracked,
893                    Some(index_status),
894                    Some(worktree_status),
895                ),
896            },
897        );
898    (
899        status_entry.repo_path,
900        status_kind,
901        first_status,
902        second_status,
903    )
904}