1mod access_token;
2mod contact;
3mod language_server;
4mod project;
5mod project_collaborator;
6mod room;
7mod room_participant;
8mod server;
9mod signup;
10#[cfg(test)]
11mod tests;
12mod user;
13mod worktree;
14mod worktree_diagnostic_summary;
15mod worktree_entry;
16
17use crate::{Error, Result};
18use anyhow::anyhow;
19use collections::{BTreeMap, HashMap, HashSet};
20pub use contact::Contact;
21use dashmap::DashMap;
22use futures::StreamExt;
23use hyper::StatusCode;
24use rpc::{proto, ConnectionId};
25use sea_orm::Condition;
26pub use sea_orm::ConnectOptions;
27use sea_orm::{
28 entity::prelude::*, ActiveValue, ConnectionTrait, DatabaseConnection, DatabaseTransaction,
29 DbErr, FromQueryResult, IntoActiveModel, IsolationLevel, JoinType, QueryOrder, QuerySelect,
30 Statement, TransactionTrait,
31};
32use sea_query::{Alias, Expr, OnConflict, Query};
33use serde::{Deserialize, Serialize};
34pub use signup::{Invite, NewSignup, WaitlistSummary};
35use sqlx::migrate::{Migrate, Migration, MigrationSource};
36use sqlx::Connection;
37use std::ops::{Deref, DerefMut};
38use std::path::Path;
39use std::time::Duration;
40use std::{future::Future, marker::PhantomData, rc::Rc, sync::Arc};
41use tokio::sync::{Mutex, OwnedMutexGuard};
42pub use user::Model as User;
43
44pub struct Database {
45 options: ConnectOptions,
46 pool: DatabaseConnection,
47 rooms: DashMap<RoomId, Arc<Mutex<()>>>,
48 #[cfg(test)]
49 background: Option<std::sync::Arc<gpui::executor::Background>>,
50 #[cfg(test)]
51 runtime: Option<tokio::runtime::Runtime>,
52}
53
54impl Database {
55 pub async fn new(options: ConnectOptions) -> Result<Self> {
56 Ok(Self {
57 options: options.clone(),
58 pool: sea_orm::Database::connect(options).await?,
59 rooms: DashMap::with_capacity(16384),
60 #[cfg(test)]
61 background: None,
62 #[cfg(test)]
63 runtime: None,
64 })
65 }
66
67 #[cfg(test)]
68 pub fn reset(&self) {
69 self.rooms.clear();
70 }
71
72 pub async fn migrate(
73 &self,
74 migrations_path: &Path,
75 ignore_checksum_mismatch: bool,
76 ) -> anyhow::Result<Vec<(Migration, Duration)>> {
77 let migrations = MigrationSource::resolve(migrations_path)
78 .await
79 .map_err(|err| anyhow!("failed to load migrations: {err:?}"))?;
80
81 let mut connection = sqlx::AnyConnection::connect(self.options.get_url()).await?;
82
83 connection.ensure_migrations_table().await?;
84 let applied_migrations: HashMap<_, _> = connection
85 .list_applied_migrations()
86 .await?
87 .into_iter()
88 .map(|m| (m.version, m))
89 .collect();
90
91 let mut new_migrations = Vec::new();
92 for migration in migrations {
93 match applied_migrations.get(&migration.version) {
94 Some(applied_migration) => {
95 if migration.checksum != applied_migration.checksum && !ignore_checksum_mismatch
96 {
97 Err(anyhow!(
98 "checksum mismatch for applied migration {}",
99 migration.description
100 ))?;
101 }
102 }
103 None => {
104 let elapsed = connection.apply(&migration).await?;
105 new_migrations.push((migration, elapsed));
106 }
107 }
108 }
109
110 Ok(new_migrations)
111 }
112
113 pub async fn create_server(&self, environment: &str) -> Result<ServerId> {
114 self.transaction(|tx| async move {
115 let server = server::ActiveModel {
116 environment: ActiveValue::set(environment.into()),
117 ..Default::default()
118 }
119 .insert(&*tx)
120 .await?;
121 Ok(server.id)
122 })
123 .await
124 }
125
126 pub async fn stale_room_ids(
127 &self,
128 environment: &str,
129 new_server_id: ServerId,
130 ) -> Result<Vec<RoomId>> {
131 self.transaction(|tx| async move {
132 #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
133 enum QueryAs {
134 RoomId,
135 }
136
137 let stale_server_epochs = self
138 .stale_server_ids(environment, new_server_id, &tx)
139 .await?;
140 Ok(room_participant::Entity::find()
141 .select_only()
142 .column(room_participant::Column::RoomId)
143 .distinct()
144 .filter(
145 room_participant::Column::AnsweringConnectionServerId
146 .is_in(stale_server_epochs),
147 )
148 .into_values::<_, QueryAs>()
149 .all(&*tx)
150 .await?)
151 })
152 .await
153 }
154
155 pub async fn refresh_room(
156 &self,
157 room_id: RoomId,
158 new_server_id: ServerId,
159 ) -> Result<RoomGuard<RefreshedRoom>> {
160 self.room_transaction(|tx| async move {
161 let stale_participant_filter = Condition::all()
162 .add(room_participant::Column::RoomId.eq(room_id))
163 .add(room_participant::Column::AnsweringConnectionId.is_not_null())
164 .add(room_participant::Column::AnsweringConnectionServerId.ne(new_server_id));
165
166 let stale_participant_user_ids = room_participant::Entity::find()
167 .filter(stale_participant_filter.clone())
168 .all(&*tx)
169 .await?
170 .into_iter()
171 .map(|participant| participant.user_id)
172 .collect::<Vec<_>>();
173
174 // Delete participants who failed to reconnect.
175 room_participant::Entity::delete_many()
176 .filter(stale_participant_filter)
177 .exec(&*tx)
178 .await?;
179
180 let room = self.get_room(room_id, &tx).await?;
181 let mut canceled_calls_to_user_ids = Vec::new();
182 // Delete the room if it becomes empty and cancel pending calls.
183 if room.participants.is_empty() {
184 canceled_calls_to_user_ids.extend(
185 room.pending_participants
186 .iter()
187 .map(|pending_participant| UserId::from_proto(pending_participant.user_id)),
188 );
189 room_participant::Entity::delete_many()
190 .filter(room_participant::Column::RoomId.eq(room_id))
191 .exec(&*tx)
192 .await?;
193 room::Entity::delete_by_id(room_id).exec(&*tx).await?;
194 }
195
196 Ok((
197 room_id,
198 RefreshedRoom {
199 room,
200 stale_participant_user_ids,
201 canceled_calls_to_user_ids,
202 },
203 ))
204 })
205 .await
206 }
207
208 pub async fn delete_stale_servers(
209 &self,
210 environment: &str,
211 new_server_id: ServerId,
212 ) -> Result<()> {
213 self.transaction(|tx| async move {
214 server::Entity::delete_many()
215 .filter(
216 Condition::all()
217 .add(server::Column::Environment.eq(environment))
218 .add(server::Column::Id.ne(new_server_id)),
219 )
220 .exec(&*tx)
221 .await?;
222 Ok(())
223 })
224 .await
225 }
226
227 async fn stale_server_ids(
228 &self,
229 environment: &str,
230 new_server_id: ServerId,
231 tx: &DatabaseTransaction,
232 ) -> Result<Vec<ServerId>> {
233 let stale_servers = server::Entity::find()
234 .filter(
235 Condition::all()
236 .add(server::Column::Environment.eq(environment))
237 .add(server::Column::Id.ne(new_server_id)),
238 )
239 .all(&*tx)
240 .await?;
241 Ok(stale_servers.into_iter().map(|server| server.id).collect())
242 }
243
244 // users
245
246 pub async fn create_user(
247 &self,
248 email_address: &str,
249 admin: bool,
250 params: NewUserParams,
251 ) -> Result<NewUserResult> {
252 self.transaction(|tx| async {
253 let tx = tx;
254 let user = user::Entity::insert(user::ActiveModel {
255 email_address: ActiveValue::set(Some(email_address.into())),
256 github_login: ActiveValue::set(params.github_login.clone()),
257 github_user_id: ActiveValue::set(Some(params.github_user_id)),
258 admin: ActiveValue::set(admin),
259 metrics_id: ActiveValue::set(Uuid::new_v4()),
260 ..Default::default()
261 })
262 .on_conflict(
263 OnConflict::column(user::Column::GithubLogin)
264 .update_column(user::Column::GithubLogin)
265 .to_owned(),
266 )
267 .exec_with_returning(&*tx)
268 .await?;
269
270 Ok(NewUserResult {
271 user_id: user.id,
272 metrics_id: user.metrics_id.to_string(),
273 signup_device_id: None,
274 inviting_user_id: None,
275 })
276 })
277 .await
278 }
279
280 pub async fn get_user_by_id(&self, id: UserId) -> Result<Option<user::Model>> {
281 self.transaction(|tx| async move { Ok(user::Entity::find_by_id(id).one(&*tx).await?) })
282 .await
283 }
284
285 pub async fn get_users_by_ids(&self, ids: Vec<UserId>) -> Result<Vec<user::Model>> {
286 self.transaction(|tx| async {
287 let tx = tx;
288 Ok(user::Entity::find()
289 .filter(user::Column::Id.is_in(ids.iter().copied()))
290 .all(&*tx)
291 .await?)
292 })
293 .await
294 }
295
296 pub async fn get_user_by_github_account(
297 &self,
298 github_login: &str,
299 github_user_id: Option<i32>,
300 ) -> Result<Option<User>> {
301 self.transaction(|tx| async move {
302 let tx = &*tx;
303 if let Some(github_user_id) = github_user_id {
304 if let Some(user_by_github_user_id) = user::Entity::find()
305 .filter(user::Column::GithubUserId.eq(github_user_id))
306 .one(tx)
307 .await?
308 {
309 let mut user_by_github_user_id = user_by_github_user_id.into_active_model();
310 user_by_github_user_id.github_login = ActiveValue::set(github_login.into());
311 Ok(Some(user_by_github_user_id.update(tx).await?))
312 } else if let Some(user_by_github_login) = user::Entity::find()
313 .filter(user::Column::GithubLogin.eq(github_login))
314 .one(tx)
315 .await?
316 {
317 let mut user_by_github_login = user_by_github_login.into_active_model();
318 user_by_github_login.github_user_id = ActiveValue::set(Some(github_user_id));
319 Ok(Some(user_by_github_login.update(tx).await?))
320 } else {
321 Ok(None)
322 }
323 } else {
324 Ok(user::Entity::find()
325 .filter(user::Column::GithubLogin.eq(github_login))
326 .one(tx)
327 .await?)
328 }
329 })
330 .await
331 }
332
333 pub async fn get_all_users(&self, page: u32, limit: u32) -> Result<Vec<User>> {
334 self.transaction(|tx| async move {
335 Ok(user::Entity::find()
336 .order_by_asc(user::Column::GithubLogin)
337 .limit(limit as u64)
338 .offset(page as u64 * limit as u64)
339 .all(&*tx)
340 .await?)
341 })
342 .await
343 }
344
345 pub async fn get_users_with_no_invites(
346 &self,
347 invited_by_another_user: bool,
348 ) -> Result<Vec<User>> {
349 self.transaction(|tx| async move {
350 Ok(user::Entity::find()
351 .filter(
352 user::Column::InviteCount
353 .eq(0)
354 .and(if invited_by_another_user {
355 user::Column::InviterId.is_not_null()
356 } else {
357 user::Column::InviterId.is_null()
358 }),
359 )
360 .all(&*tx)
361 .await?)
362 })
363 .await
364 }
365
366 pub async fn get_user_metrics_id(&self, id: UserId) -> Result<String> {
367 #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
368 enum QueryAs {
369 MetricsId,
370 }
371
372 self.transaction(|tx| async move {
373 let metrics_id: Uuid = user::Entity::find_by_id(id)
374 .select_only()
375 .column(user::Column::MetricsId)
376 .into_values::<_, QueryAs>()
377 .one(&*tx)
378 .await?
379 .ok_or_else(|| anyhow!("could not find user"))?;
380 Ok(metrics_id.to_string())
381 })
382 .await
383 }
384
385 pub async fn set_user_is_admin(&self, id: UserId, is_admin: bool) -> Result<()> {
386 self.transaction(|tx| async move {
387 user::Entity::update_many()
388 .filter(user::Column::Id.eq(id))
389 .set(user::ActiveModel {
390 admin: ActiveValue::set(is_admin),
391 ..Default::default()
392 })
393 .exec(&*tx)
394 .await?;
395 Ok(())
396 })
397 .await
398 }
399
400 pub async fn set_user_connected_once(&self, id: UserId, connected_once: bool) -> Result<()> {
401 self.transaction(|tx| async move {
402 user::Entity::update_many()
403 .filter(user::Column::Id.eq(id))
404 .set(user::ActiveModel {
405 connected_once: ActiveValue::set(connected_once),
406 ..Default::default()
407 })
408 .exec(&*tx)
409 .await?;
410 Ok(())
411 })
412 .await
413 }
414
415 pub async fn destroy_user(&self, id: UserId) -> Result<()> {
416 self.transaction(|tx| async move {
417 access_token::Entity::delete_many()
418 .filter(access_token::Column::UserId.eq(id))
419 .exec(&*tx)
420 .await?;
421 user::Entity::delete_by_id(id).exec(&*tx).await?;
422 Ok(())
423 })
424 .await
425 }
426
427 // contacts
428
429 pub async fn get_contacts(&self, user_id: UserId) -> Result<Vec<Contact>> {
430 #[derive(Debug, FromQueryResult)]
431 struct ContactWithUserBusyStatuses {
432 user_id_a: UserId,
433 user_id_b: UserId,
434 a_to_b: bool,
435 accepted: bool,
436 should_notify: bool,
437 user_a_busy: bool,
438 user_b_busy: bool,
439 }
440
441 self.transaction(|tx| async move {
442 let user_a_participant = Alias::new("user_a_participant");
443 let user_b_participant = Alias::new("user_b_participant");
444 let mut db_contacts = contact::Entity::find()
445 .column_as(
446 Expr::tbl(user_a_participant.clone(), room_participant::Column::Id)
447 .is_not_null(),
448 "user_a_busy",
449 )
450 .column_as(
451 Expr::tbl(user_b_participant.clone(), room_participant::Column::Id)
452 .is_not_null(),
453 "user_b_busy",
454 )
455 .filter(
456 contact::Column::UserIdA
457 .eq(user_id)
458 .or(contact::Column::UserIdB.eq(user_id)),
459 )
460 .join_as(
461 JoinType::LeftJoin,
462 contact::Relation::UserARoomParticipant.def(),
463 user_a_participant,
464 )
465 .join_as(
466 JoinType::LeftJoin,
467 contact::Relation::UserBRoomParticipant.def(),
468 user_b_participant,
469 )
470 .into_model::<ContactWithUserBusyStatuses>()
471 .stream(&*tx)
472 .await?;
473
474 let mut contacts = Vec::new();
475 while let Some(db_contact) = db_contacts.next().await {
476 let db_contact = db_contact?;
477 if db_contact.user_id_a == user_id {
478 if db_contact.accepted {
479 contacts.push(Contact::Accepted {
480 user_id: db_contact.user_id_b,
481 should_notify: db_contact.should_notify && db_contact.a_to_b,
482 busy: db_contact.user_b_busy,
483 });
484 } else if db_contact.a_to_b {
485 contacts.push(Contact::Outgoing {
486 user_id: db_contact.user_id_b,
487 })
488 } else {
489 contacts.push(Contact::Incoming {
490 user_id: db_contact.user_id_b,
491 should_notify: db_contact.should_notify,
492 });
493 }
494 } else if db_contact.accepted {
495 contacts.push(Contact::Accepted {
496 user_id: db_contact.user_id_a,
497 should_notify: db_contact.should_notify && !db_contact.a_to_b,
498 busy: db_contact.user_a_busy,
499 });
500 } else if db_contact.a_to_b {
501 contacts.push(Contact::Incoming {
502 user_id: db_contact.user_id_a,
503 should_notify: db_contact.should_notify,
504 });
505 } else {
506 contacts.push(Contact::Outgoing {
507 user_id: db_contact.user_id_a,
508 });
509 }
510 }
511
512 contacts.sort_unstable_by_key(|contact| contact.user_id());
513
514 Ok(contacts)
515 })
516 .await
517 }
518
519 pub async fn is_user_busy(&self, user_id: UserId) -> Result<bool> {
520 self.transaction(|tx| async move {
521 let participant = room_participant::Entity::find()
522 .filter(room_participant::Column::UserId.eq(user_id))
523 .one(&*tx)
524 .await?;
525 Ok(participant.is_some())
526 })
527 .await
528 }
529
530 pub async fn has_contact(&self, user_id_1: UserId, user_id_2: UserId) -> Result<bool> {
531 self.transaction(|tx| async move {
532 let (id_a, id_b) = if user_id_1 < user_id_2 {
533 (user_id_1, user_id_2)
534 } else {
535 (user_id_2, user_id_1)
536 };
537
538 Ok(contact::Entity::find()
539 .filter(
540 contact::Column::UserIdA
541 .eq(id_a)
542 .and(contact::Column::UserIdB.eq(id_b))
543 .and(contact::Column::Accepted.eq(true)),
544 )
545 .one(&*tx)
546 .await?
547 .is_some())
548 })
549 .await
550 }
551
552 pub async fn send_contact_request(&self, sender_id: UserId, receiver_id: UserId) -> Result<()> {
553 self.transaction(|tx| async move {
554 let (id_a, id_b, a_to_b) = if sender_id < receiver_id {
555 (sender_id, receiver_id, true)
556 } else {
557 (receiver_id, sender_id, false)
558 };
559
560 let rows_affected = contact::Entity::insert(contact::ActiveModel {
561 user_id_a: ActiveValue::set(id_a),
562 user_id_b: ActiveValue::set(id_b),
563 a_to_b: ActiveValue::set(a_to_b),
564 accepted: ActiveValue::set(false),
565 should_notify: ActiveValue::set(true),
566 ..Default::default()
567 })
568 .on_conflict(
569 OnConflict::columns([contact::Column::UserIdA, contact::Column::UserIdB])
570 .values([
571 (contact::Column::Accepted, true.into()),
572 (contact::Column::ShouldNotify, false.into()),
573 ])
574 .action_and_where(
575 contact::Column::Accepted.eq(false).and(
576 contact::Column::AToB
577 .eq(a_to_b)
578 .and(contact::Column::UserIdA.eq(id_b))
579 .or(contact::Column::AToB
580 .ne(a_to_b)
581 .and(contact::Column::UserIdA.eq(id_a))),
582 ),
583 )
584 .to_owned(),
585 )
586 .exec_without_returning(&*tx)
587 .await?;
588
589 if rows_affected == 1 {
590 Ok(())
591 } else {
592 Err(anyhow!("contact already requested"))?
593 }
594 })
595 .await
596 }
597
598 /// Returns a bool indicating whether the removed contact had originally accepted or not
599 ///
600 /// Deletes the contact identified by the requester and responder ids, and then returns
601 /// whether the deleted contact had originally accepted or was a pending contact request.
602 ///
603 /// # Arguments
604 ///
605 /// * `requester_id` - The user that initiates this request
606 /// * `responder_id` - The user that will be removed
607 pub async fn remove_contact(&self, requester_id: UserId, responder_id: UserId) -> Result<bool> {
608 self.transaction(|tx| async move {
609 let (id_a, id_b) = if responder_id < requester_id {
610 (responder_id, requester_id)
611 } else {
612 (requester_id, responder_id)
613 };
614
615 let contact = contact::Entity::find()
616 .filter(
617 contact::Column::UserIdA
618 .eq(id_a)
619 .and(contact::Column::UserIdB.eq(id_b)),
620 )
621 .one(&*tx)
622 .await?
623 .ok_or_else(|| anyhow!("no such contact"))?;
624
625 contact::Entity::delete_by_id(contact.id).exec(&*tx).await?;
626 Ok(contact.accepted)
627 })
628 .await
629 }
630
631 pub async fn dismiss_contact_notification(
632 &self,
633 user_id: UserId,
634 contact_user_id: UserId,
635 ) -> Result<()> {
636 self.transaction(|tx| async move {
637 let (id_a, id_b, a_to_b) = if user_id < contact_user_id {
638 (user_id, contact_user_id, true)
639 } else {
640 (contact_user_id, user_id, false)
641 };
642
643 let result = contact::Entity::update_many()
644 .set(contact::ActiveModel {
645 should_notify: ActiveValue::set(false),
646 ..Default::default()
647 })
648 .filter(
649 contact::Column::UserIdA
650 .eq(id_a)
651 .and(contact::Column::UserIdB.eq(id_b))
652 .and(
653 contact::Column::AToB
654 .eq(a_to_b)
655 .and(contact::Column::Accepted.eq(true))
656 .or(contact::Column::AToB
657 .ne(a_to_b)
658 .and(contact::Column::Accepted.eq(false))),
659 ),
660 )
661 .exec(&*tx)
662 .await?;
663 if result.rows_affected == 0 {
664 Err(anyhow!("no such contact request"))?
665 } else {
666 Ok(())
667 }
668 })
669 .await
670 }
671
672 pub async fn respond_to_contact_request(
673 &self,
674 responder_id: UserId,
675 requester_id: UserId,
676 accept: bool,
677 ) -> Result<()> {
678 self.transaction(|tx| async move {
679 let (id_a, id_b, a_to_b) = if responder_id < requester_id {
680 (responder_id, requester_id, false)
681 } else {
682 (requester_id, responder_id, true)
683 };
684 let rows_affected = if accept {
685 let result = contact::Entity::update_many()
686 .set(contact::ActiveModel {
687 accepted: ActiveValue::set(true),
688 should_notify: ActiveValue::set(true),
689 ..Default::default()
690 })
691 .filter(
692 contact::Column::UserIdA
693 .eq(id_a)
694 .and(contact::Column::UserIdB.eq(id_b))
695 .and(contact::Column::AToB.eq(a_to_b)),
696 )
697 .exec(&*tx)
698 .await?;
699 result.rows_affected
700 } else {
701 let result = contact::Entity::delete_many()
702 .filter(
703 contact::Column::UserIdA
704 .eq(id_a)
705 .and(contact::Column::UserIdB.eq(id_b))
706 .and(contact::Column::AToB.eq(a_to_b))
707 .and(contact::Column::Accepted.eq(false)),
708 )
709 .exec(&*tx)
710 .await?;
711
712 result.rows_affected
713 };
714
715 if rows_affected == 1 {
716 Ok(())
717 } else {
718 Err(anyhow!("no such contact request"))?
719 }
720 })
721 .await
722 }
723
724 pub fn fuzzy_like_string(string: &str) -> String {
725 let mut result = String::with_capacity(string.len() * 2 + 1);
726 for c in string.chars() {
727 if c.is_alphanumeric() {
728 result.push('%');
729 result.push(c);
730 }
731 }
732 result.push('%');
733 result
734 }
735
736 pub async fn fuzzy_search_users(&self, name_query: &str, limit: u32) -> Result<Vec<User>> {
737 self.transaction(|tx| async {
738 let tx = tx;
739 let like_string = Self::fuzzy_like_string(name_query);
740 let query = "
741 SELECT users.*
742 FROM users
743 WHERE github_login ILIKE $1
744 ORDER BY github_login <-> $2
745 LIMIT $3
746 ";
747
748 Ok(user::Entity::find()
749 .from_raw_sql(Statement::from_sql_and_values(
750 self.pool.get_database_backend(),
751 query.into(),
752 vec![like_string.into(), name_query.into(), limit.into()],
753 ))
754 .all(&*tx)
755 .await?)
756 })
757 .await
758 }
759
760 // signups
761
762 pub async fn create_signup(&self, signup: &NewSignup) -> Result<()> {
763 self.transaction(|tx| async move {
764 signup::Entity::insert(signup::ActiveModel {
765 email_address: ActiveValue::set(signup.email_address.clone()),
766 email_confirmation_code: ActiveValue::set(random_email_confirmation_code()),
767 email_confirmation_sent: ActiveValue::set(false),
768 platform_mac: ActiveValue::set(signup.platform_mac),
769 platform_windows: ActiveValue::set(signup.platform_windows),
770 platform_linux: ActiveValue::set(signup.platform_linux),
771 platform_unknown: ActiveValue::set(false),
772 editor_features: ActiveValue::set(Some(signup.editor_features.clone())),
773 programming_languages: ActiveValue::set(Some(signup.programming_languages.clone())),
774 device_id: ActiveValue::set(signup.device_id.clone()),
775 added_to_mailing_list: ActiveValue::set(signup.added_to_mailing_list),
776 ..Default::default()
777 })
778 .on_conflict(
779 OnConflict::column(signup::Column::EmailAddress)
780 .update_columns([
781 signup::Column::PlatformMac,
782 signup::Column::PlatformWindows,
783 signup::Column::PlatformLinux,
784 signup::Column::EditorFeatures,
785 signup::Column::ProgrammingLanguages,
786 signup::Column::DeviceId,
787 signup::Column::AddedToMailingList,
788 ])
789 .to_owned(),
790 )
791 .exec(&*tx)
792 .await?;
793 Ok(())
794 })
795 .await
796 }
797
798 pub async fn get_signup(&self, email_address: &str) -> Result<signup::Model> {
799 self.transaction(|tx| async move {
800 let signup = signup::Entity::find()
801 .filter(signup::Column::EmailAddress.eq(email_address))
802 .one(&*tx)
803 .await?
804 .ok_or_else(|| {
805 anyhow!("signup with email address {} doesn't exist", email_address)
806 })?;
807
808 Ok(signup)
809 })
810 .await
811 }
812
813 pub async fn get_waitlist_summary(&self) -> Result<WaitlistSummary> {
814 self.transaction(|tx| async move {
815 let query = "
816 SELECT
817 COUNT(*) as count,
818 COALESCE(SUM(CASE WHEN platform_linux THEN 1 ELSE 0 END), 0) as linux_count,
819 COALESCE(SUM(CASE WHEN platform_mac THEN 1 ELSE 0 END), 0) as mac_count,
820 COALESCE(SUM(CASE WHEN platform_windows THEN 1 ELSE 0 END), 0) as windows_count,
821 COALESCE(SUM(CASE WHEN platform_unknown THEN 1 ELSE 0 END), 0) as unknown_count
822 FROM (
823 SELECT *
824 FROM signups
825 WHERE
826 NOT email_confirmation_sent
827 ) AS unsent
828 ";
829 Ok(
830 WaitlistSummary::find_by_statement(Statement::from_sql_and_values(
831 self.pool.get_database_backend(),
832 query.into(),
833 vec![],
834 ))
835 .one(&*tx)
836 .await?
837 .ok_or_else(|| anyhow!("invalid result"))?,
838 )
839 })
840 .await
841 }
842
843 pub async fn record_sent_invites(&self, invites: &[Invite]) -> Result<()> {
844 let emails = invites
845 .iter()
846 .map(|s| s.email_address.as_str())
847 .collect::<Vec<_>>();
848 self.transaction(|tx| async {
849 let tx = tx;
850 signup::Entity::update_many()
851 .filter(signup::Column::EmailAddress.is_in(emails.iter().copied()))
852 .set(signup::ActiveModel {
853 email_confirmation_sent: ActiveValue::set(true),
854 ..Default::default()
855 })
856 .exec(&*tx)
857 .await?;
858 Ok(())
859 })
860 .await
861 }
862
863 pub async fn get_unsent_invites(&self, count: usize) -> Result<Vec<Invite>> {
864 self.transaction(|tx| async move {
865 Ok(signup::Entity::find()
866 .select_only()
867 .column(signup::Column::EmailAddress)
868 .column(signup::Column::EmailConfirmationCode)
869 .filter(
870 signup::Column::EmailConfirmationSent.eq(false).and(
871 signup::Column::PlatformMac
872 .eq(true)
873 .or(signup::Column::PlatformUnknown.eq(true)),
874 ),
875 )
876 .order_by_asc(signup::Column::CreatedAt)
877 .limit(count as u64)
878 .into_model()
879 .all(&*tx)
880 .await?)
881 })
882 .await
883 }
884
885 // invite codes
886
887 pub async fn create_invite_from_code(
888 &self,
889 code: &str,
890 email_address: &str,
891 device_id: Option<&str>,
892 added_to_mailing_list: bool,
893 ) -> Result<Invite> {
894 self.transaction(|tx| async move {
895 let existing_user = user::Entity::find()
896 .filter(user::Column::EmailAddress.eq(email_address))
897 .one(&*tx)
898 .await?;
899
900 if existing_user.is_some() {
901 Err(anyhow!("email address is already in use"))?;
902 }
903
904 let inviting_user_with_invites = match user::Entity::find()
905 .filter(
906 user::Column::InviteCode
907 .eq(code)
908 .and(user::Column::InviteCount.gt(0)),
909 )
910 .one(&*tx)
911 .await?
912 {
913 Some(inviting_user) => inviting_user,
914 None => {
915 return Err(Error::Http(
916 StatusCode::UNAUTHORIZED,
917 "unable to find an invite code with invites remaining".to_string(),
918 ))?
919 }
920 };
921 user::Entity::update_many()
922 .filter(
923 user::Column::Id
924 .eq(inviting_user_with_invites.id)
925 .and(user::Column::InviteCount.gt(0)),
926 )
927 .col_expr(
928 user::Column::InviteCount,
929 Expr::col(user::Column::InviteCount).sub(1),
930 )
931 .exec(&*tx)
932 .await?;
933
934 let signup = signup::Entity::insert(signup::ActiveModel {
935 email_address: ActiveValue::set(email_address.into()),
936 email_confirmation_code: ActiveValue::set(random_email_confirmation_code()),
937 email_confirmation_sent: ActiveValue::set(false),
938 inviting_user_id: ActiveValue::set(Some(inviting_user_with_invites.id)),
939 platform_linux: ActiveValue::set(false),
940 platform_mac: ActiveValue::set(false),
941 platform_windows: ActiveValue::set(false),
942 platform_unknown: ActiveValue::set(true),
943 device_id: ActiveValue::set(device_id.map(|device_id| device_id.into())),
944 added_to_mailing_list: ActiveValue::set(added_to_mailing_list),
945 ..Default::default()
946 })
947 .on_conflict(
948 OnConflict::column(signup::Column::EmailAddress)
949 .update_column(signup::Column::InvitingUserId)
950 .to_owned(),
951 )
952 .exec_with_returning(&*tx)
953 .await?;
954
955 Ok(Invite {
956 email_address: signup.email_address,
957 email_confirmation_code: signup.email_confirmation_code,
958 })
959 })
960 .await
961 }
962
963 pub async fn create_user_from_invite(
964 &self,
965 invite: &Invite,
966 user: NewUserParams,
967 ) -> Result<Option<NewUserResult>> {
968 self.transaction(|tx| async {
969 let tx = tx;
970 let signup = signup::Entity::find()
971 .filter(
972 signup::Column::EmailAddress
973 .eq(invite.email_address.as_str())
974 .and(
975 signup::Column::EmailConfirmationCode
976 .eq(invite.email_confirmation_code.as_str()),
977 ),
978 )
979 .one(&*tx)
980 .await?
981 .ok_or_else(|| Error::Http(StatusCode::NOT_FOUND, "no such invite".to_string()))?;
982
983 if signup.user_id.is_some() {
984 return Ok(None);
985 }
986
987 let user = user::Entity::insert(user::ActiveModel {
988 email_address: ActiveValue::set(Some(invite.email_address.clone())),
989 github_login: ActiveValue::set(user.github_login.clone()),
990 github_user_id: ActiveValue::set(Some(user.github_user_id)),
991 admin: ActiveValue::set(false),
992 invite_count: ActiveValue::set(user.invite_count),
993 invite_code: ActiveValue::set(Some(random_invite_code())),
994 metrics_id: ActiveValue::set(Uuid::new_v4()),
995 ..Default::default()
996 })
997 .on_conflict(
998 OnConflict::column(user::Column::GithubLogin)
999 .update_columns([
1000 user::Column::EmailAddress,
1001 user::Column::GithubUserId,
1002 user::Column::Admin,
1003 ])
1004 .to_owned(),
1005 )
1006 .exec_with_returning(&*tx)
1007 .await?;
1008
1009 let mut signup = signup.into_active_model();
1010 signup.user_id = ActiveValue::set(Some(user.id));
1011 let signup = signup.update(&*tx).await?;
1012
1013 if let Some(inviting_user_id) = signup.inviting_user_id {
1014 let (user_id_a, user_id_b, a_to_b) = if inviting_user_id < user.id {
1015 (inviting_user_id, user.id, true)
1016 } else {
1017 (user.id, inviting_user_id, false)
1018 };
1019
1020 contact::Entity::insert(contact::ActiveModel {
1021 user_id_a: ActiveValue::set(user_id_a),
1022 user_id_b: ActiveValue::set(user_id_b),
1023 a_to_b: ActiveValue::set(a_to_b),
1024 should_notify: ActiveValue::set(true),
1025 accepted: ActiveValue::set(true),
1026 ..Default::default()
1027 })
1028 .on_conflict(OnConflict::new().do_nothing().to_owned())
1029 .exec_without_returning(&*tx)
1030 .await?;
1031 }
1032
1033 Ok(Some(NewUserResult {
1034 user_id: user.id,
1035 metrics_id: user.metrics_id.to_string(),
1036 inviting_user_id: signup.inviting_user_id,
1037 signup_device_id: signup.device_id,
1038 }))
1039 })
1040 .await
1041 }
1042
1043 pub async fn set_invite_count_for_user(&self, id: UserId, count: i32) -> Result<()> {
1044 self.transaction(|tx| async move {
1045 if count > 0 {
1046 user::Entity::update_many()
1047 .filter(
1048 user::Column::Id
1049 .eq(id)
1050 .and(user::Column::InviteCode.is_null()),
1051 )
1052 .set(user::ActiveModel {
1053 invite_code: ActiveValue::set(Some(random_invite_code())),
1054 ..Default::default()
1055 })
1056 .exec(&*tx)
1057 .await?;
1058 }
1059
1060 user::Entity::update_many()
1061 .filter(user::Column::Id.eq(id))
1062 .set(user::ActiveModel {
1063 invite_count: ActiveValue::set(count),
1064 ..Default::default()
1065 })
1066 .exec(&*tx)
1067 .await?;
1068 Ok(())
1069 })
1070 .await
1071 }
1072
1073 pub async fn get_invite_code_for_user(&self, id: UserId) -> Result<Option<(String, i32)>> {
1074 self.transaction(|tx| async move {
1075 match user::Entity::find_by_id(id).one(&*tx).await? {
1076 Some(user) if user.invite_code.is_some() => {
1077 Ok(Some((user.invite_code.unwrap(), user.invite_count)))
1078 }
1079 _ => Ok(None),
1080 }
1081 })
1082 .await
1083 }
1084
1085 pub async fn get_user_for_invite_code(&self, code: &str) -> Result<User> {
1086 self.transaction(|tx| async move {
1087 user::Entity::find()
1088 .filter(user::Column::InviteCode.eq(code))
1089 .one(&*tx)
1090 .await?
1091 .ok_or_else(|| {
1092 Error::Http(
1093 StatusCode::NOT_FOUND,
1094 "that invite code does not exist".to_string(),
1095 )
1096 })
1097 })
1098 .await
1099 }
1100
1101 // rooms
1102
1103 pub async fn incoming_call_for_user(
1104 &self,
1105 user_id: UserId,
1106 ) -> Result<Option<proto::IncomingCall>> {
1107 self.transaction(|tx| async move {
1108 let pending_participant = room_participant::Entity::find()
1109 .filter(
1110 room_participant::Column::UserId
1111 .eq(user_id)
1112 .and(room_participant::Column::AnsweringConnectionId.is_null()),
1113 )
1114 .one(&*tx)
1115 .await?;
1116
1117 if let Some(pending_participant) = pending_participant {
1118 let room = self.get_room(pending_participant.room_id, &tx).await?;
1119 Ok(Self::build_incoming_call(&room, user_id))
1120 } else {
1121 Ok(None)
1122 }
1123 })
1124 .await
1125 }
1126
1127 pub async fn create_room(
1128 &self,
1129 user_id: UserId,
1130 connection: ConnectionId,
1131 live_kit_room: &str,
1132 ) -> Result<RoomGuard<proto::Room>> {
1133 self.room_transaction(|tx| async move {
1134 let room = room::ActiveModel {
1135 live_kit_room: ActiveValue::set(live_kit_room.into()),
1136 ..Default::default()
1137 }
1138 .insert(&*tx)
1139 .await?;
1140 let room_id = room.id;
1141
1142 room_participant::ActiveModel {
1143 room_id: ActiveValue::set(room_id),
1144 user_id: ActiveValue::set(user_id),
1145 answering_connection_id: ActiveValue::set(Some(connection.id as i32)),
1146 answering_connection_server_id: ActiveValue::set(Some(ServerId(
1147 connection.owner_id as i32,
1148 ))),
1149 answering_connection_lost: ActiveValue::set(false),
1150 calling_user_id: ActiveValue::set(user_id),
1151 calling_connection_id: ActiveValue::set(connection.id as i32),
1152 calling_connection_server_id: ActiveValue::set(Some(ServerId(
1153 connection.owner_id as i32,
1154 ))),
1155 ..Default::default()
1156 }
1157 .insert(&*tx)
1158 .await?;
1159
1160 let room = self.get_room(room_id, &tx).await?;
1161 Ok((room_id, room))
1162 })
1163 .await
1164 }
1165
1166 pub async fn call(
1167 &self,
1168 room_id: RoomId,
1169 calling_user_id: UserId,
1170 calling_connection: ConnectionId,
1171 called_user_id: UserId,
1172 initial_project_id: Option<ProjectId>,
1173 ) -> Result<RoomGuard<(proto::Room, proto::IncomingCall)>> {
1174 self.room_transaction(|tx| async move {
1175 room_participant::ActiveModel {
1176 room_id: ActiveValue::set(room_id),
1177 user_id: ActiveValue::set(called_user_id),
1178 answering_connection_lost: ActiveValue::set(false),
1179 calling_user_id: ActiveValue::set(calling_user_id),
1180 calling_connection_id: ActiveValue::set(calling_connection.id as i32),
1181 calling_connection_server_id: ActiveValue::set(Some(ServerId(
1182 calling_connection.owner_id as i32,
1183 ))),
1184 initial_project_id: ActiveValue::set(initial_project_id),
1185 ..Default::default()
1186 }
1187 .insert(&*tx)
1188 .await?;
1189
1190 let room = self.get_room(room_id, &tx).await?;
1191 let incoming_call = Self::build_incoming_call(&room, called_user_id)
1192 .ok_or_else(|| anyhow!("failed to build incoming call"))?;
1193 Ok((room_id, (room, incoming_call)))
1194 })
1195 .await
1196 }
1197
1198 pub async fn call_failed(
1199 &self,
1200 room_id: RoomId,
1201 called_user_id: UserId,
1202 ) -> Result<RoomGuard<proto::Room>> {
1203 self.room_transaction(|tx| async move {
1204 room_participant::Entity::delete_many()
1205 .filter(
1206 room_participant::Column::RoomId
1207 .eq(room_id)
1208 .and(room_participant::Column::UserId.eq(called_user_id)),
1209 )
1210 .exec(&*tx)
1211 .await?;
1212 let room = self.get_room(room_id, &tx).await?;
1213 Ok((room_id, room))
1214 })
1215 .await
1216 }
1217
1218 pub async fn decline_call(
1219 &self,
1220 expected_room_id: Option<RoomId>,
1221 user_id: UserId,
1222 ) -> Result<Option<RoomGuard<proto::Room>>> {
1223 self.optional_room_transaction(|tx| async move {
1224 let mut filter = Condition::all()
1225 .add(room_participant::Column::UserId.eq(user_id))
1226 .add(room_participant::Column::AnsweringConnectionId.is_null());
1227 if let Some(room_id) = expected_room_id {
1228 filter = filter.add(room_participant::Column::RoomId.eq(room_id));
1229 }
1230 let participant = room_participant::Entity::find()
1231 .filter(filter)
1232 .one(&*tx)
1233 .await?;
1234
1235 let participant = if let Some(participant) = participant {
1236 participant
1237 } else if expected_room_id.is_some() {
1238 return Err(anyhow!("could not find call to decline"))?;
1239 } else {
1240 return Ok(None);
1241 };
1242
1243 let room_id = participant.room_id;
1244 room_participant::Entity::delete(participant.into_active_model())
1245 .exec(&*tx)
1246 .await?;
1247
1248 let room = self.get_room(room_id, &tx).await?;
1249 Ok(Some((room_id, room)))
1250 })
1251 .await
1252 }
1253
1254 pub async fn cancel_call(
1255 &self,
1256 room_id: RoomId,
1257 calling_connection: ConnectionId,
1258 called_user_id: UserId,
1259 ) -> Result<RoomGuard<proto::Room>> {
1260 self.room_transaction(|tx| async move {
1261 let participant = room_participant::Entity::find()
1262 .filter(
1263 Condition::all()
1264 .add(room_participant::Column::UserId.eq(called_user_id))
1265 .add(room_participant::Column::RoomId.eq(room_id))
1266 .add(
1267 room_participant::Column::CallingConnectionId
1268 .eq(calling_connection.id as i32),
1269 )
1270 .add(
1271 room_participant::Column::CallingConnectionServerId
1272 .eq(calling_connection.owner_id as i32),
1273 )
1274 .add(room_participant::Column::AnsweringConnectionId.is_null()),
1275 )
1276 .one(&*tx)
1277 .await?
1278 .ok_or_else(|| anyhow!("no call to cancel"))?;
1279 let room_id = participant.room_id;
1280
1281 room_participant::Entity::delete(participant.into_active_model())
1282 .exec(&*tx)
1283 .await?;
1284
1285 let room = self.get_room(room_id, &tx).await?;
1286 Ok((room_id, room))
1287 })
1288 .await
1289 }
1290
1291 pub async fn join_room(
1292 &self,
1293 room_id: RoomId,
1294 user_id: UserId,
1295 connection: ConnectionId,
1296 ) -> Result<RoomGuard<proto::Room>> {
1297 self.room_transaction(|tx| async move {
1298 let result = room_participant::Entity::update_many()
1299 .filter(
1300 Condition::all()
1301 .add(room_participant::Column::RoomId.eq(room_id))
1302 .add(room_participant::Column::UserId.eq(user_id))
1303 .add(room_participant::Column::AnsweringConnectionId.is_null()),
1304 )
1305 .set(room_participant::ActiveModel {
1306 answering_connection_id: ActiveValue::set(Some(connection.id as i32)),
1307 answering_connection_server_id: ActiveValue::set(Some(ServerId(
1308 connection.owner_id as i32,
1309 ))),
1310 answering_connection_lost: ActiveValue::set(false),
1311 ..Default::default()
1312 })
1313 .exec(&*tx)
1314 .await?;
1315 if result.rows_affected == 0 {
1316 Err(anyhow!("room does not exist or was already joined"))?
1317 } else {
1318 let room = self.get_room(room_id, &tx).await?;
1319 Ok((room_id, room))
1320 }
1321 })
1322 .await
1323 }
1324
1325 pub async fn rejoin_room(
1326 &self,
1327 rejoin_room: proto::RejoinRoom,
1328 user_id: UserId,
1329 connection: ConnectionId,
1330 ) -> Result<RoomGuard<RejoinedRoom>> {
1331 self.room_transaction(|tx| async {
1332 let tx = tx;
1333 let room_id = RoomId::from_proto(rejoin_room.id);
1334 let participant_update = room_participant::Entity::update_many()
1335 .filter(
1336 Condition::all()
1337 .add(room_participant::Column::RoomId.eq(room_id))
1338 .add(room_participant::Column::UserId.eq(user_id))
1339 .add(room_participant::Column::AnsweringConnectionId.is_not_null())
1340 .add(
1341 Condition::any()
1342 .add(room_participant::Column::AnsweringConnectionLost.eq(true))
1343 .add(
1344 room_participant::Column::AnsweringConnectionServerId
1345 .ne(connection.owner_id as i32),
1346 ),
1347 ),
1348 )
1349 .set(room_participant::ActiveModel {
1350 answering_connection_id: ActiveValue::set(Some(connection.id as i32)),
1351 answering_connection_server_id: ActiveValue::set(Some(ServerId(
1352 connection.owner_id as i32,
1353 ))),
1354 answering_connection_lost: ActiveValue::set(false),
1355 ..Default::default()
1356 })
1357 .exec(&*tx)
1358 .await?;
1359 if participant_update.rows_affected == 0 {
1360 return Err(anyhow!("room does not exist or was already joined"))?;
1361 }
1362
1363 let mut reshared_projects = Vec::new();
1364 for reshared_project in &rejoin_room.reshared_projects {
1365 let project_id = ProjectId::from_proto(reshared_project.project_id);
1366 let project = project::Entity::find_by_id(project_id)
1367 .one(&*tx)
1368 .await?
1369 .ok_or_else(|| anyhow!("project does not exist"))?;
1370 if project.host_user_id != user_id {
1371 return Err(anyhow!("no such project"))?;
1372 }
1373
1374 let mut collaborators = project
1375 .find_related(project_collaborator::Entity)
1376 .all(&*tx)
1377 .await?;
1378 let host_ix = collaborators
1379 .iter()
1380 .position(|collaborator| {
1381 collaborator.user_id == user_id && collaborator.is_host
1382 })
1383 .ok_or_else(|| anyhow!("host not found among collaborators"))?;
1384 let host = collaborators.swap_remove(host_ix);
1385 let old_connection_id = host.connection();
1386
1387 project::Entity::update(project::ActiveModel {
1388 host_connection_id: ActiveValue::set(Some(connection.id as i32)),
1389 host_connection_server_id: ActiveValue::set(Some(ServerId(
1390 connection.owner_id as i32,
1391 ))),
1392 ..project.into_active_model()
1393 })
1394 .exec(&*tx)
1395 .await?;
1396 project_collaborator::Entity::update(project_collaborator::ActiveModel {
1397 connection_id: ActiveValue::set(connection.id as i32),
1398 connection_server_id: ActiveValue::set(ServerId(connection.owner_id as i32)),
1399 ..host.into_active_model()
1400 })
1401 .exec(&*tx)
1402 .await?;
1403
1404 self.update_project_worktrees(project_id, &reshared_project.worktrees, &tx)
1405 .await?;
1406
1407 reshared_projects.push(ResharedProject {
1408 id: project_id,
1409 old_connection_id,
1410 collaborators: collaborators
1411 .iter()
1412 .map(|collaborator| ProjectCollaborator {
1413 connection_id: collaborator.connection(),
1414 user_id: collaborator.user_id,
1415 replica_id: collaborator.replica_id,
1416 is_host: collaborator.is_host,
1417 })
1418 .collect(),
1419 worktrees: reshared_project.worktrees.clone(),
1420 });
1421 }
1422
1423 project::Entity::delete_many()
1424 .filter(
1425 Condition::all()
1426 .add(project::Column::RoomId.eq(room_id))
1427 .add(project::Column::HostUserId.eq(user_id))
1428 .add(
1429 project::Column::Id
1430 .is_not_in(reshared_projects.iter().map(|project| project.id)),
1431 ),
1432 )
1433 .exec(&*tx)
1434 .await?;
1435
1436 let mut rejoined_projects = Vec::new();
1437 for rejoined_project in &rejoin_room.rejoined_projects {
1438 let project_id = ProjectId::from_proto(rejoined_project.id);
1439 let Some(project) = project::Entity::find_by_id(project_id)
1440 .one(&*tx)
1441 .await? else { continue };
1442
1443 let mut worktrees = Vec::new();
1444 let db_worktrees = project.find_related(worktree::Entity).all(&*tx).await?;
1445 for db_worktree in db_worktrees {
1446 let mut worktree = RejoinedWorktree {
1447 id: db_worktree.id as u64,
1448 abs_path: db_worktree.abs_path,
1449 root_name: db_worktree.root_name,
1450 visible: db_worktree.visible,
1451 updated_entries: Default::default(),
1452 removed_entries: Default::default(),
1453 diagnostic_summaries: Default::default(),
1454 scan_id: db_worktree.scan_id as u64,
1455 completed_scan_id: db_worktree.completed_scan_id as u64,
1456 };
1457
1458 let rejoined_worktree = rejoined_project
1459 .worktrees
1460 .iter()
1461 .find(|worktree| worktree.id == db_worktree.id as u64);
1462 let entry_filter = if let Some(rejoined_worktree) = rejoined_worktree {
1463 worktree_entry::Column::ScanId.gt(rejoined_worktree.scan_id)
1464 } else {
1465 worktree_entry::Column::IsDeleted.eq(false)
1466 };
1467
1468 let mut db_entries = worktree_entry::Entity::find()
1469 .filter(
1470 Condition::all()
1471 .add(worktree_entry::Column::WorktreeId.eq(worktree.id))
1472 .add(entry_filter),
1473 )
1474 .stream(&*tx)
1475 .await?;
1476
1477 while let Some(db_entry) = db_entries.next().await {
1478 let db_entry = db_entry?;
1479 if db_entry.is_deleted {
1480 worktree.removed_entries.push(db_entry.id as u64);
1481 } else {
1482 worktree.updated_entries.push(proto::Entry {
1483 id: db_entry.id as u64,
1484 is_dir: db_entry.is_dir,
1485 path: db_entry.path,
1486 inode: db_entry.inode as u64,
1487 mtime: Some(proto::Timestamp {
1488 seconds: db_entry.mtime_seconds as u64,
1489 nanos: db_entry.mtime_nanos as u32,
1490 }),
1491 is_symlink: db_entry.is_symlink,
1492 is_ignored: db_entry.is_ignored,
1493 });
1494 }
1495 }
1496
1497 worktrees.push(worktree);
1498 }
1499
1500 let language_servers = project
1501 .find_related(language_server::Entity)
1502 .all(&*tx)
1503 .await?
1504 .into_iter()
1505 .map(|language_server| proto::LanguageServer {
1506 id: language_server.id as u64,
1507 name: language_server.name,
1508 })
1509 .collect::<Vec<_>>();
1510
1511 let mut collaborators = project
1512 .find_related(project_collaborator::Entity)
1513 .all(&*tx)
1514 .await?;
1515 let self_collaborator = if let Some(self_collaborator_ix) = collaborators
1516 .iter()
1517 .position(|collaborator| collaborator.user_id == user_id)
1518 {
1519 collaborators.swap_remove(self_collaborator_ix)
1520 } else {
1521 continue;
1522 };
1523 let old_connection_id = self_collaborator.connection();
1524 project_collaborator::Entity::update(project_collaborator::ActiveModel {
1525 connection_id: ActiveValue::set(connection.id as i32),
1526 connection_server_id: ActiveValue::set(ServerId(connection.owner_id as i32)),
1527 ..self_collaborator.into_active_model()
1528 })
1529 .exec(&*tx)
1530 .await?;
1531
1532 let collaborators = collaborators
1533 .into_iter()
1534 .map(|collaborator| ProjectCollaborator {
1535 connection_id: collaborator.connection(),
1536 user_id: collaborator.user_id,
1537 replica_id: collaborator.replica_id,
1538 is_host: collaborator.is_host,
1539 })
1540 .collect::<Vec<_>>();
1541
1542 rejoined_projects.push(RejoinedProject {
1543 id: project_id,
1544 old_connection_id,
1545 collaborators,
1546 worktrees,
1547 language_servers,
1548 });
1549 }
1550
1551 let room = self.get_room(room_id, &tx).await?;
1552 Ok((
1553 room_id,
1554 RejoinedRoom {
1555 room,
1556 rejoined_projects,
1557 reshared_projects,
1558 },
1559 ))
1560 })
1561 .await
1562 }
1563
1564 pub async fn leave_room(
1565 &self,
1566 connection: ConnectionId,
1567 ) -> Result<Option<RoomGuard<LeftRoom>>> {
1568 self.optional_room_transaction(|tx| async move {
1569 let leaving_participant = room_participant::Entity::find()
1570 .filter(
1571 Condition::all()
1572 .add(
1573 room_participant::Column::AnsweringConnectionId
1574 .eq(connection.id as i32),
1575 )
1576 .add(
1577 room_participant::Column::AnsweringConnectionServerId
1578 .eq(connection.owner_id as i32),
1579 ),
1580 )
1581 .one(&*tx)
1582 .await?;
1583
1584 if let Some(leaving_participant) = leaving_participant {
1585 // Leave room.
1586 let room_id = leaving_participant.room_id;
1587 room_participant::Entity::delete_by_id(leaving_participant.id)
1588 .exec(&*tx)
1589 .await?;
1590
1591 // Cancel pending calls initiated by the leaving user.
1592 let called_participants = room_participant::Entity::find()
1593 .filter(
1594 Condition::all()
1595 .add(
1596 room_participant::Column::CallingConnectionId
1597 .eq(connection.id as i32),
1598 )
1599 .add(
1600 room_participant::Column::CallingConnectionServerId
1601 .eq(connection.owner_id as i32),
1602 )
1603 .add(room_participant::Column::AnsweringConnectionId.is_null()),
1604 )
1605 .all(&*tx)
1606 .await?;
1607 room_participant::Entity::delete_many()
1608 .filter(
1609 room_participant::Column::Id
1610 .is_in(called_participants.iter().map(|participant| participant.id)),
1611 )
1612 .exec(&*tx)
1613 .await?;
1614 let canceled_calls_to_user_ids = called_participants
1615 .into_iter()
1616 .map(|participant| participant.user_id)
1617 .collect();
1618
1619 // Detect left projects.
1620 #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
1621 enum QueryProjectIds {
1622 ProjectId,
1623 }
1624 let project_ids: Vec<ProjectId> = project_collaborator::Entity::find()
1625 .select_only()
1626 .column_as(
1627 project_collaborator::Column::ProjectId,
1628 QueryProjectIds::ProjectId,
1629 )
1630 .filter(
1631 Condition::all()
1632 .add(
1633 project_collaborator::Column::ConnectionId.eq(connection.id as i32),
1634 )
1635 .add(
1636 project_collaborator::Column::ConnectionServerId
1637 .eq(connection.owner_id as i32),
1638 ),
1639 )
1640 .into_values::<_, QueryProjectIds>()
1641 .all(&*tx)
1642 .await?;
1643 let mut left_projects = HashMap::default();
1644 let mut collaborators = project_collaborator::Entity::find()
1645 .filter(project_collaborator::Column::ProjectId.is_in(project_ids))
1646 .stream(&*tx)
1647 .await?;
1648 while let Some(collaborator) = collaborators.next().await {
1649 let collaborator = collaborator?;
1650 let left_project =
1651 left_projects
1652 .entry(collaborator.project_id)
1653 .or_insert(LeftProject {
1654 id: collaborator.project_id,
1655 host_user_id: Default::default(),
1656 connection_ids: Default::default(),
1657 host_connection_id: Default::default(),
1658 });
1659
1660 let collaborator_connection_id = collaborator.connection();
1661 if collaborator_connection_id != connection {
1662 left_project.connection_ids.push(collaborator_connection_id);
1663 }
1664
1665 if collaborator.is_host {
1666 left_project.host_user_id = collaborator.user_id;
1667 left_project.host_connection_id = collaborator_connection_id;
1668 }
1669 }
1670 drop(collaborators);
1671
1672 // Leave projects.
1673 project_collaborator::Entity::delete_many()
1674 .filter(
1675 Condition::all()
1676 .add(
1677 project_collaborator::Column::ConnectionId.eq(connection.id as i32),
1678 )
1679 .add(
1680 project_collaborator::Column::ConnectionServerId
1681 .eq(connection.owner_id as i32),
1682 ),
1683 )
1684 .exec(&*tx)
1685 .await?;
1686
1687 // Unshare projects.
1688 project::Entity::delete_many()
1689 .filter(
1690 Condition::all()
1691 .add(project::Column::RoomId.eq(room_id))
1692 .add(project::Column::HostConnectionId.eq(connection.id as i32))
1693 .add(
1694 project::Column::HostConnectionServerId
1695 .eq(connection.owner_id as i32),
1696 ),
1697 )
1698 .exec(&*tx)
1699 .await?;
1700
1701 let room = self.get_room(room_id, &tx).await?;
1702 if room.participants.is_empty() {
1703 room::Entity::delete_by_id(room_id).exec(&*tx).await?;
1704 }
1705
1706 let left_room = LeftRoom {
1707 room,
1708 left_projects,
1709 canceled_calls_to_user_ids,
1710 };
1711
1712 if left_room.room.participants.is_empty() {
1713 self.rooms.remove(&room_id);
1714 }
1715
1716 Ok(Some((room_id, left_room)))
1717 } else {
1718 Ok(None)
1719 }
1720 })
1721 .await
1722 }
1723
1724 pub async fn update_room_participant_location(
1725 &self,
1726 room_id: RoomId,
1727 connection: ConnectionId,
1728 location: proto::ParticipantLocation,
1729 ) -> Result<RoomGuard<proto::Room>> {
1730 self.room_transaction(|tx| async {
1731 let tx = tx;
1732 let location_kind;
1733 let location_project_id;
1734 match location
1735 .variant
1736 .as_ref()
1737 .ok_or_else(|| anyhow!("invalid location"))?
1738 {
1739 proto::participant_location::Variant::SharedProject(project) => {
1740 location_kind = 0;
1741 location_project_id = Some(ProjectId::from_proto(project.id));
1742 }
1743 proto::participant_location::Variant::UnsharedProject(_) => {
1744 location_kind = 1;
1745 location_project_id = None;
1746 }
1747 proto::participant_location::Variant::External(_) => {
1748 location_kind = 2;
1749 location_project_id = None;
1750 }
1751 }
1752
1753 let result = room_participant::Entity::update_many()
1754 .filter(
1755 Condition::all()
1756 .add(room_participant::Column::RoomId.eq(room_id))
1757 .add(
1758 room_participant::Column::AnsweringConnectionId
1759 .eq(connection.id as i32),
1760 )
1761 .add(
1762 room_participant::Column::AnsweringConnectionServerId
1763 .eq(connection.owner_id as i32),
1764 ),
1765 )
1766 .set(room_participant::ActiveModel {
1767 location_kind: ActiveValue::set(Some(location_kind)),
1768 location_project_id: ActiveValue::set(location_project_id),
1769 ..Default::default()
1770 })
1771 .exec(&*tx)
1772 .await?;
1773
1774 if result.rows_affected == 1 {
1775 let room = self.get_room(room_id, &tx).await?;
1776 Ok((room_id, room))
1777 } else {
1778 Err(anyhow!("could not update room participant location"))?
1779 }
1780 })
1781 .await
1782 }
1783
1784 pub async fn connection_lost(&self, connection: ConnectionId) -> Result<()> {
1785 self.transaction(|tx| async move {
1786 let participant = room_participant::Entity::find()
1787 .filter(
1788 Condition::all()
1789 .add(
1790 room_participant::Column::AnsweringConnectionId
1791 .eq(connection.id as i32),
1792 )
1793 .add(
1794 room_participant::Column::AnsweringConnectionServerId
1795 .eq(connection.owner_id as i32),
1796 ),
1797 )
1798 .one(&*tx)
1799 .await?
1800 .ok_or_else(|| anyhow!("not a participant in any room"))?;
1801
1802 room_participant::Entity::update(room_participant::ActiveModel {
1803 answering_connection_lost: ActiveValue::set(true),
1804 ..participant.into_active_model()
1805 })
1806 .exec(&*tx)
1807 .await?;
1808
1809 Ok(())
1810 })
1811 .await
1812 }
1813
1814 fn build_incoming_call(
1815 room: &proto::Room,
1816 called_user_id: UserId,
1817 ) -> Option<proto::IncomingCall> {
1818 let pending_participant = room
1819 .pending_participants
1820 .iter()
1821 .find(|participant| participant.user_id == called_user_id.to_proto())?;
1822
1823 Some(proto::IncomingCall {
1824 room_id: room.id,
1825 calling_user_id: pending_participant.calling_user_id,
1826 participant_user_ids: room
1827 .participants
1828 .iter()
1829 .map(|participant| participant.user_id)
1830 .collect(),
1831 initial_project: room.participants.iter().find_map(|participant| {
1832 let initial_project_id = pending_participant.initial_project_id?;
1833 participant
1834 .projects
1835 .iter()
1836 .find(|project| project.id == initial_project_id)
1837 .cloned()
1838 }),
1839 })
1840 }
1841
1842 async fn get_room(&self, room_id: RoomId, tx: &DatabaseTransaction) -> Result<proto::Room> {
1843 let db_room = room::Entity::find_by_id(room_id)
1844 .one(tx)
1845 .await?
1846 .ok_or_else(|| anyhow!("could not find room"))?;
1847
1848 let mut db_participants = db_room
1849 .find_related(room_participant::Entity)
1850 .stream(tx)
1851 .await?;
1852 let mut participants = HashMap::default();
1853 let mut pending_participants = Vec::new();
1854 while let Some(db_participant) = db_participants.next().await {
1855 let db_participant = db_participant?;
1856 if let Some((answering_connection_id, answering_connection_server_id)) = db_participant
1857 .answering_connection_id
1858 .zip(db_participant.answering_connection_server_id)
1859 {
1860 let location = match (
1861 db_participant.location_kind,
1862 db_participant.location_project_id,
1863 ) {
1864 (Some(0), Some(project_id)) => {
1865 Some(proto::participant_location::Variant::SharedProject(
1866 proto::participant_location::SharedProject {
1867 id: project_id.to_proto(),
1868 },
1869 ))
1870 }
1871 (Some(1), _) => Some(proto::participant_location::Variant::UnsharedProject(
1872 Default::default(),
1873 )),
1874 _ => Some(proto::participant_location::Variant::External(
1875 Default::default(),
1876 )),
1877 };
1878
1879 let answering_connection = ConnectionId {
1880 owner_id: answering_connection_server_id.0 as u32,
1881 id: answering_connection_id as u32,
1882 };
1883 participants.insert(
1884 answering_connection,
1885 proto::Participant {
1886 user_id: db_participant.user_id.to_proto(),
1887 peer_id: Some(answering_connection.into()),
1888 projects: Default::default(),
1889 location: Some(proto::ParticipantLocation { variant: location }),
1890 },
1891 );
1892 } else {
1893 pending_participants.push(proto::PendingParticipant {
1894 user_id: db_participant.user_id.to_proto(),
1895 calling_user_id: db_participant.calling_user_id.to_proto(),
1896 initial_project_id: db_participant.initial_project_id.map(|id| id.to_proto()),
1897 });
1898 }
1899 }
1900 drop(db_participants);
1901
1902 let mut db_projects = db_room
1903 .find_related(project::Entity)
1904 .find_with_related(worktree::Entity)
1905 .stream(tx)
1906 .await?;
1907
1908 while let Some(row) = db_projects.next().await {
1909 let (db_project, db_worktree) = row?;
1910 let host_connection = db_project.host_connection()?;
1911 if let Some(participant) = participants.get_mut(&host_connection) {
1912 let project = if let Some(project) = participant
1913 .projects
1914 .iter_mut()
1915 .find(|project| project.id == db_project.id.to_proto())
1916 {
1917 project
1918 } else {
1919 participant.projects.push(proto::ParticipantProject {
1920 id: db_project.id.to_proto(),
1921 worktree_root_names: Default::default(),
1922 });
1923 participant.projects.last_mut().unwrap()
1924 };
1925
1926 if let Some(db_worktree) = db_worktree {
1927 project.worktree_root_names.push(db_worktree.root_name);
1928 }
1929 }
1930 }
1931
1932 Ok(proto::Room {
1933 id: db_room.id.to_proto(),
1934 live_kit_room: db_room.live_kit_room,
1935 participants: participants.into_values().collect(),
1936 pending_participants,
1937 })
1938 }
1939
1940 // projects
1941
1942 pub async fn project_count_excluding_admins(&self) -> Result<usize> {
1943 #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
1944 enum QueryAs {
1945 Count,
1946 }
1947
1948 self.transaction(|tx| async move {
1949 Ok(project::Entity::find()
1950 .select_only()
1951 .column_as(project::Column::Id.count(), QueryAs::Count)
1952 .inner_join(user::Entity)
1953 .filter(user::Column::Admin.eq(false))
1954 .into_values::<_, QueryAs>()
1955 .one(&*tx)
1956 .await?
1957 .unwrap_or(0i64) as usize)
1958 })
1959 .await
1960 }
1961
1962 pub async fn share_project(
1963 &self,
1964 room_id: RoomId,
1965 connection: ConnectionId,
1966 worktrees: &[proto::WorktreeMetadata],
1967 ) -> Result<RoomGuard<(ProjectId, proto::Room)>> {
1968 self.room_transaction(|tx| async move {
1969 let participant = room_participant::Entity::find()
1970 .filter(
1971 Condition::all()
1972 .add(
1973 room_participant::Column::AnsweringConnectionId
1974 .eq(connection.id as i32),
1975 )
1976 .add(
1977 room_participant::Column::AnsweringConnectionServerId
1978 .eq(connection.owner_id as i32),
1979 ),
1980 )
1981 .one(&*tx)
1982 .await?
1983 .ok_or_else(|| anyhow!("could not find participant"))?;
1984 if participant.room_id != room_id {
1985 return Err(anyhow!("shared project on unexpected room"))?;
1986 }
1987
1988 let project = project::ActiveModel {
1989 room_id: ActiveValue::set(participant.room_id),
1990 host_user_id: ActiveValue::set(participant.user_id),
1991 host_connection_id: ActiveValue::set(Some(connection.id as i32)),
1992 host_connection_server_id: ActiveValue::set(Some(ServerId(
1993 connection.owner_id as i32,
1994 ))),
1995 ..Default::default()
1996 }
1997 .insert(&*tx)
1998 .await?;
1999
2000 if !worktrees.is_empty() {
2001 worktree::Entity::insert_many(worktrees.iter().map(|worktree| {
2002 worktree::ActiveModel {
2003 id: ActiveValue::set(worktree.id as i64),
2004 project_id: ActiveValue::set(project.id),
2005 abs_path: ActiveValue::set(worktree.abs_path.clone()),
2006 root_name: ActiveValue::set(worktree.root_name.clone()),
2007 visible: ActiveValue::set(worktree.visible),
2008 scan_id: ActiveValue::set(0),
2009 completed_scan_id: ActiveValue::set(0),
2010 }
2011 }))
2012 .exec(&*tx)
2013 .await?;
2014 }
2015
2016 project_collaborator::ActiveModel {
2017 project_id: ActiveValue::set(project.id),
2018 connection_id: ActiveValue::set(connection.id as i32),
2019 connection_server_id: ActiveValue::set(ServerId(connection.owner_id as i32)),
2020 user_id: ActiveValue::set(participant.user_id),
2021 replica_id: ActiveValue::set(ReplicaId(0)),
2022 is_host: ActiveValue::set(true),
2023 ..Default::default()
2024 }
2025 .insert(&*tx)
2026 .await?;
2027
2028 let room = self.get_room(room_id, &tx).await?;
2029 Ok((room_id, (project.id, room)))
2030 })
2031 .await
2032 }
2033
2034 pub async fn unshare_project(
2035 &self,
2036 project_id: ProjectId,
2037 connection: ConnectionId,
2038 ) -> Result<RoomGuard<(proto::Room, Vec<ConnectionId>)>> {
2039 self.room_transaction(|tx| async move {
2040 let guest_connection_ids = self.project_guest_connection_ids(project_id, &tx).await?;
2041
2042 let project = project::Entity::find_by_id(project_id)
2043 .one(&*tx)
2044 .await?
2045 .ok_or_else(|| anyhow!("project not found"))?;
2046 if project.host_connection()? == connection {
2047 let room_id = project.room_id;
2048 project::Entity::delete(project.into_active_model())
2049 .exec(&*tx)
2050 .await?;
2051 let room = self.get_room(room_id, &tx).await?;
2052 Ok((room_id, (room, guest_connection_ids)))
2053 } else {
2054 Err(anyhow!("cannot unshare a project hosted by another user"))?
2055 }
2056 })
2057 .await
2058 }
2059
2060 pub async fn update_project(
2061 &self,
2062 project_id: ProjectId,
2063 connection: ConnectionId,
2064 worktrees: &[proto::WorktreeMetadata],
2065 ) -> Result<RoomGuard<(proto::Room, Vec<ConnectionId>)>> {
2066 self.room_transaction(|tx| async move {
2067 let project = project::Entity::find_by_id(project_id)
2068 .filter(
2069 Condition::all()
2070 .add(project::Column::HostConnectionId.eq(connection.id as i32))
2071 .add(
2072 project::Column::HostConnectionServerId.eq(connection.owner_id as i32),
2073 ),
2074 )
2075 .one(&*tx)
2076 .await?
2077 .ok_or_else(|| anyhow!("no such project"))?;
2078
2079 self.update_project_worktrees(project.id, worktrees, &tx)
2080 .await?;
2081
2082 let guest_connection_ids = self.project_guest_connection_ids(project.id, &tx).await?;
2083 let room = self.get_room(project.room_id, &tx).await?;
2084 Ok((project.room_id, (room, guest_connection_ids)))
2085 })
2086 .await
2087 }
2088
2089 async fn update_project_worktrees(
2090 &self,
2091 project_id: ProjectId,
2092 worktrees: &[proto::WorktreeMetadata],
2093 tx: &DatabaseTransaction,
2094 ) -> Result<()> {
2095 if !worktrees.is_empty() {
2096 worktree::Entity::insert_many(worktrees.iter().map(|worktree| worktree::ActiveModel {
2097 id: ActiveValue::set(worktree.id as i64),
2098 project_id: ActiveValue::set(project_id),
2099 abs_path: ActiveValue::set(worktree.abs_path.clone()),
2100 root_name: ActiveValue::set(worktree.root_name.clone()),
2101 visible: ActiveValue::set(worktree.visible),
2102 scan_id: ActiveValue::set(0),
2103 completed_scan_id: ActiveValue::set(0),
2104 }))
2105 .on_conflict(
2106 OnConflict::columns([worktree::Column::ProjectId, worktree::Column::Id])
2107 .update_column(worktree::Column::RootName)
2108 .to_owned(),
2109 )
2110 .exec(&*tx)
2111 .await?;
2112 }
2113
2114 worktree::Entity::delete_many()
2115 .filter(worktree::Column::ProjectId.eq(project_id).and(
2116 worktree::Column::Id.is_not_in(worktrees.iter().map(|worktree| worktree.id as i64)),
2117 ))
2118 .exec(&*tx)
2119 .await?;
2120
2121 Ok(())
2122 }
2123
2124 pub async fn update_worktree(
2125 &self,
2126 update: &proto::UpdateWorktree,
2127 connection: ConnectionId,
2128 ) -> Result<RoomGuard<Vec<ConnectionId>>> {
2129 self.room_transaction(|tx| async move {
2130 let project_id = ProjectId::from_proto(update.project_id);
2131 let worktree_id = update.worktree_id as i64;
2132
2133 // Ensure the update comes from the host.
2134 let project = project::Entity::find_by_id(project_id)
2135 .filter(
2136 Condition::all()
2137 .add(project::Column::HostConnectionId.eq(connection.id as i32))
2138 .add(
2139 project::Column::HostConnectionServerId.eq(connection.owner_id as i32),
2140 ),
2141 )
2142 .one(&*tx)
2143 .await?
2144 .ok_or_else(|| anyhow!("no such project"))?;
2145 let room_id = project.room_id;
2146
2147 // Update metadata.
2148 worktree::Entity::update(worktree::ActiveModel {
2149 id: ActiveValue::set(worktree_id),
2150 project_id: ActiveValue::set(project_id),
2151 root_name: ActiveValue::set(update.root_name.clone()),
2152 scan_id: ActiveValue::set(update.scan_id as i64),
2153 completed_scan_id: if update.is_last_update {
2154 ActiveValue::set(update.scan_id as i64)
2155 } else {
2156 ActiveValue::default()
2157 },
2158 abs_path: ActiveValue::set(update.abs_path.clone()),
2159 ..Default::default()
2160 })
2161 .exec(&*tx)
2162 .await?;
2163
2164 if !update.updated_entries.is_empty() {
2165 worktree_entry::Entity::insert_many(update.updated_entries.iter().map(|entry| {
2166 let mtime = entry.mtime.clone().unwrap_or_default();
2167 worktree_entry::ActiveModel {
2168 project_id: ActiveValue::set(project_id),
2169 worktree_id: ActiveValue::set(worktree_id),
2170 id: ActiveValue::set(entry.id as i64),
2171 is_dir: ActiveValue::set(entry.is_dir),
2172 path: ActiveValue::set(entry.path.clone()),
2173 inode: ActiveValue::set(entry.inode as i64),
2174 mtime_seconds: ActiveValue::set(mtime.seconds as i64),
2175 mtime_nanos: ActiveValue::set(mtime.nanos as i32),
2176 is_symlink: ActiveValue::set(entry.is_symlink),
2177 is_ignored: ActiveValue::set(entry.is_ignored),
2178 is_deleted: ActiveValue::set(false),
2179 scan_id: ActiveValue::set(update.scan_id as i64),
2180 }
2181 }))
2182 .on_conflict(
2183 OnConflict::columns([
2184 worktree_entry::Column::ProjectId,
2185 worktree_entry::Column::WorktreeId,
2186 worktree_entry::Column::Id,
2187 ])
2188 .update_columns([
2189 worktree_entry::Column::IsDir,
2190 worktree_entry::Column::Path,
2191 worktree_entry::Column::Inode,
2192 worktree_entry::Column::MtimeSeconds,
2193 worktree_entry::Column::MtimeNanos,
2194 worktree_entry::Column::IsSymlink,
2195 worktree_entry::Column::IsIgnored,
2196 worktree_entry::Column::ScanId,
2197 ])
2198 .to_owned(),
2199 )
2200 .exec(&*tx)
2201 .await?;
2202 }
2203
2204 if !update.removed_entries.is_empty() {
2205 worktree_entry::Entity::update_many()
2206 .filter(
2207 worktree_entry::Column::ProjectId
2208 .eq(project_id)
2209 .and(worktree_entry::Column::WorktreeId.eq(worktree_id))
2210 .and(
2211 worktree_entry::Column::Id
2212 .is_in(update.removed_entries.iter().map(|id| *id as i64)),
2213 ),
2214 )
2215 .set(worktree_entry::ActiveModel {
2216 is_deleted: ActiveValue::Set(true),
2217 scan_id: ActiveValue::Set(update.scan_id as i64),
2218 ..Default::default()
2219 })
2220 .exec(&*tx)
2221 .await?;
2222 }
2223
2224 let connection_ids = self.project_guest_connection_ids(project_id, &tx).await?;
2225 Ok((room_id, connection_ids))
2226 })
2227 .await
2228 }
2229
2230 pub async fn update_diagnostic_summary(
2231 &self,
2232 update: &proto::UpdateDiagnosticSummary,
2233 connection: ConnectionId,
2234 ) -> Result<RoomGuard<Vec<ConnectionId>>> {
2235 self.room_transaction(|tx| async move {
2236 let project_id = ProjectId::from_proto(update.project_id);
2237 let worktree_id = update.worktree_id as i64;
2238 let summary = update
2239 .summary
2240 .as_ref()
2241 .ok_or_else(|| anyhow!("invalid summary"))?;
2242
2243 // Ensure the update comes from the host.
2244 let project = project::Entity::find_by_id(project_id)
2245 .one(&*tx)
2246 .await?
2247 .ok_or_else(|| anyhow!("no such project"))?;
2248 if project.host_connection()? != connection {
2249 return Err(anyhow!("can't update a project hosted by someone else"))?;
2250 }
2251
2252 // Update summary.
2253 worktree_diagnostic_summary::Entity::insert(worktree_diagnostic_summary::ActiveModel {
2254 project_id: ActiveValue::set(project_id),
2255 worktree_id: ActiveValue::set(worktree_id),
2256 path: ActiveValue::set(summary.path.clone()),
2257 language_server_id: ActiveValue::set(summary.language_server_id as i64),
2258 error_count: ActiveValue::set(summary.error_count as i32),
2259 warning_count: ActiveValue::set(summary.warning_count as i32),
2260 ..Default::default()
2261 })
2262 .on_conflict(
2263 OnConflict::columns([
2264 worktree_diagnostic_summary::Column::ProjectId,
2265 worktree_diagnostic_summary::Column::WorktreeId,
2266 worktree_diagnostic_summary::Column::Path,
2267 ])
2268 .update_columns([
2269 worktree_diagnostic_summary::Column::LanguageServerId,
2270 worktree_diagnostic_summary::Column::ErrorCount,
2271 worktree_diagnostic_summary::Column::WarningCount,
2272 ])
2273 .to_owned(),
2274 )
2275 .exec(&*tx)
2276 .await?;
2277
2278 let connection_ids = self.project_guest_connection_ids(project_id, &tx).await?;
2279 Ok((project.room_id, connection_ids))
2280 })
2281 .await
2282 }
2283
2284 pub async fn start_language_server(
2285 &self,
2286 update: &proto::StartLanguageServer,
2287 connection: ConnectionId,
2288 ) -> Result<RoomGuard<Vec<ConnectionId>>> {
2289 self.room_transaction(|tx| async move {
2290 let project_id = ProjectId::from_proto(update.project_id);
2291 let server = update
2292 .server
2293 .as_ref()
2294 .ok_or_else(|| anyhow!("invalid language server"))?;
2295
2296 // Ensure the update comes from the host.
2297 let project = project::Entity::find_by_id(project_id)
2298 .one(&*tx)
2299 .await?
2300 .ok_or_else(|| anyhow!("no such project"))?;
2301 if project.host_connection()? != connection {
2302 return Err(anyhow!("can't update a project hosted by someone else"))?;
2303 }
2304
2305 // Add the newly-started language server.
2306 language_server::Entity::insert(language_server::ActiveModel {
2307 project_id: ActiveValue::set(project_id),
2308 id: ActiveValue::set(server.id as i64),
2309 name: ActiveValue::set(server.name.clone()),
2310 ..Default::default()
2311 })
2312 .on_conflict(
2313 OnConflict::columns([
2314 language_server::Column::ProjectId,
2315 language_server::Column::Id,
2316 ])
2317 .update_column(language_server::Column::Name)
2318 .to_owned(),
2319 )
2320 .exec(&*tx)
2321 .await?;
2322
2323 let connection_ids = self.project_guest_connection_ids(project_id, &tx).await?;
2324 Ok((project.room_id, connection_ids))
2325 })
2326 .await
2327 }
2328
2329 pub async fn join_project(
2330 &self,
2331 project_id: ProjectId,
2332 connection: ConnectionId,
2333 ) -> Result<RoomGuard<(Project, ReplicaId)>> {
2334 self.room_transaction(|tx| async move {
2335 let participant = room_participant::Entity::find()
2336 .filter(
2337 Condition::all()
2338 .add(
2339 room_participant::Column::AnsweringConnectionId
2340 .eq(connection.id as i32),
2341 )
2342 .add(
2343 room_participant::Column::AnsweringConnectionServerId
2344 .eq(connection.owner_id as i32),
2345 ),
2346 )
2347 .one(&*tx)
2348 .await?
2349 .ok_or_else(|| anyhow!("must join a room first"))?;
2350
2351 let project = project::Entity::find_by_id(project_id)
2352 .one(&*tx)
2353 .await?
2354 .ok_or_else(|| anyhow!("no such project"))?;
2355 if project.room_id != participant.room_id {
2356 return Err(anyhow!("no such project"))?;
2357 }
2358
2359 let mut collaborators = project
2360 .find_related(project_collaborator::Entity)
2361 .all(&*tx)
2362 .await?;
2363 let replica_ids = collaborators
2364 .iter()
2365 .map(|c| c.replica_id)
2366 .collect::<HashSet<_>>();
2367 let mut replica_id = ReplicaId(1);
2368 while replica_ids.contains(&replica_id) {
2369 replica_id.0 += 1;
2370 }
2371 let new_collaborator = project_collaborator::ActiveModel {
2372 project_id: ActiveValue::set(project_id),
2373 connection_id: ActiveValue::set(connection.id as i32),
2374 connection_server_id: ActiveValue::set(ServerId(connection.owner_id as i32)),
2375 user_id: ActiveValue::set(participant.user_id),
2376 replica_id: ActiveValue::set(replica_id),
2377 is_host: ActiveValue::set(false),
2378 ..Default::default()
2379 }
2380 .insert(&*tx)
2381 .await?;
2382 collaborators.push(new_collaborator);
2383
2384 let db_worktrees = project.find_related(worktree::Entity).all(&*tx).await?;
2385 let mut worktrees = db_worktrees
2386 .into_iter()
2387 .map(|db_worktree| {
2388 (
2389 db_worktree.id as u64,
2390 Worktree {
2391 id: db_worktree.id as u64,
2392 abs_path: db_worktree.abs_path,
2393 root_name: db_worktree.root_name,
2394 visible: db_worktree.visible,
2395 entries: Default::default(),
2396 diagnostic_summaries: Default::default(),
2397 scan_id: db_worktree.scan_id as u64,
2398 completed_scan_id: db_worktree.completed_scan_id as u64,
2399 },
2400 )
2401 })
2402 .collect::<BTreeMap<_, _>>();
2403
2404 // Populate worktree entries.
2405 {
2406 let mut db_entries = worktree_entry::Entity::find()
2407 .filter(
2408 Condition::all()
2409 .add(worktree_entry::Column::ProjectId.eq(project_id))
2410 .add(worktree_entry::Column::IsDeleted.eq(false)),
2411 )
2412 .stream(&*tx)
2413 .await?;
2414 while let Some(db_entry) = db_entries.next().await {
2415 let db_entry = db_entry?;
2416 if let Some(worktree) = worktrees.get_mut(&(db_entry.worktree_id as u64)) {
2417 worktree.entries.push(proto::Entry {
2418 id: db_entry.id as u64,
2419 is_dir: db_entry.is_dir,
2420 path: db_entry.path,
2421 inode: db_entry.inode as u64,
2422 mtime: Some(proto::Timestamp {
2423 seconds: db_entry.mtime_seconds as u64,
2424 nanos: db_entry.mtime_nanos as u32,
2425 }),
2426 is_symlink: db_entry.is_symlink,
2427 is_ignored: db_entry.is_ignored,
2428 });
2429 }
2430 }
2431 }
2432
2433 // Populate worktree diagnostic summaries.
2434 {
2435 let mut db_summaries = worktree_diagnostic_summary::Entity::find()
2436 .filter(worktree_diagnostic_summary::Column::ProjectId.eq(project_id))
2437 .stream(&*tx)
2438 .await?;
2439 while let Some(db_summary) = db_summaries.next().await {
2440 let db_summary = db_summary?;
2441 if let Some(worktree) = worktrees.get_mut(&(db_summary.worktree_id as u64)) {
2442 worktree
2443 .diagnostic_summaries
2444 .push(proto::DiagnosticSummary {
2445 path: db_summary.path,
2446 language_server_id: db_summary.language_server_id as u64,
2447 error_count: db_summary.error_count as u32,
2448 warning_count: db_summary.warning_count as u32,
2449 });
2450 }
2451 }
2452 }
2453
2454 // Populate language servers.
2455 let language_servers = project
2456 .find_related(language_server::Entity)
2457 .all(&*tx)
2458 .await?;
2459
2460 let room_id = project.room_id;
2461 let project = Project {
2462 collaborators: collaborators
2463 .into_iter()
2464 .map(|collaborator| ProjectCollaborator {
2465 connection_id: collaborator.connection(),
2466 user_id: collaborator.user_id,
2467 replica_id: collaborator.replica_id,
2468 is_host: collaborator.is_host,
2469 })
2470 .collect(),
2471 worktrees,
2472 language_servers: language_servers
2473 .into_iter()
2474 .map(|language_server| proto::LanguageServer {
2475 id: language_server.id as u64,
2476 name: language_server.name,
2477 })
2478 .collect(),
2479 };
2480 Ok((room_id, (project, replica_id as ReplicaId)))
2481 })
2482 .await
2483 }
2484
2485 pub async fn leave_project(
2486 &self,
2487 project_id: ProjectId,
2488 connection: ConnectionId,
2489 ) -> Result<RoomGuard<LeftProject>> {
2490 self.room_transaction(|tx| async move {
2491 let result = project_collaborator::Entity::delete_many()
2492 .filter(
2493 Condition::all()
2494 .add(project_collaborator::Column::ProjectId.eq(project_id))
2495 .add(project_collaborator::Column::ConnectionId.eq(connection.id as i32))
2496 .add(
2497 project_collaborator::Column::ConnectionServerId
2498 .eq(connection.owner_id as i32),
2499 ),
2500 )
2501 .exec(&*tx)
2502 .await?;
2503 if result.rows_affected == 0 {
2504 Err(anyhow!("not a collaborator on this project"))?;
2505 }
2506
2507 let project = project::Entity::find_by_id(project_id)
2508 .one(&*tx)
2509 .await?
2510 .ok_or_else(|| anyhow!("no such project"))?;
2511 let collaborators = project
2512 .find_related(project_collaborator::Entity)
2513 .all(&*tx)
2514 .await?;
2515 let connection_ids = collaborators
2516 .into_iter()
2517 .map(|collaborator| collaborator.connection())
2518 .collect();
2519
2520 let left_project = LeftProject {
2521 id: project_id,
2522 host_user_id: project.host_user_id,
2523 host_connection_id: project.host_connection()?,
2524 connection_ids,
2525 };
2526 Ok((project.room_id, left_project))
2527 })
2528 .await
2529 }
2530
2531 pub async fn project_collaborators(
2532 &self,
2533 project_id: ProjectId,
2534 connection_id: ConnectionId,
2535 ) -> Result<RoomGuard<Vec<ProjectCollaborator>>> {
2536 self.room_transaction(|tx| async move {
2537 let project = project::Entity::find_by_id(project_id)
2538 .one(&*tx)
2539 .await?
2540 .ok_or_else(|| anyhow!("no such project"))?;
2541 let collaborators = project_collaborator::Entity::find()
2542 .filter(project_collaborator::Column::ProjectId.eq(project_id))
2543 .all(&*tx)
2544 .await?
2545 .into_iter()
2546 .map(|collaborator| ProjectCollaborator {
2547 connection_id: collaborator.connection(),
2548 user_id: collaborator.user_id,
2549 replica_id: collaborator.replica_id,
2550 is_host: collaborator.is_host,
2551 })
2552 .collect::<Vec<_>>();
2553
2554 if collaborators
2555 .iter()
2556 .any(|collaborator| collaborator.connection_id == connection_id)
2557 {
2558 Ok((project.room_id, collaborators))
2559 } else {
2560 Err(anyhow!("no such project"))?
2561 }
2562 })
2563 .await
2564 }
2565
2566 pub async fn project_connection_ids(
2567 &self,
2568 project_id: ProjectId,
2569 connection_id: ConnectionId,
2570 ) -> Result<RoomGuard<HashSet<ConnectionId>>> {
2571 self.room_transaction(|tx| async move {
2572 let project = project::Entity::find_by_id(project_id)
2573 .one(&*tx)
2574 .await?
2575 .ok_or_else(|| anyhow!("no such project"))?;
2576 let mut collaborators = project_collaborator::Entity::find()
2577 .filter(project_collaborator::Column::ProjectId.eq(project_id))
2578 .stream(&*tx)
2579 .await?;
2580
2581 let mut connection_ids = HashSet::default();
2582 while let Some(collaborator) = collaborators.next().await {
2583 let collaborator = collaborator?;
2584 connection_ids.insert(collaborator.connection());
2585 }
2586
2587 if connection_ids.contains(&connection_id) {
2588 Ok((project.room_id, connection_ids))
2589 } else {
2590 Err(anyhow!("no such project"))?
2591 }
2592 })
2593 .await
2594 }
2595
2596 async fn project_guest_connection_ids(
2597 &self,
2598 project_id: ProjectId,
2599 tx: &DatabaseTransaction,
2600 ) -> Result<Vec<ConnectionId>> {
2601 let mut collaborators = project_collaborator::Entity::find()
2602 .filter(
2603 project_collaborator::Column::ProjectId
2604 .eq(project_id)
2605 .and(project_collaborator::Column::IsHost.eq(false)),
2606 )
2607 .stream(tx)
2608 .await?;
2609
2610 let mut guest_connection_ids = Vec::new();
2611 while let Some(collaborator) = collaborators.next().await {
2612 let collaborator = collaborator?;
2613 guest_connection_ids.push(collaborator.connection());
2614 }
2615 Ok(guest_connection_ids)
2616 }
2617
2618 // access tokens
2619
2620 pub async fn create_access_token_hash(
2621 &self,
2622 user_id: UserId,
2623 access_token_hash: &str,
2624 max_access_token_count: usize,
2625 ) -> Result<()> {
2626 self.transaction(|tx| async {
2627 let tx = tx;
2628
2629 access_token::ActiveModel {
2630 user_id: ActiveValue::set(user_id),
2631 hash: ActiveValue::set(access_token_hash.into()),
2632 ..Default::default()
2633 }
2634 .insert(&*tx)
2635 .await?;
2636
2637 access_token::Entity::delete_many()
2638 .filter(
2639 access_token::Column::Id.in_subquery(
2640 Query::select()
2641 .column(access_token::Column::Id)
2642 .from(access_token::Entity)
2643 .and_where(access_token::Column::UserId.eq(user_id))
2644 .order_by(access_token::Column::Id, sea_orm::Order::Desc)
2645 .limit(10000)
2646 .offset(max_access_token_count as u64)
2647 .to_owned(),
2648 ),
2649 )
2650 .exec(&*tx)
2651 .await?;
2652 Ok(())
2653 })
2654 .await
2655 }
2656
2657 pub async fn get_access_token_hashes(&self, user_id: UserId) -> Result<Vec<String>> {
2658 #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
2659 enum QueryAs {
2660 Hash,
2661 }
2662
2663 self.transaction(|tx| async move {
2664 Ok(access_token::Entity::find()
2665 .select_only()
2666 .column(access_token::Column::Hash)
2667 .filter(access_token::Column::UserId.eq(user_id))
2668 .order_by_desc(access_token::Column::Id)
2669 .into_values::<_, QueryAs>()
2670 .all(&*tx)
2671 .await?)
2672 })
2673 .await
2674 }
2675
2676 async fn transaction<F, Fut, T>(&self, f: F) -> Result<T>
2677 where
2678 F: Send + Fn(TransactionHandle) -> Fut,
2679 Fut: Send + Future<Output = Result<T>>,
2680 {
2681 let body = async {
2682 loop {
2683 let (tx, result) = self.with_transaction(&f).await?;
2684 match result {
2685 Ok(result) => {
2686 match tx.commit().await.map_err(Into::into) {
2687 Ok(()) => return Ok(result),
2688 Err(error) => {
2689 if is_serialization_error(&error) {
2690 // Retry (don't break the loop)
2691 } else {
2692 return Err(error);
2693 }
2694 }
2695 }
2696 }
2697 Err(error) => {
2698 tx.rollback().await?;
2699 if is_serialization_error(&error) {
2700 // Retry (don't break the loop)
2701 } else {
2702 return Err(error);
2703 }
2704 }
2705 }
2706 }
2707 };
2708
2709 self.run(body).await
2710 }
2711
2712 async fn optional_room_transaction<F, Fut, T>(&self, f: F) -> Result<Option<RoomGuard<T>>>
2713 where
2714 F: Send + Fn(TransactionHandle) -> Fut,
2715 Fut: Send + Future<Output = Result<Option<(RoomId, T)>>>,
2716 {
2717 let body = async {
2718 loop {
2719 let (tx, result) = self.with_transaction(&f).await?;
2720 match result {
2721 Ok(Some((room_id, data))) => {
2722 let lock = self.rooms.entry(room_id).or_default().clone();
2723 let _guard = lock.lock_owned().await;
2724 match tx.commit().await.map_err(Into::into) {
2725 Ok(()) => {
2726 return Ok(Some(RoomGuard {
2727 data,
2728 _guard,
2729 _not_send: PhantomData,
2730 }));
2731 }
2732 Err(error) => {
2733 if is_serialization_error(&error) {
2734 // Retry (don't break the loop)
2735 } else {
2736 return Err(error);
2737 }
2738 }
2739 }
2740 }
2741 Ok(None) => {
2742 match tx.commit().await.map_err(Into::into) {
2743 Ok(()) => return Ok(None),
2744 Err(error) => {
2745 if is_serialization_error(&error) {
2746 // Retry (don't break the loop)
2747 } else {
2748 return Err(error);
2749 }
2750 }
2751 }
2752 }
2753 Err(error) => {
2754 tx.rollback().await?;
2755 if is_serialization_error(&error) {
2756 // Retry (don't break the loop)
2757 } else {
2758 return Err(error);
2759 }
2760 }
2761 }
2762 }
2763 };
2764
2765 self.run(body).await
2766 }
2767
2768 async fn room_transaction<F, Fut, T>(&self, f: F) -> Result<RoomGuard<T>>
2769 where
2770 F: Send + Fn(TransactionHandle) -> Fut,
2771 Fut: Send + Future<Output = Result<(RoomId, T)>>,
2772 {
2773 let data = self
2774 .optional_room_transaction(move |tx| {
2775 let future = f(tx);
2776 async {
2777 let data = future.await?;
2778 Ok(Some(data))
2779 }
2780 })
2781 .await?;
2782 Ok(data.unwrap())
2783 }
2784
2785 async fn with_transaction<F, Fut, T>(&self, f: &F) -> Result<(DatabaseTransaction, Result<T>)>
2786 where
2787 F: Send + Fn(TransactionHandle) -> Fut,
2788 Fut: Send + Future<Output = Result<T>>,
2789 {
2790 let tx = self
2791 .pool
2792 .begin_with_config(Some(IsolationLevel::Serializable), None)
2793 .await?;
2794
2795 let mut tx = Arc::new(Some(tx));
2796 let result = f(TransactionHandle(tx.clone())).await;
2797 let Some(tx) = Arc::get_mut(&mut tx).and_then(|tx| tx.take()) else {
2798 return Err(anyhow!("couldn't complete transaction because it's still in use"))?;
2799 };
2800
2801 Ok((tx, result))
2802 }
2803
2804 async fn run<F, T>(&self, future: F) -> T
2805 where
2806 F: Future<Output = T>,
2807 {
2808 #[cfg(test)]
2809 {
2810 if let Some(background) = self.background.as_ref() {
2811 background.simulate_random_delay().await;
2812 }
2813
2814 self.runtime.as_ref().unwrap().block_on(future)
2815 }
2816
2817 #[cfg(not(test))]
2818 {
2819 future.await
2820 }
2821 }
2822}
2823
2824fn is_serialization_error(error: &Error) -> bool {
2825 const SERIALIZATION_FAILURE_CODE: &'static str = "40001";
2826 match error {
2827 Error::Database(
2828 DbErr::Exec(sea_orm::RuntimeErr::SqlxError(error))
2829 | DbErr::Query(sea_orm::RuntimeErr::SqlxError(error)),
2830 ) if error
2831 .as_database_error()
2832 .and_then(|error| error.code())
2833 .as_deref()
2834 == Some(SERIALIZATION_FAILURE_CODE) =>
2835 {
2836 true
2837 }
2838 _ => false,
2839 }
2840}
2841
2842struct TransactionHandle(Arc<Option<DatabaseTransaction>>);
2843
2844impl Deref for TransactionHandle {
2845 type Target = DatabaseTransaction;
2846
2847 fn deref(&self) -> &Self::Target {
2848 self.0.as_ref().as_ref().unwrap()
2849 }
2850}
2851
2852pub struct RoomGuard<T> {
2853 data: T,
2854 _guard: OwnedMutexGuard<()>,
2855 _not_send: PhantomData<Rc<()>>,
2856}
2857
2858impl<T> Deref for RoomGuard<T> {
2859 type Target = T;
2860
2861 fn deref(&self) -> &T {
2862 &self.data
2863 }
2864}
2865
2866impl<T> DerefMut for RoomGuard<T> {
2867 fn deref_mut(&mut self) -> &mut T {
2868 &mut self.data
2869 }
2870}
2871
2872#[derive(Debug, Serialize, Deserialize)]
2873pub struct NewUserParams {
2874 pub github_login: String,
2875 pub github_user_id: i32,
2876 pub invite_count: i32,
2877}
2878
2879#[derive(Debug)]
2880pub struct NewUserResult {
2881 pub user_id: UserId,
2882 pub metrics_id: String,
2883 pub inviting_user_id: Option<UserId>,
2884 pub signup_device_id: Option<String>,
2885}
2886
2887fn random_invite_code() -> String {
2888 nanoid::nanoid!(16)
2889}
2890
2891fn random_email_confirmation_code() -> String {
2892 nanoid::nanoid!(64)
2893}
2894
2895macro_rules! id_type {
2896 ($name:ident) => {
2897 #[derive(
2898 Clone,
2899 Copy,
2900 Debug,
2901 Default,
2902 PartialEq,
2903 Eq,
2904 PartialOrd,
2905 Ord,
2906 Hash,
2907 Serialize,
2908 Deserialize,
2909 )]
2910 #[serde(transparent)]
2911 pub struct $name(pub i32);
2912
2913 impl $name {
2914 #[allow(unused)]
2915 pub const MAX: Self = Self(i32::MAX);
2916
2917 #[allow(unused)]
2918 pub fn from_proto(value: u64) -> Self {
2919 Self(value as i32)
2920 }
2921
2922 #[allow(unused)]
2923 pub fn to_proto(self) -> u64 {
2924 self.0 as u64
2925 }
2926 }
2927
2928 impl std::fmt::Display for $name {
2929 fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
2930 self.0.fmt(f)
2931 }
2932 }
2933
2934 impl From<$name> for sea_query::Value {
2935 fn from(value: $name) -> Self {
2936 sea_query::Value::Int(Some(value.0))
2937 }
2938 }
2939
2940 impl sea_orm::TryGetable for $name {
2941 fn try_get(
2942 res: &sea_orm::QueryResult,
2943 pre: &str,
2944 col: &str,
2945 ) -> Result<Self, sea_orm::TryGetError> {
2946 Ok(Self(i32::try_get(res, pre, col)?))
2947 }
2948 }
2949
2950 impl sea_query::ValueType for $name {
2951 fn try_from(v: Value) -> Result<Self, sea_query::ValueTypeErr> {
2952 match v {
2953 Value::TinyInt(Some(int)) => {
2954 Ok(Self(int.try_into().map_err(|_| sea_query::ValueTypeErr)?))
2955 }
2956 Value::SmallInt(Some(int)) => {
2957 Ok(Self(int.try_into().map_err(|_| sea_query::ValueTypeErr)?))
2958 }
2959 Value::Int(Some(int)) => {
2960 Ok(Self(int.try_into().map_err(|_| sea_query::ValueTypeErr)?))
2961 }
2962 Value::BigInt(Some(int)) => {
2963 Ok(Self(int.try_into().map_err(|_| sea_query::ValueTypeErr)?))
2964 }
2965 Value::TinyUnsigned(Some(int)) => {
2966 Ok(Self(int.try_into().map_err(|_| sea_query::ValueTypeErr)?))
2967 }
2968 Value::SmallUnsigned(Some(int)) => {
2969 Ok(Self(int.try_into().map_err(|_| sea_query::ValueTypeErr)?))
2970 }
2971 Value::Unsigned(Some(int)) => {
2972 Ok(Self(int.try_into().map_err(|_| sea_query::ValueTypeErr)?))
2973 }
2974 Value::BigUnsigned(Some(int)) => {
2975 Ok(Self(int.try_into().map_err(|_| sea_query::ValueTypeErr)?))
2976 }
2977 _ => Err(sea_query::ValueTypeErr),
2978 }
2979 }
2980
2981 fn type_name() -> String {
2982 stringify!($name).into()
2983 }
2984
2985 fn array_type() -> sea_query::ArrayType {
2986 sea_query::ArrayType::Int
2987 }
2988
2989 fn column_type() -> sea_query::ColumnType {
2990 sea_query::ColumnType::Integer(None)
2991 }
2992 }
2993
2994 impl sea_orm::TryFromU64 for $name {
2995 fn try_from_u64(n: u64) -> Result<Self, DbErr> {
2996 Ok(Self(n.try_into().map_err(|_| {
2997 DbErr::ConvertFromU64(concat!(
2998 "error converting ",
2999 stringify!($name),
3000 " to u64"
3001 ))
3002 })?))
3003 }
3004 }
3005
3006 impl sea_query::Nullable for $name {
3007 fn null() -> Value {
3008 Value::Int(None)
3009 }
3010 }
3011 };
3012}
3013
3014id_type!(AccessTokenId);
3015id_type!(ContactId);
3016id_type!(RoomId);
3017id_type!(RoomParticipantId);
3018id_type!(ProjectId);
3019id_type!(ProjectCollaboratorId);
3020id_type!(ReplicaId);
3021id_type!(ServerId);
3022id_type!(SignupId);
3023id_type!(UserId);
3024
3025pub struct RejoinedRoom {
3026 pub room: proto::Room,
3027 pub rejoined_projects: Vec<RejoinedProject>,
3028 pub reshared_projects: Vec<ResharedProject>,
3029}
3030
3031pub struct ResharedProject {
3032 pub id: ProjectId,
3033 pub old_connection_id: ConnectionId,
3034 pub collaborators: Vec<ProjectCollaborator>,
3035 pub worktrees: Vec<proto::WorktreeMetadata>,
3036}
3037
3038pub struct RejoinedProject {
3039 pub id: ProjectId,
3040 pub old_connection_id: ConnectionId,
3041 pub collaborators: Vec<ProjectCollaborator>,
3042 pub worktrees: Vec<RejoinedWorktree>,
3043 pub language_servers: Vec<proto::LanguageServer>,
3044}
3045
3046#[derive(Debug)]
3047pub struct RejoinedWorktree {
3048 pub id: u64,
3049 pub abs_path: String,
3050 pub root_name: String,
3051 pub visible: bool,
3052 pub updated_entries: Vec<proto::Entry>,
3053 pub removed_entries: Vec<u64>,
3054 pub diagnostic_summaries: Vec<proto::DiagnosticSummary>,
3055 pub scan_id: u64,
3056 pub completed_scan_id: u64,
3057}
3058
3059pub struct LeftRoom {
3060 pub room: proto::Room,
3061 pub left_projects: HashMap<ProjectId, LeftProject>,
3062 pub canceled_calls_to_user_ids: Vec<UserId>,
3063}
3064
3065pub struct RefreshedRoom {
3066 pub room: proto::Room,
3067 pub stale_participant_user_ids: Vec<UserId>,
3068 pub canceled_calls_to_user_ids: Vec<UserId>,
3069}
3070
3071pub struct Project {
3072 pub collaborators: Vec<ProjectCollaborator>,
3073 pub worktrees: BTreeMap<u64, Worktree>,
3074 pub language_servers: Vec<proto::LanguageServer>,
3075}
3076
3077pub struct ProjectCollaborator {
3078 pub connection_id: ConnectionId,
3079 pub user_id: UserId,
3080 pub replica_id: ReplicaId,
3081 pub is_host: bool,
3082}
3083
3084impl ProjectCollaborator {
3085 pub fn to_proto(&self) -> proto::Collaborator {
3086 proto::Collaborator {
3087 peer_id: Some(self.connection_id.into()),
3088 replica_id: self.replica_id.0 as u32,
3089 user_id: self.user_id.to_proto(),
3090 }
3091 }
3092}
3093
3094#[derive(Debug)]
3095pub struct LeftProject {
3096 pub id: ProjectId,
3097 pub host_user_id: UserId,
3098 pub host_connection_id: ConnectionId,
3099 pub connection_ids: Vec<ConnectionId>,
3100}
3101
3102pub struct Worktree {
3103 pub id: u64,
3104 pub abs_path: String,
3105 pub root_name: String,
3106 pub visible: bool,
3107 pub entries: Vec<proto::Entry>,
3108 pub diagnostic_summaries: Vec<proto::DiagnosticSummary>,
3109 pub scan_id: u64,
3110 pub completed_scan_id: u64,
3111}
3112
3113#[cfg(test)]
3114pub use test::*;
3115
3116#[cfg(test)]
3117mod test {
3118 use super::*;
3119 use gpui::executor::Background;
3120 use lazy_static::lazy_static;
3121 use parking_lot::Mutex;
3122 use rand::prelude::*;
3123 use sea_orm::ConnectionTrait;
3124 use sqlx::migrate::MigrateDatabase;
3125 use std::sync::Arc;
3126
3127 pub struct TestDb {
3128 pub db: Option<Arc<Database>>,
3129 pub connection: Option<sqlx::AnyConnection>,
3130 }
3131
3132 impl TestDb {
3133 pub fn sqlite(background: Arc<Background>) -> Self {
3134 let url = format!("sqlite::memory:");
3135 let runtime = tokio::runtime::Builder::new_current_thread()
3136 .enable_io()
3137 .enable_time()
3138 .build()
3139 .unwrap();
3140
3141 let mut db = runtime.block_on(async {
3142 let mut options = ConnectOptions::new(url);
3143 options.max_connections(5);
3144 let db = Database::new(options).await.unwrap();
3145 let sql = include_str!(concat!(
3146 env!("CARGO_MANIFEST_DIR"),
3147 "/migrations.sqlite/20221109000000_test_schema.sql"
3148 ));
3149 db.pool
3150 .execute(sea_orm::Statement::from_string(
3151 db.pool.get_database_backend(),
3152 sql.into(),
3153 ))
3154 .await
3155 .unwrap();
3156 db
3157 });
3158
3159 db.background = Some(background);
3160 db.runtime = Some(runtime);
3161
3162 Self {
3163 db: Some(Arc::new(db)),
3164 connection: None,
3165 }
3166 }
3167
3168 pub fn postgres(background: Arc<Background>) -> Self {
3169 lazy_static! {
3170 static ref LOCK: Mutex<()> = Mutex::new(());
3171 }
3172
3173 let _guard = LOCK.lock();
3174 let mut rng = StdRng::from_entropy();
3175 let url = format!(
3176 "postgres://postgres@localhost/zed-test-{}",
3177 rng.gen::<u128>()
3178 );
3179 let runtime = tokio::runtime::Builder::new_current_thread()
3180 .enable_io()
3181 .enable_time()
3182 .build()
3183 .unwrap();
3184
3185 let mut db = runtime.block_on(async {
3186 sqlx::Postgres::create_database(&url)
3187 .await
3188 .expect("failed to create test db");
3189 let mut options = ConnectOptions::new(url);
3190 options
3191 .max_connections(5)
3192 .idle_timeout(Duration::from_secs(0));
3193 let db = Database::new(options).await.unwrap();
3194 let migrations_path = concat!(env!("CARGO_MANIFEST_DIR"), "/migrations");
3195 db.migrate(Path::new(migrations_path), false).await.unwrap();
3196 db
3197 });
3198
3199 db.background = Some(background);
3200 db.runtime = Some(runtime);
3201
3202 Self {
3203 db: Some(Arc::new(db)),
3204 connection: None,
3205 }
3206 }
3207
3208 pub fn db(&self) -> &Arc<Database> {
3209 self.db.as_ref().unwrap()
3210 }
3211 }
3212
3213 impl Drop for TestDb {
3214 fn drop(&mut self) {
3215 let db = self.db.take().unwrap();
3216 if let sea_orm::DatabaseBackend::Postgres = db.pool.get_database_backend() {
3217 db.runtime.as_ref().unwrap().block_on(async {
3218 use util::ResultExt;
3219 let query = "
3220 SELECT pg_terminate_backend(pg_stat_activity.pid)
3221 FROM pg_stat_activity
3222 WHERE
3223 pg_stat_activity.datname = current_database() AND
3224 pid <> pg_backend_pid();
3225 ";
3226 db.pool
3227 .execute(sea_orm::Statement::from_string(
3228 db.pool.get_database_backend(),
3229 query.into(),
3230 ))
3231 .await
3232 .log_err();
3233 sqlx::Postgres::drop_database(db.options.get_url())
3234 .await
3235 .log_err();
3236 })
3237 }
3238 }
3239 }
3240}