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