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_local_worktree("/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_local_worktree("/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_local_worktree("/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, _| {
1474 dbg!(buf.text()) == "i-am-c, i-am-b, i-am-a"
1475 })
1476 .await;
1477 buffer_c
1478 .condition(&mut cx_c, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1479 .await;
1480
1481 // Edit the buffer as the host and concurrently save as guest B.
1482 let save_b = buffer_b.update(&mut cx_b, |buf, cx| buf.save(cx));
1483 buffer_a.update(&mut cx_a, |buf, cx| buf.edit([0..0], "hi-a, ", cx));
1484 save_b.await.unwrap();
1485 assert_eq!(
1486 fs.load("/a/file1".as_ref()).await.unwrap(),
1487 "hi-a, i-am-c, i-am-b, i-am-a"
1488 );
1489 buffer_a.read_with(&cx_a, |buf, _| assert!(!buf.is_dirty()));
1490 buffer_b.read_with(&cx_b, |buf, _| assert!(!buf.is_dirty()));
1491 buffer_c.condition(&cx_c, |buf, _| !buf.is_dirty()).await;
1492
1493 // Make changes on host's file system, see those changes on the guests.
1494 fs.rename("/a/file2".as_ref(), "/a/file3".as_ref())
1495 .await
1496 .unwrap();
1497 fs.insert_file(Path::new("/a/file4"), "4".into())
1498 .await
1499 .unwrap();
1500
1501 worktree_b
1502 .condition(&cx_b, |tree, _| tree.file_count() == 4)
1503 .await;
1504 worktree_c
1505 .condition(&cx_c, |tree, _| tree.file_count() == 4)
1506 .await;
1507 worktree_b.read_with(&cx_b, |tree, _| {
1508 assert_eq!(
1509 tree.paths()
1510 .map(|p| p.to_string_lossy())
1511 .collect::<Vec<_>>(),
1512 &[".zed.toml", "file1", "file3", "file4"]
1513 )
1514 });
1515 worktree_c.read_with(&cx_c, |tree, _| {
1516 assert_eq!(
1517 tree.paths()
1518 .map(|p| p.to_string_lossy())
1519 .collect::<Vec<_>>(),
1520 &[".zed.toml", "file1", "file3", "file4"]
1521 )
1522 });
1523 }
1524
1525 #[gpui::test]
1526 async fn test_buffer_conflict_after_save(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1527 cx_a.foreground().forbid_parking();
1528 let lang_registry = Arc::new(LanguageRegistry::new());
1529 let fs = Arc::new(FakeFs::new());
1530
1531 // Connect to a server as 2 clients.
1532 let mut server = TestServer::start(cx_a.foreground()).await;
1533 let client_a = server.create_client(&mut cx_a, "user_a").await;
1534 let client_b = server.create_client(&mut cx_b, "user_b").await;
1535
1536 // Share a project as client A
1537 fs.insert_tree(
1538 "/dir",
1539 json!({
1540 ".zed.toml": r#"collaborators = ["user_b", "user_c"]"#,
1541 "a.txt": "a-contents",
1542 }),
1543 )
1544 .await;
1545
1546 let project_a = cx_a.update(|cx| {
1547 Project::local(
1548 client_a.clone(),
1549 client_a.user_store.clone(),
1550 lang_registry.clone(),
1551 fs.clone(),
1552 cx,
1553 )
1554 });
1555 let (worktree_a, _) = project_a
1556 .update(&mut cx_a, |p, cx| {
1557 p.find_or_create_local_worktree("/dir", false, cx)
1558 })
1559 .await
1560 .unwrap();
1561 worktree_a
1562 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1563 .await;
1564 let project_id = project_a.update(&mut cx_a, |p, _| p.next_remote_id()).await;
1565 let worktree_id = worktree_a.read_with(&cx_a, |tree, _| tree.id());
1566 project_a
1567 .update(&mut cx_a, |p, cx| p.share(cx))
1568 .await
1569 .unwrap();
1570
1571 // Join that project as client B
1572 let project_b = Project::remote(
1573 project_id,
1574 client_b.clone(),
1575 client_b.user_store.clone(),
1576 lang_registry.clone(),
1577 fs.clone(),
1578 &mut cx_b.to_async(),
1579 )
1580 .await
1581 .unwrap();
1582 let worktree_b = project_b.update(&mut cx_b, |p, cx| p.worktrees(cx).next().unwrap());
1583
1584 // Open a buffer as client B
1585 let buffer_b = project_b
1586 .update(&mut cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
1587 .await
1588 .unwrap();
1589 let mtime = buffer_b.read_with(&cx_b, |buf, _| buf.file().unwrap().mtime());
1590
1591 buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "world ", cx));
1592 buffer_b.read_with(&cx_b, |buf, _| {
1593 assert!(buf.is_dirty());
1594 assert!(!buf.has_conflict());
1595 });
1596
1597 buffer_b
1598 .update(&mut cx_b, |buf, cx| buf.save(cx))
1599 .await
1600 .unwrap();
1601 worktree_b
1602 .condition(&cx_b, |_, cx| {
1603 buffer_b.read(cx).file().unwrap().mtime() != mtime
1604 })
1605 .await;
1606 buffer_b.read_with(&cx_b, |buf, _| {
1607 assert!(!buf.is_dirty());
1608 assert!(!buf.has_conflict());
1609 });
1610
1611 buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "hello ", cx));
1612 buffer_b.read_with(&cx_b, |buf, _| {
1613 assert!(buf.is_dirty());
1614 assert!(!buf.has_conflict());
1615 });
1616 }
1617
1618 #[gpui::test]
1619 async fn test_editing_while_guest_opens_buffer(
1620 mut cx_a: TestAppContext,
1621 mut cx_b: TestAppContext,
1622 ) {
1623 cx_a.foreground().forbid_parking();
1624 let lang_registry = Arc::new(LanguageRegistry::new());
1625 let fs = Arc::new(FakeFs::new());
1626
1627 // Connect to a server as 2 clients.
1628 let mut server = TestServer::start(cx_a.foreground()).await;
1629 let client_a = server.create_client(&mut cx_a, "user_a").await;
1630 let client_b = server.create_client(&mut cx_b, "user_b").await;
1631
1632 // Share a project as client A
1633 fs.insert_tree(
1634 "/dir",
1635 json!({
1636 ".zed.toml": r#"collaborators = ["user_b"]"#,
1637 "a.txt": "a-contents",
1638 }),
1639 )
1640 .await;
1641 let project_a = cx_a.update(|cx| {
1642 Project::local(
1643 client_a.clone(),
1644 client_a.user_store.clone(),
1645 lang_registry.clone(),
1646 fs.clone(),
1647 cx,
1648 )
1649 });
1650 let (worktree_a, _) = project_a
1651 .update(&mut cx_a, |p, cx| {
1652 p.find_or_create_local_worktree("/dir", false, cx)
1653 })
1654 .await
1655 .unwrap();
1656 worktree_a
1657 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1658 .await;
1659 let project_id = project_a.update(&mut cx_a, |p, _| p.next_remote_id()).await;
1660 let worktree_id = worktree_a.read_with(&cx_a, |tree, _| tree.id());
1661 project_a
1662 .update(&mut cx_a, |p, cx| p.share(cx))
1663 .await
1664 .unwrap();
1665
1666 // Join that project as client B
1667 let project_b = Project::remote(
1668 project_id,
1669 client_b.clone(),
1670 client_b.user_store.clone(),
1671 lang_registry.clone(),
1672 fs.clone(),
1673 &mut cx_b.to_async(),
1674 )
1675 .await
1676 .unwrap();
1677
1678 // Open a buffer as client A
1679 let buffer_a = project_a
1680 .update(&mut cx_a, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx))
1681 .await
1682 .unwrap();
1683
1684 // Start opening the same buffer as client B
1685 let buffer_b = cx_b
1686 .background()
1687 .spawn(project_b.update(&mut cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx)));
1688 task::yield_now().await;
1689
1690 // Edit the buffer as client A while client B is still opening it.
1691 buffer_a.update(&mut cx_a, |buf, cx| buf.edit([0..0], "z", cx));
1692
1693 let text = buffer_a.read_with(&cx_a, |buf, _| buf.text());
1694 let buffer_b = buffer_b.await.unwrap();
1695 buffer_b.condition(&cx_b, |buf, _| buf.text() == text).await;
1696 }
1697
1698 #[gpui::test]
1699 async fn test_leaving_worktree_while_opening_buffer(
1700 mut cx_a: TestAppContext,
1701 mut cx_b: TestAppContext,
1702 ) {
1703 cx_a.foreground().forbid_parking();
1704 let lang_registry = Arc::new(LanguageRegistry::new());
1705 let fs = Arc::new(FakeFs::new());
1706
1707 // Connect to a server as 2 clients.
1708 let mut server = TestServer::start(cx_a.foreground()).await;
1709 let client_a = server.create_client(&mut cx_a, "user_a").await;
1710 let client_b = server.create_client(&mut cx_b, "user_b").await;
1711
1712 // Share a project as client A
1713 fs.insert_tree(
1714 "/dir",
1715 json!({
1716 ".zed.toml": r#"collaborators = ["user_b"]"#,
1717 "a.txt": "a-contents",
1718 }),
1719 )
1720 .await;
1721 let project_a = cx_a.update(|cx| {
1722 Project::local(
1723 client_a.clone(),
1724 client_a.user_store.clone(),
1725 lang_registry.clone(),
1726 fs.clone(),
1727 cx,
1728 )
1729 });
1730 let (worktree_a, _) = project_a
1731 .update(&mut cx_a, |p, cx| {
1732 p.find_or_create_local_worktree("/dir", false, cx)
1733 })
1734 .await
1735 .unwrap();
1736 worktree_a
1737 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1738 .await;
1739 let project_id = project_a.update(&mut cx_a, |p, _| p.next_remote_id()).await;
1740 let worktree_id = worktree_a.read_with(&cx_a, |tree, _| tree.id());
1741 project_a
1742 .update(&mut cx_a, |p, cx| p.share(cx))
1743 .await
1744 .unwrap();
1745
1746 // Join that project as client B
1747 let project_b = Project::remote(
1748 project_id,
1749 client_b.clone(),
1750 client_b.user_store.clone(),
1751 lang_registry.clone(),
1752 fs.clone(),
1753 &mut cx_b.to_async(),
1754 )
1755 .await
1756 .unwrap();
1757
1758 // See that a guest has joined as client A.
1759 project_a
1760 .condition(&cx_a, |p, _| p.collaborators().len() == 1)
1761 .await;
1762
1763 // Begin opening a buffer as client B, but leave the project before the open completes.
1764 let buffer_b = cx_b
1765 .background()
1766 .spawn(project_b.update(&mut cx_b, |p, cx| p.open_buffer((worktree_id, "a.txt"), cx)));
1767 cx_b.update(|_| drop(project_b));
1768 drop(buffer_b);
1769
1770 // See that the guest has left.
1771 project_a
1772 .condition(&cx_a, |p, _| p.collaborators().len() == 0)
1773 .await;
1774 }
1775
1776 #[gpui::test]
1777 async fn test_peer_disconnection(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1778 cx_a.foreground().forbid_parking();
1779 let lang_registry = Arc::new(LanguageRegistry::new());
1780 let fs = Arc::new(FakeFs::new());
1781
1782 // Connect to a server as 2 clients.
1783 let mut server = TestServer::start(cx_a.foreground()).await;
1784 let client_a = server.create_client(&mut cx_a, "user_a").await;
1785 let client_b = server.create_client(&mut cx_b, "user_b").await;
1786
1787 // Share a project as client A
1788 fs.insert_tree(
1789 "/a",
1790 json!({
1791 ".zed.toml": r#"collaborators = ["user_b"]"#,
1792 "a.txt": "a-contents",
1793 "b.txt": "b-contents",
1794 }),
1795 )
1796 .await;
1797 let project_a = cx_a.update(|cx| {
1798 Project::local(
1799 client_a.clone(),
1800 client_a.user_store.clone(),
1801 lang_registry.clone(),
1802 fs.clone(),
1803 cx,
1804 )
1805 });
1806 let (worktree_a, _) = project_a
1807 .update(&mut cx_a, |p, cx| {
1808 p.find_or_create_local_worktree("/a", false, cx)
1809 })
1810 .await
1811 .unwrap();
1812 worktree_a
1813 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1814 .await;
1815 let project_id = project_a
1816 .update(&mut cx_a, |project, _| project.next_remote_id())
1817 .await;
1818 project_a
1819 .update(&mut cx_a, |project, cx| project.share(cx))
1820 .await
1821 .unwrap();
1822
1823 // Join that project as client B
1824 let _project_b = Project::remote(
1825 project_id,
1826 client_b.clone(),
1827 client_b.user_store.clone(),
1828 lang_registry.clone(),
1829 fs.clone(),
1830 &mut cx_b.to_async(),
1831 )
1832 .await
1833 .unwrap();
1834
1835 // See that a guest has joined as client A.
1836 project_a
1837 .condition(&cx_a, |p, _| p.collaborators().len() == 1)
1838 .await;
1839
1840 // Drop client B's connection and ensure client A observes client B leaving the worktree.
1841 client_b.disconnect(&cx_b.to_async()).unwrap();
1842 project_a
1843 .condition(&cx_a, |p, _| p.collaborators().len() == 0)
1844 .await;
1845 }
1846
1847 #[gpui::test]
1848 async fn test_collaborating_with_diagnostics(
1849 mut cx_a: TestAppContext,
1850 mut cx_b: TestAppContext,
1851 ) {
1852 cx_a.foreground().forbid_parking();
1853 let mut lang_registry = Arc::new(LanguageRegistry::new());
1854 let fs = Arc::new(FakeFs::new());
1855
1856 // Set up a fake language server.
1857 let (language_server_config, mut fake_language_server) =
1858 LanguageServerConfig::fake(cx_a.background()).await;
1859 Arc::get_mut(&mut lang_registry)
1860 .unwrap()
1861 .add(Arc::new(Language::new(
1862 LanguageConfig {
1863 name: "Rust".to_string(),
1864 path_suffixes: vec!["rs".to_string()],
1865 language_server: Some(language_server_config),
1866 ..Default::default()
1867 },
1868 Some(tree_sitter_rust::language()),
1869 )));
1870
1871 // Connect to a server as 2 clients.
1872 let mut server = TestServer::start(cx_a.foreground()).await;
1873 let client_a = server.create_client(&mut cx_a, "user_a").await;
1874 let client_b = server.create_client(&mut cx_b, "user_b").await;
1875
1876 // Share a project as client A
1877 fs.insert_tree(
1878 "/a",
1879 json!({
1880 ".zed.toml": r#"collaborators = ["user_b"]"#,
1881 "a.rs": "let one = two",
1882 "other.rs": "",
1883 }),
1884 )
1885 .await;
1886 let project_a = cx_a.update(|cx| {
1887 Project::local(
1888 client_a.clone(),
1889 client_a.user_store.clone(),
1890 lang_registry.clone(),
1891 fs.clone(),
1892 cx,
1893 )
1894 });
1895 let (worktree_a, _) = project_a
1896 .update(&mut cx_a, |p, cx| {
1897 p.find_or_create_local_worktree("/a", false, cx)
1898 })
1899 .await
1900 .unwrap();
1901 worktree_a
1902 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1903 .await;
1904 let project_id = project_a.update(&mut cx_a, |p, _| p.next_remote_id()).await;
1905 let worktree_id = worktree_a.read_with(&cx_a, |tree, _| tree.id());
1906 project_a
1907 .update(&mut cx_a, |p, cx| p.share(cx))
1908 .await
1909 .unwrap();
1910
1911 // Cause the language server to start.
1912 let _ = cx_a
1913 .background()
1914 .spawn(project_a.update(&mut cx_a, |project, cx| {
1915 project.open_buffer(
1916 ProjectPath {
1917 worktree_id,
1918 path: Path::new("other.rs").into(),
1919 },
1920 cx,
1921 )
1922 }))
1923 .await
1924 .unwrap();
1925
1926 // Simulate a language server reporting errors for a file.
1927 fake_language_server
1928 .notify::<lsp::notification::PublishDiagnostics>(lsp::PublishDiagnosticsParams {
1929 uri: lsp::Url::from_file_path("/a/a.rs").unwrap(),
1930 version: None,
1931 diagnostics: vec![lsp::Diagnostic {
1932 severity: Some(lsp::DiagnosticSeverity::ERROR),
1933 range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 7)),
1934 message: "message 1".to_string(),
1935 ..Default::default()
1936 }],
1937 })
1938 .await;
1939
1940 // Wait for server to see the diagnostics update.
1941 server
1942 .condition(|store| {
1943 let worktree = store
1944 .project(project_id)
1945 .unwrap()
1946 .worktrees
1947 .get(&worktree_id.to_proto())
1948 .unwrap();
1949
1950 !worktree
1951 .share
1952 .as_ref()
1953 .unwrap()
1954 .diagnostic_summaries
1955 .is_empty()
1956 })
1957 .await;
1958
1959 // Join the worktree as client B.
1960 let project_b = Project::remote(
1961 project_id,
1962 client_b.clone(),
1963 client_b.user_store.clone(),
1964 lang_registry.clone(),
1965 fs.clone(),
1966 &mut cx_b.to_async(),
1967 )
1968 .await
1969 .unwrap();
1970
1971 project_b.read_with(&cx_b, |project, cx| {
1972 assert_eq!(
1973 project.diagnostic_summaries(cx).collect::<Vec<_>>(),
1974 &[(
1975 ProjectPath {
1976 worktree_id,
1977 path: Arc::from(Path::new("a.rs")),
1978 },
1979 DiagnosticSummary {
1980 error_count: 1,
1981 warning_count: 0,
1982 ..Default::default()
1983 },
1984 )]
1985 )
1986 });
1987
1988 // Simulate a language server reporting more errors for a file.
1989 fake_language_server
1990 .notify::<lsp::notification::PublishDiagnostics>(lsp::PublishDiagnosticsParams {
1991 uri: lsp::Url::from_file_path("/a/a.rs").unwrap(),
1992 version: None,
1993 diagnostics: vec![
1994 lsp::Diagnostic {
1995 severity: Some(lsp::DiagnosticSeverity::ERROR),
1996 range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 7)),
1997 message: "message 1".to_string(),
1998 ..Default::default()
1999 },
2000 lsp::Diagnostic {
2001 severity: Some(lsp::DiagnosticSeverity::WARNING),
2002 range: lsp::Range::new(
2003 lsp::Position::new(0, 10),
2004 lsp::Position::new(0, 13),
2005 ),
2006 message: "message 2".to_string(),
2007 ..Default::default()
2008 },
2009 ],
2010 })
2011 .await;
2012
2013 // Client b gets the updated summaries
2014 project_b
2015 .condition(&cx_b, |project, cx| {
2016 project.diagnostic_summaries(cx).collect::<Vec<_>>()
2017 == &[(
2018 ProjectPath {
2019 worktree_id,
2020 path: Arc::from(Path::new("a.rs")),
2021 },
2022 DiagnosticSummary {
2023 error_count: 1,
2024 warning_count: 1,
2025 ..Default::default()
2026 },
2027 )]
2028 })
2029 .await;
2030
2031 // Open the file with the errors on client B. They should be present.
2032 let buffer_b = cx_b
2033 .background()
2034 .spawn(project_b.update(&mut cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx)))
2035 .await
2036 .unwrap();
2037
2038 buffer_b.read_with(&cx_b, |buffer, _| {
2039 assert_eq!(
2040 buffer
2041 .snapshot()
2042 .diagnostics_in_range::<_, Point>(0..buffer.len())
2043 .map(|entry| entry)
2044 .collect::<Vec<_>>(),
2045 &[
2046 DiagnosticEntry {
2047 range: Point::new(0, 4)..Point::new(0, 7),
2048 diagnostic: Diagnostic {
2049 group_id: 0,
2050 message: "message 1".to_string(),
2051 severity: lsp::DiagnosticSeverity::ERROR,
2052 is_primary: true,
2053 ..Default::default()
2054 }
2055 },
2056 DiagnosticEntry {
2057 range: Point::new(0, 10)..Point::new(0, 13),
2058 diagnostic: Diagnostic {
2059 group_id: 1,
2060 severity: lsp::DiagnosticSeverity::WARNING,
2061 message: "message 2".to_string(),
2062 is_primary: true,
2063 ..Default::default()
2064 }
2065 }
2066 ]
2067 );
2068 });
2069 }
2070
2071 #[gpui::test]
2072 async fn test_formatting_buffer(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
2073 cx_a.foreground().forbid_parking();
2074 let mut lang_registry = Arc::new(LanguageRegistry::new());
2075 let fs = Arc::new(FakeFs::new());
2076
2077 // Set up a fake language server.
2078 let (language_server_config, mut fake_language_server) =
2079 LanguageServerConfig::fake(cx_a.background()).await;
2080 Arc::get_mut(&mut lang_registry)
2081 .unwrap()
2082 .add(Arc::new(Language::new(
2083 LanguageConfig {
2084 name: "Rust".to_string(),
2085 path_suffixes: vec!["rs".to_string()],
2086 language_server: Some(language_server_config),
2087 ..Default::default()
2088 },
2089 Some(tree_sitter_rust::language()),
2090 )));
2091
2092 // Connect to a server as 2 clients.
2093 let mut server = TestServer::start(cx_a.foreground()).await;
2094 let client_a = server.create_client(&mut cx_a, "user_a").await;
2095 let client_b = server.create_client(&mut cx_b, "user_b").await;
2096
2097 // Share a project as client A
2098 fs.insert_tree(
2099 "/a",
2100 json!({
2101 ".zed.toml": r#"collaborators = ["user_b"]"#,
2102 "a.rs": "let one = two",
2103 }),
2104 )
2105 .await;
2106 let project_a = cx_a.update(|cx| {
2107 Project::local(
2108 client_a.clone(),
2109 client_a.user_store.clone(),
2110 lang_registry.clone(),
2111 fs.clone(),
2112 cx,
2113 )
2114 });
2115 let (worktree_a, _) = project_a
2116 .update(&mut cx_a, |p, cx| {
2117 p.find_or_create_local_worktree("/a", false, cx)
2118 })
2119 .await
2120 .unwrap();
2121 worktree_a
2122 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
2123 .await;
2124 let project_id = project_a.update(&mut cx_a, |p, _| p.next_remote_id()).await;
2125 let worktree_id = worktree_a.read_with(&cx_a, |tree, _| tree.id());
2126 project_a
2127 .update(&mut cx_a, |p, cx| p.share(cx))
2128 .await
2129 .unwrap();
2130
2131 // Join the worktree as client B.
2132 let project_b = Project::remote(
2133 project_id,
2134 client_b.clone(),
2135 client_b.user_store.clone(),
2136 lang_registry.clone(),
2137 fs.clone(),
2138 &mut cx_b.to_async(),
2139 )
2140 .await
2141 .unwrap();
2142
2143 // Open the file to be formatted on client B.
2144 let buffer_b = cx_b
2145 .background()
2146 .spawn(project_b.update(&mut cx_b, |p, cx| p.open_buffer((worktree_id, "a.rs"), cx)))
2147 .await
2148 .unwrap();
2149
2150 let format = buffer_b.update(&mut cx_b, |buffer, cx| buffer.format(cx));
2151 let (request_id, _) = fake_language_server
2152 .receive_request::<lsp::request::Formatting>()
2153 .await;
2154 fake_language_server
2155 .respond(
2156 request_id,
2157 Some(vec![
2158 lsp::TextEdit {
2159 range: lsp::Range::new(lsp::Position::new(0, 4), lsp::Position::new(0, 4)),
2160 new_text: "h".to_string(),
2161 },
2162 lsp::TextEdit {
2163 range: lsp::Range::new(lsp::Position::new(0, 7), lsp::Position::new(0, 7)),
2164 new_text: "y".to_string(),
2165 },
2166 ]),
2167 )
2168 .await;
2169 format.await.unwrap();
2170 assert_eq!(
2171 buffer_b.read_with(&cx_b, |buffer, _| buffer.text()),
2172 "let honey = two"
2173 );
2174 }
2175
2176 #[gpui::test]
2177 async fn test_basic_chat(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
2178 cx_a.foreground().forbid_parking();
2179
2180 // Connect to a server as 2 clients.
2181 let mut server = TestServer::start(cx_a.foreground()).await;
2182 let client_a = server.create_client(&mut cx_a, "user_a").await;
2183 let client_b = server.create_client(&mut cx_b, "user_b").await;
2184
2185 // Create an org that includes these 2 users.
2186 let db = &server.app_state.db;
2187 let org_id = db.create_org("Test Org", "test-org").await.unwrap();
2188 db.add_org_member(org_id, client_a.current_user_id(&cx_a), false)
2189 .await
2190 .unwrap();
2191 db.add_org_member(org_id, client_b.current_user_id(&cx_b), false)
2192 .await
2193 .unwrap();
2194
2195 // Create a channel that includes all the users.
2196 let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
2197 db.add_channel_member(channel_id, client_a.current_user_id(&cx_a), false)
2198 .await
2199 .unwrap();
2200 db.add_channel_member(channel_id, client_b.current_user_id(&cx_b), false)
2201 .await
2202 .unwrap();
2203 db.create_channel_message(
2204 channel_id,
2205 client_b.current_user_id(&cx_b),
2206 "hello A, it's B.",
2207 OffsetDateTime::now_utc(),
2208 1,
2209 )
2210 .await
2211 .unwrap();
2212
2213 let channels_a = cx_a
2214 .add_model(|cx| ChannelList::new(client_a.user_store.clone(), client_a.clone(), cx));
2215 channels_a
2216 .condition(&mut cx_a, |list, _| list.available_channels().is_some())
2217 .await;
2218 channels_a.read_with(&cx_a, |list, _| {
2219 assert_eq!(
2220 list.available_channels().unwrap(),
2221 &[ChannelDetails {
2222 id: channel_id.to_proto(),
2223 name: "test-channel".to_string()
2224 }]
2225 )
2226 });
2227 let channel_a = channels_a.update(&mut cx_a, |this, cx| {
2228 this.get_channel(channel_id.to_proto(), cx).unwrap()
2229 });
2230 channel_a.read_with(&cx_a, |channel, _| assert!(channel.messages().is_empty()));
2231 channel_a
2232 .condition(&cx_a, |channel, _| {
2233 channel_messages(channel)
2234 == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2235 })
2236 .await;
2237
2238 let channels_b = cx_b
2239 .add_model(|cx| ChannelList::new(client_b.user_store.clone(), client_b.clone(), cx));
2240 channels_b
2241 .condition(&mut cx_b, |list, _| list.available_channels().is_some())
2242 .await;
2243 channels_b.read_with(&cx_b, |list, _| {
2244 assert_eq!(
2245 list.available_channels().unwrap(),
2246 &[ChannelDetails {
2247 id: channel_id.to_proto(),
2248 name: "test-channel".to_string()
2249 }]
2250 )
2251 });
2252
2253 let channel_b = channels_b.update(&mut cx_b, |this, cx| {
2254 this.get_channel(channel_id.to_proto(), cx).unwrap()
2255 });
2256 channel_b.read_with(&cx_b, |channel, _| assert!(channel.messages().is_empty()));
2257 channel_b
2258 .condition(&cx_b, |channel, _| {
2259 channel_messages(channel)
2260 == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2261 })
2262 .await;
2263
2264 channel_a
2265 .update(&mut cx_a, |channel, cx| {
2266 channel
2267 .send_message("oh, hi B.".to_string(), cx)
2268 .unwrap()
2269 .detach();
2270 let task = channel.send_message("sup".to_string(), cx).unwrap();
2271 assert_eq!(
2272 channel_messages(channel),
2273 &[
2274 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2275 ("user_a".to_string(), "oh, hi B.".to_string(), true),
2276 ("user_a".to_string(), "sup".to_string(), true)
2277 ]
2278 );
2279 task
2280 })
2281 .await
2282 .unwrap();
2283
2284 channel_b
2285 .condition(&cx_b, |channel, _| {
2286 channel_messages(channel)
2287 == [
2288 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2289 ("user_a".to_string(), "oh, hi B.".to_string(), false),
2290 ("user_a".to_string(), "sup".to_string(), false),
2291 ]
2292 })
2293 .await;
2294
2295 assert_eq!(
2296 server
2297 .state()
2298 .await
2299 .channel(channel_id)
2300 .unwrap()
2301 .connection_ids
2302 .len(),
2303 2
2304 );
2305 cx_b.update(|_| drop(channel_b));
2306 server
2307 .condition(|state| state.channel(channel_id).unwrap().connection_ids.len() == 1)
2308 .await;
2309
2310 cx_a.update(|_| drop(channel_a));
2311 server
2312 .condition(|state| state.channel(channel_id).is_none())
2313 .await;
2314 }
2315
2316 #[gpui::test]
2317 async fn test_chat_message_validation(mut cx_a: TestAppContext) {
2318 cx_a.foreground().forbid_parking();
2319
2320 let mut server = TestServer::start(cx_a.foreground()).await;
2321 let client_a = server.create_client(&mut cx_a, "user_a").await;
2322
2323 let db = &server.app_state.db;
2324 let org_id = db.create_org("Test Org", "test-org").await.unwrap();
2325 let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
2326 db.add_org_member(org_id, client_a.current_user_id(&cx_a), false)
2327 .await
2328 .unwrap();
2329 db.add_channel_member(channel_id, client_a.current_user_id(&cx_a), false)
2330 .await
2331 .unwrap();
2332
2333 let channels_a = cx_a
2334 .add_model(|cx| ChannelList::new(client_a.user_store.clone(), client_a.clone(), cx));
2335 channels_a
2336 .condition(&mut cx_a, |list, _| list.available_channels().is_some())
2337 .await;
2338 let channel_a = channels_a.update(&mut cx_a, |this, cx| {
2339 this.get_channel(channel_id.to_proto(), cx).unwrap()
2340 });
2341
2342 // Messages aren't allowed to be too long.
2343 channel_a
2344 .update(&mut cx_a, |channel, cx| {
2345 let long_body = "this is long.\n".repeat(1024);
2346 channel.send_message(long_body, cx).unwrap()
2347 })
2348 .await
2349 .unwrap_err();
2350
2351 // Messages aren't allowed to be blank.
2352 channel_a.update(&mut cx_a, |channel, cx| {
2353 channel.send_message(String::new(), cx).unwrap_err()
2354 });
2355
2356 // Leading and trailing whitespace are trimmed.
2357 channel_a
2358 .update(&mut cx_a, |channel, cx| {
2359 channel
2360 .send_message("\n surrounded by whitespace \n".to_string(), cx)
2361 .unwrap()
2362 })
2363 .await
2364 .unwrap();
2365 assert_eq!(
2366 db.get_channel_messages(channel_id, 10, None)
2367 .await
2368 .unwrap()
2369 .iter()
2370 .map(|m| &m.body)
2371 .collect::<Vec<_>>(),
2372 &["surrounded by whitespace"]
2373 );
2374 }
2375
2376 #[gpui::test]
2377 async fn test_chat_reconnection(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
2378 cx_a.foreground().forbid_parking();
2379
2380 // Connect to a server as 2 clients.
2381 let mut server = TestServer::start(cx_a.foreground()).await;
2382 let client_a = server.create_client(&mut cx_a, "user_a").await;
2383 let client_b = server.create_client(&mut cx_b, "user_b").await;
2384 let mut status_b = client_b.status();
2385
2386 // Create an org that includes these 2 users.
2387 let db = &server.app_state.db;
2388 let org_id = db.create_org("Test Org", "test-org").await.unwrap();
2389 db.add_org_member(org_id, client_a.current_user_id(&cx_a), false)
2390 .await
2391 .unwrap();
2392 db.add_org_member(org_id, client_b.current_user_id(&cx_b), false)
2393 .await
2394 .unwrap();
2395
2396 // Create a channel that includes all the users.
2397 let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
2398 db.add_channel_member(channel_id, client_a.current_user_id(&cx_a), false)
2399 .await
2400 .unwrap();
2401 db.add_channel_member(channel_id, client_b.current_user_id(&cx_b), false)
2402 .await
2403 .unwrap();
2404 db.create_channel_message(
2405 channel_id,
2406 client_b.current_user_id(&cx_b),
2407 "hello A, it's B.",
2408 OffsetDateTime::now_utc(),
2409 2,
2410 )
2411 .await
2412 .unwrap();
2413
2414 let channels_a = cx_a
2415 .add_model(|cx| ChannelList::new(client_a.user_store.clone(), client_a.clone(), cx));
2416 channels_a
2417 .condition(&mut cx_a, |list, _| list.available_channels().is_some())
2418 .await;
2419
2420 channels_a.read_with(&cx_a, |list, _| {
2421 assert_eq!(
2422 list.available_channels().unwrap(),
2423 &[ChannelDetails {
2424 id: channel_id.to_proto(),
2425 name: "test-channel".to_string()
2426 }]
2427 )
2428 });
2429 let channel_a = channels_a.update(&mut cx_a, |this, cx| {
2430 this.get_channel(channel_id.to_proto(), cx).unwrap()
2431 });
2432 channel_a.read_with(&cx_a, |channel, _| assert!(channel.messages().is_empty()));
2433 channel_a
2434 .condition(&cx_a, |channel, _| {
2435 channel_messages(channel)
2436 == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2437 })
2438 .await;
2439
2440 let channels_b = cx_b
2441 .add_model(|cx| ChannelList::new(client_b.user_store.clone(), client_b.clone(), cx));
2442 channels_b
2443 .condition(&mut cx_b, |list, _| list.available_channels().is_some())
2444 .await;
2445 channels_b.read_with(&cx_b, |list, _| {
2446 assert_eq!(
2447 list.available_channels().unwrap(),
2448 &[ChannelDetails {
2449 id: channel_id.to_proto(),
2450 name: "test-channel".to_string()
2451 }]
2452 )
2453 });
2454
2455 let channel_b = channels_b.update(&mut cx_b, |this, cx| {
2456 this.get_channel(channel_id.to_proto(), cx).unwrap()
2457 });
2458 channel_b.read_with(&cx_b, |channel, _| assert!(channel.messages().is_empty()));
2459 channel_b
2460 .condition(&cx_b, |channel, _| {
2461 channel_messages(channel)
2462 == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2463 })
2464 .await;
2465
2466 // Disconnect client B, ensuring we can still access its cached channel data.
2467 server.forbid_connections();
2468 server.disconnect_client(client_b.current_user_id(&cx_b));
2469 while !matches!(
2470 status_b.next().await,
2471 Some(client::Status::ReconnectionError { .. })
2472 ) {}
2473
2474 channels_b.read_with(&cx_b, |channels, _| {
2475 assert_eq!(
2476 channels.available_channels().unwrap(),
2477 [ChannelDetails {
2478 id: channel_id.to_proto(),
2479 name: "test-channel".to_string()
2480 }]
2481 )
2482 });
2483 channel_b.read_with(&cx_b, |channel, _| {
2484 assert_eq!(
2485 channel_messages(channel),
2486 [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
2487 )
2488 });
2489
2490 // Send a message from client B while it is disconnected.
2491 channel_b
2492 .update(&mut cx_b, |channel, cx| {
2493 let task = channel
2494 .send_message("can you see this?".to_string(), cx)
2495 .unwrap();
2496 assert_eq!(
2497 channel_messages(channel),
2498 &[
2499 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2500 ("user_b".to_string(), "can you see this?".to_string(), true)
2501 ]
2502 );
2503 task
2504 })
2505 .await
2506 .unwrap_err();
2507
2508 // Send a message from client A while B is disconnected.
2509 channel_a
2510 .update(&mut cx_a, |channel, cx| {
2511 channel
2512 .send_message("oh, hi B.".to_string(), cx)
2513 .unwrap()
2514 .detach();
2515 let task = channel.send_message("sup".to_string(), cx).unwrap();
2516 assert_eq!(
2517 channel_messages(channel),
2518 &[
2519 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2520 ("user_a".to_string(), "oh, hi B.".to_string(), true),
2521 ("user_a".to_string(), "sup".to_string(), true)
2522 ]
2523 );
2524 task
2525 })
2526 .await
2527 .unwrap();
2528
2529 // Give client B a chance to reconnect.
2530 server.allow_connections();
2531 cx_b.foreground().advance_clock(Duration::from_secs(10));
2532
2533 // Verify that B sees the new messages upon reconnection, as well as the message client B
2534 // sent while offline.
2535 channel_b
2536 .condition(&cx_b, |channel, _| {
2537 channel_messages(channel)
2538 == [
2539 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2540 ("user_a".to_string(), "oh, hi B.".to_string(), false),
2541 ("user_a".to_string(), "sup".to_string(), false),
2542 ("user_b".to_string(), "can you see this?".to_string(), false),
2543 ]
2544 })
2545 .await;
2546
2547 // Ensure client A and B can communicate normally after reconnection.
2548 channel_a
2549 .update(&mut cx_a, |channel, cx| {
2550 channel.send_message("you online?".to_string(), cx).unwrap()
2551 })
2552 .await
2553 .unwrap();
2554 channel_b
2555 .condition(&cx_b, |channel, _| {
2556 channel_messages(channel)
2557 == [
2558 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2559 ("user_a".to_string(), "oh, hi B.".to_string(), false),
2560 ("user_a".to_string(), "sup".to_string(), false),
2561 ("user_b".to_string(), "can you see this?".to_string(), false),
2562 ("user_a".to_string(), "you online?".to_string(), false),
2563 ]
2564 })
2565 .await;
2566
2567 channel_b
2568 .update(&mut cx_b, |channel, cx| {
2569 channel.send_message("yep".to_string(), cx).unwrap()
2570 })
2571 .await
2572 .unwrap();
2573 channel_a
2574 .condition(&cx_a, |channel, _| {
2575 channel_messages(channel)
2576 == [
2577 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2578 ("user_a".to_string(), "oh, hi B.".to_string(), false),
2579 ("user_a".to_string(), "sup".to_string(), false),
2580 ("user_b".to_string(), "can you see this?".to_string(), false),
2581 ("user_a".to_string(), "you online?".to_string(), false),
2582 ("user_b".to_string(), "yep".to_string(), false),
2583 ]
2584 })
2585 .await;
2586 }
2587
2588 #[gpui::test]
2589 async fn test_contacts(
2590 mut cx_a: TestAppContext,
2591 mut cx_b: TestAppContext,
2592 mut cx_c: TestAppContext,
2593 ) {
2594 cx_a.foreground().forbid_parking();
2595 let lang_registry = Arc::new(LanguageRegistry::new());
2596 let fs = Arc::new(FakeFs::new());
2597
2598 // Connect to a server as 3 clients.
2599 let mut server = TestServer::start(cx_a.foreground()).await;
2600 let client_a = server.create_client(&mut cx_a, "user_a").await;
2601 let client_b = server.create_client(&mut cx_b, "user_b").await;
2602 let client_c = server.create_client(&mut cx_c, "user_c").await;
2603
2604 // Share a worktree as client A.
2605 fs.insert_tree(
2606 "/a",
2607 json!({
2608 ".zed.toml": r#"collaborators = ["user_b", "user_c"]"#,
2609 }),
2610 )
2611 .await;
2612
2613 let project_a = cx_a.update(|cx| {
2614 Project::local(
2615 client_a.clone(),
2616 client_a.user_store.clone(),
2617 lang_registry.clone(),
2618 fs.clone(),
2619 cx,
2620 )
2621 });
2622 let (worktree_a, _) = project_a
2623 .update(&mut cx_a, |p, cx| {
2624 p.find_or_create_local_worktree("/a", false, cx)
2625 })
2626 .await
2627 .unwrap();
2628 worktree_a
2629 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
2630 .await;
2631
2632 client_a
2633 .user_store
2634 .condition(&cx_a, |user_store, _| {
2635 contacts(user_store) == vec![("user_a", vec![("a", vec![])])]
2636 })
2637 .await;
2638 client_b
2639 .user_store
2640 .condition(&cx_b, |user_store, _| {
2641 contacts(user_store) == vec![("user_a", vec![("a", vec![])])]
2642 })
2643 .await;
2644 client_c
2645 .user_store
2646 .condition(&cx_c, |user_store, _| {
2647 contacts(user_store) == vec![("user_a", vec![("a", vec![])])]
2648 })
2649 .await;
2650
2651 let project_id = project_a
2652 .update(&mut cx_a, |project, _| project.next_remote_id())
2653 .await;
2654 project_a
2655 .update(&mut cx_a, |project, cx| project.share(cx))
2656 .await
2657 .unwrap();
2658
2659 let _project_b = Project::remote(
2660 project_id,
2661 client_b.clone(),
2662 client_b.user_store.clone(),
2663 lang_registry.clone(),
2664 fs.clone(),
2665 &mut cx_b.to_async(),
2666 )
2667 .await
2668 .unwrap();
2669
2670 client_a
2671 .user_store
2672 .condition(&cx_a, |user_store, _| {
2673 contacts(user_store) == vec![("user_a", vec![("a", vec!["user_b"])])]
2674 })
2675 .await;
2676 client_b
2677 .user_store
2678 .condition(&cx_b, |user_store, _| {
2679 contacts(user_store) == vec![("user_a", vec![("a", vec!["user_b"])])]
2680 })
2681 .await;
2682 client_c
2683 .user_store
2684 .condition(&cx_c, |user_store, _| {
2685 contacts(user_store) == vec![("user_a", vec![("a", vec!["user_b"])])]
2686 })
2687 .await;
2688
2689 project_a
2690 .condition(&cx_a, |project, _| {
2691 project.collaborators().contains_key(&client_b.peer_id)
2692 })
2693 .await;
2694
2695 cx_a.update(move |_| drop(project_a));
2696 client_a
2697 .user_store
2698 .condition(&cx_a, |user_store, _| contacts(user_store) == vec![])
2699 .await;
2700 client_b
2701 .user_store
2702 .condition(&cx_b, |user_store, _| contacts(user_store) == vec![])
2703 .await;
2704 client_c
2705 .user_store
2706 .condition(&cx_c, |user_store, _| contacts(user_store) == vec![])
2707 .await;
2708
2709 fn contacts(user_store: &UserStore) -> Vec<(&str, Vec<(&str, Vec<&str>)>)> {
2710 user_store
2711 .contacts()
2712 .iter()
2713 .map(|contact| {
2714 let worktrees = contact
2715 .projects
2716 .iter()
2717 .map(|p| {
2718 (
2719 p.worktree_root_names[0].as_str(),
2720 p.guests.iter().map(|p| p.github_login.as_str()).collect(),
2721 )
2722 })
2723 .collect();
2724 (contact.user.github_login.as_str(), worktrees)
2725 })
2726 .collect()
2727 }
2728 }
2729
2730 struct TestServer {
2731 peer: Arc<Peer>,
2732 app_state: Arc<AppState>,
2733 server: Arc<Server>,
2734 foreground: Rc<executor::Foreground>,
2735 notifications: mpsc::Receiver<()>,
2736 connection_killers: Arc<Mutex<HashMap<UserId, watch::Sender<Option<()>>>>>,
2737 forbid_connections: Arc<AtomicBool>,
2738 _test_db: TestDb,
2739 }
2740
2741 impl TestServer {
2742 async fn start(foreground: Rc<executor::Foreground>) -> Self {
2743 let test_db = TestDb::new();
2744 let app_state = Self::build_app_state(&test_db).await;
2745 let peer = Peer::new();
2746 let notifications = mpsc::channel(128);
2747 let server = Server::new(app_state.clone(), peer.clone(), Some(notifications.0));
2748 Self {
2749 peer,
2750 app_state,
2751 server,
2752 foreground,
2753 notifications: notifications.1,
2754 connection_killers: Default::default(),
2755 forbid_connections: Default::default(),
2756 _test_db: test_db,
2757 }
2758 }
2759
2760 async fn create_client(&mut self, cx: &mut TestAppContext, name: &str) -> TestClient {
2761 let http = FakeHttpClient::with_404_response();
2762 let user_id = self.app_state.db.create_user(name, false).await.unwrap();
2763 let client_name = name.to_string();
2764 let mut client = Client::new(http.clone());
2765 let server = self.server.clone();
2766 let connection_killers = self.connection_killers.clone();
2767 let forbid_connections = self.forbid_connections.clone();
2768 let (connection_id_tx, mut connection_id_rx) = postage::mpsc::channel(16);
2769
2770 Arc::get_mut(&mut client)
2771 .unwrap()
2772 .override_authenticate(move |cx| {
2773 cx.spawn(|_| async move {
2774 let access_token = "the-token".to_string();
2775 Ok(Credentials {
2776 user_id: user_id.0 as u64,
2777 access_token,
2778 })
2779 })
2780 })
2781 .override_establish_connection(move |credentials, cx| {
2782 assert_eq!(credentials.user_id, user_id.0 as u64);
2783 assert_eq!(credentials.access_token, "the-token");
2784
2785 let server = server.clone();
2786 let connection_killers = connection_killers.clone();
2787 let forbid_connections = forbid_connections.clone();
2788 let client_name = client_name.clone();
2789 let connection_id_tx = connection_id_tx.clone();
2790 cx.spawn(move |cx| async move {
2791 if forbid_connections.load(SeqCst) {
2792 Err(EstablishConnectionError::other(anyhow!(
2793 "server is forbidding connections"
2794 )))
2795 } else {
2796 let (client_conn, server_conn, kill_conn) = Connection::in_memory();
2797 connection_killers.lock().insert(user_id, kill_conn);
2798 cx.background()
2799 .spawn(server.handle_connection(
2800 server_conn,
2801 client_name,
2802 user_id,
2803 Some(connection_id_tx),
2804 ))
2805 .detach();
2806 Ok(client_conn)
2807 }
2808 })
2809 });
2810
2811 client
2812 .authenticate_and_connect(&cx.to_async())
2813 .await
2814 .unwrap();
2815
2816 let peer_id = PeerId(connection_id_rx.next().await.unwrap().0);
2817 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http, cx));
2818 let mut authed_user =
2819 user_store.read_with(cx, |user_store, _| user_store.watch_current_user());
2820 while authed_user.next().await.unwrap().is_none() {}
2821
2822 TestClient {
2823 client,
2824 peer_id,
2825 user_store,
2826 }
2827 }
2828
2829 fn disconnect_client(&self, user_id: UserId) {
2830 if let Some(mut kill_conn) = self.connection_killers.lock().remove(&user_id) {
2831 let _ = kill_conn.try_send(Some(()));
2832 }
2833 }
2834
2835 fn forbid_connections(&self) {
2836 self.forbid_connections.store(true, SeqCst);
2837 }
2838
2839 fn allow_connections(&self) {
2840 self.forbid_connections.store(false, SeqCst);
2841 }
2842
2843 async fn build_app_state(test_db: &TestDb) -> Arc<AppState> {
2844 let mut config = Config::default();
2845 config.session_secret = "a".repeat(32);
2846 config.database_url = test_db.url.clone();
2847 let github_client = github::AppClient::test();
2848 Arc::new(AppState {
2849 db: test_db.db().clone(),
2850 handlebars: Default::default(),
2851 auth_client: auth::build_client("", ""),
2852 repo_client: github::RepoClient::test(&github_client),
2853 github_client,
2854 config,
2855 })
2856 }
2857
2858 async fn state<'a>(&'a self) -> RwLockReadGuard<'a, Store> {
2859 self.server.store.read()
2860 }
2861
2862 async fn condition<F>(&mut self, mut predicate: F)
2863 where
2864 F: FnMut(&Store) -> bool,
2865 {
2866 async_std::future::timeout(Duration::from_millis(500), async {
2867 while !(predicate)(&*self.server.store.read()) {
2868 self.foreground.start_waiting();
2869 self.notifications.next().await;
2870 self.foreground.finish_waiting();
2871 }
2872 })
2873 .await
2874 .expect("condition timed out");
2875 }
2876 }
2877
2878 impl Drop for TestServer {
2879 fn drop(&mut self) {
2880 self.peer.reset();
2881 }
2882 }
2883
2884 struct TestClient {
2885 client: Arc<Client>,
2886 pub peer_id: PeerId,
2887 pub user_store: ModelHandle<UserStore>,
2888 }
2889
2890 impl Deref for TestClient {
2891 type Target = Arc<Client>;
2892
2893 fn deref(&self) -> &Self::Target {
2894 &self.client
2895 }
2896 }
2897
2898 impl TestClient {
2899 pub fn current_user_id(&self, cx: &TestAppContext) -> UserId {
2900 UserId::from_proto(
2901 self.user_store
2902 .read_with(cx, |user_store, _| user_store.current_user().unwrap().id),
2903 )
2904 }
2905 }
2906
2907 fn channel_messages(channel: &Channel) -> Vec<(String, String, bool)> {
2908 channel
2909 .messages()
2910 .cursor::<()>()
2911 .map(|m| {
2912 (
2913 m.sender.github_login.clone(),
2914 m.body.clone(),
2915 m.is_pending(),
2916 )
2917 })
2918 .collect()
2919 }
2920
2921 struct EmptyView;
2922
2923 impl gpui::Entity for EmptyView {
2924 type Event = ();
2925 }
2926
2927 impl gpui::View for EmptyView {
2928 fn ui_name() -> &'static str {
2929 "empty view"
2930 }
2931
2932 fn render(&mut self, _: &mut gpui::RenderContext<Self>) -> gpui::ElementBox {
2933 gpui::Element::boxed(gpui::elements::Empty)
2934 }
2935 }
2936}