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 pub channel_order: i32,
586}
587
588impl Channel {
589 pub fn from_model(value: channel::Model) -> Self {
590 Channel {
591 id: value.id,
592 visibility: value.visibility,
593 name: value.clone().name,
594 parent_path: value.ancestors().collect(),
595 channel_order: value.channel_order,
596 }
597 }
598
599 pub fn to_proto(&self) -> proto::Channel {
600 proto::Channel {
601 id: self.id.to_proto(),
602 name: self.name.clone(),
603 visibility: self.visibility.into(),
604 parent_path: self.parent_path.iter().map(|c| c.to_proto()).collect(),
605 channel_order: self.channel_order,
606 }
607 }
608
609 pub fn root_id(&self) -> ChannelId {
610 self.parent_path.first().copied().unwrap_or(self.id)
611 }
612}
613
614#[derive(Debug, PartialEq, Eq, Hash)]
615pub struct ChannelMember {
616 pub role: ChannelRole,
617 pub user_id: UserId,
618 pub kind: proto::channel_member::Kind,
619}
620
621impl ChannelMember {
622 pub fn to_proto(&self) -> proto::ChannelMember {
623 proto::ChannelMember {
624 role: self.role.into(),
625 user_id: self.user_id.to_proto(),
626 kind: self.kind.into(),
627 }
628 }
629}
630
631#[derive(Debug, PartialEq)]
632pub struct ChannelsForUser {
633 pub channels: Vec<Channel>,
634 pub channel_memberships: Vec<channel_member::Model>,
635 pub channel_participants: HashMap<ChannelId, Vec<UserId>>,
636 pub invited_channels: Vec<Channel>,
637
638 pub observed_buffer_versions: Vec<proto::ChannelBufferVersion>,
639 pub observed_channel_messages: Vec<proto::ChannelMessageId>,
640 pub latest_buffer_versions: Vec<proto::ChannelBufferVersion>,
641 pub latest_channel_messages: Vec<proto::ChannelMessageId>,
642}
643
644#[derive(Debug)]
645pub struct RejoinedChannelBuffer {
646 pub buffer: proto::RejoinedChannelBuffer,
647 pub old_connection_id: ConnectionId,
648}
649
650#[derive(Clone)]
651pub struct JoinRoom {
652 pub room: proto::Room,
653 pub channel: Option<channel::Model>,
654}
655
656pub struct RejoinedRoom {
657 pub room: proto::Room,
658 pub rejoined_projects: Vec<RejoinedProject>,
659 pub reshared_projects: Vec<ResharedProject>,
660 pub channel: Option<channel::Model>,
661}
662
663pub struct ResharedProject {
664 pub id: ProjectId,
665 pub old_connection_id: ConnectionId,
666 pub collaborators: Vec<ProjectCollaborator>,
667 pub worktrees: Vec<proto::WorktreeMetadata>,
668}
669
670pub struct RejoinedProject {
671 pub id: ProjectId,
672 pub old_connection_id: ConnectionId,
673 pub collaborators: Vec<ProjectCollaborator>,
674 pub worktrees: Vec<RejoinedWorktree>,
675 pub updated_repositories: Vec<proto::UpdateRepository>,
676 pub removed_repositories: Vec<u64>,
677 pub language_servers: Vec<proto::LanguageServer>,
678}
679
680impl RejoinedProject {
681 pub fn to_proto(&self) -> proto::RejoinedProject {
682 proto::RejoinedProject {
683 id: self.id.to_proto(),
684 worktrees: self
685 .worktrees
686 .iter()
687 .map(|worktree| proto::WorktreeMetadata {
688 id: worktree.id,
689 root_name: worktree.root_name.clone(),
690 visible: worktree.visible,
691 abs_path: worktree.abs_path.clone(),
692 })
693 .collect(),
694 collaborators: self
695 .collaborators
696 .iter()
697 .map(|collaborator| collaborator.to_proto())
698 .collect(),
699 language_servers: self.language_servers.clone(),
700 }
701 }
702}
703
704#[derive(Debug)]
705pub struct RejoinedWorktree {
706 pub id: u64,
707 pub abs_path: String,
708 pub root_name: String,
709 pub visible: bool,
710 pub updated_entries: Vec<proto::Entry>,
711 pub removed_entries: Vec<u64>,
712 pub updated_repositories: Vec<proto::RepositoryEntry>,
713 pub removed_repositories: Vec<u64>,
714 pub diagnostic_summaries: Vec<proto::DiagnosticSummary>,
715 pub settings_files: Vec<WorktreeSettingsFile>,
716 pub scan_id: u64,
717 pub completed_scan_id: u64,
718}
719
720pub struct LeftRoom {
721 pub room: proto::Room,
722 pub channel: Option<channel::Model>,
723 pub left_projects: HashMap<ProjectId, LeftProject>,
724 pub canceled_calls_to_user_ids: Vec<UserId>,
725 pub deleted: bool,
726}
727
728pub struct RefreshedRoom {
729 pub room: proto::Room,
730 pub channel: Option<channel::Model>,
731 pub stale_participant_user_ids: Vec<UserId>,
732 pub canceled_calls_to_user_ids: Vec<UserId>,
733}
734
735pub struct RefreshedChannelBuffer {
736 pub connection_ids: Vec<ConnectionId>,
737 pub collaborators: Vec<proto::Collaborator>,
738}
739
740pub struct Project {
741 pub id: ProjectId,
742 pub role: ChannelRole,
743 pub collaborators: Vec<ProjectCollaborator>,
744 pub worktrees: BTreeMap<u64, Worktree>,
745 pub repositories: Vec<proto::UpdateRepository>,
746 pub language_servers: Vec<proto::LanguageServer>,
747}
748
749pub struct ProjectCollaborator {
750 pub connection_id: ConnectionId,
751 pub user_id: UserId,
752 pub replica_id: ReplicaId,
753 pub is_host: bool,
754 pub committer_name: Option<String>,
755 pub committer_email: Option<String>,
756}
757
758impl ProjectCollaborator {
759 pub fn to_proto(&self) -> proto::Collaborator {
760 proto::Collaborator {
761 peer_id: Some(self.connection_id.into()),
762 replica_id: self.replica_id.0 as u32,
763 user_id: self.user_id.to_proto(),
764 is_host: self.is_host,
765 committer_name: self.committer_name.clone(),
766 committer_email: self.committer_email.clone(),
767 }
768 }
769}
770
771#[derive(Debug)]
772pub struct LeftProject {
773 pub id: ProjectId,
774 pub should_unshare: bool,
775 pub connection_ids: Vec<ConnectionId>,
776}
777
778pub struct Worktree {
779 pub id: u64,
780 pub abs_path: String,
781 pub root_name: String,
782 pub visible: bool,
783 pub entries: Vec<proto::Entry>,
784 pub legacy_repository_entries: BTreeMap<u64, proto::RepositoryEntry>,
785 pub diagnostic_summaries: Vec<proto::DiagnosticSummary>,
786 pub settings_files: Vec<WorktreeSettingsFile>,
787 pub scan_id: u64,
788 pub completed_scan_id: u64,
789}
790
791#[derive(Debug)]
792pub struct WorktreeSettingsFile {
793 pub path: String,
794 pub content: String,
795 pub kind: LocalSettingsKind,
796}
797
798pub struct NewExtensionVersion {
799 pub name: String,
800 pub version: semver::Version,
801 pub description: String,
802 pub authors: Vec<String>,
803 pub repository: String,
804 pub schema_version: i32,
805 pub wasm_api_version: Option<String>,
806 pub provides: BTreeSet<ExtensionProvides>,
807 pub published_at: PrimitiveDateTime,
808}
809
810pub struct ExtensionVersionConstraints {
811 pub schema_versions: RangeInclusive<i32>,
812 pub wasm_api_versions: RangeInclusive<SemanticVersion>,
813}
814
815impl LocalSettingsKind {
816 pub fn from_proto(proto_kind: proto::LocalSettingsKind) -> Self {
817 match proto_kind {
818 proto::LocalSettingsKind::Settings => Self::Settings,
819 proto::LocalSettingsKind::Tasks => Self::Tasks,
820 proto::LocalSettingsKind::Editorconfig => Self::Editorconfig,
821 proto::LocalSettingsKind::Debug => Self::Debug,
822 }
823 }
824
825 pub fn to_proto(&self) -> proto::LocalSettingsKind {
826 match self {
827 Self::Settings => proto::LocalSettingsKind::Settings,
828 Self::Tasks => proto::LocalSettingsKind::Tasks,
829 Self::Editorconfig => proto::LocalSettingsKind::Editorconfig,
830 Self::Debug => proto::LocalSettingsKind::Debug,
831 }
832 }
833}
834
835fn db_status_to_proto(
836 entry: project_repository_statuses::Model,
837) -> anyhow::Result<proto::StatusEntry> {
838 use proto::git_file_status::{Tracked, Unmerged, Variant};
839
840 let (simple_status, variant) =
841 match (entry.status_kind, entry.first_status, entry.second_status) {
842 (StatusKind::Untracked, None, None) => (
843 proto::GitStatus::Added as i32,
844 Variant::Untracked(Default::default()),
845 ),
846 (StatusKind::Ignored, None, None) => (
847 proto::GitStatus::Added as i32,
848 Variant::Ignored(Default::default()),
849 ),
850 (StatusKind::Unmerged, Some(first_head), Some(second_head)) => (
851 proto::GitStatus::Conflict as i32,
852 Variant::Unmerged(Unmerged {
853 first_head,
854 second_head,
855 }),
856 ),
857 (StatusKind::Tracked, Some(index_status), Some(worktree_status)) => {
858 let simple_status = if worktree_status != proto::GitStatus::Unmodified as i32 {
859 worktree_status
860 } else if index_status != proto::GitStatus::Unmodified as i32 {
861 index_status
862 } else {
863 proto::GitStatus::Unmodified as i32
864 };
865 (
866 simple_status,
867 Variant::Tracked(Tracked {
868 index_status,
869 worktree_status,
870 }),
871 )
872 }
873 _ => {
874 anyhow::bail!("Unexpected combination of status fields: {entry:?}");
875 }
876 };
877 Ok(proto::StatusEntry {
878 repo_path: entry.repo_path,
879 simple_status,
880 status: Some(proto::GitFileStatus {
881 variant: Some(variant),
882 }),
883 })
884}
885
886fn proto_status_to_db(
887 status_entry: proto::StatusEntry,
888) -> (String, StatusKind, Option<i32>, Option<i32>) {
889 use proto::git_file_status::{Tracked, Unmerged, Variant};
890
891 let (status_kind, first_status, second_status) = status_entry
892 .status
893 .clone()
894 .and_then(|status| status.variant)
895 .map_or(
896 (StatusKind::Untracked, None, None),
897 |variant| match variant {
898 Variant::Untracked(_) => (StatusKind::Untracked, None, None),
899 Variant::Ignored(_) => (StatusKind::Ignored, None, None),
900 Variant::Unmerged(Unmerged {
901 first_head,
902 second_head,
903 }) => (StatusKind::Unmerged, Some(first_head), Some(second_head)),
904 Variant::Tracked(Tracked {
905 index_status,
906 worktree_status,
907 }) => (
908 StatusKind::Tracked,
909 Some(index_status),
910 Some(worktree_status),
911 ),
912 },
913 );
914 (
915 status_entry.repo_path,
916 status_kind,
917 first_status,
918 second_status,
919 )
920}