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