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