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