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