1use anyhow::Context as _;
2
3use super::*;
4
5impl Database {
6 /// Clears all room participants in rooms attached to a stale server.
7 pub async fn clear_stale_room_participants(
8 &self,
9 room_id: RoomId,
10 new_server_id: ServerId,
11 ) -> Result<TransactionGuard<RefreshedRoom>> {
12 self.room_transaction(room_id, |tx| async move {
13 let stale_participant_filter = Condition::all()
14 .add(room_participant::Column::RoomId.eq(room_id))
15 .add(room_participant::Column::AnsweringConnectionId.is_not_null())
16 .add(room_participant::Column::AnsweringConnectionServerId.ne(new_server_id));
17
18 let stale_participant_user_ids = room_participant::Entity::find()
19 .filter(stale_participant_filter.clone())
20 .all(&*tx)
21 .await?
22 .into_iter()
23 .map(|participant| participant.user_id)
24 .collect::<Vec<_>>();
25
26 // Delete participants who failed to reconnect and cancel their calls.
27 let mut canceled_calls_to_user_ids = Vec::new();
28 room_participant::Entity::delete_many()
29 .filter(stale_participant_filter)
30 .exec(&*tx)
31 .await?;
32 let called_participants = room_participant::Entity::find()
33 .filter(
34 Condition::all()
35 .add(
36 room_participant::Column::CallingUserId
37 .is_in(stale_participant_user_ids.iter().copied()),
38 )
39 .add(room_participant::Column::AnsweringConnectionId.is_null()),
40 )
41 .all(&*tx)
42 .await?;
43 room_participant::Entity::delete_many()
44 .filter(
45 room_participant::Column::Id
46 .is_in(called_participants.iter().map(|participant| participant.id)),
47 )
48 .exec(&*tx)
49 .await?;
50 canceled_calls_to_user_ids.extend(
51 called_participants
52 .into_iter()
53 .map(|participant| participant.user_id),
54 );
55
56 let (channel, room) = self.get_channel_room(room_id, &tx).await?;
57 if channel.is_none() {
58 // Delete the room if it becomes empty.
59 if room.participants.is_empty() {
60 project::Entity::delete_many()
61 .filter(project::Column::RoomId.eq(room_id))
62 .exec(&*tx)
63 .await?;
64 room::Entity::delete_by_id(room_id).exec(&*tx).await?;
65 }
66 };
67
68 Ok(RefreshedRoom {
69 room,
70 channel,
71 stale_participant_user_ids,
72 canceled_calls_to_user_ids,
73 })
74 })
75 .await
76 }
77
78 /// Returns the incoming calls for user with the given ID.
79 pub async fn incoming_call_for_user(
80 &self,
81 user_id: UserId,
82 ) -> Result<Option<proto::IncomingCall>> {
83 self.transaction(|tx| async move {
84 let pending_participant = room_participant::Entity::find()
85 .filter(
86 room_participant::Column::UserId
87 .eq(user_id)
88 .and(room_participant::Column::AnsweringConnectionId.is_null()),
89 )
90 .one(&*tx)
91 .await?;
92
93 if let Some(pending_participant) = pending_participant {
94 let room = self.get_room(pending_participant.room_id, &tx).await?;
95 Ok(Self::build_incoming_call(&room, user_id))
96 } else {
97 Ok(None)
98 }
99 })
100 .await
101 }
102
103 /// Creates a new room.
104 pub async fn create_room(
105 &self,
106 user_id: UserId,
107 connection: ConnectionId,
108 livekit_room: &str,
109 ) -> Result<proto::Room> {
110 self.transaction(|tx| async move {
111 let room = room::ActiveModel {
112 live_kit_room: ActiveValue::set(livekit_room.into()),
113 ..Default::default()
114 }
115 .insert(&*tx)
116 .await?;
117 room_participant::ActiveModel {
118 room_id: ActiveValue::set(room.id),
119 user_id: ActiveValue::set(user_id),
120 answering_connection_id: ActiveValue::set(Some(connection.id as i32)),
121 answering_connection_server_id: ActiveValue::set(Some(ServerId(
122 connection.owner_id as i32,
123 ))),
124 answering_connection_lost: ActiveValue::set(false),
125 calling_user_id: ActiveValue::set(user_id),
126 calling_connection_id: ActiveValue::set(connection.id as i32),
127 calling_connection_server_id: ActiveValue::set(Some(ServerId(
128 connection.owner_id as i32,
129 ))),
130 participant_index: ActiveValue::set(Some(0)),
131 role: ActiveValue::set(Some(ChannelRole::Admin)),
132
133 id: ActiveValue::NotSet,
134 location_kind: ActiveValue::NotSet,
135 location_project_id: ActiveValue::NotSet,
136 initial_project_id: ActiveValue::NotSet,
137 }
138 .insert(&*tx)
139 .await?;
140
141 let room = self.get_room(room.id, &tx).await?;
142 Ok(room)
143 })
144 .await
145 }
146
147 pub async fn call(
148 &self,
149 room_id: RoomId,
150 calling_user_id: UserId,
151 calling_connection: ConnectionId,
152 called_user_id: UserId,
153 initial_project_id: Option<ProjectId>,
154 ) -> Result<TransactionGuard<(proto::Room, proto::IncomingCall)>> {
155 self.room_transaction(room_id, |tx| async move {
156 let caller = room_participant::Entity::find()
157 .filter(
158 room_participant::Column::UserId
159 .eq(calling_user_id)
160 .and(room_participant::Column::RoomId.eq(room_id)),
161 )
162 .one(&*tx)
163 .await?
164 .ok_or_else(|| anyhow!("user is not in the room"))?;
165
166 let called_user_role = match caller.role.unwrap_or(ChannelRole::Member) {
167 ChannelRole::Admin | ChannelRole::Member => ChannelRole::Member,
168 ChannelRole::Guest | ChannelRole::Talker => ChannelRole::Guest,
169 ChannelRole::Banned => return Err(anyhow!("banned users cannot invite").into()),
170 };
171
172 room_participant::ActiveModel {
173 room_id: ActiveValue::set(room_id),
174 user_id: ActiveValue::set(called_user_id),
175 answering_connection_lost: ActiveValue::set(false),
176 participant_index: ActiveValue::NotSet,
177 calling_user_id: ActiveValue::set(calling_user_id),
178 calling_connection_id: ActiveValue::set(calling_connection.id as i32),
179 calling_connection_server_id: ActiveValue::set(Some(ServerId(
180 calling_connection.owner_id as i32,
181 ))),
182 initial_project_id: ActiveValue::set(initial_project_id),
183 role: ActiveValue::set(Some(called_user_role)),
184
185 id: ActiveValue::NotSet,
186 answering_connection_id: ActiveValue::NotSet,
187 answering_connection_server_id: ActiveValue::NotSet,
188 location_kind: ActiveValue::NotSet,
189 location_project_id: ActiveValue::NotSet,
190 }
191 .insert(&*tx)
192 .await?;
193
194 let room = self.get_room(room_id, &tx).await?;
195 let incoming_call = Self::build_incoming_call(&room, called_user_id)
196 .ok_or_else(|| anyhow!("failed to build incoming call"))?;
197 Ok((room, incoming_call))
198 })
199 .await
200 }
201
202 pub async fn call_failed(
203 &self,
204 room_id: RoomId,
205 called_user_id: UserId,
206 ) -> Result<TransactionGuard<proto::Room>> {
207 self.room_transaction(room_id, |tx| async move {
208 room_participant::Entity::delete_many()
209 .filter(
210 room_participant::Column::RoomId
211 .eq(room_id)
212 .and(room_participant::Column::UserId.eq(called_user_id)),
213 )
214 .exec(&*tx)
215 .await?;
216 let room = self.get_room(room_id, &tx).await?;
217 Ok(room)
218 })
219 .await
220 }
221
222 pub async fn decline_call(
223 &self,
224 expected_room_id: Option<RoomId>,
225 user_id: UserId,
226 ) -> Result<Option<TransactionGuard<proto::Room>>> {
227 self.optional_room_transaction(|tx| async move {
228 let mut filter = Condition::all()
229 .add(room_participant::Column::UserId.eq(user_id))
230 .add(room_participant::Column::AnsweringConnectionId.is_null());
231 if let Some(room_id) = expected_room_id {
232 filter = filter.add(room_participant::Column::RoomId.eq(room_id));
233 }
234 let participant = room_participant::Entity::find()
235 .filter(filter)
236 .one(&*tx)
237 .await?;
238
239 let participant = if let Some(participant) = participant {
240 participant
241 } else if expected_room_id.is_some() {
242 return Err(anyhow!("could not find call to decline"))?;
243 } else {
244 return Ok(None);
245 };
246
247 let room_id = participant.room_id;
248 room_participant::Entity::delete(participant.into_active_model())
249 .exec(&*tx)
250 .await?;
251
252 let room = self.get_room(room_id, &tx).await?;
253 Ok(Some((room_id, room)))
254 })
255 .await
256 }
257
258 pub async fn cancel_call(
259 &self,
260 room_id: RoomId,
261 calling_connection: ConnectionId,
262 called_user_id: UserId,
263 ) -> Result<TransactionGuard<proto::Room>> {
264 self.room_transaction(room_id, |tx| async move {
265 let participant = room_participant::Entity::find()
266 .filter(
267 Condition::all()
268 .add(room_participant::Column::UserId.eq(called_user_id))
269 .add(room_participant::Column::RoomId.eq(room_id))
270 .add(
271 room_participant::Column::CallingConnectionId
272 .eq(calling_connection.id as i32),
273 )
274 .add(
275 room_participant::Column::CallingConnectionServerId
276 .eq(calling_connection.owner_id as i32),
277 )
278 .add(room_participant::Column::AnsweringConnectionId.is_null()),
279 )
280 .one(&*tx)
281 .await?
282 .ok_or_else(|| anyhow!("no call to cancel"))?;
283
284 room_participant::Entity::delete(participant.into_active_model())
285 .exec(&*tx)
286 .await?;
287
288 let room = self.get_room(room_id, &tx).await?;
289 Ok(room)
290 })
291 .await
292 }
293
294 pub async fn join_room(
295 &self,
296 room_id: RoomId,
297 user_id: UserId,
298 connection: ConnectionId,
299 ) -> Result<TransactionGuard<JoinRoom>> {
300 self.room_transaction(room_id, |tx| async move {
301 #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
302 enum QueryChannelId {
303 ChannelId,
304 }
305
306 let channel_id: Option<ChannelId> = room::Entity::find()
307 .select_only()
308 .column(room::Column::ChannelId)
309 .filter(room::Column::Id.eq(room_id))
310 .into_values::<_, QueryChannelId>()
311 .one(&*tx)
312 .await?
313 .ok_or_else(|| anyhow!("no such room"))?;
314
315 if channel_id.is_some() {
316 Err(anyhow!("tried to join channel call directly"))?
317 }
318
319 let participant_index = self
320 .get_next_participant_index_internal(room_id, &tx)
321 .await?;
322
323 let result = room_participant::Entity::update_many()
324 .filter(
325 Condition::all()
326 .add(room_participant::Column::RoomId.eq(room_id))
327 .add(room_participant::Column::UserId.eq(user_id))
328 .add(room_participant::Column::AnsweringConnectionId.is_null()),
329 )
330 .set(room_participant::ActiveModel {
331 participant_index: ActiveValue::Set(Some(participant_index)),
332 answering_connection_id: ActiveValue::set(Some(connection.id as i32)),
333 answering_connection_server_id: ActiveValue::set(Some(ServerId(
334 connection.owner_id as i32,
335 ))),
336 answering_connection_lost: ActiveValue::set(false),
337 ..Default::default()
338 })
339 .exec(&*tx)
340 .await?;
341 if result.rows_affected == 0 {
342 Err(anyhow!("room does not exist or was already joined"))?;
343 }
344
345 let room = self.get_room(room_id, &tx).await?;
346 Ok(JoinRoom {
347 room,
348 channel: None,
349 })
350 })
351 .await
352 }
353
354 pub async fn stale_room_connection(&self, user_id: UserId) -> Result<Option<ConnectionId>> {
355 self.transaction(|tx| async move {
356 let participant = room_participant::Entity::find()
357 .filter(room_participant::Column::UserId.eq(user_id))
358 .one(&*tx)
359 .await?;
360 Ok(participant.and_then(|p| p.answering_connection()))
361 })
362 .await
363 }
364
365 async fn get_next_participant_index_internal(
366 &self,
367 room_id: RoomId,
368 tx: &DatabaseTransaction,
369 ) -> Result<i32> {
370 #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
371 enum QueryParticipantIndices {
372 ParticipantIndex,
373 }
374 let existing_participant_indices: Vec<i32> = room_participant::Entity::find()
375 .filter(
376 room_participant::Column::RoomId
377 .eq(room_id)
378 .and(room_participant::Column::ParticipantIndex.is_not_null()),
379 )
380 .select_only()
381 .column(room_participant::Column::ParticipantIndex)
382 .into_values::<_, QueryParticipantIndices>()
383 .all(tx)
384 .await?;
385
386 let mut participant_index = 0;
387 while existing_participant_indices.contains(&participant_index) {
388 participant_index += 1;
389 }
390
391 Ok(participant_index)
392 }
393
394 /// Returns the channel ID for the given room, if it has one.
395 pub async fn channel_id_for_room(&self, room_id: RoomId) -> Result<Option<ChannelId>> {
396 self.transaction(|tx| async move {
397 let room: Option<room::Model> = room::Entity::find()
398 .filter(room::Column::Id.eq(room_id))
399 .one(&*tx)
400 .await?;
401
402 Ok(room.and_then(|room| room.channel_id))
403 })
404 .await
405 }
406
407 pub(crate) async fn join_channel_room_internal(
408 &self,
409 room_id: RoomId,
410 user_id: UserId,
411 connection: ConnectionId,
412 role: ChannelRole,
413 tx: &DatabaseTransaction,
414 ) -> Result<JoinRoom> {
415 let participant_index = self
416 .get_next_participant_index_internal(room_id, tx)
417 .await?;
418
419 // If someone has been invited into the room, accept the invite instead of inserting
420 let result = room_participant::Entity::update_many()
421 .filter(
422 Condition::all()
423 .add(room_participant::Column::RoomId.eq(room_id))
424 .add(room_participant::Column::UserId.eq(user_id))
425 .add(room_participant::Column::AnsweringConnectionId.is_null()),
426 )
427 .set(room_participant::ActiveModel {
428 participant_index: ActiveValue::Set(Some(participant_index)),
429 answering_connection_id: ActiveValue::set(Some(connection.id as i32)),
430 answering_connection_server_id: ActiveValue::set(Some(ServerId(
431 connection.owner_id as i32,
432 ))),
433 answering_connection_lost: ActiveValue::set(false),
434 ..Default::default()
435 })
436 .exec(tx)
437 .await?;
438
439 if result.rows_affected == 0 {
440 room_participant::Entity::insert(room_participant::ActiveModel {
441 room_id: ActiveValue::set(room_id),
442 user_id: ActiveValue::set(user_id),
443 answering_connection_id: ActiveValue::set(Some(connection.id as i32)),
444 answering_connection_server_id: ActiveValue::set(Some(ServerId(
445 connection.owner_id as i32,
446 ))),
447 answering_connection_lost: ActiveValue::set(false),
448 calling_user_id: ActiveValue::set(user_id),
449 calling_connection_id: ActiveValue::set(connection.id as i32),
450 calling_connection_server_id: ActiveValue::set(Some(ServerId(
451 connection.owner_id as i32,
452 ))),
453 participant_index: ActiveValue::Set(Some(participant_index)),
454 role: ActiveValue::set(Some(role)),
455 id: ActiveValue::NotSet,
456 location_kind: ActiveValue::NotSet,
457 location_project_id: ActiveValue::NotSet,
458 initial_project_id: ActiveValue::NotSet,
459 })
460 .exec(tx)
461 .await?;
462 }
463
464 let (channel, room) = self.get_channel_room(room_id, tx).await?;
465 let channel = channel.ok_or_else(|| anyhow!("no channel for room"))?;
466 Ok(JoinRoom {
467 room,
468 channel: Some(channel),
469 })
470 }
471
472 pub async fn rejoin_room(
473 &self,
474 rejoin_room: proto::RejoinRoom,
475 user_id: UserId,
476 connection: ConnectionId,
477 ) -> Result<TransactionGuard<RejoinedRoom>> {
478 let room_id = RoomId::from_proto(rejoin_room.id);
479 self.room_transaction(room_id, |tx| async {
480 let tx = tx;
481 let participant_update = room_participant::Entity::update_many()
482 .filter(
483 Condition::all()
484 .add(room_participant::Column::RoomId.eq(room_id))
485 .add(room_participant::Column::UserId.eq(user_id))
486 .add(room_participant::Column::AnsweringConnectionId.is_not_null()),
487 )
488 .set(room_participant::ActiveModel {
489 answering_connection_id: ActiveValue::set(Some(connection.id as i32)),
490 answering_connection_server_id: ActiveValue::set(Some(ServerId(
491 connection.owner_id as i32,
492 ))),
493 answering_connection_lost: ActiveValue::set(false),
494 ..Default::default()
495 })
496 .exec(&*tx)
497 .await?;
498 if participant_update.rows_affected == 0 {
499 return Err(anyhow!("room does not exist or was already joined"))?;
500 }
501
502 let mut reshared_projects = Vec::new();
503 for reshared_project in &rejoin_room.reshared_projects {
504 let project_id = ProjectId::from_proto(reshared_project.project_id);
505 let project = project::Entity::find_by_id(project_id)
506 .one(&*tx)
507 .await?
508 .ok_or_else(|| anyhow!("project does not exist"))?;
509 if project.host_user_id != Some(user_id) {
510 return Err(anyhow!("no such project"))?;
511 }
512
513 let mut collaborators = project
514 .find_related(project_collaborator::Entity)
515 .all(&*tx)
516 .await?;
517 let host_ix = collaborators
518 .iter()
519 .position(|collaborator| {
520 collaborator.user_id == user_id && collaborator.is_host
521 })
522 .ok_or_else(|| anyhow!("host not found among collaborators"))?;
523 let host = collaborators.swap_remove(host_ix);
524 let old_connection_id = host.connection();
525
526 project::Entity::update(project::ActiveModel {
527 host_connection_id: ActiveValue::set(Some(connection.id as i32)),
528 host_connection_server_id: ActiveValue::set(Some(ServerId(
529 connection.owner_id as i32,
530 ))),
531 ..project.into_active_model()
532 })
533 .exec(&*tx)
534 .await?;
535 project_collaborator::Entity::update(project_collaborator::ActiveModel {
536 connection_id: ActiveValue::set(connection.id as i32),
537 connection_server_id: ActiveValue::set(ServerId(connection.owner_id as i32)),
538 ..host.into_active_model()
539 })
540 .exec(&*tx)
541 .await?;
542
543 self.update_project_worktrees(project_id, &reshared_project.worktrees, &tx)
544 .await?;
545
546 reshared_projects.push(ResharedProject {
547 id: project_id,
548 old_connection_id,
549 collaborators: collaborators
550 .iter()
551 .map(|collaborator| ProjectCollaborator {
552 connection_id: collaborator.connection(),
553 user_id: collaborator.user_id,
554 replica_id: collaborator.replica_id,
555 is_host: collaborator.is_host,
556 })
557 .collect(),
558 worktrees: reshared_project.worktrees.clone(),
559 });
560 }
561
562 project::Entity::delete_many()
563 .filter(
564 Condition::all()
565 .add(project::Column::RoomId.eq(room_id))
566 .add(project::Column::HostUserId.eq(user_id))
567 .add(
568 project::Column::Id
569 .is_not_in(reshared_projects.iter().map(|project| project.id)),
570 ),
571 )
572 .exec(&*tx)
573 .await?;
574
575 let mut rejoined_projects = Vec::new();
576 for rejoined_project in &rejoin_room.rejoined_projects {
577 if let Some(rejoined_project) = self
578 .rejoin_project_internal(&tx, rejoined_project, user_id, connection)
579 .await?
580 {
581 rejoined_projects.push(rejoined_project);
582 }
583 }
584
585 let (channel, room) = self.get_channel_room(room_id, &tx).await?;
586
587 Ok(RejoinedRoom {
588 room,
589 channel,
590 rejoined_projects,
591 reshared_projects,
592 })
593 })
594 .await
595 }
596
597 pub async fn rejoin_project_internal(
598 &self,
599 tx: &DatabaseTransaction,
600 rejoined_project: &proto::RejoinProject,
601 user_id: UserId,
602 connection: ConnectionId,
603 ) -> Result<Option<RejoinedProject>> {
604 let project_id = ProjectId::from_proto(rejoined_project.id);
605 let Some(project) = project::Entity::find_by_id(project_id).one(tx).await? else {
606 return Ok(None);
607 };
608
609 let mut worktrees = Vec::new();
610 let db_worktrees = project.find_related(worktree::Entity).all(tx).await?;
611 let db_repos = project
612 .find_related(project_repository::Entity)
613 .all(tx)
614 .await?;
615
616 for db_worktree in db_worktrees {
617 let mut worktree = RejoinedWorktree {
618 id: db_worktree.id as u64,
619 abs_path: db_worktree.abs_path,
620 root_name: db_worktree.root_name,
621 visible: db_worktree.visible,
622 updated_entries: Default::default(),
623 removed_entries: Default::default(),
624 updated_repositories: Default::default(),
625 removed_repositories: Default::default(),
626 diagnostic_summaries: Default::default(),
627 settings_files: Default::default(),
628 scan_id: db_worktree.scan_id as u64,
629 completed_scan_id: db_worktree.completed_scan_id as u64,
630 };
631
632 let rejoined_worktree = rejoined_project
633 .worktrees
634 .iter()
635 .find(|worktree| worktree.id == db_worktree.id as u64);
636
637 // File entries
638 {
639 let entry_filter = if let Some(rejoined_worktree) = rejoined_worktree {
640 worktree_entry::Column::ScanId.gt(rejoined_worktree.scan_id)
641 } else {
642 worktree_entry::Column::IsDeleted.eq(false)
643 };
644
645 let mut db_entries = worktree_entry::Entity::find()
646 .filter(
647 Condition::all()
648 .add(worktree_entry::Column::ProjectId.eq(project.id))
649 .add(worktree_entry::Column::WorktreeId.eq(worktree.id))
650 .add(entry_filter),
651 )
652 .stream(tx)
653 .await?;
654
655 while let Some(db_entry) = db_entries.next().await {
656 let db_entry = db_entry?;
657 if db_entry.is_deleted {
658 worktree.removed_entries.push(db_entry.id as u64);
659 } else {
660 worktree.updated_entries.push(proto::Entry {
661 id: db_entry.id as u64,
662 is_dir: db_entry.is_dir,
663 path: db_entry.path,
664 inode: db_entry.inode as u64,
665 mtime: Some(proto::Timestamp {
666 seconds: db_entry.mtime_seconds as u64,
667 nanos: db_entry.mtime_nanos as u32,
668 }),
669 canonical_path: db_entry.canonical_path,
670 is_ignored: db_entry.is_ignored,
671 is_external: db_entry.is_external,
672 // This is only used in the summarization backlog, so if it's None,
673 // that just means we won't be able to detect when to resummarize
674 // based on total number of backlogged bytes - instead, we'd go
675 // on number of files only. That shouldn't be a huge deal in practice.
676 size: None,
677 is_fifo: db_entry.is_fifo,
678 });
679 }
680 }
681 }
682
683 worktrees.push(worktree);
684 }
685
686 let mut removed_repositories = Vec::new();
687 let mut updated_repositories = Vec::new();
688 for db_repo in db_repos {
689 let rejoined_repository = rejoined_project
690 .repositories
691 .iter()
692 .find(|repo| repo.id == db_repo.id as u64);
693
694 let repository_filter = if let Some(rejoined_repository) = rejoined_repository {
695 project_repository::Column::ScanId.gt(rejoined_repository.scan_id)
696 } else {
697 project_repository::Column::IsDeleted.eq(false)
698 };
699
700 let db_repositories = project_repository::Entity::find()
701 .filter(
702 Condition::all()
703 .add(project_repository::Column::ProjectId.eq(project.id))
704 .add(repository_filter),
705 )
706 .all(tx)
707 .await?;
708
709 for db_repository in db_repositories.into_iter() {
710 if db_repository.is_deleted {
711 removed_repositories.push(db_repository.id as u64);
712 } else {
713 let status_entry_filter = if let Some(rejoined_repository) = rejoined_repository
714 {
715 project_repository_statuses::Column::ScanId.gt(rejoined_repository.scan_id)
716 } else {
717 project_repository_statuses::Column::IsDeleted.eq(false)
718 };
719
720 let mut db_statuses = project_repository_statuses::Entity::find()
721 .filter(
722 Condition::all()
723 .add(project_repository_statuses::Column::ProjectId.eq(project.id))
724 .add(
725 project_repository_statuses::Column::RepositoryId
726 .eq(db_repository.id),
727 )
728 .add(status_entry_filter),
729 )
730 .stream(tx)
731 .await?;
732 let mut removed_statuses = Vec::new();
733 let mut updated_statuses = Vec::new();
734
735 while let Some(db_status) = db_statuses.next().await {
736 let db_status: project_repository_statuses::Model = db_status?;
737 if db_status.is_deleted {
738 removed_statuses.push(db_status.repo_path);
739 } else {
740 updated_statuses.push(db_status_to_proto(db_status)?);
741 }
742 }
743
744 let current_merge_conflicts = db_repository
745 .current_merge_conflicts
746 .as_ref()
747 .map(|conflicts| serde_json::from_str(&conflicts))
748 .transpose()?
749 .unwrap_or_default();
750
751 let branch_summary = db_repository
752 .branch_summary
753 .as_ref()
754 .map(|branch_summary| serde_json::from_str(&branch_summary))
755 .transpose()?
756 .unwrap_or_default();
757
758 let entry_ids = serde_json::from_str(&db_repository.entry_ids)
759 .context("failed to deserialize repository's entry ids")?;
760
761 if let Some(legacy_worktree_id) = db_repository.legacy_worktree_id {
762 if let Some(worktree) = worktrees
763 .iter_mut()
764 .find(|worktree| worktree.id as i64 == legacy_worktree_id)
765 {
766 worktree.updated_repositories.push(proto::RepositoryEntry {
767 work_directory_id: db_repository.id as u64,
768 updated_statuses,
769 removed_statuses,
770 current_merge_conflicts,
771 branch_summary,
772 });
773 }
774 } else {
775 updated_repositories.push(proto::UpdateRepository {
776 entry_ids,
777 updated_statuses,
778 removed_statuses,
779 current_merge_conflicts,
780 branch_summary,
781 project_id: project_id.to_proto(),
782 id: db_repository.id as u64,
783 abs_path: db_repository.abs_path,
784 scan_id: db_repository.scan_id as u64,
785 });
786 }
787 }
788 }
789 }
790
791 let language_servers = project
792 .find_related(language_server::Entity)
793 .all(tx)
794 .await?
795 .into_iter()
796 .map(|language_server| proto::LanguageServer {
797 id: language_server.id as u64,
798 name: language_server.name,
799 worktree_id: None,
800 })
801 .collect::<Vec<_>>();
802
803 {
804 let mut db_settings_files = worktree_settings_file::Entity::find()
805 .filter(worktree_settings_file::Column::ProjectId.eq(project_id))
806 .stream(tx)
807 .await?;
808 while let Some(db_settings_file) = db_settings_files.next().await {
809 let db_settings_file = db_settings_file?;
810 if let Some(worktree) = worktrees
811 .iter_mut()
812 .find(|w| w.id == db_settings_file.worktree_id as u64)
813 {
814 worktree.settings_files.push(WorktreeSettingsFile {
815 path: db_settings_file.path,
816 content: db_settings_file.content,
817 kind: db_settings_file.kind,
818 });
819 }
820 }
821 }
822
823 let mut collaborators = project
824 .find_related(project_collaborator::Entity)
825 .all(tx)
826 .await?;
827 let self_collaborator = if let Some(self_collaborator_ix) = collaborators
828 .iter()
829 .position(|collaborator| collaborator.user_id == user_id)
830 {
831 collaborators.swap_remove(self_collaborator_ix)
832 } else {
833 return Ok(None);
834 };
835 let old_connection_id = self_collaborator.connection();
836 project_collaborator::Entity::update(project_collaborator::ActiveModel {
837 connection_id: ActiveValue::set(connection.id as i32),
838 connection_server_id: ActiveValue::set(ServerId(connection.owner_id as i32)),
839 ..self_collaborator.into_active_model()
840 })
841 .exec(tx)
842 .await?;
843
844 let collaborators = collaborators
845 .into_iter()
846 .map(|collaborator| ProjectCollaborator {
847 connection_id: collaborator.connection(),
848 user_id: collaborator.user_id,
849 replica_id: collaborator.replica_id,
850 is_host: collaborator.is_host,
851 })
852 .collect::<Vec<_>>();
853
854 Ok(Some(RejoinedProject {
855 id: project_id,
856 old_connection_id,
857 collaborators,
858 updated_repositories,
859 removed_repositories,
860 worktrees,
861 language_servers,
862 }))
863 }
864
865 pub async fn leave_room(
866 &self,
867 connection: ConnectionId,
868 ) -> Result<Option<TransactionGuard<LeftRoom>>> {
869 self.optional_room_transaction(|tx| async move {
870 let leaving_participant = room_participant::Entity::find()
871 .filter(
872 Condition::all()
873 .add(
874 room_participant::Column::AnsweringConnectionId
875 .eq(connection.id as i32),
876 )
877 .add(
878 room_participant::Column::AnsweringConnectionServerId
879 .eq(connection.owner_id as i32),
880 ),
881 )
882 .one(&*tx)
883 .await?;
884
885 if let Some(leaving_participant) = leaving_participant {
886 // Leave room.
887 let room_id = leaving_participant.room_id;
888 room_participant::Entity::delete_by_id(leaving_participant.id)
889 .exec(&*tx)
890 .await?;
891
892 // Cancel pending calls initiated by the leaving user.
893 let called_participants = room_participant::Entity::find()
894 .filter(
895 Condition::all()
896 .add(
897 room_participant::Column::CallingUserId
898 .eq(leaving_participant.user_id),
899 )
900 .add(room_participant::Column::AnsweringConnectionId.is_null()),
901 )
902 .all(&*tx)
903 .await?;
904 room_participant::Entity::delete_many()
905 .filter(
906 room_participant::Column::Id
907 .is_in(called_participants.iter().map(|participant| participant.id)),
908 )
909 .exec(&*tx)
910 .await?;
911 let canceled_calls_to_user_ids = called_participants
912 .into_iter()
913 .map(|participant| participant.user_id)
914 .collect();
915
916 // Detect left projects.
917 #[derive(Copy, Clone, Debug, EnumIter, DeriveColumn)]
918 enum QueryProjectIds {
919 ProjectId,
920 }
921 let project_ids: Vec<ProjectId> = project_collaborator::Entity::find()
922 .select_only()
923 .column_as(
924 project_collaborator::Column::ProjectId,
925 QueryProjectIds::ProjectId,
926 )
927 .filter(
928 Condition::all()
929 .add(
930 project_collaborator::Column::ConnectionId.eq(connection.id as i32),
931 )
932 .add(
933 project_collaborator::Column::ConnectionServerId
934 .eq(connection.owner_id as i32),
935 ),
936 )
937 .into_values::<_, QueryProjectIds>()
938 .all(&*tx)
939 .await?;
940
941 let mut left_projects = HashMap::default();
942 let mut collaborators = project_collaborator::Entity::find()
943 .filter(project_collaborator::Column::ProjectId.is_in(project_ids))
944 .stream(&*tx)
945 .await?;
946
947 while let Some(collaborator) = collaborators.next().await {
948 let collaborator = collaborator?;
949 let left_project =
950 left_projects
951 .entry(collaborator.project_id)
952 .or_insert(LeftProject {
953 id: collaborator.project_id,
954 connection_ids: Default::default(),
955 should_unshare: false,
956 });
957
958 let collaborator_connection_id = collaborator.connection();
959 if collaborator_connection_id != connection {
960 left_project.connection_ids.push(collaborator_connection_id);
961 }
962
963 if collaborator.is_host && collaborator.connection() == connection {
964 left_project.should_unshare = true;
965 }
966 }
967 drop(collaborators);
968
969 // Leave projects.
970 project_collaborator::Entity::delete_many()
971 .filter(
972 Condition::all()
973 .add(
974 project_collaborator::Column::ConnectionId.eq(connection.id as i32),
975 )
976 .add(
977 project_collaborator::Column::ConnectionServerId
978 .eq(connection.owner_id as i32),
979 ),
980 )
981 .exec(&*tx)
982 .await?;
983
984 follower::Entity::delete_many()
985 .filter(
986 Condition::all()
987 .add(follower::Column::FollowerConnectionId.eq(connection.id as i32)),
988 )
989 .exec(&*tx)
990 .await?;
991
992 // Unshare projects.
993 project::Entity::delete_many()
994 .filter(
995 Condition::all()
996 .add(project::Column::RoomId.eq(room_id))
997 .add(project::Column::HostConnectionId.eq(connection.id as i32))
998 .add(
999 project::Column::HostConnectionServerId
1000 .eq(connection.owner_id as i32),
1001 ),
1002 )
1003 .exec(&*tx)
1004 .await?;
1005
1006 let (channel, room) = self.get_channel_room(room_id, &tx).await?;
1007 let deleted = if room.participants.is_empty() {
1008 let result = room::Entity::delete_by_id(room_id).exec(&*tx).await?;
1009 result.rows_affected > 0
1010 } else {
1011 false
1012 };
1013
1014 let left_room = LeftRoom {
1015 room,
1016 channel,
1017 left_projects,
1018 canceled_calls_to_user_ids,
1019 deleted,
1020 };
1021
1022 if left_room.room.participants.is_empty() {
1023 self.rooms.remove(&room_id);
1024 }
1025
1026 Ok(Some((room_id, left_room)))
1027 } else {
1028 Ok(None)
1029 }
1030 })
1031 .await
1032 }
1033
1034 /// Updates the location of a participant in the given room.
1035 pub async fn update_room_participant_location(
1036 &self,
1037 room_id: RoomId,
1038 connection: ConnectionId,
1039 location: proto::ParticipantLocation,
1040 ) -> Result<TransactionGuard<proto::Room>> {
1041 self.room_transaction(room_id, |tx| async {
1042 let tx = tx;
1043 let location_kind;
1044 let location_project_id;
1045 match location
1046 .variant
1047 .as_ref()
1048 .ok_or_else(|| anyhow!("invalid location"))?
1049 {
1050 proto::participant_location::Variant::SharedProject(project) => {
1051 location_kind = 0;
1052 location_project_id = Some(ProjectId::from_proto(project.id));
1053 }
1054 proto::participant_location::Variant::UnsharedProject(_) => {
1055 location_kind = 1;
1056 location_project_id = None;
1057 }
1058 proto::participant_location::Variant::External(_) => {
1059 location_kind = 2;
1060 location_project_id = None;
1061 }
1062 }
1063
1064 let result = room_participant::Entity::update_many()
1065 .filter(
1066 Condition::all()
1067 .add(room_participant::Column::RoomId.eq(room_id))
1068 .add(
1069 room_participant::Column::AnsweringConnectionId
1070 .eq(connection.id as i32),
1071 )
1072 .add(
1073 room_participant::Column::AnsweringConnectionServerId
1074 .eq(connection.owner_id as i32),
1075 ),
1076 )
1077 .set(room_participant::ActiveModel {
1078 location_kind: ActiveValue::set(Some(location_kind)),
1079 location_project_id: ActiveValue::set(location_project_id),
1080 ..Default::default()
1081 })
1082 .exec(&*tx)
1083 .await?;
1084
1085 if result.rows_affected == 1 {
1086 let room = self.get_room(room_id, &tx).await?;
1087 Ok(room)
1088 } else {
1089 Err(anyhow!("could not update room participant location"))?
1090 }
1091 })
1092 .await
1093 }
1094
1095 /// Sets the role of a participant in the given room.
1096 pub async fn set_room_participant_role(
1097 &self,
1098 admin_id: UserId,
1099 room_id: RoomId,
1100 user_id: UserId,
1101 role: ChannelRole,
1102 ) -> Result<TransactionGuard<proto::Room>> {
1103 self.room_transaction(room_id, |tx| async move {
1104 room_participant::Entity::find()
1105 .filter(
1106 Condition::all()
1107 .add(room_participant::Column::RoomId.eq(room_id))
1108 .add(room_participant::Column::UserId.eq(admin_id))
1109 .add(room_participant::Column::Role.eq(ChannelRole::Admin)),
1110 )
1111 .one(&*tx)
1112 .await?
1113 .ok_or_else(|| anyhow!("only admins can set participant role"))?;
1114
1115 if role.requires_cla() {
1116 self.check_user_has_signed_cla(user_id, room_id, &tx)
1117 .await?;
1118 }
1119
1120 let result = room_participant::Entity::update_many()
1121 .filter(
1122 Condition::all()
1123 .add(room_participant::Column::RoomId.eq(room_id))
1124 .add(room_participant::Column::UserId.eq(user_id)),
1125 )
1126 .set(room_participant::ActiveModel {
1127 role: ActiveValue::set(Some(role)),
1128 ..Default::default()
1129 })
1130 .exec(&*tx)
1131 .await?;
1132
1133 if result.rows_affected != 1 {
1134 Err(anyhow!("could not update room participant role"))?;
1135 }
1136 self.get_room(room_id, &tx).await
1137 })
1138 .await
1139 }
1140
1141 async fn check_user_has_signed_cla(
1142 &self,
1143 user_id: UserId,
1144 room_id: RoomId,
1145 tx: &DatabaseTransaction,
1146 ) -> Result<()> {
1147 let channel = room::Entity::find_by_id(room_id)
1148 .one(tx)
1149 .await?
1150 .ok_or_else(|| anyhow!("could not find room"))?
1151 .find_related(channel::Entity)
1152 .one(tx)
1153 .await?;
1154
1155 if let Some(channel) = channel {
1156 let requires_zed_cla = channel.requires_zed_cla
1157 || channel::Entity::find()
1158 .filter(
1159 channel::Column::Id
1160 .is_in(channel.ancestors())
1161 .and(channel::Column::RequiresZedCla.eq(true)),
1162 )
1163 .count(tx)
1164 .await?
1165 > 0;
1166 if requires_zed_cla
1167 && contributor::Entity::find()
1168 .filter(contributor::Column::UserId.eq(user_id))
1169 .one(tx)
1170 .await?
1171 .is_none()
1172 {
1173 Err(anyhow!("user has not signed the Zed CLA"))?;
1174 }
1175 }
1176 Ok(())
1177 }
1178
1179 pub async fn connection_lost(&self, connection: ConnectionId) -> Result<()> {
1180 self.transaction(|tx| async move {
1181 self.room_connection_lost(connection, &tx).await?;
1182 self.channel_buffer_connection_lost(connection, &tx).await?;
1183 self.channel_chat_connection_lost(connection, &tx).await?;
1184 Ok(())
1185 })
1186 .await
1187 }
1188
1189 pub async fn room_connection_lost(
1190 &self,
1191 connection: ConnectionId,
1192 tx: &DatabaseTransaction,
1193 ) -> Result<()> {
1194 let participant = room_participant::Entity::find()
1195 .filter(
1196 Condition::all()
1197 .add(room_participant::Column::AnsweringConnectionId.eq(connection.id as i32))
1198 .add(
1199 room_participant::Column::AnsweringConnectionServerId
1200 .eq(connection.owner_id as i32),
1201 ),
1202 )
1203 .one(tx)
1204 .await?;
1205
1206 if let Some(participant) = participant {
1207 room_participant::Entity::update(room_participant::ActiveModel {
1208 answering_connection_lost: ActiveValue::set(true),
1209 ..participant.into_active_model()
1210 })
1211 .exec(tx)
1212 .await?;
1213 }
1214 Ok(())
1215 }
1216
1217 fn build_incoming_call(
1218 room: &proto::Room,
1219 called_user_id: UserId,
1220 ) -> Option<proto::IncomingCall> {
1221 let pending_participant = room
1222 .pending_participants
1223 .iter()
1224 .find(|participant| participant.user_id == called_user_id.to_proto())?;
1225
1226 Some(proto::IncomingCall {
1227 room_id: room.id,
1228 calling_user_id: pending_participant.calling_user_id,
1229 participant_user_ids: room
1230 .participants
1231 .iter()
1232 .map(|participant| participant.user_id)
1233 .collect(),
1234 initial_project: room.participants.iter().find_map(|participant| {
1235 let initial_project_id = pending_participant.initial_project_id?;
1236 participant
1237 .projects
1238 .iter()
1239 .find(|project| project.id == initial_project_id)
1240 .cloned()
1241 }),
1242 })
1243 }
1244
1245 pub async fn get_room(&self, room_id: RoomId, tx: &DatabaseTransaction) -> Result<proto::Room> {
1246 let (_, room) = self.get_channel_room(room_id, tx).await?;
1247 Ok(room)
1248 }
1249
1250 pub async fn room_connection_ids(
1251 &self,
1252 room_id: RoomId,
1253 connection_id: ConnectionId,
1254 ) -> Result<TransactionGuard<HashSet<ConnectionId>>> {
1255 self.room_transaction(room_id, |tx| async move {
1256 let mut participants = room_participant::Entity::find()
1257 .filter(room_participant::Column::RoomId.eq(room_id))
1258 .stream(&*tx)
1259 .await?;
1260
1261 let mut is_participant = false;
1262 let mut connection_ids = HashSet::default();
1263 while let Some(participant) = participants.next().await {
1264 let participant = participant?;
1265 if let Some(answering_connection) = participant.answering_connection() {
1266 if answering_connection == connection_id {
1267 is_participant = true;
1268 } else {
1269 connection_ids.insert(answering_connection);
1270 }
1271 }
1272 }
1273
1274 if !is_participant {
1275 Err(anyhow!("not a room participant"))?;
1276 }
1277
1278 Ok(connection_ids)
1279 })
1280 .await
1281 }
1282
1283 async fn get_channel_room(
1284 &self,
1285 room_id: RoomId,
1286 tx: &DatabaseTransaction,
1287 ) -> Result<(Option<channel::Model>, proto::Room)> {
1288 let db_room = room::Entity::find_by_id(room_id)
1289 .one(tx)
1290 .await?
1291 .ok_or_else(|| anyhow!("could not find room"))?;
1292
1293 let mut db_participants = db_room
1294 .find_related(room_participant::Entity)
1295 .stream(tx)
1296 .await?;
1297 let mut participants = HashMap::default();
1298 let mut pending_participants = Vec::new();
1299 while let Some(db_participant) = db_participants.next().await {
1300 let db_participant = db_participant?;
1301 if let (
1302 Some(answering_connection_id),
1303 Some(answering_connection_server_id),
1304 Some(participant_index),
1305 ) = (
1306 db_participant.answering_connection_id,
1307 db_participant.answering_connection_server_id,
1308 db_participant.participant_index,
1309 ) {
1310 let location = match (
1311 db_participant.location_kind,
1312 db_participant.location_project_id,
1313 ) {
1314 (Some(0), Some(project_id)) => {
1315 Some(proto::participant_location::Variant::SharedProject(
1316 proto::participant_location::SharedProject {
1317 id: project_id.to_proto(),
1318 },
1319 ))
1320 }
1321 (Some(1), _) => Some(proto::participant_location::Variant::UnsharedProject(
1322 Default::default(),
1323 )),
1324 _ => Some(proto::participant_location::Variant::External(
1325 Default::default(),
1326 )),
1327 };
1328
1329 let answering_connection = ConnectionId {
1330 owner_id: answering_connection_server_id.0 as u32,
1331 id: answering_connection_id as u32,
1332 };
1333 participants.insert(
1334 answering_connection,
1335 proto::Participant {
1336 user_id: db_participant.user_id.to_proto(),
1337 peer_id: Some(answering_connection.into()),
1338 projects: Default::default(),
1339 location: Some(proto::ParticipantLocation { variant: location }),
1340 participant_index: participant_index as u32,
1341 role: db_participant.role.unwrap_or(ChannelRole::Member).into(),
1342 },
1343 );
1344 } else {
1345 pending_participants.push(proto::PendingParticipant {
1346 user_id: db_participant.user_id.to_proto(),
1347 calling_user_id: db_participant.calling_user_id.to_proto(),
1348 initial_project_id: db_participant.initial_project_id.map(|id| id.to_proto()),
1349 });
1350 }
1351 }
1352 drop(db_participants);
1353
1354 let db_projects = db_room
1355 .find_related(project::Entity)
1356 .find_with_related(worktree::Entity)
1357 .all(tx)
1358 .await?;
1359
1360 for (db_project, db_worktrees) in db_projects {
1361 let host_connection = db_project.host_connection()?;
1362 if let Some(participant) = participants.get_mut(&host_connection) {
1363 participant.projects.push(proto::ParticipantProject {
1364 id: db_project.id.to_proto(),
1365 worktree_root_names: Default::default(),
1366 });
1367 let project = participant.projects.last_mut().unwrap();
1368
1369 for db_worktree in db_worktrees {
1370 if db_worktree.visible {
1371 project.worktree_root_names.push(db_worktree.root_name);
1372 }
1373 }
1374 }
1375 }
1376
1377 let mut db_followers = db_room.find_related(follower::Entity).stream(tx).await?;
1378 let mut followers = Vec::new();
1379 while let Some(db_follower) = db_followers.next().await {
1380 let db_follower = db_follower?;
1381 followers.push(proto::Follower {
1382 leader_id: Some(db_follower.leader_connection().into()),
1383 follower_id: Some(db_follower.follower_connection().into()),
1384 project_id: db_follower.project_id.to_proto(),
1385 });
1386 }
1387 drop(db_followers);
1388
1389 let channel = if let Some(channel_id) = db_room.channel_id {
1390 Some(self.get_channel_internal(channel_id, tx).await?)
1391 } else {
1392 None
1393 };
1394
1395 Ok((
1396 channel,
1397 proto::Room {
1398 id: db_room.id.to_proto(),
1399 livekit_room: db_room.live_kit_room,
1400 participants: participants.into_values().collect(),
1401 pending_participants,
1402 followers,
1403 },
1404 ))
1405 }
1406}