db.rs

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