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