1mod store;
2
3use super::{
4 auth::process_auth_header,
5 db::{ChannelId, MessageId, UserId},
6 AppState,
7};
8use anyhow::anyhow;
9use async_std::task;
10use async_tungstenite::{tungstenite::protocol::Role, WebSocketStream};
11use collections::{HashMap, HashSet};
12use futures::{future::BoxFuture, FutureExt, StreamExt};
13use parking_lot::{RwLock, RwLockReadGuard, RwLockWriteGuard};
14use postage::{mpsc, prelude::Sink as _};
15use rpc::{
16 proto::{self, AnyTypedEnvelope, EnvelopedMessage},
17 Connection, ConnectionId, Peer, TypedEnvelope,
18};
19use sha1::{Digest as _, Sha1};
20use std::{any::TypeId, future::Future, mem, path::PathBuf, sync::Arc, time::Instant};
21use store::{Store, Worktree};
22use surf::StatusCode;
23use tide::log;
24use tide::{
25 http::headers::{HeaderName, CONNECTION, UPGRADE},
26 Request, Response,
27};
28use time::OffsetDateTime;
29
30type MessageHandler = Box<
31 dyn Send
32 + Sync
33 + Fn(Arc<Server>, Box<dyn AnyTypedEnvelope>) -> BoxFuture<'static, tide::Result<()>>,
34>;
35
36pub struct Server {
37 peer: Arc<Peer>,
38 store: RwLock<Store>,
39 app_state: Arc<AppState>,
40 handlers: HashMap<TypeId, MessageHandler>,
41 notifications: Option<mpsc::Sender<()>>,
42}
43
44const MESSAGE_COUNT_PER_PAGE: usize = 100;
45const MAX_MESSAGE_LEN: usize = 1024;
46const NO_SUCH_PROJECT: &'static str = "no such project";
47
48impl Server {
49 pub fn new(
50 app_state: Arc<AppState>,
51 peer: Arc<Peer>,
52 notifications: Option<mpsc::Sender<()>>,
53 ) -> Arc<Self> {
54 let mut server = Self {
55 peer,
56 app_state,
57 store: Default::default(),
58 handlers: Default::default(),
59 notifications,
60 };
61
62 server
63 .add_handler(Server::ping)
64 .add_handler(Server::register_project)
65 .add_handler(Server::unregister_project)
66 .add_handler(Server::share_project)
67 .add_handler(Server::unshare_project)
68 .add_handler(Server::join_project)
69 .add_handler(Server::leave_project)
70 .add_handler(Server::register_worktree)
71 .add_handler(Server::unregister_worktree)
72 .add_handler(Server::share_worktree)
73 .add_handler(Server::update_worktree)
74 .add_handler(Server::update_diagnostic_summary)
75 .add_handler(Server::disk_based_diagnostics_updating)
76 .add_handler(Server::disk_based_diagnostics_updated)
77 .add_handler(Server::open_buffer)
78 .add_handler(Server::close_buffer)
79 .add_handler(Server::update_buffer)
80 .add_handler(Server::buffer_saved)
81 .add_handler(Server::save_buffer)
82 .add_handler(Server::format_buffer)
83 .add_handler(Server::get_channels)
84 .add_handler(Server::get_users)
85 .add_handler(Server::join_channel)
86 .add_handler(Server::leave_channel)
87 .add_handler(Server::send_channel_message)
88 .add_handler(Server::get_channel_messages);
89
90 Arc::new(server)
91 }
92
93 fn add_handler<F, Fut, M>(&mut self, handler: F) -> &mut Self
94 where
95 F: 'static + Send + Sync + Fn(Arc<Self>, TypedEnvelope<M>) -> Fut,
96 Fut: 'static + Send + Future<Output = tide::Result<()>>,
97 M: EnvelopedMessage,
98 {
99 let prev_handler = self.handlers.insert(
100 TypeId::of::<M>(),
101 Box::new(move |server, envelope| {
102 let envelope = envelope.into_any().downcast::<TypedEnvelope<M>>().unwrap();
103 (handler)(server, *envelope).boxed()
104 }),
105 );
106 if prev_handler.is_some() {
107 panic!("registered a handler for the same message twice");
108 }
109 self
110 }
111
112 pub fn handle_connection(
113 self: &Arc<Self>,
114 connection: Connection,
115 addr: String,
116 user_id: UserId,
117 mut send_connection_id: Option<postage::mpsc::Sender<ConnectionId>>,
118 ) -> impl Future<Output = ()> {
119 let mut this = self.clone();
120 async move {
121 let (connection_id, handle_io, mut incoming_rx) =
122 this.peer.add_connection(connection).await;
123
124 if let Some(send_connection_id) = send_connection_id.as_mut() {
125 let _ = send_connection_id.send(connection_id).await;
126 }
127
128 this.state_mut().add_connection(connection_id, user_id);
129 if let Err(err) = this.update_contacts_for_users(&[user_id]).await {
130 log::error!("error updating contacts for {:?}: {}", user_id, err);
131 }
132
133 let handle_io = handle_io.fuse();
134 futures::pin_mut!(handle_io);
135 loop {
136 let next_message = incoming_rx.next().fuse();
137 futures::pin_mut!(next_message);
138 futures::select_biased! {
139 message = next_message => {
140 if let Some(message) = message {
141 let start_time = Instant::now();
142 log::info!("RPC message received: {}", message.payload_type_name());
143 if let Some(handler) = this.handlers.get(&message.payload_type_id()) {
144 if let Err(err) = (handler)(this.clone(), message).await {
145 log::error!("error handling message: {:?}", err);
146 } else {
147 log::info!("RPC message handled. duration:{:?}", start_time.elapsed());
148 }
149
150 if let Some(mut notifications) = this.notifications.clone() {
151 let _ = notifications.send(()).await;
152 }
153 } else {
154 log::warn!("unhandled message: {}", message.payload_type_name());
155 }
156 } else {
157 log::info!("rpc connection closed {:?}", addr);
158 break;
159 }
160 }
161 handle_io = handle_io => {
162 if let Err(err) = handle_io {
163 log::error!("error handling rpc connection {:?} - {:?}", addr, err);
164 }
165 break;
166 }
167 }
168 }
169
170 if let Err(err) = this.sign_out(connection_id).await {
171 log::error!("error signing out connection {:?} - {:?}", addr, err);
172 }
173 }
174 }
175
176 async fn sign_out(self: &mut Arc<Self>, connection_id: ConnectionId) -> tide::Result<()> {
177 self.peer.disconnect(connection_id);
178 let removed_connection = self.state_mut().remove_connection(connection_id)?;
179
180 for (project_id, project) in removed_connection.hosted_projects {
181 if let Some(share) = project.share {
182 broadcast(
183 connection_id,
184 share.guests.keys().copied().collect(),
185 |conn_id| {
186 self.peer
187 .send(conn_id, proto::UnshareProject { project_id })
188 },
189 )
190 .await?;
191 }
192 }
193
194 for (project_id, peer_ids) in removed_connection.guest_project_ids {
195 broadcast(connection_id, peer_ids, |conn_id| {
196 self.peer.send(
197 conn_id,
198 proto::RemoveProjectCollaborator {
199 project_id,
200 peer_id: connection_id.0,
201 },
202 )
203 })
204 .await?;
205 }
206
207 self.update_contacts_for_users(removed_connection.contact_ids.iter())
208 .await?;
209
210 Ok(())
211 }
212
213 async fn ping(self: Arc<Server>, request: TypedEnvelope<proto::Ping>) -> tide::Result<()> {
214 self.peer.respond(request.receipt(), proto::Ack {}).await?;
215 Ok(())
216 }
217
218 async fn register_project(
219 mut self: Arc<Server>,
220 request: TypedEnvelope<proto::RegisterProject>,
221 ) -> tide::Result<()> {
222 let project_id = {
223 let mut state = self.state_mut();
224 let user_id = state.user_id_for_connection(request.sender_id)?;
225 state.register_project(request.sender_id, user_id)
226 };
227 self.peer
228 .respond(
229 request.receipt(),
230 proto::RegisterProjectResponse { project_id },
231 )
232 .await?;
233 Ok(())
234 }
235
236 async fn unregister_project(
237 mut self: Arc<Server>,
238 request: TypedEnvelope<proto::UnregisterProject>,
239 ) -> tide::Result<()> {
240 let project = self
241 .state_mut()
242 .unregister_project(request.payload.project_id, request.sender_id)
243 .ok_or_else(|| anyhow!("no such project"))?;
244 self.update_contacts_for_users(project.authorized_user_ids().iter())
245 .await?;
246 Ok(())
247 }
248
249 async fn share_project(
250 mut self: Arc<Server>,
251 request: TypedEnvelope<proto::ShareProject>,
252 ) -> tide::Result<()> {
253 self.state_mut()
254 .share_project(request.payload.project_id, request.sender_id);
255 self.peer.respond(request.receipt(), proto::Ack {}).await?;
256 Ok(())
257 }
258
259 async fn unshare_project(
260 mut self: Arc<Server>,
261 request: TypedEnvelope<proto::UnshareProject>,
262 ) -> tide::Result<()> {
263 let project_id = request.payload.project_id;
264 let project = self
265 .state_mut()
266 .unshare_project(project_id, request.sender_id)?;
267
268 broadcast(request.sender_id, project.connection_ids, |conn_id| {
269 self.peer
270 .send(conn_id, proto::UnshareProject { project_id })
271 })
272 .await?;
273 self.update_contacts_for_users(&project.authorized_user_ids)
274 .await?;
275
276 Ok(())
277 }
278
279 async fn join_project(
280 mut self: Arc<Server>,
281 request: TypedEnvelope<proto::JoinProject>,
282 ) -> tide::Result<()> {
283 let project_id = request.payload.project_id;
284
285 let user_id = self.state().user_id_for_connection(request.sender_id)?;
286 let response_data = self
287 .state_mut()
288 .join_project(request.sender_id, user_id, project_id)
289 .and_then(|joined| {
290 let share = joined.project.share()?;
291 let peer_count = share.guests.len();
292 let mut collaborators = Vec::with_capacity(peer_count);
293 collaborators.push(proto::Collaborator {
294 peer_id: joined.project.host_connection_id.0,
295 replica_id: 0,
296 user_id: joined.project.host_user_id.to_proto(),
297 });
298 let worktrees = joined
299 .project
300 .worktrees
301 .iter()
302 .filter_map(|(id, worktree)| {
303 worktree.share.as_ref().map(|share| proto::Worktree {
304 id: *id,
305 root_name: worktree.root_name.clone(),
306 entries: share.entries.values().cloned().collect(),
307 diagnostic_summaries: share
308 .diagnostic_summaries
309 .values()
310 .cloned()
311 .collect(),
312 weak: worktree.weak,
313 })
314 })
315 .collect();
316 for (peer_conn_id, (peer_replica_id, peer_user_id)) in &share.guests {
317 if *peer_conn_id != request.sender_id {
318 collaborators.push(proto::Collaborator {
319 peer_id: peer_conn_id.0,
320 replica_id: *peer_replica_id as u32,
321 user_id: peer_user_id.to_proto(),
322 });
323 }
324 }
325 let response = proto::JoinProjectResponse {
326 worktrees,
327 replica_id: joined.replica_id as u32,
328 collaborators,
329 };
330 let connection_ids = joined.project.connection_ids();
331 let contact_user_ids = joined.project.authorized_user_ids();
332 Ok((response, connection_ids, contact_user_ids))
333 });
334
335 match response_data {
336 Ok((response, connection_ids, contact_user_ids)) => {
337 broadcast(request.sender_id, connection_ids, |conn_id| {
338 self.peer.send(
339 conn_id,
340 proto::AddProjectCollaborator {
341 project_id: project_id,
342 collaborator: Some(proto::Collaborator {
343 peer_id: request.sender_id.0,
344 replica_id: response.replica_id,
345 user_id: user_id.to_proto(),
346 }),
347 },
348 )
349 })
350 .await?;
351 self.peer.respond(request.receipt(), response).await?;
352 self.update_contacts_for_users(&contact_user_ids).await?;
353 }
354 Err(error) => {
355 self.peer
356 .respond_with_error(
357 request.receipt(),
358 proto::Error {
359 message: error.to_string(),
360 },
361 )
362 .await?;
363 }
364 }
365
366 Ok(())
367 }
368
369 async fn leave_project(
370 mut self: Arc<Server>,
371 request: TypedEnvelope<proto::LeaveProject>,
372 ) -> tide::Result<()> {
373 let sender_id = request.sender_id;
374 let project_id = request.payload.project_id;
375 let worktree = self.state_mut().leave_project(sender_id, project_id);
376 if let Some(worktree) = worktree {
377 broadcast(sender_id, worktree.connection_ids, |conn_id| {
378 self.peer.send(
379 conn_id,
380 proto::RemoveProjectCollaborator {
381 project_id,
382 peer_id: sender_id.0,
383 },
384 )
385 })
386 .await?;
387 self.update_contacts_for_users(&worktree.authorized_user_ids)
388 .await?;
389 }
390 Ok(())
391 }
392
393 async fn register_worktree(
394 mut self: Arc<Server>,
395 request: TypedEnvelope<proto::RegisterWorktree>,
396 ) -> tide::Result<()> {
397 let receipt = request.receipt();
398 let host_user_id = self.state().user_id_for_connection(request.sender_id)?;
399
400 let mut contact_user_ids = HashSet::default();
401 contact_user_ids.insert(host_user_id);
402 for github_login in request.payload.authorized_logins {
403 match self.app_state.db.create_user(&github_login, false).await {
404 Ok(contact_user_id) => {
405 contact_user_ids.insert(contact_user_id);
406 }
407 Err(err) => {
408 let message = err.to_string();
409 self.peer
410 .respond_with_error(receipt, proto::Error { message })
411 .await?;
412 return Ok(());
413 }
414 }
415 }
416
417 let contact_user_ids = contact_user_ids.into_iter().collect::<Vec<_>>();
418 let ok = self.state_mut().register_worktree(
419 request.payload.project_id,
420 request.payload.worktree_id,
421 Worktree {
422 authorized_user_ids: contact_user_ids.clone(),
423 root_name: request.payload.root_name,
424 share: None,
425 weak: false,
426 },
427 );
428
429 if ok {
430 self.peer.respond(receipt, proto::Ack {}).await?;
431 self.update_contacts_for_users(&contact_user_ids).await?;
432 } else {
433 self.peer
434 .respond_with_error(
435 receipt,
436 proto::Error {
437 message: NO_SUCH_PROJECT.to_string(),
438 },
439 )
440 .await?;
441 }
442
443 Ok(())
444 }
445
446 async fn unregister_worktree(
447 mut self: Arc<Server>,
448 request: TypedEnvelope<proto::UnregisterWorktree>,
449 ) -> tide::Result<()> {
450 let project_id = request.payload.project_id;
451 let worktree_id = request.payload.worktree_id;
452 let (worktree, guest_connection_ids) =
453 self.state_mut()
454 .unregister_worktree(project_id, worktree_id, request.sender_id)?;
455
456 broadcast(request.sender_id, guest_connection_ids, |conn_id| {
457 self.peer.send(
458 conn_id,
459 proto::UnregisterWorktree {
460 project_id,
461 worktree_id,
462 },
463 )
464 })
465 .await?;
466 self.update_contacts_for_users(&worktree.authorized_user_ids)
467 .await?;
468 Ok(())
469 }
470
471 async fn share_worktree(
472 mut self: Arc<Server>,
473 mut request: TypedEnvelope<proto::ShareWorktree>,
474 ) -> tide::Result<()> {
475 let worktree = request
476 .payload
477 .worktree
478 .as_mut()
479 .ok_or_else(|| anyhow!("missing worktree"))?;
480 let entries = mem::take(&mut worktree.entries)
481 .into_iter()
482 .map(|entry| (entry.id, entry))
483 .collect();
484
485 let diagnostic_summaries = mem::take(&mut worktree.diagnostic_summaries)
486 .into_iter()
487 .map(|summary| (PathBuf::from(summary.path.clone()), summary))
488 .collect();
489
490 let contact_user_ids = self.state_mut().share_worktree(
491 request.payload.project_id,
492 worktree.id,
493 request.sender_id,
494 entries,
495 diagnostic_summaries,
496 );
497 if let Some(contact_user_ids) = contact_user_ids {
498 self.peer.respond(request.receipt(), proto::Ack {}).await?;
499 self.update_contacts_for_users(&contact_user_ids).await?;
500 } else {
501 self.peer
502 .respond_with_error(
503 request.receipt(),
504 proto::Error {
505 message: "no such worktree".to_string(),
506 },
507 )
508 .await?;
509 }
510 Ok(())
511 }
512
513 async fn update_worktree(
514 mut self: Arc<Server>,
515 request: TypedEnvelope<proto::UpdateWorktree>,
516 ) -> tide::Result<()> {
517 let connection_ids = self
518 .state_mut()
519 .update_worktree(
520 request.sender_id,
521 request.payload.project_id,
522 request.payload.worktree_id,
523 &request.payload.removed_entries,
524 &request.payload.updated_entries,
525 )
526 .ok_or_else(|| anyhow!("no such worktree"))?;
527
528 broadcast(request.sender_id, connection_ids, |connection_id| {
529 self.peer
530 .forward_send(request.sender_id, connection_id, request.payload.clone())
531 })
532 .await?;
533
534 Ok(())
535 }
536
537 async fn update_diagnostic_summary(
538 mut self: Arc<Server>,
539 request: TypedEnvelope<proto::UpdateDiagnosticSummary>,
540 ) -> tide::Result<()> {
541 let receiver_ids = request
542 .payload
543 .summary
544 .clone()
545 .and_then(|summary| {
546 self.state_mut().update_diagnostic_summary(
547 request.payload.project_id,
548 request.payload.worktree_id,
549 request.sender_id,
550 summary,
551 )
552 })
553 .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?;
554
555 broadcast(request.sender_id, receiver_ids, |connection_id| {
556 self.peer
557 .forward_send(request.sender_id, connection_id, request.payload.clone())
558 })
559 .await?;
560 Ok(())
561 }
562
563 async fn disk_based_diagnostics_updating(
564 self: Arc<Server>,
565 request: TypedEnvelope<proto::DiskBasedDiagnosticsUpdating>,
566 ) -> tide::Result<()> {
567 let receiver_ids = self
568 .state()
569 .project_connection_ids(request.payload.project_id, request.sender_id)
570 .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?;
571 broadcast(request.sender_id, receiver_ids, |connection_id| {
572 self.peer
573 .forward_send(request.sender_id, connection_id, request.payload.clone())
574 })
575 .await?;
576 Ok(())
577 }
578
579 async fn disk_based_diagnostics_updated(
580 self: Arc<Server>,
581 request: TypedEnvelope<proto::DiskBasedDiagnosticsUpdated>,
582 ) -> tide::Result<()> {
583 let receiver_ids = self
584 .state()
585 .project_connection_ids(request.payload.project_id, request.sender_id)
586 .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?;
587 broadcast(request.sender_id, receiver_ids, |connection_id| {
588 self.peer
589 .forward_send(request.sender_id, connection_id, request.payload.clone())
590 })
591 .await?;
592 Ok(())
593 }
594
595 async fn open_buffer(
596 self: Arc<Server>,
597 request: TypedEnvelope<proto::OpenBuffer>,
598 ) -> tide::Result<()> {
599 let receipt = request.receipt();
600 let host_connection_id = self
601 .state()
602 .read_project(request.payload.project_id, request.sender_id)
603 .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?
604 .host_connection_id;
605 let response = self
606 .peer
607 .forward_request(request.sender_id, host_connection_id, request.payload)
608 .await?;
609 self.peer.respond(receipt, response).await?;
610 Ok(())
611 }
612
613 async fn close_buffer(
614 self: Arc<Server>,
615 request: TypedEnvelope<proto::CloseBuffer>,
616 ) -> tide::Result<()> {
617 let host_connection_id = self
618 .state()
619 .read_project(request.payload.project_id, request.sender_id)
620 .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?
621 .host_connection_id;
622 self.peer
623 .forward_send(request.sender_id, host_connection_id, request.payload)
624 .await?;
625 Ok(())
626 }
627
628 async fn save_buffer(
629 self: Arc<Server>,
630 request: TypedEnvelope<proto::SaveBuffer>,
631 ) -> tide::Result<()> {
632 let host;
633 let guests;
634 {
635 let state = self.state();
636 let project = state
637 .read_project(request.payload.project_id, request.sender_id)
638 .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?;
639 host = project.host_connection_id;
640 guests = project.guest_connection_ids()
641 }
642
643 let sender = request.sender_id;
644 let receipt = request.receipt();
645 let response = self
646 .peer
647 .forward_request(sender, host, request.payload.clone())
648 .await?;
649
650 broadcast(host, guests, |conn_id| {
651 let response = response.clone();
652 let peer = &self.peer;
653 async move {
654 if conn_id == sender {
655 peer.respond(receipt, response).await
656 } else {
657 peer.forward_send(host, conn_id, response).await
658 }
659 }
660 })
661 .await?;
662
663 Ok(())
664 }
665
666 async fn format_buffer(
667 self: Arc<Server>,
668 request: TypedEnvelope<proto::FormatBuffer>,
669 ) -> tide::Result<()> {
670 let host;
671 {
672 let state = self.state();
673 let project = state
674 .read_project(request.payload.project_id, request.sender_id)
675 .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?;
676 host = project.host_connection_id;
677 }
678
679 let sender = request.sender_id;
680 let receipt = request.receipt();
681 let response = self
682 .peer
683 .forward_request(sender, host, request.payload.clone())
684 .await?;
685 self.peer.respond(receipt, response).await?;
686
687 Ok(())
688 }
689
690 async fn update_buffer(
691 self: Arc<Server>,
692 request: TypedEnvelope<proto::UpdateBuffer>,
693 ) -> tide::Result<()> {
694 let receiver_ids = self
695 .state()
696 .project_connection_ids(request.payload.project_id, request.sender_id)
697 .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?;
698 broadcast(request.sender_id, receiver_ids, |connection_id| {
699 self.peer
700 .forward_send(request.sender_id, connection_id, request.payload.clone())
701 })
702 .await?;
703 self.peer.respond(request.receipt(), proto::Ack {}).await?;
704 Ok(())
705 }
706
707 async fn buffer_saved(
708 self: Arc<Server>,
709 request: TypedEnvelope<proto::BufferSaved>,
710 ) -> tide::Result<()> {
711 let receiver_ids = self
712 .state()
713 .project_connection_ids(request.payload.project_id, request.sender_id)
714 .ok_or_else(|| anyhow!(NO_SUCH_PROJECT))?;
715 broadcast(request.sender_id, receiver_ids, |connection_id| {
716 self.peer
717 .forward_send(request.sender_id, connection_id, request.payload.clone())
718 })
719 .await?;
720 Ok(())
721 }
722
723 async fn get_channels(
724 self: Arc<Server>,
725 request: TypedEnvelope<proto::GetChannels>,
726 ) -> tide::Result<()> {
727 let user_id = self.state().user_id_for_connection(request.sender_id)?;
728 let channels = self.app_state.db.get_accessible_channels(user_id).await?;
729 self.peer
730 .respond(
731 request.receipt(),
732 proto::GetChannelsResponse {
733 channels: channels
734 .into_iter()
735 .map(|chan| proto::Channel {
736 id: chan.id.to_proto(),
737 name: chan.name,
738 })
739 .collect(),
740 },
741 )
742 .await?;
743 Ok(())
744 }
745
746 async fn get_users(
747 self: Arc<Server>,
748 request: TypedEnvelope<proto::GetUsers>,
749 ) -> tide::Result<()> {
750 let receipt = request.receipt();
751 let user_ids = request.payload.user_ids.into_iter().map(UserId::from_proto);
752 let users = self
753 .app_state
754 .db
755 .get_users_by_ids(user_ids)
756 .await?
757 .into_iter()
758 .map(|user| proto::User {
759 id: user.id.to_proto(),
760 avatar_url: format!("https://github.com/{}.png?size=128", user.github_login),
761 github_login: user.github_login,
762 })
763 .collect();
764 self.peer
765 .respond(receipt, proto::GetUsersResponse { users })
766 .await?;
767 Ok(())
768 }
769
770 async fn update_contacts_for_users<'a>(
771 self: &Arc<Server>,
772 user_ids: impl IntoIterator<Item = &'a UserId>,
773 ) -> tide::Result<()> {
774 let mut send_futures = Vec::new();
775
776 {
777 let state = self.state();
778 for user_id in user_ids {
779 let contacts = state.contacts_for_user(*user_id);
780 for connection_id in state.connection_ids_for_user(*user_id) {
781 send_futures.push(self.peer.send(
782 connection_id,
783 proto::UpdateContacts {
784 contacts: contacts.clone(),
785 },
786 ));
787 }
788 }
789 }
790 futures::future::try_join_all(send_futures).await?;
791
792 Ok(())
793 }
794
795 async fn join_channel(
796 mut self: Arc<Self>,
797 request: TypedEnvelope<proto::JoinChannel>,
798 ) -> tide::Result<()> {
799 let user_id = self.state().user_id_for_connection(request.sender_id)?;
800 let channel_id = ChannelId::from_proto(request.payload.channel_id);
801 if !self
802 .app_state
803 .db
804 .can_user_access_channel(user_id, channel_id)
805 .await?
806 {
807 Err(anyhow!("access denied"))?;
808 }
809
810 self.state_mut().join_channel(request.sender_id, channel_id);
811 let messages = self
812 .app_state
813 .db
814 .get_channel_messages(channel_id, MESSAGE_COUNT_PER_PAGE, None)
815 .await?
816 .into_iter()
817 .map(|msg| proto::ChannelMessage {
818 id: msg.id.to_proto(),
819 body: msg.body,
820 timestamp: msg.sent_at.unix_timestamp() as u64,
821 sender_id: msg.sender_id.to_proto(),
822 nonce: Some(msg.nonce.as_u128().into()),
823 })
824 .collect::<Vec<_>>();
825 self.peer
826 .respond(
827 request.receipt(),
828 proto::JoinChannelResponse {
829 done: messages.len() < MESSAGE_COUNT_PER_PAGE,
830 messages,
831 },
832 )
833 .await?;
834 Ok(())
835 }
836
837 async fn leave_channel(
838 mut self: Arc<Self>,
839 request: TypedEnvelope<proto::LeaveChannel>,
840 ) -> tide::Result<()> {
841 let user_id = self.state().user_id_for_connection(request.sender_id)?;
842 let channel_id = ChannelId::from_proto(request.payload.channel_id);
843 if !self
844 .app_state
845 .db
846 .can_user_access_channel(user_id, channel_id)
847 .await?
848 {
849 Err(anyhow!("access denied"))?;
850 }
851
852 self.state_mut()
853 .leave_channel(request.sender_id, channel_id);
854
855 Ok(())
856 }
857
858 async fn send_channel_message(
859 self: Arc<Self>,
860 request: TypedEnvelope<proto::SendChannelMessage>,
861 ) -> tide::Result<()> {
862 let receipt = request.receipt();
863 let channel_id = ChannelId::from_proto(request.payload.channel_id);
864 let user_id;
865 let connection_ids;
866 {
867 let state = self.state();
868 user_id = state.user_id_for_connection(request.sender_id)?;
869 if let Some(ids) = state.channel_connection_ids(channel_id) {
870 connection_ids = ids;
871 } else {
872 return Ok(());
873 }
874 }
875
876 // Validate the message body.
877 let body = request.payload.body.trim().to_string();
878 if body.len() > MAX_MESSAGE_LEN {
879 self.peer
880 .respond_with_error(
881 receipt,
882 proto::Error {
883 message: "message is too long".to_string(),
884 },
885 )
886 .await?;
887 return Ok(());
888 }
889 if body.is_empty() {
890 self.peer
891 .respond_with_error(
892 receipt,
893 proto::Error {
894 message: "message can't be blank".to_string(),
895 },
896 )
897 .await?;
898 return Ok(());
899 }
900
901 let timestamp = OffsetDateTime::now_utc();
902 let nonce = if let Some(nonce) = request.payload.nonce {
903 nonce
904 } else {
905 self.peer
906 .respond_with_error(
907 receipt,
908 proto::Error {
909 message: "nonce can't be blank".to_string(),
910 },
911 )
912 .await?;
913 return Ok(());
914 };
915
916 let message_id = self
917 .app_state
918 .db
919 .create_channel_message(channel_id, user_id, &body, timestamp, nonce.clone().into())
920 .await?
921 .to_proto();
922 let message = proto::ChannelMessage {
923 sender_id: user_id.to_proto(),
924 id: message_id,
925 body,
926 timestamp: timestamp.unix_timestamp() as u64,
927 nonce: Some(nonce),
928 };
929 broadcast(request.sender_id, connection_ids, |conn_id| {
930 self.peer.send(
931 conn_id,
932 proto::ChannelMessageSent {
933 channel_id: channel_id.to_proto(),
934 message: Some(message.clone()),
935 },
936 )
937 })
938 .await?;
939 self.peer
940 .respond(
941 receipt,
942 proto::SendChannelMessageResponse {
943 message: Some(message),
944 },
945 )
946 .await?;
947 Ok(())
948 }
949
950 async fn get_channel_messages(
951 self: Arc<Self>,
952 request: TypedEnvelope<proto::GetChannelMessages>,
953 ) -> tide::Result<()> {
954 let user_id = self.state().user_id_for_connection(request.sender_id)?;
955 let channel_id = ChannelId::from_proto(request.payload.channel_id);
956 if !self
957 .app_state
958 .db
959 .can_user_access_channel(user_id, channel_id)
960 .await?
961 {
962 Err(anyhow!("access denied"))?;
963 }
964
965 let messages = self
966 .app_state
967 .db
968 .get_channel_messages(
969 channel_id,
970 MESSAGE_COUNT_PER_PAGE,
971 Some(MessageId::from_proto(request.payload.before_message_id)),
972 )
973 .await?
974 .into_iter()
975 .map(|msg| proto::ChannelMessage {
976 id: msg.id.to_proto(),
977 body: msg.body,
978 timestamp: msg.sent_at.unix_timestamp() as u64,
979 sender_id: msg.sender_id.to_proto(),
980 nonce: Some(msg.nonce.as_u128().into()),
981 })
982 .collect::<Vec<_>>();
983 self.peer
984 .respond(
985 request.receipt(),
986 proto::GetChannelMessagesResponse {
987 done: messages.len() < MESSAGE_COUNT_PER_PAGE,
988 messages,
989 },
990 )
991 .await?;
992 Ok(())
993 }
994
995 fn state<'a>(self: &'a Arc<Self>) -> RwLockReadGuard<'a, Store> {
996 self.store.read()
997 }
998
999 fn state_mut<'a>(self: &'a mut Arc<Self>) -> RwLockWriteGuard<'a, Store> {
1000 self.store.write()
1001 }
1002}
1003
1004pub async fn broadcast<F, T>(
1005 sender_id: ConnectionId,
1006 receiver_ids: Vec<ConnectionId>,
1007 mut f: F,
1008) -> anyhow::Result<()>
1009where
1010 F: FnMut(ConnectionId) -> T,
1011 T: Future<Output = anyhow::Result<()>>,
1012{
1013 let futures = receiver_ids
1014 .into_iter()
1015 .filter(|id| *id != sender_id)
1016 .map(|id| f(id));
1017 futures::future::try_join_all(futures).await?;
1018 Ok(())
1019}
1020
1021pub fn add_routes(app: &mut tide::Server<Arc<AppState>>, rpc: &Arc<Peer>) {
1022 let server = Server::new(app.state().clone(), rpc.clone(), None);
1023 app.at("/rpc").get(move |request: Request<Arc<AppState>>| {
1024 let server = server.clone();
1025 async move {
1026 const WEBSOCKET_GUID: &str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
1027
1028 let connection_upgrade = header_contains_ignore_case(&request, CONNECTION, "upgrade");
1029 let upgrade_to_websocket = header_contains_ignore_case(&request, UPGRADE, "websocket");
1030 let upgrade_requested = connection_upgrade && upgrade_to_websocket;
1031 let client_protocol_version: Option<u32> = request
1032 .header("X-Zed-Protocol-Version")
1033 .and_then(|v| v.as_str().parse().ok());
1034
1035 if !upgrade_requested || client_protocol_version != Some(rpc::PROTOCOL_VERSION) {
1036 return Ok(Response::new(StatusCode::UpgradeRequired));
1037 }
1038
1039 let header = match request.header("Sec-Websocket-Key") {
1040 Some(h) => h.as_str(),
1041 None => return Err(anyhow!("expected sec-websocket-key"))?,
1042 };
1043
1044 let user_id = process_auth_header(&request).await?;
1045
1046 let mut response = Response::new(StatusCode::SwitchingProtocols);
1047 response.insert_header(UPGRADE, "websocket");
1048 response.insert_header(CONNECTION, "Upgrade");
1049 let hash = Sha1::new().chain(header).chain(WEBSOCKET_GUID).finalize();
1050 response.insert_header("Sec-Websocket-Accept", base64::encode(&hash[..]));
1051 response.insert_header("Sec-Websocket-Version", "13");
1052
1053 let http_res: &mut tide::http::Response = response.as_mut();
1054 let upgrade_receiver = http_res.recv_upgrade().await;
1055 let addr = request.remote().unwrap_or("unknown").to_string();
1056 task::spawn(async move {
1057 if let Some(stream) = upgrade_receiver.await {
1058 server
1059 .handle_connection(
1060 Connection::new(
1061 WebSocketStream::from_raw_socket(stream, Role::Server, None).await,
1062 ),
1063 addr,
1064 user_id,
1065 None,
1066 )
1067 .await;
1068 }
1069 });
1070
1071 Ok(response)
1072 }
1073 });
1074}
1075
1076fn header_contains_ignore_case<T>(
1077 request: &tide::Request<T>,
1078 header_name: HeaderName,
1079 value: &str,
1080) -> bool {
1081 request
1082 .header(header_name)
1083 .map(|h| {
1084 h.as_str()
1085 .split(',')
1086 .any(|s| s.trim().eq_ignore_ascii_case(value.trim()))
1087 })
1088 .unwrap_or(false)
1089}
1090
1091#[cfg(test)]
1092mod tests {
1093 use super::*;
1094 use crate::{
1095 auth,
1096 db::{tests::TestDb, UserId},
1097 github, AppState, Config,
1098 };
1099 use ::rpc::Peer;
1100 use async_std::task;
1101 use gpui::{executor, ModelHandle, TestAppContext};
1102 use parking_lot::Mutex;
1103 use postage::{mpsc, watch};
1104 use rpc::PeerId;
1105 use serde_json::json;
1106 use sqlx::types::time::OffsetDateTime;
1107 use std::{
1108 ops::Deref,
1109 path::Path,
1110 rc::Rc,
1111 sync::{
1112 atomic::{AtomicBool, Ordering::SeqCst},
1113 Arc,
1114 },
1115 time::Duration,
1116 };
1117 use zed::{
1118 client::{
1119 self, test::FakeHttpClient, Channel, ChannelDetails, ChannelList, Client, Credentials,
1120 EstablishConnectionError, UserStore,
1121 },
1122 editor::{Editor, EditorSettings, Input, MultiBuffer},
1123 fs::{FakeFs, Fs as _},
1124 language::{
1125 tree_sitter_rust, Diagnostic, DiagnosticEntry, Language, LanguageConfig,
1126 LanguageRegistry, LanguageServerConfig, Point,
1127 },
1128 lsp,
1129 project::{DiagnosticSummary, Project, ProjectPath},
1130 };
1131
1132 #[gpui::test]
1133 async fn test_share_project(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1134 let (window_b, _) = cx_b.add_window(|_| EmptyView);
1135 let lang_registry = Arc::new(LanguageRegistry::new());
1136 let fs = Arc::new(FakeFs::new());
1137 cx_a.foreground().forbid_parking();
1138
1139 // Connect to a server as 2 clients.
1140 let mut server = TestServer::start(cx_a.foreground()).await;
1141 let client_a = server.create_client(&mut cx_a, "user_a").await;
1142 let client_b = server.create_client(&mut cx_b, "user_b").await;
1143
1144 // Share a project as client A
1145 fs.insert_tree(
1146 "/a",
1147 json!({
1148 ".zed.toml": r#"collaborators = ["user_b"]"#,
1149 "a.txt": "a-contents",
1150 "b.txt": "b-contents",
1151 }),
1152 )
1153 .await;
1154 let project_a = cx_a.update(|cx| {
1155 Project::local(
1156 client_a.clone(),
1157 client_a.user_store.clone(),
1158 lang_registry.clone(),
1159 fs.clone(),
1160 cx,
1161 )
1162 });
1163 let (worktree_a, _) = project_a
1164 .update(&mut cx_a, |p, cx| {
1165 p.find_or_create_worktree_for_abs_path("/a", false, cx)
1166 })
1167 .await
1168 .unwrap();
1169 let worktree_id = worktree_a.read_with(&cx_a, |tree, _| tree.id());
1170 worktree_a
1171 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1172 .await;
1173 let project_id = project_a.update(&mut cx_a, |p, _| p.next_remote_id()).await;
1174 project_a
1175 .update(&mut cx_a, |p, cx| p.share(cx))
1176 .await
1177 .unwrap();
1178
1179 // Join that project as client B
1180 let project_b = Project::remote(
1181 project_id,
1182 client_b.clone(),
1183 client_b.user_store.clone(),
1184 lang_registry.clone(),
1185 fs.clone(),
1186 &mut cx_b.to_async(),
1187 )
1188 .await
1189 .unwrap();
1190
1191 let replica_id_b = project_b.read_with(&cx_b, |project, _| {
1192 assert_eq!(
1193 project
1194 .collaborators()
1195 .get(&client_a.peer_id)
1196 .unwrap()
1197 .user
1198 .github_login,
1199 "user_a"
1200 );
1201 project.replica_id()
1202 });
1203 project_a
1204 .condition(&cx_a, |tree, _| {
1205 tree.collaborators()
1206 .get(&client_b.peer_id)
1207 .map_or(false, |collaborator| {
1208 collaborator.replica_id == replica_id_b
1209 && collaborator.user.github_login == "user_b"
1210 })
1211 })
1212 .await;
1213
1214 // Open the same file as client B and client A.
1215 let buffer_b = project_b
1216 .update(&mut cx_b, |p, cx| p.open_buffer((worktree_id, "b.txt"), cx))
1217 .await
1218 .unwrap();
1219 let buffer_b = cx_b.add_model(|cx| MultiBuffer::singleton(buffer_b, cx));
1220 buffer_b.read_with(&cx_b, |buf, cx| {
1221 assert_eq!(buf.read(cx).text(), "b-contents")
1222 });
1223 project_a.read_with(&cx_a, |project, cx| {
1224 assert!(project.has_open_buffer((worktree_id, "b.txt"), cx))
1225 });
1226 let buffer_a = project_a
1227 .update(&mut cx_a, |p, cx| p.open_buffer((worktree_id, "b.txt"), cx))
1228 .await
1229 .unwrap();
1230
1231 let editor_b = cx_b.add_view(window_b, |cx| {
1232 Editor::for_buffer(buffer_b, Arc::new(|cx| EditorSettings::test(cx)), cx)
1233 });
1234
1235 // TODO
1236 // // Create a selection set as client B and see that selection set as client A.
1237 // buffer_a
1238 // .condition(&cx_a, |buffer, _| buffer.selection_sets().count() == 1)
1239 // .await;
1240
1241 // Edit the buffer as client B and see that edit as client A.
1242 editor_b.update(&mut cx_b, |editor, cx| {
1243 editor.handle_input(&Input("ok, ".into()), cx)
1244 });
1245 buffer_a
1246 .condition(&cx_a, |buffer, _| buffer.text() == "ok, b-contents")
1247 .await;
1248
1249 // TODO
1250 // // Remove the selection set as client B, see those selections disappear as client A.
1251 cx_b.update(move |_| drop(editor_b));
1252 // buffer_a
1253 // .condition(&cx_a, |buffer, _| buffer.selection_sets().count() == 0)
1254 // .await;
1255
1256 // Close the buffer as client A, see that the buffer is closed.
1257 cx_a.update(move |_| drop(buffer_a));
1258 project_a
1259 .condition(&cx_a, |project, cx| {
1260 !project.has_open_buffer((worktree_id, "b.txt"), cx)
1261 })
1262 .await;
1263
1264 // Dropping the client B's project removes client B from client A's collaborators.
1265 cx_b.update(move |_| drop(project_b));
1266 project_a
1267 .condition(&cx_a, |project, _| project.collaborators().is_empty())
1268 .await;
1269 }
1270
1271 #[gpui::test]
1272 async fn test_unshare_project(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1273 let lang_registry = Arc::new(LanguageRegistry::new());
1274 let fs = Arc::new(FakeFs::new());
1275 cx_a.foreground().forbid_parking();
1276
1277 // Connect to a server as 2 clients.
1278 let mut server = TestServer::start(cx_a.foreground()).await;
1279 let client_a = server.create_client(&mut cx_a, "user_a").await;
1280 let client_b = server.create_client(&mut cx_b, "user_b").await;
1281
1282 // Share a project as client A
1283 fs.insert_tree(
1284 "/a",
1285 json!({
1286 ".zed.toml": r#"collaborators = ["user_b"]"#,
1287 "a.txt": "a-contents",
1288 "b.txt": "b-contents",
1289 }),
1290 )
1291 .await;
1292 let project_a = cx_a.update(|cx| {
1293 Project::local(
1294 client_a.clone(),
1295 client_a.user_store.clone(),
1296 lang_registry.clone(),
1297 fs.clone(),
1298 cx,
1299 )
1300 });
1301 let (worktree_a, _) = project_a
1302 .update(&mut cx_a, |p, cx| {
1303 p.find_or_create_worktree_for_abs_path("/a", false, cx)
1304 })
1305 .await
1306 .unwrap();
1307 worktree_a
1308 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1309 .await;
1310 let project_id = project_a.update(&mut cx_a, |p, _| p.next_remote_id()).await;
1311 let worktree_id = worktree_a.read_with(&cx_a, |tree, _| tree.id());
1312 project_a
1313 .update(&mut cx_a, |p, cx| p.share(cx))
1314 .await
1315 .unwrap();
1316 assert!(worktree_a.read_with(&cx_a, |tree, _| tree.as_local().unwrap().is_shared()));
1317
1318 // Join that project as client B
1319 let project_b = Project::remote(
1320 project_id,
1321 client_b.clone(),
1322 client_b.user_store.clone(),
1323 lang_registry.clone(),
1324 fs.clone(),
1325 &mut cx_b.to_async(),
1326 )
1327 .await
1328 .unwrap();
1329 project_b
1330 .update(&mut cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
1331 .await
1332 .unwrap();
1333
1334 // Unshare the project as client A
1335 project_a
1336 .update(&mut cx_a, |project, cx| project.unshare(cx))
1337 .await
1338 .unwrap();
1339 project_b
1340 .condition(&mut cx_b, |project, _| project.is_read_only())
1341 .await;
1342 assert!(worktree_a.read_with(&cx_a, |tree, _| !tree.as_local().unwrap().is_shared()));
1343 drop(project_b);
1344
1345 // Share the project again and ensure guests can still join.
1346 project_a
1347 .update(&mut cx_a, |project, cx| project.share(cx))
1348 .await
1349 .unwrap();
1350 assert!(worktree_a.read_with(&cx_a, |tree, _| tree.as_local().unwrap().is_shared()));
1351
1352 let project_c = Project::remote(
1353 project_id,
1354 client_b.clone(),
1355 client_b.user_store.clone(),
1356 lang_registry.clone(),
1357 fs.clone(),
1358 &mut cx_b.to_async(),
1359 )
1360 .await
1361 .unwrap();
1362 project_c
1363 .update(&mut cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
1364 .await
1365 .unwrap();
1366 }
1367
1368 #[gpui::test]
1369 async fn test_propagate_saves_and_fs_changes(
1370 mut cx_a: TestAppContext,
1371 mut cx_b: TestAppContext,
1372 mut cx_c: TestAppContext,
1373 ) {
1374 let lang_registry = Arc::new(LanguageRegistry::new());
1375 let fs = Arc::new(FakeFs::new());
1376 cx_a.foreground().forbid_parking();
1377
1378 // Connect to a server as 3 clients.
1379 let mut server = TestServer::start(cx_a.foreground()).await;
1380 let client_a = server.create_client(&mut cx_a, "user_a").await;
1381 let client_b = server.create_client(&mut cx_b, "user_b").await;
1382 let client_c = server.create_client(&mut cx_c, "user_c").await;
1383
1384 // Share a worktree as client A.
1385 fs.insert_tree(
1386 "/a",
1387 json!({
1388 ".zed.toml": r#"collaborators = ["user_b", "user_c"]"#,
1389 "file1": "",
1390 "file2": ""
1391 }),
1392 )
1393 .await;
1394 let project_a = cx_a.update(|cx| {
1395 Project::local(
1396 client_a.clone(),
1397 client_a.user_store.clone(),
1398 lang_registry.clone(),
1399 fs.clone(),
1400 cx,
1401 )
1402 });
1403 let (worktree_a, _) = project_a
1404 .update(&mut cx_a, |p, cx| {
1405 p.find_or_create_worktree_for_abs_path("/a", false, cx)
1406 })
1407 .await
1408 .unwrap();
1409 worktree_a
1410 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1411 .await;
1412 let project_id = project_a.update(&mut cx_a, |p, _| p.next_remote_id()).await;
1413 let worktree_id = worktree_a.read_with(&cx_a, |tree, _| tree.id());
1414 project_a
1415 .update(&mut cx_a, |p, cx| p.share(cx))
1416 .await
1417 .unwrap();
1418
1419 // Join that worktree as clients B and C.
1420 let project_b = Project::remote(
1421 project_id,
1422 client_b.clone(),
1423 client_b.user_store.clone(),
1424 lang_registry.clone(),
1425 fs.clone(),
1426 &mut cx_b.to_async(),
1427 )
1428 .await
1429 .unwrap();
1430 let project_c = Project::remote(
1431 project_id,
1432 client_c.clone(),
1433 client_c.user_store.clone(),
1434 lang_registry.clone(),
1435 fs.clone(),
1436 &mut cx_c.to_async(),
1437 )
1438 .await
1439 .unwrap();
1440 let worktree_b = project_b.read_with(&cx_b, |p, cx| p.worktrees(cx).next().unwrap());
1441 let worktree_c = project_c.read_with(&cx_c, |p, cx| p.worktrees(cx).next().unwrap());
1442
1443 // Open and edit a buffer as both guests B and C.
1444 let buffer_b = project_b
1445 .update(&mut cx_b, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
1446 .await
1447 .unwrap();
1448 let buffer_c = project_c
1449 .update(&mut cx_c, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
1450 .await
1451 .unwrap();
1452 buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "i-am-b, ", cx));
1453 buffer_c.update(&mut cx_c, |buf, cx| buf.edit([0..0], "i-am-c, ", cx));
1454
1455 // Open and edit that buffer as the host.
1456 let buffer_a = project_a
1457 .update(&mut cx_a, |p, cx| p.open_buffer((worktree_id, "file1"), cx))
1458 .await
1459 .unwrap();
1460
1461 buffer_a
1462 .condition(&mut cx_a, |buf, _| buf.text() == "i-am-c, i-am-b, ")
1463 .await;
1464 buffer_a.update(&mut cx_a, |buf, cx| {
1465 buf.edit([buf.len()..buf.len()], "i-am-a", cx)
1466 });
1467
1468 // Wait for edits to propagate
1469 buffer_a
1470 .condition(&mut cx_a, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1471 .await;
1472 buffer_b
1473 .condition(&mut cx_b, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1474 .await;
1475 buffer_c
1476 .condition(&mut cx_c, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1477 .await;
1478
1479 // Edit the buffer as the host and concurrently save as guest B.
1480 let save_b = buffer_b.update(&mut cx_b, |buf, cx| buf.save(cx));
1481 buffer_a.update(&mut cx_a, |buf, cx| buf.edit([0..0], "hi-a, ", cx));
1482 save_b.await.unwrap();
1483 assert_eq!(
1484 fs.load("/a/file1".as_ref()).await.unwrap(),
1485 "hi-a, i-am-c, i-am-b, i-am-a"
1486 );
1487 buffer_a.read_with(&cx_a, |buf, _| assert!(!buf.is_dirty()));
1488 buffer_b.read_with(&cx_b, |buf, _| assert!(!buf.is_dirty()));
1489 buffer_c.condition(&cx_c, |buf, _| !buf.is_dirty()).await;
1490
1491 // Make changes on host's file system, see those changes on the guests.
1492 fs.rename("/a/file2".as_ref(), "/a/file3".as_ref())
1493 .await
1494 .unwrap();
1495 fs.insert_file(Path::new("/a/file4"), "4".into())
1496 .await
1497 .unwrap();
1498
1499 worktree_b
1500 .condition(&cx_b, |tree, _| tree.file_count() == 4)
1501 .await;
1502 worktree_c
1503 .condition(&cx_c, |tree, _| tree.file_count() == 4)
1504 .await;
1505 worktree_b.read_with(&cx_b, |tree, _| {
1506 assert_eq!(
1507 tree.paths()
1508 .map(|p| p.to_string_lossy())
1509 .collect::<Vec<_>>(),
1510 &[".zed.toml", "file1", "file3", "file4"]
1511 )
1512 });
1513 worktree_c.read_with(&cx_c, |tree, _| {
1514 assert_eq!(
1515 tree.paths()
1516 .map(|p| p.to_string_lossy())
1517 .collect::<Vec<_>>(),
1518 &[".zed.toml", "file1", "file3", "file4"]
1519 )
1520 });
1521 }
1522
1523 #[gpui::test]
1524 async fn test_buffer_conflict_after_save(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1525 cx_a.foreground().forbid_parking();
1526 let lang_registry = Arc::new(LanguageRegistry::new());
1527 let fs = Arc::new(FakeFs::new());
1528
1529 // Connect to a server as 2 clients.
1530 let mut server = TestServer::start(cx_a.foreground()).await;
1531 let client_a = server.create_client(&mut cx_a, "user_a").await;
1532 let client_b = server.create_client(&mut cx_b, "user_b").await;
1533
1534 // Share a project as client A
1535 fs.insert_tree(
1536 "/dir",
1537 json!({
1538 ".zed.toml": r#"collaborators = ["user_b", "user_c"]"#,
1539 "a.txt": "a-contents",
1540 }),
1541 )
1542 .await;
1543
1544 let project_a = cx_a.update(|cx| {
1545 Project::local(
1546 client_a.clone(),
1547 client_a.user_store.clone(),
1548 lang_registry.clone(),
1549 fs.clone(),
1550 cx,
1551 )
1552 });
1553 let (worktree_a, _) = project_a
1554 .update(&mut cx_a, |p, cx| {
1555 p.find_or_create_worktree_for_abs_path("/dir", false, cx)
1556 })
1557 .await
1558 .unwrap();
1559 worktree_a
1560 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1561 .await;
1562 let project_id = project_a.update(&mut cx_a, |p, _| p.next_remote_id()).await;
1563 let worktree_id = worktree_a.read_with(&cx_a, |tree, _| tree.id());
1564 project_a
1565 .update(&mut cx_a, |p, cx| p.share(cx))
1566 .await
1567 .unwrap();
1568
1569 // Join that project as client B
1570 let project_b = Project::remote(
1571 project_id,
1572 client_b.clone(),
1573 client_b.user_store.clone(),
1574 lang_registry.clone(),
1575 fs.clone(),
1576 &mut cx_b.to_async(),
1577 )
1578 .await
1579 .unwrap();
1580 let worktree_b = project_b.update(&mut cx_b, |p, cx| p.worktrees(cx).next().unwrap());
1581
1582 // Open a buffer as client B
1583 let buffer_b = project_b
1584 .update(&mut cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
1585 .await
1586 .unwrap();
1587 let mtime = buffer_b.read_with(&cx_b, |buf, _| buf.file().unwrap().mtime());
1588
1589 buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "world ", cx));
1590 buffer_b.read_with(&cx_b, |buf, _| {
1591 assert!(buf.is_dirty());
1592 assert!(!buf.has_conflict());
1593 });
1594
1595 buffer_b
1596 .update(&mut cx_b, |buf, cx| buf.save(cx))
1597 .await
1598 .unwrap();
1599 worktree_b
1600 .condition(&cx_b, |_, cx| {
1601 buffer_b.read(cx).file().unwrap().mtime() != mtime
1602 })
1603 .await;
1604 buffer_b.read_with(&cx_b, |buf, _| {
1605 assert!(!buf.is_dirty());
1606 assert!(!buf.has_conflict());
1607 });
1608
1609 buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "hello ", cx));
1610 buffer_b.read_with(&cx_b, |buf, _| {
1611 assert!(buf.is_dirty());
1612 assert!(!buf.has_conflict());
1613 });
1614 }
1615
1616 #[gpui::test]
1617 async fn test_editing_while_guest_opens_buffer(
1618 mut cx_a: TestAppContext,
1619 mut cx_b: TestAppContext,
1620 ) {
1621 cx_a.foreground().forbid_parking();
1622 let lang_registry = Arc::new(LanguageRegistry::new());
1623 let fs = Arc::new(FakeFs::new());
1624
1625 // Connect to a server as 2 clients.
1626 let mut server = TestServer::start(cx_a.foreground()).await;
1627 let client_a = server.create_client(&mut cx_a, "user_a").await;
1628 let client_b = server.create_client(&mut cx_b, "user_b").await;
1629
1630 // Share a project as client A
1631 fs.insert_tree(
1632 "/dir",
1633 json!({
1634 ".zed.toml": r#"collaborators = ["user_b"]"#,
1635 "a.txt": "a-contents",
1636 }),
1637 )
1638 .await;
1639 let project_a = cx_a.update(|cx| {
1640 Project::local(
1641 client_a.clone(),
1642 client_a.user_store.clone(),
1643 lang_registry.clone(),
1644 fs.clone(),
1645 cx,
1646 )
1647 });
1648 let (worktree_a, _) = project_a
1649 .update(&mut cx_a, |p, cx| {
1650 p.find_or_create_worktree_for_abs_path("/dir", false, cx)
1651 })
1652 .await
1653 .unwrap();
1654 worktree_a
1655 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1656 .await;
1657 let project_id = project_a.update(&mut cx_a, |p, _| p.next_remote_id()).await;
1658 let worktree_id = worktree_a.read_with(&cx_a, |tree, _| tree.id());
1659 project_a
1660 .update(&mut cx_a, |p, cx| p.share(cx))
1661 .await
1662 .unwrap();
1663
1664 // Join that project as client B
1665 let project_b = Project::remote(
1666 project_id,
1667 client_b.clone(),
1668 client_b.user_store.clone(),
1669 lang_registry.clone(),
1670 fs.clone(),
1671 &mut cx_b.to_async(),
1672 )
1673 .await
1674 .unwrap();
1675
1676 // Open a buffer as client A
1677 let buffer_a = project_a
1678 .update(&mut cx_a, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
1679 .await
1680 .unwrap();
1681
1682 // Start opening the same buffer as client B
1683 let buffer_b = cx_b
1684 .background()
1685 .spawn(project_b.update(&mut cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx)));
1686 task::yield_now().await;
1687
1688 // Edit the buffer as client A while client B is still opening it.
1689 buffer_a.update(&mut cx_a, |buf, cx| buf.edit([0..0], "z", cx));
1690
1691 let text = buffer_a.read_with(&cx_a, |buf, _| buf.text());
1692 let buffer_b = buffer_b.await.unwrap();
1693 buffer_b.condition(&cx_b, |buf, _| buf.text() == text).await;
1694 }
1695
1696 #[gpui::test]
1697 async fn test_leaving_worktree_while_opening_buffer(
1698 mut cx_a: TestAppContext,
1699 mut cx_b: TestAppContext,
1700 ) {
1701 cx_a.foreground().forbid_parking();
1702 let lang_registry = Arc::new(LanguageRegistry::new());
1703 let fs = Arc::new(FakeFs::new());
1704
1705 // Connect to a server as 2 clients.
1706 let mut server = TestServer::start(cx_a.foreground()).await;
1707 let client_a = server.create_client(&mut cx_a, "user_a").await;
1708 let client_b = server.create_client(&mut cx_b, "user_b").await;
1709
1710 // Share a project as client A
1711 fs.insert_tree(
1712 "/dir",
1713 json!({
1714 ".zed.toml": r#"collaborators = ["user_b"]"#,
1715 "a.txt": "a-contents",
1716 }),
1717 )
1718 .await;
1719 let project_a = cx_a.update(|cx| {
1720 Project::local(
1721 client_a.clone(),
1722 client_a.user_store.clone(),
1723 lang_registry.clone(),
1724 fs.clone(),
1725 cx,
1726 )
1727 });
1728 let (worktree_a, _) = project_a
1729 .update(&mut cx_a, |p, cx| {
1730 p.find_or_create_worktree_for_abs_path("/dir", false, cx)
1731 })
1732 .await
1733 .unwrap();
1734 worktree_a
1735 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1736 .await;
1737 let project_id = project_a.update(&mut cx_a, |p, _| p.next_remote_id()).await;
1738 let worktree_id = worktree_a.read_with(&cx_a, |tree, _| tree.id());
1739 project_a
1740 .update(&mut cx_a, |p, cx| p.share(cx))
1741 .await
1742 .unwrap();
1743
1744 // Join that project as client B
1745 let project_b = Project::remote(
1746 project_id,
1747 client_b.clone(),
1748 client_b.user_store.clone(),
1749 lang_registry.clone(),
1750 fs.clone(),
1751 &mut cx_b.to_async(),
1752 )
1753 .await
1754 .unwrap();
1755
1756 // See that a guest has joined as client A.
1757 project_a
1758 .condition(&cx_a, |p, _| p.collaborators().len() == 1)
1759 .await;
1760
1761 // Begin opening a buffer as client B, but leave the project before the open completes.
1762 let buffer_b = cx_b
1763 .background()
1764 .spawn(project_b.update(&mut cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx)));
1765 cx_b.update(|_| drop(project_b));
1766 drop(buffer_b);
1767
1768 // See that the guest has left.
1769 project_a
1770 .condition(&cx_a, |p, _| p.collaborators().len() == 0)
1771 .await;
1772 }
1773
1774 #[gpui::test]
1775 async fn test_peer_disconnection(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1776 cx_a.foreground().forbid_parking();
1777 let lang_registry = Arc::new(LanguageRegistry::new());
1778 let fs = Arc::new(FakeFs::new());
1779
1780 // Connect to a server as 2 clients.
1781 let mut server = TestServer::start(cx_a.foreground()).await;
1782 let client_a = server.create_client(&mut cx_a, "user_a").await;
1783 let client_b = server.create_client(&mut cx_b, "user_b").await;
1784
1785 // Share a project as client A
1786 fs.insert_tree(
1787 "/a",
1788 json!({
1789 ".zed.toml": r#"collaborators = ["user_b"]"#,
1790 "a.txt": "a-contents",
1791 "b.txt": "b-contents",
1792 }),
1793 )
1794 .await;
1795 let project_a = cx_a.update(|cx| {
1796 Project::local(
1797 client_a.clone(),
1798 client_a.user_store.clone(),
1799 lang_registry.clone(),
1800 fs.clone(),
1801 cx,
1802 )
1803 });
1804 let (worktree_a, _) = project_a
1805 .update(&mut cx_a, |p, cx| {
1806 p.find_or_create_worktree_for_abs_path("/a", false, cx)
1807 })
1808 .await
1809 .unwrap();
1810 worktree_a
1811 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1812 .await;
1813 let project_id = project_a
1814 .update(&mut cx_a, |project, _| project.next_remote_id())
1815 .await;
1816 project_a
1817 .update(&mut cx_a, |project, cx| project.share(cx))
1818 .await
1819 .unwrap();
1820
1821 // Join that project as client B
1822 let _project_b = Project::remote(
1823 project_id,
1824 client_b.clone(),
1825 client_b.user_store.clone(),
1826 lang_registry.clone(),
1827 fs.clone(),
1828 &mut cx_b.to_async(),
1829 )
1830 .await
1831 .unwrap();
1832
1833 // See that a guest has joined as client A.
1834 project_a
1835 .condition(&cx_a, |p, _| p.collaborators().len() == 1)
1836 .await;
1837
1838 // Drop client B's connection and ensure client A observes client B leaving the worktree.
1839 client_b.disconnect(&cx_b.to_async()).unwrap();
1840 project_a
1841 .condition(&cx_a, |p, _| p.collaborators().len() == 0)
1842 .await;
1843 }
1844
1845 #[gpui::test]
1846 async fn test_collaborating_with_diagnostics(
1847 mut cx_a: TestAppContext,
1848 mut cx_b: TestAppContext,
1849 ) {
1850 cx_a.foreground().forbid_parking();
1851 let mut lang_registry = Arc::new(LanguageRegistry::new());
1852 let fs = Arc::new(FakeFs::new());
1853
1854 // Set up a fake language server.
1855 let (language_server_config, mut fake_language_server) =
1856 LanguageServerConfig::fake(cx_a.background()).await;
1857 Arc::get_mut(&mut lang_registry)
1858 .unwrap()
1859 .add(Arc::new(Language::new(
1860 LanguageConfig {
1861 name: "Rust".to_string(),
1862 path_suffixes: vec!["rs".to_string()],
1863 language_server: Some(language_server_config),
1864 ..Default::default()
1865 },
1866 Some(tree_sitter_rust::language()),
1867 )));
1868
1869 // Connect to a server as 2 clients.
1870 let mut server = TestServer::start(cx_a.foreground()).await;
1871 let client_a = server.create_client(&mut cx_a, "user_a").await;
1872 let client_b = server.create_client(&mut cx_b, "user_b").await;
1873
1874 // Share a project as client A
1875 fs.insert_tree(
1876 "/a",
1877 json!({
1878 ".zed.toml": r#"collaborators = ["user_b"]"#,
1879 "a.rs": "let one = two",
1880 "other.rs": "",
1881 }),
1882 )
1883 .await;
1884 let project_a = cx_a.update(|cx| {
1885 Project::local(
1886 client_a.clone(),
1887 client_a.user_store.clone(),
1888 lang_registry.clone(),
1889 fs.clone(),
1890 cx,
1891 )
1892 });
1893 let (worktree_a, _) = project_a
1894 .update(&mut cx_a, |p, cx| {
1895 p.find_or_create_worktree_for_abs_path("/a", false, cx)
1896 })
1897 .await
1898 .unwrap();
1899 worktree_a
1900 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1901 .await;
1902 let project_id = project_a.update(&mut cx_a, |p, _| p.next_remote_id()).await;
1903 let worktree_id = worktree_a.read_with(&cx_a, |tree, _| tree.id());
1904 project_a
1905 .update(&mut cx_a, |p, cx| p.share(cx))
1906 .await
1907 .unwrap();
1908
1909 // Cause the language server to start.
1910 let _ = cx_a
1911 .background()
1912 .spawn(project_a.update(&mut cx_a, |project, cx| {
1913 project.open_buffer(
1914 ProjectPath {
1915 worktree_id,
1916 path: Path::new("other.rs").into(),
1917 },
1918 cx,
1919 )
1920 }))
1921 .await
1922 .unwrap();
1923
1924 // Simulate a language server reporting errors for a file.
1925 fake_language_server
1926 .notify::<lsp::notification::PublishDiagnostics>(lsp::PublishDiagnosticsParams {
1927 uri: lsp::Url::from_file_path("/a/a.rs").unwrap(),
1928 version: None,
1929 diagnostics: vec![lsp::Diagnostic {
1930 severity: Some(lsp::DiagnosticSeverity::ERROR),
1931 range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 7)),
1932 message: "message 1".to_string(),
1933 ..Default::default()
1934 }],
1935 })
1936 .await;
1937
1938 // Wait for server to see the diagnostics update.
1939 server
1940 .condition(|store| {
1941 let worktree = store
1942 .project(project_id)
1943 .unwrap()
1944 .worktrees
1945 .get(&worktree_id.to_proto())
1946 .unwrap();
1947
1948 !worktree
1949 .share
1950 .as_ref()
1951 .unwrap()
1952 .diagnostic_summaries
1953 .is_empty()
1954 })
1955 .await;
1956
1957 // Join the worktree as client B.
1958 let project_b = Project::remote(
1959 project_id,
1960 client_b.clone(),
1961 client_b.user_store.clone(),
1962 lang_registry.clone(),
1963 fs.clone(),
1964 &mut cx_b.to_async(),
1965 )
1966 .await
1967 .unwrap();
1968
1969 project_b.read_with(&cx_b, |project, cx| {
1970 assert_eq!(
1971 project.diagnostic_summaries(cx).collect::<Vec<_>>(),
1972 &[(
1973 ProjectPath {
1974 worktree_id,
1975 path: Arc::from(Path::new("a.rs")),
1976 },
1977 DiagnosticSummary {
1978 error_count: 1,
1979 warning_count: 0,
1980 ..Default::default()
1981 },
1982 )]
1983 )
1984 });
1985
1986 // Simulate a language server reporting more errors for a file.
1987 fake_language_server
1988 .notify::<lsp::notification::PublishDiagnostics>(lsp::PublishDiagnosticsParams {
1989 uri: lsp::Url::from_file_path("/a/a.rs").unwrap(),
1990 version: None,
1991 diagnostics: vec![
1992 lsp::Diagnostic {
1993 severity: Some(lsp::DiagnosticSeverity::ERROR),
1994 range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 7)),
1995 message: "message 1".to_string(),
1996 ..Default::default()
1997 },
1998 lsp::Diagnostic {
1999 severity: Some(lsp::DiagnosticSeverity::WARNING),
2000 range: lsp::Range::new(
2001 lsp::Position::new(0, 10),
2002 lsp::Position::new(0, 13),
2003 ),
2004 message: "message 2".to_string(),
2005 ..Default::default()
2006 },
2007 ],
2008 })
2009 .await;
2010
2011 // Client b gets the updated summaries
2012 project_b
2013 .condition(&cx_b, |project, cx| {
2014 project.diagnostic_summaries(cx).collect::<Vec<_>>()
2015 == &[(
2016 ProjectPath {
2017 worktree_id,
2018 path: Arc::from(Path::new("a.rs")),
2019 },
2020 DiagnosticSummary {
2021 error_count: 1,
2022 warning_count: 1,
2023 ..Default::default()
2024 },
2025 )]
2026 })
2027 .await;
2028
2029 // Open the file with the errors on client B. They should be present.
2030 let buffer_b = cx_b
2031 .background()
2032 .spawn(project_b.update(&mut cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx)))
2033 .await
2034 .unwrap();
2035
2036 buffer_b.read_with(&cx_b, |buffer, _| {
2037 assert_eq!(
2038 buffer
2039 .snapshot()
2040 .diagnostics_in_range::<_, Point>(0..buffer.len())
2041 .map(|entry| entry)
2042 .collect::<Vec<_>>(),
2043 &[
2044 DiagnosticEntry {
2045 range: Point::new(0, 4)..Point::new(0, 7),
2046 diagnostic: Diagnostic {
2047 group_id: 0,
2048 message: "message 1".to_string(),
2049 severity: lsp::DiagnosticSeverity::ERROR,
2050 is_primary: true,
2051 ..Default::default()
2052 }
2053 },
2054 DiagnosticEntry {
2055 range: Point::new(0, 10)..Point::new(0, 13),
2056 diagnostic: Diagnostic {
2057 group_id: 1,
2058 severity: lsp::DiagnosticSeverity::WARNING,
2059 message: "message 2".to_string(),
2060 is_primary: true,
2061 ..Default::default()
2062 }
2063 }
2064 ]
2065 );
2066 });
2067 }
2068
2069 #[gpui::test]
2070 async fn test_formatting_buffer(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
2071 cx_a.foreground().forbid_parking();
2072 let mut lang_registry = Arc::new(LanguageRegistry::new());
2073 let fs = Arc::new(FakeFs::new());
2074
2075 // Set up a fake language server.
2076 let (language_server_config, mut fake_language_server) =
2077 LanguageServerConfig::fake(cx_a.background()).await;
2078 Arc::get_mut(&mut lang_registry)
2079 .unwrap()
2080 .add(Arc::new(Language::new(
2081 LanguageConfig {
2082 name: "Rust".to_string(),
2083 path_suffixes: vec!["rs".to_string()],
2084 language_server: Some(language_server_config),
2085 ..Default::default()
2086 },
2087 Some(tree_sitter_rust::language()),
2088 )));
2089
2090 // Connect to a server as 2 clients.
2091 let mut server = TestServer::start(cx_a.foreground()).await;
2092 let client_a = server.create_client(&mut cx_a, "user_a").await;
2093 let client_b = server.create_client(&mut cx_b, "user_b").await;
2094
2095 // Share a project as client A
2096 fs.insert_tree(
2097 "/a",
2098 json!({
2099 ".zed.toml": r#"collaborators = ["user_b"]"#,
2100 "a.rs": "let one = two",
2101 }),
2102 )
2103 .await;
2104 let project_a = cx_a.update(|cx| {
2105 Project::local(
2106 client_a.clone(),
2107 client_a.user_store.clone(),
2108 lang_registry.clone(),
2109 fs.clone(),
2110 cx,
2111 )
2112 });
2113 let (worktree_a, _) = project_a
2114 .update(&mut cx_a, |p, cx| {
2115 p.find_or_create_worktree_for_abs_path("/a", false, cx)
2116 })
2117 .await
2118 .unwrap();
2119 worktree_a
2120 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
2121 .await;
2122 let project_id = project_a.update(&mut cx_a, |p, _| p.next_remote_id()).await;
2123 let worktree_id = worktree_a.read_with(&cx_a, |tree, _| tree.id());
2124 project_a
2125 .update(&mut cx_a, |p, cx| p.share(cx))
2126 .await
2127 .unwrap();
2128
2129 // Join the worktree as client B.
2130 let project_b = Project::remote(
2131 project_id,
2132 client_b.clone(),
2133 client_b.user_store.clone(),
2134 lang_registry.clone(),
2135 fs.clone(),
2136 &mut cx_b.to_async(),
2137 )
2138 .await
2139 .unwrap();
2140
2141 // Open the file to be formatted on client B.
2142 let buffer_b = cx_b
2143 .background()
2144 .spawn(project_b.update(&mut cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx)))
2145 .await
2146 .unwrap();
2147
2148 let format = buffer_b.update(&mut cx_b, |buffer, cx| buffer.format(cx));
2149 let (request_id, _) = fake_language_server
2150 .receive_request::<lsp::request::Formatting>()
2151 .await;
2152 fake_language_server
2153 .respond(
2154 request_id,
2155 Some(vec![
2156 lsp::TextEdit {
2157 range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 4)),
2158 new_text: "h".to_string(),
2159 },
2160 lsp::TextEdit {
2161 range: lsp::Range::new(lsp::Position::new(0, 7), lsp::Position::new(0, 7)),
2162 new_text: "y".to_string(),
2163 },
2164 ]),
2165 )
2166 .await;
2167 format.await.unwrap();
2168 assert_eq!(
2169 buffer_b.read_with(&cx_b, |buffer, _| buffer.text()),
2170 "let honey = two"
2171 );
2172 }
2173
2174 #[gpui::test]
2175 async fn test_basic_chat(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
2176 cx_a.foreground().forbid_parking();
2177
2178 // Connect to a server as 2 clients.
2179 let mut server = TestServer::start(cx_a.foreground()).await;
2180 let client_a = server.create_client(&mut cx_a, "user_a").await;
2181 let client_b = server.create_client(&mut cx_b, "user_b").await;
2182
2183 // Create an org that includes these 2 users.
2184 let db = &server.app_state.db;
2185 let org_id = db.create_org("Test Org", "test-org").await.unwrap();
2186 db.add_org_member(org_id, client_a.current_user_id(&cx_a), false)
2187 .await
2188 .unwrap();
2189 db.add_org_member(org_id, client_b.current_user_id(&cx_b), false)
2190 .await
2191 .unwrap();
2192
2193 // Create a channel that includes all the users.
2194 let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
2195 db.add_channel_member(channel_id, client_a.current_user_id(&cx_a), false)
2196 .await
2197 .unwrap();
2198 db.add_channel_member(channel_id, client_b.current_user_id(&cx_b), false)
2199 .await
2200 .unwrap();
2201 db.create_channel_message(
2202 channel_id,
2203 client_b.current_user_id(&cx_b),
2204 "hello A, it's B.",
2205 OffsetDateTime::now_utc(),
2206 1,
2207 )
2208 .await
2209 .unwrap();
2210
2211 let channels_a = cx_a
2212 .add_model(|cx| ChannelList::new(client_a.user_store.clone(), client_a.clone(), cx));
2213 channels_a
2214 .condition(&mut cx_a, |list, _| list.available_channels().is_some())
2215 .await;
2216 channels_a.read_with(&cx_a, |list, _| {
2217 assert_eq!(
2218 list.available_channels().unwrap(),
2219 &[ChannelDetails {
2220 id: channel_id.to_proto(),
2221 name: "test-channel".to_string()
2222 }]
2223 )
2224 });
2225 let channel_a = channels_a.update(&mut cx_a, |this, cx| {
2226 this.get_channel(channel_id.to_proto(), cx).unwrap()
2227 });
2228 channel_a.read_with(&cx_a, |channel, _| assert!(channel.messages().is_empty()));
2229 channel_a
2230 .condition(&cx_a, |channel, _| {
2231 channel_messages(channel)
2232 == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2233 })
2234 .await;
2235
2236 let channels_b = cx_b
2237 .add_model(|cx| ChannelList::new(client_b.user_store.clone(), client_b.clone(), cx));
2238 channels_b
2239 .condition(&mut cx_b, |list, _| list.available_channels().is_some())
2240 .await;
2241 channels_b.read_with(&cx_b, |list, _| {
2242 assert_eq!(
2243 list.available_channels().unwrap(),
2244 &[ChannelDetails {
2245 id: channel_id.to_proto(),
2246 name: "test-channel".to_string()
2247 }]
2248 )
2249 });
2250
2251 let channel_b = channels_b.update(&mut cx_b, |this, cx| {
2252 this.get_channel(channel_id.to_proto(), cx).unwrap()
2253 });
2254 channel_b.read_with(&cx_b, |channel, _| assert!(channel.messages().is_empty()));
2255 channel_b
2256 .condition(&cx_b, |channel, _| {
2257 channel_messages(channel)
2258 == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2259 })
2260 .await;
2261
2262 channel_a
2263 .update(&mut cx_a, |channel, cx| {
2264 channel
2265 .send_message("oh, hi B.".to_string(), cx)
2266 .unwrap()
2267 .detach();
2268 let task = channel.send_message("sup".to_string(), cx).unwrap();
2269 assert_eq!(
2270 channel_messages(channel),
2271 &[
2272 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2273 ("user_a".to_string(), "oh, hi B.".to_string(), true),
2274 ("user_a".to_string(), "sup".to_string(), true)
2275 ]
2276 );
2277 task
2278 })
2279 .await
2280 .unwrap();
2281
2282 channel_b
2283 .condition(&cx_b, |channel, _| {
2284 channel_messages(channel)
2285 == [
2286 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2287 ("user_a".to_string(), "oh, hi B.".to_string(), false),
2288 ("user_a".to_string(), "sup".to_string(), false),
2289 ]
2290 })
2291 .await;
2292
2293 assert_eq!(
2294 server
2295 .state()
2296 .await
2297 .channel(channel_id)
2298 .unwrap()
2299 .connection_ids
2300 .len(),
2301 2
2302 );
2303 cx_b.update(|_| drop(channel_b));
2304 server
2305 .condition(|state| state.channel(channel_id).unwrap().connection_ids.len() == 1)
2306 .await;
2307
2308 cx_a.update(|_| drop(channel_a));
2309 server
2310 .condition(|state| state.channel(channel_id).is_none())
2311 .await;
2312 }
2313
2314 #[gpui::test]
2315 async fn test_chat_message_validation(mut cx_a: TestAppContext) {
2316 cx_a.foreground().forbid_parking();
2317
2318 let mut server = TestServer::start(cx_a.foreground()).await;
2319 let client_a = server.create_client(&mut cx_a, "user_a").await;
2320
2321 let db = &server.app_state.db;
2322 let org_id = db.create_org("Test Org", "test-org").await.unwrap();
2323 let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
2324 db.add_org_member(org_id, client_a.current_user_id(&cx_a), false)
2325 .await
2326 .unwrap();
2327 db.add_channel_member(channel_id, client_a.current_user_id(&cx_a), false)
2328 .await
2329 .unwrap();
2330
2331 let channels_a = cx_a
2332 .add_model(|cx| ChannelList::new(client_a.user_store.clone(), client_a.clone(), cx));
2333 channels_a
2334 .condition(&mut cx_a, |list, _| list.available_channels().is_some())
2335 .await;
2336 let channel_a = channels_a.update(&mut cx_a, |this, cx| {
2337 this.get_channel(channel_id.to_proto(), cx).unwrap()
2338 });
2339
2340 // Messages aren't allowed to be too long.
2341 channel_a
2342 .update(&mut cx_a, |channel, cx| {
2343 let long_body = "this is long.\n".repeat(1024);
2344 channel.send_message(long_body, cx).unwrap()
2345 })
2346 .await
2347 .unwrap_err();
2348
2349 // Messages aren't allowed to be blank.
2350 channel_a.update(&mut cx_a, |channel, cx| {
2351 channel.send_message(String::new(), cx).unwrap_err()
2352 });
2353
2354 // Leading and trailing whitespace are trimmed.
2355 channel_a
2356 .update(&mut cx_a, |channel, cx| {
2357 channel
2358 .send_message("\n surrounded by whitespace \n".to_string(), cx)
2359 .unwrap()
2360 })
2361 .await
2362 .unwrap();
2363 assert_eq!(
2364 db.get_channel_messages(channel_id, 10, None)
2365 .await
2366 .unwrap()
2367 .iter()
2368 .map(|m| &m.body)
2369 .collect::<Vec<_>>(),
2370 &["surrounded by whitespace"]
2371 );
2372 }
2373
2374 #[gpui::test]
2375 async fn test_chat_reconnection(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
2376 cx_a.foreground().forbid_parking();
2377
2378 // Connect to a server as 2 clients.
2379 let mut server = TestServer::start(cx_a.foreground()).await;
2380 let client_a = server.create_client(&mut cx_a, "user_a").await;
2381 let client_b = server.create_client(&mut cx_b, "user_b").await;
2382 let mut status_b = client_b.status();
2383
2384 // Create an org that includes these 2 users.
2385 let db = &server.app_state.db;
2386 let org_id = db.create_org("Test Org", "test-org").await.unwrap();
2387 db.add_org_member(org_id, client_a.current_user_id(&cx_a), false)
2388 .await
2389 .unwrap();
2390 db.add_org_member(org_id, client_b.current_user_id(&cx_b), false)
2391 .await
2392 .unwrap();
2393
2394 // Create a channel that includes all the users.
2395 let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
2396 db.add_channel_member(channel_id, client_a.current_user_id(&cx_a), false)
2397 .await
2398 .unwrap();
2399 db.add_channel_member(channel_id, client_b.current_user_id(&cx_b), false)
2400 .await
2401 .unwrap();
2402 db.create_channel_message(
2403 channel_id,
2404 client_b.current_user_id(&cx_b),
2405 "hello A, it's B.",
2406 OffsetDateTime::now_utc(),
2407 2,
2408 )
2409 .await
2410 .unwrap();
2411
2412 let channels_a = cx_a
2413 .add_model(|cx| ChannelList::new(client_a.user_store.clone(), client_a.clone(), cx));
2414 channels_a
2415 .condition(&mut cx_a, |list, _| list.available_channels().is_some())
2416 .await;
2417
2418 channels_a.read_with(&cx_a, |list, _| {
2419 assert_eq!(
2420 list.available_channels().unwrap(),
2421 &[ChannelDetails {
2422 id: channel_id.to_proto(),
2423 name: "test-channel".to_string()
2424 }]
2425 )
2426 });
2427 let channel_a = channels_a.update(&mut cx_a, |this, cx| {
2428 this.get_channel(channel_id.to_proto(), cx).unwrap()
2429 });
2430 channel_a.read_with(&cx_a, |channel, _| assert!(channel.messages().is_empty()));
2431 channel_a
2432 .condition(&cx_a, |channel, _| {
2433 channel_messages(channel)
2434 == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2435 })
2436 .await;
2437
2438 let channels_b = cx_b
2439 .add_model(|cx| ChannelList::new(client_b.user_store.clone(), client_b.clone(), cx));
2440 channels_b
2441 .condition(&mut cx_b, |list, _| list.available_channels().is_some())
2442 .await;
2443 channels_b.read_with(&cx_b, |list, _| {
2444 assert_eq!(
2445 list.available_channels().unwrap(),
2446 &[ChannelDetails {
2447 id: channel_id.to_proto(),
2448 name: "test-channel".to_string()
2449 }]
2450 )
2451 });
2452
2453 let channel_b = channels_b.update(&mut cx_b, |this, cx| {
2454 this.get_channel(channel_id.to_proto(), cx).unwrap()
2455 });
2456 channel_b.read_with(&cx_b, |channel, _| assert!(channel.messages().is_empty()));
2457 channel_b
2458 .condition(&cx_b, |channel, _| {
2459 channel_messages(channel)
2460 == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2461 })
2462 .await;
2463
2464 // Disconnect client B, ensuring we can still access its cached channel data.
2465 server.forbid_connections();
2466 server.disconnect_client(client_b.current_user_id(&cx_b));
2467 while !matches!(
2468 status_b.next().await,
2469 Some(client::Status::ReconnectionError { .. })
2470 ) {}
2471
2472 channels_b.read_with(&cx_b, |channels, _| {
2473 assert_eq!(
2474 channels.available_channels().unwrap(),
2475 [ChannelDetails {
2476 id: channel_id.to_proto(),
2477 name: "test-channel".to_string()
2478 }]
2479 )
2480 });
2481 channel_b.read_with(&cx_b, |channel, _| {
2482 assert_eq!(
2483 channel_messages(channel),
2484 [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2485 )
2486 });
2487
2488 // Send a message from client B while it is disconnected.
2489 channel_b
2490 .update(&mut cx_b, |channel, cx| {
2491 let task = channel
2492 .send_message("can you see this?".to_string(), cx)
2493 .unwrap();
2494 assert_eq!(
2495 channel_messages(channel),
2496 &[
2497 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2498 ("user_b".to_string(), "can you see this?".to_string(), true)
2499 ]
2500 );
2501 task
2502 })
2503 .await
2504 .unwrap_err();
2505
2506 // Send a message from client A while B is disconnected.
2507 channel_a
2508 .update(&mut cx_a, |channel, cx| {
2509 channel
2510 .send_message("oh, hi B.".to_string(), cx)
2511 .unwrap()
2512 .detach();
2513 let task = channel.send_message("sup".to_string(), cx).unwrap();
2514 assert_eq!(
2515 channel_messages(channel),
2516 &[
2517 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2518 ("user_a".to_string(), "oh, hi B.".to_string(), true),
2519 ("user_a".to_string(), "sup".to_string(), true)
2520 ]
2521 );
2522 task
2523 })
2524 .await
2525 .unwrap();
2526
2527 // Give client B a chance to reconnect.
2528 server.allow_connections();
2529 cx_b.foreground().advance_clock(Duration::from_secs(10));
2530
2531 // Verify that B sees the new messages upon reconnection, as well as the message client B
2532 // sent while offline.
2533 channel_b
2534 .condition(&cx_b, |channel, _| {
2535 channel_messages(channel)
2536 == [
2537 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2538 ("user_a".to_string(), "oh, hi B.".to_string(), false),
2539 ("user_a".to_string(), "sup".to_string(), false),
2540 ("user_b".to_string(), "can you see this?".to_string(), false),
2541 ]
2542 })
2543 .await;
2544
2545 // Ensure client A and B can communicate normally after reconnection.
2546 channel_a
2547 .update(&mut cx_a, |channel, cx| {
2548 channel.send_message("you online?".to_string(), cx).unwrap()
2549 })
2550 .await
2551 .unwrap();
2552 channel_b
2553 .condition(&cx_b, |channel, _| {
2554 channel_messages(channel)
2555 == [
2556 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2557 ("user_a".to_string(), "oh, hi B.".to_string(), false),
2558 ("user_a".to_string(), "sup".to_string(), false),
2559 ("user_b".to_string(), "can you see this?".to_string(), false),
2560 ("user_a".to_string(), "you online?".to_string(), false),
2561 ]
2562 })
2563 .await;
2564
2565 channel_b
2566 .update(&mut cx_b, |channel, cx| {
2567 channel.send_message("yep".to_string(), cx).unwrap()
2568 })
2569 .await
2570 .unwrap();
2571 channel_a
2572 .condition(&cx_a, |channel, _| {
2573 channel_messages(channel)
2574 == [
2575 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2576 ("user_a".to_string(), "oh, hi B.".to_string(), false),
2577 ("user_a".to_string(), "sup".to_string(), false),
2578 ("user_b".to_string(), "can you see this?".to_string(), false),
2579 ("user_a".to_string(), "you online?".to_string(), false),
2580 ("user_b".to_string(), "yep".to_string(), false),
2581 ]
2582 })
2583 .await;
2584 }
2585
2586 #[gpui::test]
2587 async fn test_contacts(
2588 mut cx_a: TestAppContext,
2589 mut cx_b: TestAppContext,
2590 mut cx_c: TestAppContext,
2591 ) {
2592 cx_a.foreground().forbid_parking();
2593 let lang_registry = Arc::new(LanguageRegistry::new());
2594 let fs = Arc::new(FakeFs::new());
2595
2596 // Connect to a server as 3 clients.
2597 let mut server = TestServer::start(cx_a.foreground()).await;
2598 let client_a = server.create_client(&mut cx_a, "user_a").await;
2599 let client_b = server.create_client(&mut cx_b, "user_b").await;
2600 let client_c = server.create_client(&mut cx_c, "user_c").await;
2601
2602 // Share a worktree as client A.
2603 fs.insert_tree(
2604 "/a",
2605 json!({
2606 ".zed.toml": r#"collaborators = ["user_b", "user_c"]"#,
2607 }),
2608 )
2609 .await;
2610
2611 let project_a = cx_a.update(|cx| {
2612 Project::local(
2613 client_a.clone(),
2614 client_a.user_store.clone(),
2615 lang_registry.clone(),
2616 fs.clone(),
2617 cx,
2618 )
2619 });
2620 let (worktree_a, _) = project_a
2621 .update(&mut cx_a, |p, cx| {
2622 p.find_or_create_worktree_for_abs_path("/a", false, cx)
2623 })
2624 .await
2625 .unwrap();
2626 worktree_a
2627 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
2628 .await;
2629
2630 client_a
2631 .user_store
2632 .condition(&cx_a, |user_store, _| {
2633 contacts(user_store) == vec![("user_a", vec![("a", vec![])])]
2634 })
2635 .await;
2636 client_b
2637 .user_store
2638 .condition(&cx_b, |user_store, _| {
2639 contacts(user_store) == vec![("user_a", vec![("a", vec![])])]
2640 })
2641 .await;
2642 client_c
2643 .user_store
2644 .condition(&cx_c, |user_store, _| {
2645 contacts(user_store) == vec![("user_a", vec![("a", vec![])])]
2646 })
2647 .await;
2648
2649 let project_id = project_a
2650 .update(&mut cx_a, |project, _| project.next_remote_id())
2651 .await;
2652 project_a
2653 .update(&mut cx_a, |project, cx| project.share(cx))
2654 .await
2655 .unwrap();
2656
2657 let _project_b = Project::remote(
2658 project_id,
2659 client_b.clone(),
2660 client_b.user_store.clone(),
2661 lang_registry.clone(),
2662 fs.clone(),
2663 &mut cx_b.to_async(),
2664 )
2665 .await
2666 .unwrap();
2667
2668 client_a
2669 .user_store
2670 .condition(&cx_a, |user_store, _| {
2671 contacts(user_store) == vec![("user_a", vec![("a", vec!["user_b"])])]
2672 })
2673 .await;
2674 client_b
2675 .user_store
2676 .condition(&cx_b, |user_store, _| {
2677 contacts(user_store) == vec![("user_a", vec![("a", vec!["user_b"])])]
2678 })
2679 .await;
2680 client_c
2681 .user_store
2682 .condition(&cx_c, |user_store, _| {
2683 contacts(user_store) == vec![("user_a", vec![("a", vec!["user_b"])])]
2684 })
2685 .await;
2686
2687 project_a
2688 .condition(&cx_a, |project, _| {
2689 project.collaborators().contains_key(&client_b.peer_id)
2690 })
2691 .await;
2692
2693 cx_a.update(move |_| drop(project_a));
2694 client_a
2695 .user_store
2696 .condition(&cx_a, |user_store, _| contacts(user_store) == vec![])
2697 .await;
2698 client_b
2699 .user_store
2700 .condition(&cx_b, |user_store, _| contacts(user_store) == vec![])
2701 .await;
2702 client_c
2703 .user_store
2704 .condition(&cx_c, |user_store, _| contacts(user_store) == vec![])
2705 .await;
2706
2707 fn contacts(user_store: &UserStore) -> Vec<(&str, Vec<(&str, Vec<&str>)>)> {
2708 user_store
2709 .contacts()
2710 .iter()
2711 .map(|contact| {
2712 let worktrees = contact
2713 .projects
2714 .iter()
2715 .map(|p| {
2716 (
2717 p.worktree_root_names[0].as_str(),
2718 p.guests.iter().map(|p| p.github_login.as_str()).collect(),
2719 )
2720 })
2721 .collect();
2722 (contact.user.github_login.as_str(), worktrees)
2723 })
2724 .collect()
2725 }
2726 }
2727
2728 struct TestServer {
2729 peer: Arc<Peer>,
2730 app_state: Arc<AppState>,
2731 server: Arc<Server>,
2732 foreground: Rc<executor::Foreground>,
2733 notifications: mpsc::Receiver<()>,
2734 connection_killers: Arc<Mutex<HashMap<UserId, watch::Sender<Option<()>>>>>,
2735 forbid_connections: Arc<AtomicBool>,
2736 _test_db: TestDb,
2737 }
2738
2739 impl TestServer {
2740 async fn start(foreground: Rc<executor::Foreground>) -> Self {
2741 let test_db = TestDb::new();
2742 let app_state = Self::build_app_state(&test_db).await;
2743 let peer = Peer::new();
2744 let notifications = mpsc::channel(128);
2745 let server = Server::new(app_state.clone(), peer.clone(), Some(notifications.0));
2746 Self {
2747 peer,
2748 app_state,
2749 server,
2750 foreground,
2751 notifications: notifications.1,
2752 connection_killers: Default::default(),
2753 forbid_connections: Default::default(),
2754 _test_db: test_db,
2755 }
2756 }
2757
2758 async fn create_client(&mut self, cx: &mut TestAppContext, name: &str) -> TestClient {
2759 let http = FakeHttpClient::with_404_response();
2760 let user_id = self.app_state.db.create_user(name, false).await.unwrap();
2761 let client_name = name.to_string();
2762 let mut client = Client::new(http.clone());
2763 let server = self.server.clone();
2764 let connection_killers = self.connection_killers.clone();
2765 let forbid_connections = self.forbid_connections.clone();
2766 let (connection_id_tx, mut connection_id_rx) = postage::mpsc::channel(16);
2767
2768 Arc::get_mut(&mut client)
2769 .unwrap()
2770 .override_authenticate(move |cx| {
2771 cx.spawn(|_| async move {
2772 let access_token = "the-token".to_string();
2773 Ok(Credentials {
2774 user_id: user_id.0 as u64,
2775 access_token,
2776 })
2777 })
2778 })
2779 .override_establish_connection(move |credentials, cx| {
2780 assert_eq!(credentials.user_id, user_id.0 as u64);
2781 assert_eq!(credentials.access_token, "the-token");
2782
2783 let server = server.clone();
2784 let connection_killers = connection_killers.clone();
2785 let forbid_connections = forbid_connections.clone();
2786 let client_name = client_name.clone();
2787 let connection_id_tx = connection_id_tx.clone();
2788 cx.spawn(move |cx| async move {
2789 if forbid_connections.load(SeqCst) {
2790 Err(EstablishConnectionError::other(anyhow!(
2791 "server is forbidding connections"
2792 )))
2793 } else {
2794 let (client_conn, server_conn, kill_conn) = Connection::in_memory();
2795 connection_killers.lock().insert(user_id, kill_conn);
2796 cx.background()
2797 .spawn(server.handle_connection(
2798 server_conn,
2799 client_name,
2800 user_id,
2801 Some(connection_id_tx),
2802 ))
2803 .detach();
2804 Ok(client_conn)
2805 }
2806 })
2807 });
2808
2809 client
2810 .authenticate_and_connect(&cx.to_async())
2811 .await
2812 .unwrap();
2813
2814 let peer_id = PeerId(connection_id_rx.next().await.unwrap().0);
2815 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http, cx));
2816 let mut authed_user =
2817 user_store.read_with(cx, |user_store, _| user_store.watch_current_user());
2818 while authed_user.next().await.unwrap().is_none() {}
2819
2820 TestClient {
2821 client,
2822 peer_id,
2823 user_store,
2824 }
2825 }
2826
2827 fn disconnect_client(&self, user_id: UserId) {
2828 if let Some(mut kill_conn) = self.connection_killers.lock().remove(&user_id) {
2829 let _ = kill_conn.try_send(Some(()));
2830 }
2831 }
2832
2833 fn forbid_connections(&self) {
2834 self.forbid_connections.store(true, SeqCst);
2835 }
2836
2837 fn allow_connections(&self) {
2838 self.forbid_connections.store(false, SeqCst);
2839 }
2840
2841 async fn build_app_state(test_db: &TestDb) -> Arc<AppState> {
2842 let mut config = Config::default();
2843 config.session_secret = "a".repeat(32);
2844 config.database_url = test_db.url.clone();
2845 let github_client = github::AppClient::test();
2846 Arc::new(AppState {
2847 db: test_db.db().clone(),
2848 handlebars: Default::default(),
2849 auth_client: auth::build_client("", ""),
2850 repo_client: github::RepoClient::test(&github_client),
2851 github_client,
2852 config,
2853 })
2854 }
2855
2856 async fn state<'a>(&'a self) -> RwLockReadGuard<'a, Store> {
2857 self.server.store.read()
2858 }
2859
2860 async fn condition<F>(&mut self, mut predicate: F)
2861 where
2862 F: FnMut(&Store) -> bool,
2863 {
2864 async_std::future::timeout(Duration::from_millis(500), async {
2865 while !(predicate)(&*self.server.store.read()) {
2866 self.foreground.start_waiting();
2867 self.notifications.next().await;
2868 self.foreground.finish_waiting();
2869 }
2870 })
2871 .await
2872 .expect("condition timed out");
2873 }
2874 }
2875
2876 impl Drop for TestServer {
2877 fn drop(&mut self) {
2878 self.peer.reset();
2879 }
2880 }
2881
2882 struct TestClient {
2883 client: Arc<Client>,
2884 pub peer_id: PeerId,
2885 pub user_store: ModelHandle<UserStore>,
2886 }
2887
2888 impl Deref for TestClient {
2889 type Target = Arc<Client>;
2890
2891 fn deref(&self) -> &Self::Target {
2892 &self.client
2893 }
2894 }
2895
2896 impl TestClient {
2897 pub fn current_user_id(&self, cx: &TestAppContext) -> UserId {
2898 UserId::from_proto(
2899 self.user_store
2900 .read_with(cx, |user_store, _| user_store.current_user().unwrap().id),
2901 )
2902 }
2903 }
2904
2905 fn channel_messages(channel: &Channel) -> Vec<(String, String, bool)> {
2906 channel
2907 .messages()
2908 .cursor::<()>()
2909 .map(|m| {
2910 (
2911 m.sender.github_login.clone(),
2912 m.body.clone(),
2913 m.is_pending(),
2914 )
2915 })
2916 .collect()
2917 }
2918
2919 struct EmptyView;
2920
2921 impl gpui::Entity for EmptyView {
2922 type Event = ();
2923 }
2924
2925 impl gpui::View for EmptyView {
2926 fn ui_name() -> &'static str {
2927 "empty view"
2928 }
2929
2930 fn render(&mut self, _: &mut gpui::RenderContext<Self>) -> gpui::ElementBox {
2931 gpui::Element::boxed(gpui::elements::Empty)
2932 }
2933 }
2934}