1mod store;
2
3use super::{
4 auth::process_auth_header,
5 db::{ChannelId, MessageId, UserId},
6 AppState,
7};
8use anyhow::anyhow;
9use async_std::{sync::RwLock, task};
10use async_tungstenite::{tungstenite::protocol::Role, WebSocketStream};
11use futures::{future::BoxFuture, FutureExt};
12use postage::{mpsc, prelude::Sink as _, prelude::Stream as _};
13use rpc::{
14 proto::{self, AnyTypedEnvelope, EnvelopedMessage},
15 Connection, ConnectionId, Peer, TypedEnvelope,
16};
17use sha1::{Digest as _, Sha1};
18use std::{
19 any::TypeId,
20 collections::{HashMap, HashSet},
21 future::Future,
22 mem,
23 sync::Arc,
24 time::Instant,
25};
26use store::{JoinedWorktree, Store, Worktree};
27use surf::StatusCode;
28use tide::log;
29use tide::{
30 http::headers::{HeaderName, CONNECTION, UPGRADE},
31 Request, Response,
32};
33use time::OffsetDateTime;
34
35type MessageHandler = Box<
36 dyn Send
37 + Sync
38 + Fn(Arc<Server>, Box<dyn AnyTypedEnvelope>) -> BoxFuture<'static, tide::Result<()>>,
39>;
40
41pub struct Server {
42 peer: Arc<Peer>,
43 store: RwLock<Store>,
44 app_state: Arc<AppState>,
45 handlers: HashMap<TypeId, MessageHandler>,
46 notifications: Option<mpsc::Sender<()>>,
47}
48
49const MESSAGE_COUNT_PER_PAGE: usize = 100;
50const MAX_MESSAGE_LEN: usize = 1024;
51
52impl Server {
53 pub fn new(
54 app_state: Arc<AppState>,
55 peer: Arc<Peer>,
56 notifications: Option<mpsc::Sender<()>>,
57 ) -> Arc<Self> {
58 let mut server = Self {
59 peer,
60 app_state,
61 store: Default::default(),
62 handlers: Default::default(),
63 notifications,
64 };
65
66 server
67 .add_handler(Server::ping)
68 .add_handler(Server::open_worktree)
69 .add_handler(Server::close_worktree)
70 .add_handler(Server::share_worktree)
71 .add_handler(Server::unshare_worktree)
72 .add_handler(Server::join_worktree)
73 .add_handler(Server::leave_worktree)
74 .add_handler(Server::update_worktree)
75 .add_handler(Server::open_buffer)
76 .add_handler(Server::close_buffer)
77 .add_handler(Server::update_buffer)
78 .add_handler(Server::buffer_saved)
79 .add_handler(Server::save_buffer)
80 .add_handler(Server::get_channels)
81 .add_handler(Server::get_users)
82 .add_handler(Server::join_channel)
83 .add_handler(Server::leave_channel)
84 .add_handler(Server::send_channel_message)
85 .add_handler(Server::get_channel_messages);
86
87 Arc::new(server)
88 }
89
90 fn add_handler<F, Fut, M>(&mut self, handler: F) -> &mut Self
91 where
92 F: 'static + Send + Sync + Fn(Arc<Self>, TypedEnvelope<M>) -> Fut,
93 Fut: 'static + Send + Future<Output = tide::Result<()>>,
94 M: EnvelopedMessage,
95 {
96 let prev_handler = self.handlers.insert(
97 TypeId::of::<M>(),
98 Box::new(move |server, envelope| {
99 let envelope = envelope.into_any().downcast::<TypedEnvelope<M>>().unwrap();
100 (handler)(server, *envelope).boxed()
101 }),
102 );
103 if prev_handler.is_some() {
104 panic!("registered a handler for the same message twice");
105 }
106 self
107 }
108
109 pub fn handle_connection(
110 self: &Arc<Self>,
111 connection: Connection,
112 addr: String,
113 user_id: UserId,
114 ) -> impl Future<Output = ()> {
115 let mut this = self.clone();
116 async move {
117 let (connection_id, handle_io, mut incoming_rx) =
118 this.peer.add_connection(connection).await;
119 this.state_mut()
120 .await
121 .add_connection(connection_id, user_id);
122 if let Err(err) = this.update_collaborators_for_users(&[user_id]).await {
123 log::error!("error updating collaborators for {:?}: {}", user_id, err);
124 }
125
126 let handle_io = handle_io.fuse();
127 futures::pin_mut!(handle_io);
128 loop {
129 let next_message = incoming_rx.recv().fuse();
130 futures::pin_mut!(next_message);
131 futures::select_biased! {
132 message = next_message => {
133 if let Some(message) = message {
134 let start_time = Instant::now();
135 log::info!("RPC message received: {}", message.payload_type_name());
136 if let Some(handler) = this.handlers.get(&message.payload_type_id()) {
137 if let Err(err) = (handler)(this.clone(), message).await {
138 log::error!("error handling message: {:?}", err);
139 } else {
140 log::info!("RPC message handled. duration:{:?}", start_time.elapsed());
141 }
142
143 if let Some(mut notifications) = this.notifications.clone() {
144 let _ = notifications.send(()).await;
145 }
146 } else {
147 log::warn!("unhandled message: {}", message.payload_type_name());
148 }
149 } else {
150 log::info!("rpc connection closed {:?}", addr);
151 break;
152 }
153 }
154 handle_io = handle_io => {
155 if let Err(err) = handle_io {
156 log::error!("error handling rpc connection {:?} - {:?}", addr, err);
157 }
158 break;
159 }
160 }
161 }
162
163 if let Err(err) = this.sign_out(connection_id).await {
164 log::error!("error signing out connection {:?} - {:?}", addr, err);
165 }
166 }
167 }
168
169 async fn sign_out(self: &mut Arc<Self>, connection_id: ConnectionId) -> tide::Result<()> {
170 self.peer.disconnect(connection_id).await;
171 let removed_connection = self.state_mut().await.remove_connection(connection_id)?;
172
173 for (worktree_id, worktree) in removed_connection.hosted_worktrees {
174 if let Some(share) = worktree.share {
175 broadcast(
176 connection_id,
177 share.guest_connection_ids.keys().copied().collect(),
178 |conn_id| {
179 self.peer
180 .send(conn_id, proto::UnshareWorktree { worktree_id })
181 },
182 )
183 .await?;
184 }
185 }
186
187 for (worktree_id, peer_ids) in removed_connection.guest_worktree_ids {
188 broadcast(connection_id, peer_ids, |conn_id| {
189 self.peer.send(
190 conn_id,
191 proto::RemovePeer {
192 worktree_id,
193 peer_id: connection_id.0,
194 },
195 )
196 })
197 .await?;
198 }
199
200 self.update_collaborators_for_users(removed_connection.collaborator_ids.iter())
201 .await?;
202
203 Ok(())
204 }
205
206 async fn ping(self: Arc<Server>, request: TypedEnvelope<proto::Ping>) -> tide::Result<()> {
207 self.peer.respond(request.receipt(), proto::Ack {}).await?;
208 Ok(())
209 }
210
211 async fn open_worktree(
212 mut self: Arc<Server>,
213 request: TypedEnvelope<proto::OpenWorktree>,
214 ) -> tide::Result<()> {
215 let receipt = request.receipt();
216 let host_user_id = self
217 .state()
218 .await
219 .user_id_for_connection(request.sender_id)?;
220
221 let mut collaborator_user_ids = HashSet::new();
222 collaborator_user_ids.insert(host_user_id);
223 for github_login in request.payload.collaborator_logins {
224 match self.app_state.db.create_user(&github_login, false).await {
225 Ok(collaborator_user_id) => {
226 collaborator_user_ids.insert(collaborator_user_id);
227 }
228 Err(err) => {
229 let message = err.to_string();
230 self.peer
231 .respond_with_error(receipt, proto::Error { message })
232 .await?;
233 return Ok(());
234 }
235 }
236 }
237
238 let collaborator_user_ids = collaborator_user_ids.into_iter().collect::<Vec<_>>();
239 let worktree_id = self.state_mut().await.add_worktree(Worktree {
240 host_connection_id: request.sender_id,
241 collaborator_user_ids: collaborator_user_ids.clone(),
242 root_name: request.payload.root_name,
243 share: None,
244 });
245
246 self.peer
247 .respond(receipt, proto::OpenWorktreeResponse { worktree_id })
248 .await?;
249 self.update_collaborators_for_users(&collaborator_user_ids)
250 .await?;
251
252 Ok(())
253 }
254
255 async fn close_worktree(
256 mut self: Arc<Server>,
257 request: TypedEnvelope<proto::CloseWorktree>,
258 ) -> tide::Result<()> {
259 let worktree_id = request.payload.worktree_id;
260 let worktree = self
261 .state_mut()
262 .await
263 .remove_worktree(worktree_id, request.sender_id)?;
264
265 if let Some(share) = worktree.share {
266 broadcast(
267 request.sender_id,
268 share.guest_connection_ids.keys().copied().collect(),
269 |conn_id| {
270 self.peer
271 .send(conn_id, proto::UnshareWorktree { worktree_id })
272 },
273 )
274 .await?;
275 }
276 self.update_collaborators_for_users(&worktree.collaborator_user_ids)
277 .await?;
278 Ok(())
279 }
280
281 async fn share_worktree(
282 mut self: Arc<Server>,
283 mut request: TypedEnvelope<proto::ShareWorktree>,
284 ) -> tide::Result<()> {
285 let worktree = request
286 .payload
287 .worktree
288 .as_mut()
289 .ok_or_else(|| anyhow!("missing worktree"))?;
290 let entries = mem::take(&mut worktree.entries)
291 .into_iter()
292 .map(|entry| (entry.id, entry))
293 .collect();
294
295 let collaborator_user_ids =
296 self.state_mut()
297 .await
298 .share_worktree(worktree.id, request.sender_id, entries);
299 if let Some(collaborator_user_ids) = collaborator_user_ids {
300 self.peer
301 .respond(request.receipt(), proto::ShareWorktreeResponse {})
302 .await?;
303 self.update_collaborators_for_users(&collaborator_user_ids)
304 .await?;
305 } else {
306 self.peer
307 .respond_with_error(
308 request.receipt(),
309 proto::Error {
310 message: "no such worktree".to_string(),
311 },
312 )
313 .await?;
314 }
315 Ok(())
316 }
317
318 async fn unshare_worktree(
319 mut self: Arc<Server>,
320 request: TypedEnvelope<proto::UnshareWorktree>,
321 ) -> tide::Result<()> {
322 let worktree_id = request.payload.worktree_id;
323 let worktree = self
324 .state_mut()
325 .await
326 .unshare_worktree(worktree_id, request.sender_id)?;
327
328 broadcast(request.sender_id, worktree.connection_ids, |conn_id| {
329 self.peer
330 .send(conn_id, proto::UnshareWorktree { worktree_id })
331 })
332 .await?;
333 self.update_collaborators_for_users(&worktree.collaborator_ids)
334 .await?;
335
336 Ok(())
337 }
338
339 async fn join_worktree(
340 mut self: Arc<Server>,
341 request: TypedEnvelope<proto::JoinWorktree>,
342 ) -> tide::Result<()> {
343 let worktree_id = request.payload.worktree_id;
344 let user_id = self
345 .state()
346 .await
347 .user_id_for_connection(request.sender_id)?;
348
349 let mut state = self.state_mut().await;
350 match state.join_worktree(request.sender_id, user_id, worktree_id) {
351 Ok(JoinedWorktree {
352 replica_id,
353 worktree,
354 }) => {
355 let share = worktree.share()?;
356 let peer_count = share.guest_connection_ids.len();
357 let mut peers = Vec::with_capacity(peer_count);
358 peers.push(proto::Peer {
359 peer_id: worktree.host_connection_id.0,
360 replica_id: 0,
361 });
362 for (peer_conn_id, peer_replica_id) in &share.guest_connection_ids {
363 if *peer_conn_id != request.sender_id {
364 peers.push(proto::Peer {
365 peer_id: peer_conn_id.0,
366 replica_id: *peer_replica_id as u32,
367 });
368 }
369 }
370 let response = proto::JoinWorktreeResponse {
371 worktree: Some(proto::Worktree {
372 id: worktree_id,
373 root_name: worktree.root_name.clone(),
374 entries: share.entries.values().cloned().collect(),
375 }),
376 replica_id: replica_id as u32,
377 peers,
378 };
379 let connection_ids = worktree.connection_ids();
380 let collaborator_user_ids = worktree.collaborator_user_ids.clone();
381 drop(state);
382
383 broadcast(request.sender_id, connection_ids, |conn_id| {
384 self.peer.send(
385 conn_id,
386 proto::AddPeer {
387 worktree_id,
388 peer: Some(proto::Peer {
389 peer_id: request.sender_id.0,
390 replica_id: response.replica_id,
391 }),
392 },
393 )
394 })
395 .await?;
396 self.peer.respond(request.receipt(), response).await?;
397 self.update_collaborators_for_users(&collaborator_user_ids)
398 .await?;
399 }
400 Err(error) => {
401 drop(state);
402 self.peer
403 .respond_with_error(
404 request.receipt(),
405 proto::Error {
406 message: error.to_string(),
407 },
408 )
409 .await?;
410 }
411 }
412
413 Ok(())
414 }
415
416 async fn leave_worktree(
417 mut self: Arc<Server>,
418 request: TypedEnvelope<proto::LeaveWorktree>,
419 ) -> tide::Result<()> {
420 let sender_id = request.sender_id;
421 let worktree_id = request.payload.worktree_id;
422 let worktree = self
423 .state_mut()
424 .await
425 .leave_worktree(sender_id, worktree_id);
426 if let Some(worktree) = worktree {
427 broadcast(sender_id, worktree.connection_ids, |conn_id| {
428 self.peer.send(
429 conn_id,
430 proto::RemovePeer {
431 worktree_id,
432 peer_id: sender_id.0,
433 },
434 )
435 })
436 .await?;
437 self.update_collaborators_for_users(&worktree.collaborator_ids)
438 .await?;
439 }
440 Ok(())
441 }
442
443 async fn update_worktree(
444 mut self: Arc<Server>,
445 request: TypedEnvelope<proto::UpdateWorktree>,
446 ) -> tide::Result<()> {
447 let connection_ids = self.state_mut().await.update_worktree(
448 request.sender_id,
449 request.payload.worktree_id,
450 &request.payload.removed_entries,
451 &request.payload.updated_entries,
452 )?;
453
454 broadcast(request.sender_id, connection_ids, |connection_id| {
455 self.peer
456 .forward_send(request.sender_id, connection_id, request.payload.clone())
457 })
458 .await?;
459
460 Ok(())
461 }
462
463 async fn open_buffer(
464 self: Arc<Server>,
465 request: TypedEnvelope<proto::OpenBuffer>,
466 ) -> tide::Result<()> {
467 let receipt = request.receipt();
468 let host_connection_id = self
469 .state()
470 .await
471 .worktree_host_connection_id(request.sender_id, request.payload.worktree_id)?;
472 let response = self
473 .peer
474 .forward_request(request.sender_id, host_connection_id, request.payload)
475 .await?;
476 self.peer.respond(receipt, response).await?;
477 Ok(())
478 }
479
480 async fn close_buffer(
481 self: Arc<Server>,
482 request: TypedEnvelope<proto::CloseBuffer>,
483 ) -> tide::Result<()> {
484 let host_connection_id = self
485 .state()
486 .await
487 .worktree_host_connection_id(request.sender_id, request.payload.worktree_id)?;
488 self.peer
489 .forward_send(request.sender_id, host_connection_id, request.payload)
490 .await?;
491 Ok(())
492 }
493
494 async fn save_buffer(
495 self: Arc<Server>,
496 request: TypedEnvelope<proto::SaveBuffer>,
497 ) -> tide::Result<()> {
498 let host;
499 let guests;
500 {
501 let state = self.state().await;
502 host = state
503 .worktree_host_connection_id(request.sender_id, request.payload.worktree_id)?;
504 guests = state
505 .worktree_guest_connection_ids(request.sender_id, request.payload.worktree_id)?;
506 }
507
508 let sender = request.sender_id;
509 let receipt = request.receipt();
510 let response = self
511 .peer
512 .forward_request(sender, host, request.payload.clone())
513 .await?;
514
515 broadcast(host, guests, |conn_id| {
516 let response = response.clone();
517 let peer = &self.peer;
518 async move {
519 if conn_id == sender {
520 peer.respond(receipt, response).await
521 } else {
522 peer.forward_send(host, conn_id, response).await
523 }
524 }
525 })
526 .await?;
527
528 Ok(())
529 }
530
531 async fn update_buffer(
532 self: Arc<Server>,
533 request: TypedEnvelope<proto::UpdateBuffer>,
534 ) -> tide::Result<()> {
535 broadcast(
536 request.sender_id,
537 self.state()
538 .await
539 .worktree_connection_ids(request.sender_id, request.payload.worktree_id)?,
540 |connection_id| {
541 self.peer
542 .forward_send(request.sender_id, connection_id, request.payload.clone())
543 },
544 )
545 .await?;
546 self.peer.respond(request.receipt(), proto::Ack {}).await?;
547 Ok(())
548 }
549
550 async fn buffer_saved(
551 self: Arc<Server>,
552 request: TypedEnvelope<proto::BufferSaved>,
553 ) -> tide::Result<()> {
554 broadcast(
555 request.sender_id,
556 self.store
557 .read()
558 .await
559 .worktree_connection_ids(request.sender_id, request.payload.worktree_id)?,
560 |connection_id| {
561 self.peer
562 .forward_send(request.sender_id, connection_id, request.payload.clone())
563 },
564 )
565 .await?;
566 Ok(())
567 }
568
569 async fn get_channels(
570 self: Arc<Server>,
571 request: TypedEnvelope<proto::GetChannels>,
572 ) -> tide::Result<()> {
573 let user_id = self
574 .state()
575 .await
576 .user_id_for_connection(request.sender_id)?;
577 let channels = self.app_state.db.get_accessible_channels(user_id).await?;
578 self.peer
579 .respond(
580 request.receipt(),
581 proto::GetChannelsResponse {
582 channels: channels
583 .into_iter()
584 .map(|chan| proto::Channel {
585 id: chan.id.to_proto(),
586 name: chan.name,
587 })
588 .collect(),
589 },
590 )
591 .await?;
592 Ok(())
593 }
594
595 async fn get_users(
596 self: Arc<Server>,
597 request: TypedEnvelope<proto::GetUsers>,
598 ) -> tide::Result<()> {
599 let receipt = request.receipt();
600 let user_ids = request.payload.user_ids.into_iter().map(UserId::from_proto);
601 let users = self
602 .app_state
603 .db
604 .get_users_by_ids(user_ids)
605 .await?
606 .into_iter()
607 .map(|user| proto::User {
608 id: user.id.to_proto(),
609 avatar_url: format!("https://github.com/{}.png?size=128", user.github_login),
610 github_login: user.github_login,
611 })
612 .collect();
613 self.peer
614 .respond(receipt, proto::GetUsersResponse { users })
615 .await?;
616 Ok(())
617 }
618
619 async fn update_collaborators_for_users<'a>(
620 self: &Arc<Server>,
621 user_ids: impl IntoIterator<Item = &'a UserId>,
622 ) -> tide::Result<()> {
623 let mut send_futures = Vec::new();
624
625 let state = self.state().await;
626 for user_id in user_ids {
627 let collaborators = state.collaborators_for_user(*user_id);
628 for connection_id in state.connection_ids_for_user(*user_id) {
629 send_futures.push(self.peer.send(
630 connection_id,
631 proto::UpdateCollaborators {
632 collaborators: collaborators.clone(),
633 },
634 ));
635 }
636 }
637
638 drop(state);
639 futures::future::try_join_all(send_futures).await?;
640
641 Ok(())
642 }
643
644 async fn join_channel(
645 mut self: Arc<Self>,
646 request: TypedEnvelope<proto::JoinChannel>,
647 ) -> tide::Result<()> {
648 let user_id = self
649 .state()
650 .await
651 .user_id_for_connection(request.sender_id)?;
652 let channel_id = ChannelId::from_proto(request.payload.channel_id);
653 if !self
654 .app_state
655 .db
656 .can_user_access_channel(user_id, channel_id)
657 .await?
658 {
659 Err(anyhow!("access denied"))?;
660 }
661
662 self.state_mut()
663 .await
664 .join_channel(request.sender_id, channel_id);
665 let messages = self
666 .app_state
667 .db
668 .get_channel_messages(channel_id, MESSAGE_COUNT_PER_PAGE, None)
669 .await?
670 .into_iter()
671 .map(|msg| proto::ChannelMessage {
672 id: msg.id.to_proto(),
673 body: msg.body,
674 timestamp: msg.sent_at.unix_timestamp() as u64,
675 sender_id: msg.sender_id.to_proto(),
676 nonce: Some(msg.nonce.as_u128().into()),
677 })
678 .collect::<Vec<_>>();
679 self.peer
680 .respond(
681 request.receipt(),
682 proto::JoinChannelResponse {
683 done: messages.len() < MESSAGE_COUNT_PER_PAGE,
684 messages,
685 },
686 )
687 .await?;
688 Ok(())
689 }
690
691 async fn leave_channel(
692 mut self: Arc<Self>,
693 request: TypedEnvelope<proto::LeaveChannel>,
694 ) -> tide::Result<()> {
695 let user_id = self
696 .state()
697 .await
698 .user_id_for_connection(request.sender_id)?;
699 let channel_id = ChannelId::from_proto(request.payload.channel_id);
700 if !self
701 .app_state
702 .db
703 .can_user_access_channel(user_id, channel_id)
704 .await?
705 {
706 Err(anyhow!("access denied"))?;
707 }
708
709 self.state_mut()
710 .await
711 .leave_channel(request.sender_id, channel_id);
712
713 Ok(())
714 }
715
716 async fn send_channel_message(
717 self: Arc<Self>,
718 request: TypedEnvelope<proto::SendChannelMessage>,
719 ) -> tide::Result<()> {
720 let receipt = request.receipt();
721 let channel_id = ChannelId::from_proto(request.payload.channel_id);
722 let user_id;
723 let connection_ids;
724 {
725 let state = self.state().await;
726 user_id = state.user_id_for_connection(request.sender_id)?;
727 if let Some(ids) = state.channel_connection_ids(channel_id) {
728 connection_ids = ids;
729 } else {
730 return Ok(());
731 }
732 }
733
734 // Validate the message body.
735 let body = request.payload.body.trim().to_string();
736 if body.len() > MAX_MESSAGE_LEN {
737 self.peer
738 .respond_with_error(
739 receipt,
740 proto::Error {
741 message: "message is too long".to_string(),
742 },
743 )
744 .await?;
745 return Ok(());
746 }
747 if body.is_empty() {
748 self.peer
749 .respond_with_error(
750 receipt,
751 proto::Error {
752 message: "message can't be blank".to_string(),
753 },
754 )
755 .await?;
756 return Ok(());
757 }
758
759 let timestamp = OffsetDateTime::now_utc();
760 let nonce = if let Some(nonce) = request.payload.nonce {
761 nonce
762 } else {
763 self.peer
764 .respond_with_error(
765 receipt,
766 proto::Error {
767 message: "nonce can't be blank".to_string(),
768 },
769 )
770 .await?;
771 return Ok(());
772 };
773
774 let message_id = self
775 .app_state
776 .db
777 .create_channel_message(channel_id, user_id, &body, timestamp, nonce.clone().into())
778 .await?
779 .to_proto();
780 let message = proto::ChannelMessage {
781 sender_id: user_id.to_proto(),
782 id: message_id,
783 body,
784 timestamp: timestamp.unix_timestamp() as u64,
785 nonce: Some(nonce),
786 };
787 broadcast(request.sender_id, connection_ids, |conn_id| {
788 self.peer.send(
789 conn_id,
790 proto::ChannelMessageSent {
791 channel_id: channel_id.to_proto(),
792 message: Some(message.clone()),
793 },
794 )
795 })
796 .await?;
797 self.peer
798 .respond(
799 receipt,
800 proto::SendChannelMessageResponse {
801 message: Some(message),
802 },
803 )
804 .await?;
805 Ok(())
806 }
807
808 async fn get_channel_messages(
809 self: Arc<Self>,
810 request: TypedEnvelope<proto::GetChannelMessages>,
811 ) -> tide::Result<()> {
812 let user_id = self
813 .state()
814 .await
815 .user_id_for_connection(request.sender_id)?;
816 let channel_id = ChannelId::from_proto(request.payload.channel_id);
817 if !self
818 .app_state
819 .db
820 .can_user_access_channel(user_id, channel_id)
821 .await?
822 {
823 Err(anyhow!("access denied"))?;
824 }
825
826 let messages = self
827 .app_state
828 .db
829 .get_channel_messages(
830 channel_id,
831 MESSAGE_COUNT_PER_PAGE,
832 Some(MessageId::from_proto(request.payload.before_message_id)),
833 )
834 .await?
835 .into_iter()
836 .map(|msg| proto::ChannelMessage {
837 id: msg.id.to_proto(),
838 body: msg.body,
839 timestamp: msg.sent_at.unix_timestamp() as u64,
840 sender_id: msg.sender_id.to_proto(),
841 nonce: Some(msg.nonce.as_u128().into()),
842 })
843 .collect::<Vec<_>>();
844 self.peer
845 .respond(
846 request.receipt(),
847 proto::GetChannelMessagesResponse {
848 done: messages.len() < MESSAGE_COUNT_PER_PAGE,
849 messages,
850 },
851 )
852 .await?;
853 Ok(())
854 }
855
856 fn state<'a>(
857 self: &'a Arc<Self>,
858 ) -> impl Future<Output = async_std::sync::RwLockReadGuard<'a, Store>> {
859 self.store.read()
860 }
861
862 fn state_mut<'a>(
863 self: &'a mut Arc<Self>,
864 ) -> impl Future<Output = async_std::sync::RwLockWriteGuard<'a, Store>> {
865 self.store.write()
866 }
867}
868
869pub async fn broadcast<F, T>(
870 sender_id: ConnectionId,
871 receiver_ids: Vec<ConnectionId>,
872 mut f: F,
873) -> anyhow::Result<()>
874where
875 F: FnMut(ConnectionId) -> T,
876 T: Future<Output = anyhow::Result<()>>,
877{
878 let futures = receiver_ids
879 .into_iter()
880 .filter(|id| *id != sender_id)
881 .map(|id| f(id));
882 futures::future::try_join_all(futures).await?;
883 Ok(())
884}
885
886pub fn add_routes(app: &mut tide::Server<Arc<AppState>>, rpc: &Arc<Peer>) {
887 let server = Server::new(app.state().clone(), rpc.clone(), None);
888 app.at("/rpc").get(move |request: Request<Arc<AppState>>| {
889 let server = server.clone();
890 async move {
891 const WEBSOCKET_GUID: &str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
892
893 let connection_upgrade = header_contains_ignore_case(&request, CONNECTION, "upgrade");
894 let upgrade_to_websocket = header_contains_ignore_case(&request, UPGRADE, "websocket");
895 let upgrade_requested = connection_upgrade && upgrade_to_websocket;
896 let client_protocol_version: Option<u32> = request
897 .header("X-Zed-Protocol-Version")
898 .and_then(|v| v.as_str().parse().ok());
899
900 if !upgrade_requested || client_protocol_version != Some(rpc::PROTOCOL_VERSION) {
901 return Ok(Response::new(StatusCode::UpgradeRequired));
902 }
903
904 let header = match request.header("Sec-Websocket-Key") {
905 Some(h) => h.as_str(),
906 None => return Err(anyhow!("expected sec-websocket-key"))?,
907 };
908
909 let user_id = process_auth_header(&request).await?;
910
911 let mut response = Response::new(StatusCode::SwitchingProtocols);
912 response.insert_header(UPGRADE, "websocket");
913 response.insert_header(CONNECTION, "Upgrade");
914 let hash = Sha1::new().chain(header).chain(WEBSOCKET_GUID).finalize();
915 response.insert_header("Sec-Websocket-Accept", base64::encode(&hash[..]));
916 response.insert_header("Sec-Websocket-Version", "13");
917
918 let http_res: &mut tide::http::Response = response.as_mut();
919 let upgrade_receiver = http_res.recv_upgrade().await;
920 let addr = request.remote().unwrap_or("unknown").to_string();
921 task::spawn(async move {
922 if let Some(stream) = upgrade_receiver.await {
923 server
924 .handle_connection(
925 Connection::new(
926 WebSocketStream::from_raw_socket(stream, Role::Server, None).await,
927 ),
928 addr,
929 user_id,
930 )
931 .await;
932 }
933 });
934
935 Ok(response)
936 }
937 });
938}
939
940fn header_contains_ignore_case<T>(
941 request: &tide::Request<T>,
942 header_name: HeaderName,
943 value: &str,
944) -> bool {
945 request
946 .header(header_name)
947 .map(|h| {
948 h.as_str()
949 .split(',')
950 .any(|s| s.trim().eq_ignore_ascii_case(value.trim()))
951 })
952 .unwrap_or(false)
953}
954
955#[cfg(test)]
956mod tests {
957 use super::*;
958 use crate::{
959 auth,
960 db::{tests::TestDb, UserId},
961 github, AppState, Config,
962 };
963 use ::rpc::Peer;
964 use async_std::{sync::RwLockReadGuard, task};
965 use gpui::{ModelHandle, TestAppContext};
966 use parking_lot::Mutex;
967 use postage::{mpsc, watch};
968 use serde_json::json;
969 use sqlx::types::time::OffsetDateTime;
970 use std::{
971 path::Path,
972 sync::{
973 atomic::{AtomicBool, Ordering::SeqCst},
974 Arc,
975 },
976 time::Duration,
977 };
978 use zed::{
979 client::{
980 self, test::FakeHttpClient, Channel, ChannelDetails, ChannelList, Client, Credentials,
981 EstablishConnectionError, UserStore,
982 },
983 editor::{Editor, EditorSettings, Input},
984 fs::{FakeFs, Fs as _},
985 language::LanguageRegistry,
986 people_panel::JoinWorktree,
987 project::{ProjectPath, Worktree},
988 workspace::{Workspace, WorkspaceParams},
989 };
990
991 #[gpui::test]
992 async fn test_share_worktree(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
993 let (window_b, _) = cx_b.add_window(|_| EmptyView);
994 let lang_registry = Arc::new(LanguageRegistry::new());
995
996 // Connect to a server as 2 clients.
997 let mut server = TestServer::start().await;
998 let (client_a, _) = server.create_client(&mut cx_a, "user_a").await;
999 let (client_b, _) = server.create_client(&mut cx_b, "user_b").await;
1000
1001 cx_a.foreground().forbid_parking();
1002
1003 // Share a local worktree as client A
1004 let fs = Arc::new(FakeFs::new());
1005 fs.insert_tree(
1006 "/a",
1007 json!({
1008 ".zed.toml": r#"collaborators = ["user_b"]"#,
1009 "a.txt": "a-contents",
1010 "b.txt": "b-contents",
1011 }),
1012 )
1013 .await;
1014 let worktree_a = Worktree::open_local(
1015 client_a.clone(),
1016 "/a".as_ref(),
1017 fs,
1018 lang_registry.clone(),
1019 None,
1020 &mut cx_a.to_async(),
1021 )
1022 .await
1023 .unwrap();
1024 worktree_a
1025 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1026 .await;
1027 let worktree_id = worktree_a
1028 .update(&mut cx_a, |tree, cx| tree.as_local_mut().unwrap().share(cx))
1029 .await
1030 .unwrap();
1031
1032 // Join that worktree as client B, and see that a guest has joined as client A.
1033 let worktree_b = Worktree::open_remote(
1034 client_b.clone(),
1035 worktree_id,
1036 lang_registry.clone(),
1037 &mut cx_b.to_async(),
1038 )
1039 .await
1040 .unwrap();
1041 let replica_id_b = worktree_b.read_with(&cx_b, |tree, _| tree.replica_id());
1042 worktree_a
1043 .condition(&cx_a, |tree, _| {
1044 tree.peers()
1045 .values()
1046 .any(|replica_id| *replica_id == replica_id_b)
1047 })
1048 .await;
1049
1050 // Open the same file as client B and client A.
1051 let buffer_b = worktree_b
1052 .update(&mut cx_b, |worktree, cx| worktree.open_buffer("b.txt", cx))
1053 .await
1054 .unwrap();
1055 buffer_b.read_with(&cx_b, |buf, _| assert_eq!(buf.text(), "b-contents"));
1056 worktree_a.read_with(&cx_a, |tree, cx| assert!(tree.has_open_buffer("b.txt", cx)));
1057 let buffer_a = worktree_a
1058 .update(&mut cx_a, |tree, cx| tree.open_buffer("b.txt", cx))
1059 .await
1060 .unwrap();
1061
1062 // Create a selection set as client B and see that selection set as client A.
1063 let editor_b = cx_b.add_view(window_b, |cx| {
1064 Editor::for_buffer(buffer_b, |cx| EditorSettings::test(cx), cx)
1065 });
1066 buffer_a
1067 .condition(&cx_a, |buffer, _| buffer.selection_sets().count() == 1)
1068 .await;
1069
1070 // Edit the buffer as client B and see that edit as client A.
1071 editor_b.update(&mut cx_b, |editor, cx| {
1072 editor.handle_input(&Input("ok, ".into()), cx)
1073 });
1074 buffer_a
1075 .condition(&cx_a, |buffer, _| buffer.text() == "ok, b-contents")
1076 .await;
1077
1078 // Remove the selection set as client B, see those selections disappear as client A.
1079 cx_b.update(move |_| drop(editor_b));
1080 buffer_a
1081 .condition(&cx_a, |buffer, _| buffer.selection_sets().count() == 0)
1082 .await;
1083
1084 // Close the buffer as client A, see that the buffer is closed.
1085 cx_a.update(move |_| drop(buffer_a));
1086 worktree_a
1087 .condition(&cx_a, |tree, cx| !tree.has_open_buffer("b.txt", cx))
1088 .await;
1089
1090 // Dropping the worktree removes client B from client A's peers.
1091 cx_b.update(move |_| drop(worktree_b));
1092 worktree_a
1093 .condition(&cx_a, |tree, _| tree.peers().is_empty())
1094 .await;
1095 }
1096
1097 #[gpui::test]
1098 async fn test_unshare_worktree(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1099 cx_b.update(zed::people_panel::init);
1100 let lang_registry = Arc::new(LanguageRegistry::new());
1101
1102 // Connect to a server as 2 clients.
1103 let mut server = TestServer::start().await;
1104 let (client_a, _) = server.create_client(&mut cx_a, "user_a").await;
1105 let (client_b, user_store_b) = server.create_client(&mut cx_b, "user_b").await;
1106 let mut workspace_b_params = cx_b.update(WorkspaceParams::test);
1107 workspace_b_params.client = client_b;
1108 workspace_b_params.user_store = user_store_b;
1109
1110 cx_a.foreground().forbid_parking();
1111
1112 // Share a local worktree as client A
1113 let fs = Arc::new(FakeFs::new());
1114 fs.insert_tree(
1115 "/a",
1116 json!({
1117 ".zed.toml": r#"collaborators = ["user_b"]"#,
1118 "a.txt": "a-contents",
1119 "b.txt": "b-contents",
1120 }),
1121 )
1122 .await;
1123 let worktree_a = Worktree::open_local(
1124 client_a.clone(),
1125 "/a".as_ref(),
1126 fs,
1127 lang_registry.clone(),
1128 None,
1129 &mut cx_a.to_async(),
1130 )
1131 .await
1132 .unwrap();
1133 worktree_a
1134 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1135 .await;
1136
1137 let remote_worktree_id = worktree_a
1138 .update(&mut cx_a, |tree, cx| tree.as_local_mut().unwrap().share(cx))
1139 .await
1140 .unwrap();
1141
1142 let (window_b, workspace_b) = cx_b.add_window(|cx| Workspace::new(&workspace_b_params, cx));
1143 cx_b.update(|cx| {
1144 cx.dispatch_action(
1145 window_b,
1146 vec![workspace_b.id()],
1147 &JoinWorktree(remote_worktree_id),
1148 );
1149 });
1150 workspace_b
1151 .condition(&cx_b, |workspace, cx| workspace.worktrees(cx).len() == 1)
1152 .await;
1153
1154 let local_worktree_id_b = workspace_b.read_with(&cx_b, |workspace, cx| {
1155 let active_pane = workspace.active_pane().read(cx);
1156 assert!(active_pane.active_item().is_none());
1157 workspace.worktrees(cx).first().unwrap().id()
1158 });
1159 workspace_b
1160 .update(&mut cx_b, |workspace, cx| {
1161 workspace.open_entry(
1162 ProjectPath {
1163 worktree_id: local_worktree_id_b,
1164 path: Path::new("a.txt").into(),
1165 },
1166 cx,
1167 )
1168 })
1169 .unwrap()
1170 .await;
1171 workspace_b.read_with(&cx_b, |workspace, cx| {
1172 let active_pane = workspace.active_pane().read(cx);
1173 assert!(active_pane.active_item().is_some());
1174 });
1175
1176 worktree_a.update(&mut cx_a, |tree, cx| {
1177 tree.as_local_mut().unwrap().unshare(cx);
1178 });
1179 workspace_b
1180 .condition(&cx_b, |workspace, cx| workspace.worktrees(cx).len() == 0)
1181 .await;
1182 workspace_b.read_with(&cx_b, |workspace, cx| {
1183 let active_pane = workspace.active_pane().read(cx);
1184 assert!(active_pane.active_item().is_none());
1185 });
1186 }
1187
1188 #[gpui::test]
1189 async fn test_propagate_saves_and_fs_changes_in_shared_worktree(
1190 mut cx_a: TestAppContext,
1191 mut cx_b: TestAppContext,
1192 mut cx_c: TestAppContext,
1193 ) {
1194 cx_a.foreground().forbid_parking();
1195 let lang_registry = Arc::new(LanguageRegistry::new());
1196
1197 // Connect to a server as 3 clients.
1198 let mut server = TestServer::start().await;
1199 let (client_a, _) = server.create_client(&mut cx_a, "user_a").await;
1200 let (client_b, _) = server.create_client(&mut cx_b, "user_b").await;
1201 let (client_c, _) = server.create_client(&mut cx_c, "user_c").await;
1202
1203 let fs = Arc::new(FakeFs::new());
1204
1205 // Share a worktree as client A.
1206 fs.insert_tree(
1207 "/a",
1208 json!({
1209 ".zed.toml": r#"collaborators = ["user_b", "user_c"]"#,
1210 "file1": "",
1211 "file2": ""
1212 }),
1213 )
1214 .await;
1215
1216 let worktree_a = Worktree::open_local(
1217 client_a.clone(),
1218 "/a".as_ref(),
1219 fs.clone(),
1220 lang_registry.clone(),
1221 None,
1222 &mut cx_a.to_async(),
1223 )
1224 .await
1225 .unwrap();
1226 worktree_a
1227 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1228 .await;
1229 let worktree_id = worktree_a
1230 .update(&mut cx_a, |tree, cx| tree.as_local_mut().unwrap().share(cx))
1231 .await
1232 .unwrap();
1233
1234 // Join that worktree as clients B and C.
1235 let worktree_b = Worktree::open_remote(
1236 client_b.clone(),
1237 worktree_id,
1238 lang_registry.clone(),
1239 &mut cx_b.to_async(),
1240 )
1241 .await
1242 .unwrap();
1243 let worktree_c = Worktree::open_remote(
1244 client_c.clone(),
1245 worktree_id,
1246 lang_registry.clone(),
1247 &mut cx_c.to_async(),
1248 )
1249 .await
1250 .unwrap();
1251
1252 // Open and edit a buffer as both guests B and C.
1253 let buffer_b = worktree_b
1254 .update(&mut cx_b, |tree, cx| tree.open_buffer("file1", cx))
1255 .await
1256 .unwrap();
1257 let buffer_c = worktree_c
1258 .update(&mut cx_c, |tree, cx| tree.open_buffer("file1", cx))
1259 .await
1260 .unwrap();
1261 buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "i-am-b, ", cx));
1262 buffer_c.update(&mut cx_c, |buf, cx| buf.edit([0..0], "i-am-c, ", cx));
1263
1264 // Open and edit that buffer as the host.
1265 let buffer_a = worktree_a
1266 .update(&mut cx_a, |tree, cx| tree.open_buffer("file1", cx))
1267 .await
1268 .unwrap();
1269
1270 buffer_a
1271 .condition(&mut cx_a, |buf, _| buf.text() == "i-am-c, i-am-b, ")
1272 .await;
1273 buffer_a.update(&mut cx_a, |buf, cx| {
1274 buf.edit([buf.len()..buf.len()], "i-am-a", cx)
1275 });
1276
1277 // Wait for edits to propagate
1278 buffer_a
1279 .condition(&mut cx_a, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1280 .await;
1281 buffer_b
1282 .condition(&mut cx_b, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1283 .await;
1284 buffer_c
1285 .condition(&mut cx_c, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1286 .await;
1287
1288 // Edit the buffer as the host and concurrently save as guest B.
1289 let save_b = buffer_b.update(&mut cx_b, |buf, cx| buf.save(cx).unwrap());
1290 buffer_a.update(&mut cx_a, |buf, cx| buf.edit([0..0], "hi-a, ", cx));
1291 save_b.await.unwrap();
1292 assert_eq!(
1293 fs.load("/a/file1".as_ref()).await.unwrap(),
1294 "hi-a, i-am-c, i-am-b, i-am-a"
1295 );
1296 buffer_a.read_with(&cx_a, |buf, _| assert!(!buf.is_dirty()));
1297 buffer_b.read_with(&cx_b, |buf, _| assert!(!buf.is_dirty()));
1298 buffer_c.condition(&cx_c, |buf, _| !buf.is_dirty()).await;
1299
1300 // Make changes on host's file system, see those changes on the guests.
1301 fs.rename("/a/file2".as_ref(), "/a/file3".as_ref())
1302 .await
1303 .unwrap();
1304 fs.insert_file(Path::new("/a/file4"), "4".into())
1305 .await
1306 .unwrap();
1307
1308 worktree_b
1309 .condition(&cx_b, |tree, _| tree.file_count() == 4)
1310 .await;
1311 worktree_c
1312 .condition(&cx_c, |tree, _| tree.file_count() == 4)
1313 .await;
1314 worktree_b.read_with(&cx_b, |tree, _| {
1315 assert_eq!(
1316 tree.paths()
1317 .map(|p| p.to_string_lossy())
1318 .collect::<Vec<_>>(),
1319 &[".zed.toml", "file1", "file3", "file4"]
1320 )
1321 });
1322 worktree_c.read_with(&cx_c, |tree, _| {
1323 assert_eq!(
1324 tree.paths()
1325 .map(|p| p.to_string_lossy())
1326 .collect::<Vec<_>>(),
1327 &[".zed.toml", "file1", "file3", "file4"]
1328 )
1329 });
1330 }
1331
1332 #[gpui::test]
1333 async fn test_buffer_conflict_after_save(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1334 cx_a.foreground().forbid_parking();
1335 let lang_registry = Arc::new(LanguageRegistry::new());
1336
1337 // Connect to a server as 2 clients.
1338 let mut server = TestServer::start().await;
1339 let (client_a, _) = server.create_client(&mut cx_a, "user_a").await;
1340 let (client_b, _) = server.create_client(&mut cx_b, "user_b").await;
1341
1342 // Share a local worktree as client A
1343 let fs = Arc::new(FakeFs::new());
1344 fs.insert_tree(
1345 "/dir",
1346 json!({
1347 ".zed.toml": r#"collaborators = ["user_b", "user_c"]"#,
1348 "a.txt": "a-contents",
1349 }),
1350 )
1351 .await;
1352
1353 let worktree_a = Worktree::open_local(
1354 client_a.clone(),
1355 "/dir".as_ref(),
1356 fs,
1357 lang_registry.clone(),
1358 None,
1359 &mut cx_a.to_async(),
1360 )
1361 .await
1362 .unwrap();
1363 worktree_a
1364 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1365 .await;
1366 let worktree_id = worktree_a
1367 .update(&mut cx_a, |tree, cx| tree.as_local_mut().unwrap().share(cx))
1368 .await
1369 .unwrap();
1370
1371 // Join that worktree as client B, and see that a guest has joined as client A.
1372 let worktree_b = Worktree::open_remote(
1373 client_b.clone(),
1374 worktree_id,
1375 lang_registry.clone(),
1376 &mut cx_b.to_async(),
1377 )
1378 .await
1379 .unwrap();
1380
1381 let buffer_b = worktree_b
1382 .update(&mut cx_b, |worktree, cx| worktree.open_buffer("a.txt", cx))
1383 .await
1384 .unwrap();
1385 let mtime = buffer_b.read_with(&cx_b, |buf, _| buf.file().unwrap().mtime());
1386
1387 buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "world ", cx));
1388 buffer_b.read_with(&cx_b, |buf, _| {
1389 assert!(buf.is_dirty());
1390 assert!(!buf.has_conflict());
1391 });
1392
1393 buffer_b
1394 .update(&mut cx_b, |buf, cx| buf.save(cx))
1395 .unwrap()
1396 .await
1397 .unwrap();
1398 worktree_b
1399 .condition(&cx_b, |_, cx| {
1400 buffer_b.read(cx).file().unwrap().mtime() != mtime
1401 })
1402 .await;
1403 buffer_b.read_with(&cx_b, |buf, _| {
1404 assert!(!buf.is_dirty());
1405 assert!(!buf.has_conflict());
1406 });
1407
1408 buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "hello ", cx));
1409 buffer_b.read_with(&cx_b, |buf, _| {
1410 assert!(buf.is_dirty());
1411 assert!(!buf.has_conflict());
1412 });
1413 }
1414
1415 #[gpui::test]
1416 async fn test_editing_while_guest_opens_buffer(
1417 mut cx_a: TestAppContext,
1418 mut cx_b: TestAppContext,
1419 ) {
1420 cx_a.foreground().forbid_parking();
1421 let lang_registry = Arc::new(LanguageRegistry::new());
1422
1423 // Connect to a server as 2 clients.
1424 let mut server = TestServer::start().await;
1425 let (client_a, _) = server.create_client(&mut cx_a, "user_a").await;
1426 let (client_b, _) = server.create_client(&mut cx_b, "user_b").await;
1427
1428 // Share a local worktree as client A
1429 let fs = Arc::new(FakeFs::new());
1430 fs.insert_tree(
1431 "/dir",
1432 json!({
1433 ".zed.toml": r#"collaborators = ["user_b"]"#,
1434 "a.txt": "a-contents",
1435 }),
1436 )
1437 .await;
1438 let worktree_a = Worktree::open_local(
1439 client_a.clone(),
1440 "/dir".as_ref(),
1441 fs,
1442 lang_registry.clone(),
1443 None,
1444 &mut cx_a.to_async(),
1445 )
1446 .await
1447 .unwrap();
1448 worktree_a
1449 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1450 .await;
1451 let worktree_id = worktree_a
1452 .update(&mut cx_a, |tree, cx| tree.as_local_mut().unwrap().share(cx))
1453 .await
1454 .unwrap();
1455
1456 // Join that worktree as client B, and see that a guest has joined as client A.
1457 let worktree_b = Worktree::open_remote(
1458 client_b.clone(),
1459 worktree_id,
1460 lang_registry.clone(),
1461 &mut cx_b.to_async(),
1462 )
1463 .await
1464 .unwrap();
1465
1466 let buffer_a = worktree_a
1467 .update(&mut cx_a, |tree, cx| tree.open_buffer("a.txt", cx))
1468 .await
1469 .unwrap();
1470 let buffer_b = cx_b
1471 .background()
1472 .spawn(worktree_b.update(&mut cx_b, |worktree, cx| worktree.open_buffer("a.txt", cx)));
1473
1474 task::yield_now().await;
1475 buffer_a.update(&mut cx_a, |buf, cx| buf.edit([0..0], "z", cx));
1476
1477 let text = buffer_a.read_with(&cx_a, |buf, _| buf.text());
1478 let buffer_b = buffer_b.await.unwrap();
1479 buffer_b.condition(&cx_b, |buf, _| buf.text() == text).await;
1480 }
1481
1482 #[gpui::test]
1483 async fn test_leaving_worktree_while_opening_buffer(
1484 mut cx_a: TestAppContext,
1485 mut cx_b: TestAppContext,
1486 ) {
1487 cx_a.foreground().forbid_parking();
1488 let lang_registry = Arc::new(LanguageRegistry::new());
1489
1490 // Connect to a server as 2 clients.
1491 let mut server = TestServer::start().await;
1492 let (client_a, _) = server.create_client(&mut cx_a, "user_a").await;
1493 let (client_b, _) = server.create_client(&mut cx_b, "user_b").await;
1494
1495 // Share a local worktree as client A
1496 let fs = Arc::new(FakeFs::new());
1497 fs.insert_tree(
1498 "/dir",
1499 json!({
1500 ".zed.toml": r#"collaborators = ["user_b"]"#,
1501 "a.txt": "a-contents",
1502 }),
1503 )
1504 .await;
1505 let worktree_a = Worktree::open_local(
1506 client_a.clone(),
1507 "/dir".as_ref(),
1508 fs,
1509 lang_registry.clone(),
1510 None,
1511 &mut cx_a.to_async(),
1512 )
1513 .await
1514 .unwrap();
1515 worktree_a
1516 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1517 .await;
1518 let worktree_id = worktree_a
1519 .update(&mut cx_a, |tree, cx| tree.as_local_mut().unwrap().share(cx))
1520 .await
1521 .unwrap();
1522
1523 // Join that worktree as client B, and see that a guest has joined as client A.
1524 let worktree_b = Worktree::open_remote(
1525 client_b.clone(),
1526 worktree_id,
1527 lang_registry.clone(),
1528 &mut cx_b.to_async(),
1529 )
1530 .await
1531 .unwrap();
1532 worktree_a
1533 .condition(&cx_a, |tree, _| tree.peers().len() == 1)
1534 .await;
1535
1536 let buffer_b = cx_b
1537 .background()
1538 .spawn(worktree_b.update(&mut cx_b, |worktree, cx| worktree.open_buffer("a.txt", cx)));
1539 cx_b.update(|_| drop(worktree_b));
1540 drop(buffer_b);
1541 worktree_a
1542 .condition(&cx_a, |tree, _| tree.peers().len() == 0)
1543 .await;
1544 }
1545
1546 #[gpui::test]
1547 async fn test_peer_disconnection(mut cx_a: TestAppContext, cx_b: TestAppContext) {
1548 cx_a.foreground().forbid_parking();
1549 let lang_registry = Arc::new(LanguageRegistry::new());
1550
1551 // Connect to a server as 2 clients.
1552 let mut server = TestServer::start().await;
1553 let (client_a, _) = server.create_client(&mut cx_a, "user_a").await;
1554 let (client_b, _) = server.create_client(&mut cx_a, "user_b").await;
1555
1556 // Share a local worktree as client A
1557 let fs = Arc::new(FakeFs::new());
1558 fs.insert_tree(
1559 "/a",
1560 json!({
1561 ".zed.toml": r#"collaborators = ["user_b"]"#,
1562 "a.txt": "a-contents",
1563 "b.txt": "b-contents",
1564 }),
1565 )
1566 .await;
1567 let worktree_a = Worktree::open_local(
1568 client_a.clone(),
1569 "/a".as_ref(),
1570 fs,
1571 lang_registry.clone(),
1572 None,
1573 &mut cx_a.to_async(),
1574 )
1575 .await
1576 .unwrap();
1577 worktree_a
1578 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1579 .await;
1580 let worktree_id = worktree_a
1581 .update(&mut cx_a, |tree, cx| tree.as_local_mut().unwrap().share(cx))
1582 .await
1583 .unwrap();
1584
1585 // Join that worktree as client B, and see that a guest has joined as client A.
1586 let _worktree_b = Worktree::open_remote(
1587 client_b.clone(),
1588 worktree_id,
1589 lang_registry.clone(),
1590 &mut cx_b.to_async(),
1591 )
1592 .await
1593 .unwrap();
1594 worktree_a
1595 .condition(&cx_a, |tree, _| tree.peers().len() == 1)
1596 .await;
1597
1598 // Drop client B's connection and ensure client A observes client B leaving the worktree.
1599 client_b.disconnect(&cx_b.to_async()).await.unwrap();
1600 worktree_a
1601 .condition(&cx_a, |tree, _| tree.peers().len() == 0)
1602 .await;
1603 }
1604
1605 #[gpui::test]
1606 async fn test_basic_chat(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1607 cx_a.foreground().forbid_parking();
1608
1609 // Connect to a server as 2 clients.
1610 let mut server = TestServer::start().await;
1611 let (client_a, user_store_a) = server.create_client(&mut cx_a, "user_a").await;
1612 let (client_b, user_store_b) = server.create_client(&mut cx_b, "user_b").await;
1613
1614 // Create an org that includes these 2 users.
1615 let db = &server.app_state.db;
1616 let org_id = db.create_org("Test Org", "test-org").await.unwrap();
1617 db.add_org_member(org_id, current_user_id(&user_store_a, &cx_a), false)
1618 .await
1619 .unwrap();
1620 db.add_org_member(org_id, current_user_id(&user_store_b, &cx_b), false)
1621 .await
1622 .unwrap();
1623
1624 // Create a channel that includes all the users.
1625 let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
1626 db.add_channel_member(channel_id, current_user_id(&user_store_a, &cx_a), false)
1627 .await
1628 .unwrap();
1629 db.add_channel_member(channel_id, current_user_id(&user_store_b, &cx_b), false)
1630 .await
1631 .unwrap();
1632 db.create_channel_message(
1633 channel_id,
1634 current_user_id(&user_store_b, &cx_b),
1635 "hello A, it's B.",
1636 OffsetDateTime::now_utc(),
1637 1,
1638 )
1639 .await
1640 .unwrap();
1641
1642 let channels_a = cx_a.add_model(|cx| ChannelList::new(user_store_a, client_a, cx));
1643 channels_a
1644 .condition(&mut cx_a, |list, _| list.available_channels().is_some())
1645 .await;
1646 channels_a.read_with(&cx_a, |list, _| {
1647 assert_eq!(
1648 list.available_channels().unwrap(),
1649 &[ChannelDetails {
1650 id: channel_id.to_proto(),
1651 name: "test-channel".to_string()
1652 }]
1653 )
1654 });
1655 let channel_a = channels_a.update(&mut cx_a, |this, cx| {
1656 this.get_channel(channel_id.to_proto(), cx).unwrap()
1657 });
1658 channel_a.read_with(&cx_a, |channel, _| assert!(channel.messages().is_empty()));
1659 channel_a
1660 .condition(&cx_a, |channel, _| {
1661 channel_messages(channel)
1662 == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
1663 })
1664 .await;
1665
1666 let channels_b = cx_b.add_model(|cx| ChannelList::new(user_store_b, client_b, cx));
1667 channels_b
1668 .condition(&mut cx_b, |list, _| list.available_channels().is_some())
1669 .await;
1670 channels_b.read_with(&cx_b, |list, _| {
1671 assert_eq!(
1672 list.available_channels().unwrap(),
1673 &[ChannelDetails {
1674 id: channel_id.to_proto(),
1675 name: "test-channel".to_string()
1676 }]
1677 )
1678 });
1679
1680 let channel_b = channels_b.update(&mut cx_b, |this, cx| {
1681 this.get_channel(channel_id.to_proto(), cx).unwrap()
1682 });
1683 channel_b.read_with(&cx_b, |channel, _| assert!(channel.messages().is_empty()));
1684 channel_b
1685 .condition(&cx_b, |channel, _| {
1686 channel_messages(channel)
1687 == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
1688 })
1689 .await;
1690
1691 channel_a
1692 .update(&mut cx_a, |channel, cx| {
1693 channel
1694 .send_message("oh, hi B.".to_string(), cx)
1695 .unwrap()
1696 .detach();
1697 let task = channel.send_message("sup".to_string(), cx).unwrap();
1698 assert_eq!(
1699 channel_messages(channel),
1700 &[
1701 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
1702 ("user_a".to_string(), "oh, hi B.".to_string(), true),
1703 ("user_a".to_string(), "sup".to_string(), true)
1704 ]
1705 );
1706 task
1707 })
1708 .await
1709 .unwrap();
1710
1711 channel_b
1712 .condition(&cx_b, |channel, _| {
1713 channel_messages(channel)
1714 == [
1715 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
1716 ("user_a".to_string(), "oh, hi B.".to_string(), false),
1717 ("user_a".to_string(), "sup".to_string(), false),
1718 ]
1719 })
1720 .await;
1721
1722 assert_eq!(
1723 server
1724 .state()
1725 .await
1726 .channel(channel_id)
1727 .unwrap()
1728 .connection_ids
1729 .len(),
1730 2
1731 );
1732 cx_b.update(|_| drop(channel_b));
1733 server
1734 .condition(|state| state.channel(channel_id).unwrap().connection_ids.len() == 1)
1735 .await;
1736
1737 cx_a.update(|_| drop(channel_a));
1738 server
1739 .condition(|state| state.channel(channel_id).is_none())
1740 .await;
1741 }
1742
1743 #[gpui::test]
1744 async fn test_chat_message_validation(mut cx_a: TestAppContext) {
1745 cx_a.foreground().forbid_parking();
1746
1747 let mut server = TestServer::start().await;
1748 let (client_a, user_store_a) = server.create_client(&mut cx_a, "user_a").await;
1749
1750 let db = &server.app_state.db;
1751 let org_id = db.create_org("Test Org", "test-org").await.unwrap();
1752 let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
1753 db.add_org_member(org_id, current_user_id(&user_store_a, &cx_a), false)
1754 .await
1755 .unwrap();
1756 db.add_channel_member(channel_id, current_user_id(&user_store_a, &cx_a), false)
1757 .await
1758 .unwrap();
1759
1760 let channels_a = cx_a.add_model(|cx| ChannelList::new(user_store_a, client_a, cx));
1761 channels_a
1762 .condition(&mut cx_a, |list, _| list.available_channels().is_some())
1763 .await;
1764 let channel_a = channels_a.update(&mut cx_a, |this, cx| {
1765 this.get_channel(channel_id.to_proto(), cx).unwrap()
1766 });
1767
1768 // Messages aren't allowed to be too long.
1769 channel_a
1770 .update(&mut cx_a, |channel, cx| {
1771 let long_body = "this is long.\n".repeat(1024);
1772 channel.send_message(long_body, cx).unwrap()
1773 })
1774 .await
1775 .unwrap_err();
1776
1777 // Messages aren't allowed to be blank.
1778 channel_a.update(&mut cx_a, |channel, cx| {
1779 channel.send_message(String::new(), cx).unwrap_err()
1780 });
1781
1782 // Leading and trailing whitespace are trimmed.
1783 channel_a
1784 .update(&mut cx_a, |channel, cx| {
1785 channel
1786 .send_message("\n surrounded by whitespace \n".to_string(), cx)
1787 .unwrap()
1788 })
1789 .await
1790 .unwrap();
1791 assert_eq!(
1792 db.get_channel_messages(channel_id, 10, None)
1793 .await
1794 .unwrap()
1795 .iter()
1796 .map(|m| &m.body)
1797 .collect::<Vec<_>>(),
1798 &["surrounded by whitespace"]
1799 );
1800 }
1801
1802 #[gpui::test]
1803 async fn test_chat_reconnection(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1804 cx_a.foreground().forbid_parking();
1805
1806 // Connect to a server as 2 clients.
1807 let mut server = TestServer::start().await;
1808 let (client_a, user_store_a) = server.create_client(&mut cx_a, "user_a").await;
1809 let (client_b, user_store_b) = server.create_client(&mut cx_b, "user_b").await;
1810 let mut status_b = client_b.status();
1811
1812 // Create an org that includes these 2 users.
1813 let db = &server.app_state.db;
1814 let org_id = db.create_org("Test Org", "test-org").await.unwrap();
1815 db.add_org_member(org_id, current_user_id(&user_store_a, &cx_a), false)
1816 .await
1817 .unwrap();
1818 db.add_org_member(org_id, current_user_id(&user_store_b, &cx_b), false)
1819 .await
1820 .unwrap();
1821
1822 // Create a channel that includes all the users.
1823 let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
1824 db.add_channel_member(channel_id, current_user_id(&user_store_a, &cx_a), false)
1825 .await
1826 .unwrap();
1827 db.add_channel_member(channel_id, current_user_id(&user_store_b, &cx_b), false)
1828 .await
1829 .unwrap();
1830 db.create_channel_message(
1831 channel_id,
1832 current_user_id(&user_store_b, &cx_b),
1833 "hello A, it's B.",
1834 OffsetDateTime::now_utc(),
1835 2,
1836 )
1837 .await
1838 .unwrap();
1839
1840 let channels_a = cx_a.add_model(|cx| ChannelList::new(user_store_a, client_a, cx));
1841 channels_a
1842 .condition(&mut cx_a, |list, _| list.available_channels().is_some())
1843 .await;
1844
1845 channels_a.read_with(&cx_a, |list, _| {
1846 assert_eq!(
1847 list.available_channels().unwrap(),
1848 &[ChannelDetails {
1849 id: channel_id.to_proto(),
1850 name: "test-channel".to_string()
1851 }]
1852 )
1853 });
1854 let channel_a = channels_a.update(&mut cx_a, |this, cx| {
1855 this.get_channel(channel_id.to_proto(), cx).unwrap()
1856 });
1857 channel_a.read_with(&cx_a, |channel, _| assert!(channel.messages().is_empty()));
1858 channel_a
1859 .condition(&cx_a, |channel, _| {
1860 channel_messages(channel)
1861 == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
1862 })
1863 .await;
1864
1865 let channels_b = cx_b.add_model(|cx| ChannelList::new(user_store_b.clone(), client_b, cx));
1866 channels_b
1867 .condition(&mut cx_b, |list, _| list.available_channels().is_some())
1868 .await;
1869 channels_b.read_with(&cx_b, |list, _| {
1870 assert_eq!(
1871 list.available_channels().unwrap(),
1872 &[ChannelDetails {
1873 id: channel_id.to_proto(),
1874 name: "test-channel".to_string()
1875 }]
1876 )
1877 });
1878
1879 let channel_b = channels_b.update(&mut cx_b, |this, cx| {
1880 this.get_channel(channel_id.to_proto(), cx).unwrap()
1881 });
1882 channel_b.read_with(&cx_b, |channel, _| assert!(channel.messages().is_empty()));
1883 channel_b
1884 .condition(&cx_b, |channel, _| {
1885 channel_messages(channel)
1886 == [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
1887 })
1888 .await;
1889
1890 // Disconnect client B, ensuring we can still access its cached channel data.
1891 server.forbid_connections();
1892 server.disconnect_client(current_user_id(&user_store_b, &cx_b));
1893 while !matches!(
1894 status_b.recv().await,
1895 Some(client::Status::ReconnectionError { .. })
1896 ) {}
1897
1898 channels_b.read_with(&cx_b, |channels, _| {
1899 assert_eq!(
1900 channels.available_channels().unwrap(),
1901 [ChannelDetails {
1902 id: channel_id.to_proto(),
1903 name: "test-channel".to_string()
1904 }]
1905 )
1906 });
1907 channel_b.read_with(&cx_b, |channel, _| {
1908 assert_eq!(
1909 channel_messages(channel),
1910 [("user_b".to_string(), "hello A, it's B.".to_string(), false)]
1911 )
1912 });
1913
1914 // Send a message from client B while it is disconnected.
1915 channel_b
1916 .update(&mut cx_b, |channel, cx| {
1917 let task = channel
1918 .send_message("can you see this?".to_string(), cx)
1919 .unwrap();
1920 assert_eq!(
1921 channel_messages(channel),
1922 &[
1923 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
1924 ("user_b".to_string(), "can you see this?".to_string(), true)
1925 ]
1926 );
1927 task
1928 })
1929 .await
1930 .unwrap_err();
1931
1932 // Send a message from client A while B is disconnected.
1933 channel_a
1934 .update(&mut cx_a, |channel, cx| {
1935 channel
1936 .send_message("oh, hi B.".to_string(), cx)
1937 .unwrap()
1938 .detach();
1939 let task = channel.send_message("sup".to_string(), cx).unwrap();
1940 assert_eq!(
1941 channel_messages(channel),
1942 &[
1943 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
1944 ("user_a".to_string(), "oh, hi B.".to_string(), true),
1945 ("user_a".to_string(), "sup".to_string(), true)
1946 ]
1947 );
1948 task
1949 })
1950 .await
1951 .unwrap();
1952
1953 // Give client B a chance to reconnect.
1954 server.allow_connections();
1955 cx_b.foreground().advance_clock(Duration::from_secs(10));
1956
1957 // Verify that B sees the new messages upon reconnection, as well as the message client B
1958 // sent while offline.
1959 channel_b
1960 .condition(&cx_b, |channel, _| {
1961 channel_messages(channel)
1962 == [
1963 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
1964 ("user_a".to_string(), "oh, hi B.".to_string(), false),
1965 ("user_a".to_string(), "sup".to_string(), false),
1966 ("user_b".to_string(), "can you see this?".to_string(), false),
1967 ]
1968 })
1969 .await;
1970
1971 // Ensure client A and B can communicate normally after reconnection.
1972 channel_a
1973 .update(&mut cx_a, |channel, cx| {
1974 channel.send_message("you online?".to_string(), cx).unwrap()
1975 })
1976 .await
1977 .unwrap();
1978 channel_b
1979 .condition(&cx_b, |channel, _| {
1980 channel_messages(channel)
1981 == [
1982 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
1983 ("user_a".to_string(), "oh, hi B.".to_string(), false),
1984 ("user_a".to_string(), "sup".to_string(), false),
1985 ("user_b".to_string(), "can you see this?".to_string(), false),
1986 ("user_a".to_string(), "you online?".to_string(), false),
1987 ]
1988 })
1989 .await;
1990
1991 channel_b
1992 .update(&mut cx_b, |channel, cx| {
1993 channel.send_message("yep".to_string(), cx).unwrap()
1994 })
1995 .await
1996 .unwrap();
1997 channel_a
1998 .condition(&cx_a, |channel, _| {
1999 channel_messages(channel)
2000 == [
2001 ("user_b".to_string(), "hello A, it's B.".to_string(), false),
2002 ("user_a".to_string(), "oh, hi B.".to_string(), false),
2003 ("user_a".to_string(), "sup".to_string(), false),
2004 ("user_b".to_string(), "can you see this?".to_string(), false),
2005 ("user_a".to_string(), "you online?".to_string(), false),
2006 ("user_b".to_string(), "yep".to_string(), false),
2007 ]
2008 })
2009 .await;
2010 }
2011
2012 #[gpui::test]
2013 async fn test_collaborators(
2014 mut cx_a: TestAppContext,
2015 mut cx_b: TestAppContext,
2016 mut cx_c: TestAppContext,
2017 ) {
2018 cx_a.foreground().forbid_parking();
2019 let lang_registry = Arc::new(LanguageRegistry::new());
2020
2021 // Connect to a server as 3 clients.
2022 let mut server = TestServer::start().await;
2023 let (client_a, user_store_a) = server.create_client(&mut cx_a, "user_a").await;
2024 let (client_b, user_store_b) = server.create_client(&mut cx_b, "user_b").await;
2025 let (_client_c, user_store_c) = server.create_client(&mut cx_c, "user_c").await;
2026
2027 let fs = Arc::new(FakeFs::new());
2028
2029 // Share a worktree as client A.
2030 fs.insert_tree(
2031 "/a",
2032 json!({
2033 ".zed.toml": r#"collaborators = ["user_b", "user_c"]"#,
2034 }),
2035 )
2036 .await;
2037
2038 let worktree_a = Worktree::open_local(
2039 client_a.clone(),
2040 "/a".as_ref(),
2041 fs.clone(),
2042 lang_registry.clone(),
2043 None,
2044 &mut cx_a.to_async(),
2045 )
2046 .await
2047 .unwrap();
2048
2049 user_store_a
2050 .condition(&cx_a, |user_store, _| {
2051 collaborators(user_store) == vec![("user_a", vec![("a", vec![])])]
2052 })
2053 .await;
2054 user_store_b
2055 .condition(&cx_b, |user_store, _| {
2056 collaborators(user_store) == vec![("user_a", vec![("a", vec![])])]
2057 })
2058 .await;
2059 user_store_c
2060 .condition(&cx_c, |user_store, _| {
2061 collaborators(user_store) == vec![("user_a", vec![("a", vec![])])]
2062 })
2063 .await;
2064
2065 let worktree_id = worktree_a
2066 .update(&mut cx_a, |tree, cx| tree.as_local_mut().unwrap().share(cx))
2067 .await
2068 .unwrap();
2069
2070 let _worktree_b = Worktree::open_remote(
2071 client_b.clone(),
2072 worktree_id,
2073 lang_registry.clone(),
2074 &mut cx_b.to_async(),
2075 )
2076 .await
2077 .unwrap();
2078
2079 user_store_a
2080 .condition(&cx_a, |user_store, _| {
2081 collaborators(user_store) == vec![("user_a", vec![("a", vec!["user_b"])])]
2082 })
2083 .await;
2084 user_store_b
2085 .condition(&cx_b, |user_store, _| {
2086 collaborators(user_store) == vec![("user_a", vec![("a", vec!["user_b"])])]
2087 })
2088 .await;
2089 user_store_c
2090 .condition(&cx_c, |user_store, _| {
2091 collaborators(user_store) == vec![("user_a", vec![("a", vec!["user_b"])])]
2092 })
2093 .await;
2094
2095 cx_a.update(move |_| drop(worktree_a));
2096 user_store_a
2097 .condition(&cx_a, |user_store, _| collaborators(user_store) == vec![])
2098 .await;
2099 user_store_b
2100 .condition(&cx_b, |user_store, _| collaborators(user_store) == vec![])
2101 .await;
2102 user_store_c
2103 .condition(&cx_c, |user_store, _| collaborators(user_store) == vec![])
2104 .await;
2105
2106 fn collaborators(user_store: &UserStore) -> Vec<(&str, Vec<(&str, Vec<&str>)>)> {
2107 user_store
2108 .collaborators()
2109 .iter()
2110 .map(|collaborator| {
2111 let worktrees = collaborator
2112 .worktrees
2113 .iter()
2114 .map(|w| {
2115 (
2116 w.root_name.as_str(),
2117 w.guests.iter().map(|p| p.github_login.as_str()).collect(),
2118 )
2119 })
2120 .collect();
2121 (collaborator.user.github_login.as_str(), worktrees)
2122 })
2123 .collect()
2124 }
2125 }
2126
2127 struct TestServer {
2128 peer: Arc<Peer>,
2129 app_state: Arc<AppState>,
2130 server: Arc<Server>,
2131 notifications: mpsc::Receiver<()>,
2132 connection_killers: Arc<Mutex<HashMap<UserId, watch::Sender<Option<()>>>>>,
2133 forbid_connections: Arc<AtomicBool>,
2134 _test_db: TestDb,
2135 }
2136
2137 impl TestServer {
2138 async fn start() -> Self {
2139 let test_db = TestDb::new();
2140 let app_state = Self::build_app_state(&test_db).await;
2141 let peer = Peer::new();
2142 let notifications = mpsc::channel(128);
2143 let server = Server::new(app_state.clone(), peer.clone(), Some(notifications.0));
2144 Self {
2145 peer,
2146 app_state,
2147 server,
2148 notifications: notifications.1,
2149 connection_killers: Default::default(),
2150 forbid_connections: Default::default(),
2151 _test_db: test_db,
2152 }
2153 }
2154
2155 async fn create_client(
2156 &mut self,
2157 cx: &mut TestAppContext,
2158 name: &str,
2159 ) -> (Arc<Client>, ModelHandle<UserStore>) {
2160 let user_id = self.app_state.db.create_user(name, false).await.unwrap();
2161 let client_name = name.to_string();
2162 let mut client = Client::new();
2163 let server = self.server.clone();
2164 let connection_killers = self.connection_killers.clone();
2165 let forbid_connections = self.forbid_connections.clone();
2166 Arc::get_mut(&mut client)
2167 .unwrap()
2168 .override_authenticate(move |cx| {
2169 cx.spawn(|_| async move {
2170 let access_token = "the-token".to_string();
2171 Ok(Credentials {
2172 user_id: user_id.0 as u64,
2173 access_token,
2174 })
2175 })
2176 })
2177 .override_establish_connection(move |credentials, cx| {
2178 assert_eq!(credentials.user_id, user_id.0 as u64);
2179 assert_eq!(credentials.access_token, "the-token");
2180
2181 let server = server.clone();
2182 let connection_killers = connection_killers.clone();
2183 let forbid_connections = forbid_connections.clone();
2184 let client_name = client_name.clone();
2185 cx.spawn(move |cx| async move {
2186 if forbid_connections.load(SeqCst) {
2187 Err(EstablishConnectionError::other(anyhow!(
2188 "server is forbidding connections"
2189 )))
2190 } else {
2191 let (client_conn, server_conn, kill_conn) = Connection::in_memory();
2192 connection_killers.lock().insert(user_id, kill_conn);
2193 cx.background()
2194 .spawn(server.handle_connection(server_conn, client_name, user_id))
2195 .detach();
2196 Ok(client_conn)
2197 }
2198 })
2199 });
2200
2201 let http = FakeHttpClient::new(|_| async move { Ok(surf::http::Response::new(404)) });
2202 client
2203 .authenticate_and_connect(&cx.to_async())
2204 .await
2205 .unwrap();
2206
2207 let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http, cx));
2208 let mut authed_user =
2209 user_store.read_with(cx, |user_store, _| user_store.watch_current_user());
2210 while authed_user.recv().await.unwrap().is_none() {}
2211
2212 (client, user_store)
2213 }
2214
2215 fn disconnect_client(&self, user_id: UserId) {
2216 if let Some(mut kill_conn) = self.connection_killers.lock().remove(&user_id) {
2217 let _ = kill_conn.try_send(Some(()));
2218 }
2219 }
2220
2221 fn forbid_connections(&self) {
2222 self.forbid_connections.store(true, SeqCst);
2223 }
2224
2225 fn allow_connections(&self) {
2226 self.forbid_connections.store(false, SeqCst);
2227 }
2228
2229 async fn build_app_state(test_db: &TestDb) -> Arc<AppState> {
2230 let mut config = Config::default();
2231 config.session_secret = "a".repeat(32);
2232 config.database_url = test_db.url.clone();
2233 let github_client = github::AppClient::test();
2234 Arc::new(AppState {
2235 db: test_db.db().clone(),
2236 handlebars: Default::default(),
2237 auth_client: auth::build_client("", ""),
2238 repo_client: github::RepoClient::test(&github_client),
2239 github_client,
2240 config,
2241 })
2242 }
2243
2244 async fn state<'a>(&'a self) -> RwLockReadGuard<'a, Store> {
2245 self.server.store.read().await
2246 }
2247
2248 async fn condition<F>(&mut self, mut predicate: F)
2249 where
2250 F: FnMut(&Store) -> bool,
2251 {
2252 async_std::future::timeout(Duration::from_millis(500), async {
2253 while !(predicate)(&*self.server.store.read().await) {
2254 self.notifications.recv().await;
2255 }
2256 })
2257 .await
2258 .expect("condition timed out");
2259 }
2260 }
2261
2262 impl Drop for TestServer {
2263 fn drop(&mut self) {
2264 task::block_on(self.peer.reset());
2265 }
2266 }
2267
2268 fn current_user_id(user_store: &ModelHandle<UserStore>, cx: &TestAppContext) -> UserId {
2269 UserId::from_proto(
2270 user_store.read_with(cx, |user_store, _| user_store.current_user().unwrap().id),
2271 )
2272 }
2273
2274 fn channel_messages(channel: &Channel) -> Vec<(String, String, bool)> {
2275 channel
2276 .messages()
2277 .cursor::<()>()
2278 .map(|m| {
2279 (
2280 m.sender.github_login.clone(),
2281 m.body.clone(),
2282 m.is_pending(),
2283 )
2284 })
2285 .collect()
2286 }
2287
2288 struct EmptyView;
2289
2290 impl gpui::Entity for EmptyView {
2291 type Event = ();
2292 }
2293
2294 impl gpui::View for EmptyView {
2295 fn ui_name() -> &'static str {
2296 "empty view"
2297 }
2298
2299 fn render(&mut self, _: &mut gpui::RenderContext<Self>) -> gpui::ElementBox {
2300 gpui::Element::boxed(gpui::elements::Empty)
2301 }
2302 }
2303}