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