1use super::{
2 auth,
3 db::{ChannelId, MessageId, UserId},
4 AppState,
5};
6use anyhow::anyhow;
7use async_std::{sync::RwLock, task};
8use async_tungstenite::{
9 tungstenite::{protocol::Role, Error as WebSocketError, Message as WebSocketMessage},
10 WebSocketStream,
11};
12use futures::{future::BoxFuture, FutureExt};
13use postage::{mpsc, prelude::Sink as _, prelude::Stream as _};
14use sha1::{Digest as _, Sha1};
15use std::{
16 any::TypeId,
17 collections::{hash_map, HashMap, HashSet},
18 future::Future,
19 mem,
20 sync::Arc,
21 time::Instant,
22};
23use surf::StatusCode;
24use tide::log;
25use tide::{
26 http::headers::{HeaderName, CONNECTION, UPGRADE},
27 Request, Response,
28};
29use time::OffsetDateTime;
30use zrpc::{
31 auth::random_token,
32 proto::{self, AnyTypedEnvelope, EnvelopedMessage},
33 ConnectionId, Peer, TypedEnvelope,
34};
35
36type ReplicaId = u16;
37
38type MessageHandler = Box<
39 dyn Send
40 + Sync
41 + Fn(Arc<Server>, Box<dyn AnyTypedEnvelope>) -> BoxFuture<'static, tide::Result<()>>,
42>;
43
44pub struct Server {
45 peer: Arc<Peer>,
46 state: RwLock<ServerState>,
47 app_state: Arc<AppState>,
48 handlers: HashMap<TypeId, MessageHandler>,
49 notifications: Option<mpsc::Sender<()>>,
50}
51
52#[derive(Default)]
53struct ServerState {
54 connections: HashMap<ConnectionId, Connection>,
55 pub worktrees: HashMap<u64, Worktree>,
56 channels: HashMap<ChannelId, Channel>,
57 next_worktree_id: u64,
58}
59
60struct Connection {
61 user_id: UserId,
62 worktrees: HashSet<u64>,
63 channels: HashSet<ChannelId>,
64}
65
66struct Worktree {
67 host_connection_id: Option<ConnectionId>,
68 guest_connection_ids: HashMap<ConnectionId, ReplicaId>,
69 active_replica_ids: HashSet<ReplicaId>,
70 access_token: String,
71 root_name: String,
72 entries: HashMap<u64, proto::Entry>,
73}
74
75#[derive(Default)]
76struct Channel {
77 connection_ids: HashSet<ConnectionId>,
78}
79
80const MESSAGE_COUNT_PER_PAGE: usize = 100;
81const MAX_MESSAGE_LEN: usize = 1024;
82
83impl Server {
84 pub fn new(
85 app_state: Arc<AppState>,
86 peer: Arc<Peer>,
87 notifications: Option<mpsc::Sender<()>>,
88 ) -> Arc<Self> {
89 let mut server = Self {
90 peer,
91 app_state,
92 state: Default::default(),
93 handlers: Default::default(),
94 notifications,
95 };
96
97 server
98 .add_handler(Server::share_worktree)
99 .add_handler(Server::join_worktree)
100 .add_handler(Server::update_worktree)
101 .add_handler(Server::close_worktree)
102 .add_handler(Server::open_buffer)
103 .add_handler(Server::close_buffer)
104 .add_handler(Server::update_buffer)
105 .add_handler(Server::buffer_saved)
106 .add_handler(Server::save_buffer)
107 .add_handler(Server::get_channels)
108 .add_handler(Server::get_users)
109 .add_handler(Server::join_channel)
110 .add_handler(Server::leave_channel)
111 .add_handler(Server::send_channel_message)
112 .add_handler(Server::get_channel_messages);
113
114 Arc::new(server)
115 }
116
117 fn add_handler<F, Fut, M>(&mut self, handler: F) -> &mut Self
118 where
119 F: 'static + Send + Sync + Fn(Arc<Self>, TypedEnvelope<M>) -> Fut,
120 Fut: 'static + Send + Future<Output = tide::Result<()>>,
121 M: EnvelopedMessage,
122 {
123 let prev_handler = self.handlers.insert(
124 TypeId::of::<M>(),
125 Box::new(move |server, envelope| {
126 let envelope = envelope.into_any().downcast::<TypedEnvelope<M>>().unwrap();
127 (handler)(server, *envelope).boxed()
128 }),
129 );
130 if prev_handler.is_some() {
131 panic!("registered a handler for the same message twice");
132 }
133 self
134 }
135
136 pub fn handle_connection<Conn>(
137 self: &Arc<Self>,
138 connection: Conn,
139 addr: String,
140 user_id: UserId,
141 ) -> impl Future<Output = ()>
142 where
143 Conn: 'static
144 + futures::Sink<WebSocketMessage, Error = WebSocketError>
145 + futures::Stream<Item = Result<WebSocketMessage, WebSocketError>>
146 + Send
147 + Unpin,
148 {
149 let this = self.clone();
150 async move {
151 let (connection_id, handle_io, mut incoming_rx) =
152 this.peer.add_connection(connection).await;
153 this.add_connection(connection_id, user_id).await;
154
155 let handle_io = handle_io.fuse();
156 futures::pin_mut!(handle_io);
157 loop {
158 let next_message = incoming_rx.recv().fuse();
159 futures::pin_mut!(next_message);
160 futures::select_biased! {
161 message = next_message => {
162 if let Some(message) = message {
163 let start_time = Instant::now();
164 log::info!("RPC message received: {}", message.payload_type_name());
165 if let Some(handler) = this.handlers.get(&message.payload_type_id()) {
166 if let Err(err) = (handler)(this.clone(), message).await {
167 log::error!("error handling message: {:?}", err);
168 } else {
169 log::info!("RPC message handled. duration:{:?}", start_time.elapsed());
170 }
171
172 if let Some(mut notifications) = this.notifications.clone() {
173 let _ = notifications.send(()).await;
174 }
175 } else {
176 log::warn!("unhandled message: {}", message.payload_type_name());
177 }
178 } else {
179 log::info!("rpc connection closed {:?}", addr);
180 break;
181 }
182 }
183 handle_io = handle_io => {
184 if let Err(err) = handle_io {
185 log::error!("error handling rpc connection {:?} - {:?}", addr, err);
186 }
187 break;
188 }
189 }
190 }
191
192 if let Err(err) = this.sign_out(connection_id).await {
193 log::error!("error signing out connection {:?} - {:?}", addr, err);
194 }
195 }
196 }
197
198 async fn sign_out(self: &Arc<Self>, connection_id: zrpc::ConnectionId) -> tide::Result<()> {
199 self.peer.disconnect(connection_id).await;
200 let worktree_ids = self.remove_connection(connection_id).await;
201 for worktree_id in worktree_ids {
202 let state = self.state.read().await;
203 if let Some(worktree) = state.worktrees.get(&worktree_id) {
204 broadcast(connection_id, worktree.connection_ids(), |conn_id| {
205 self.peer.send(
206 conn_id,
207 proto::RemovePeer {
208 worktree_id,
209 peer_id: connection_id.0,
210 },
211 )
212 })
213 .await?;
214 }
215 }
216 Ok(())
217 }
218
219 // Add a new connection associated with a given user.
220 async fn add_connection(&self, connection_id: ConnectionId, user_id: UserId) {
221 self.state.write().await.connections.insert(
222 connection_id,
223 Connection {
224 user_id,
225 worktrees: Default::default(),
226 channels: Default::default(),
227 },
228 );
229 }
230
231 // Remove the given connection and its association with any worktrees.
232 async fn remove_connection(&self, connection_id: ConnectionId) -> Vec<u64> {
233 let mut worktree_ids = Vec::new();
234 let mut state = self.state.write().await;
235 if let Some(connection) = state.connections.remove(&connection_id) {
236 for channel_id in connection.channels {
237 if let Some(channel) = state.channels.get_mut(&channel_id) {
238 channel.connection_ids.remove(&connection_id);
239 }
240 }
241 for worktree_id in connection.worktrees {
242 if let Some(worktree) = state.worktrees.get_mut(&worktree_id) {
243 if worktree.host_connection_id == Some(connection_id) {
244 worktree_ids.push(worktree_id);
245 } else if let Some(replica_id) =
246 worktree.guest_connection_ids.remove(&connection_id)
247 {
248 worktree.active_replica_ids.remove(&replica_id);
249 worktree_ids.push(worktree_id);
250 }
251 }
252 }
253 }
254 worktree_ids
255 }
256
257 async fn share_worktree(
258 self: Arc<Server>,
259 mut request: TypedEnvelope<proto::ShareWorktree>,
260 ) -> tide::Result<()> {
261 let mut state = self.state.write().await;
262 let worktree_id = state.next_worktree_id;
263 state.next_worktree_id += 1;
264 let access_token = random_token();
265 let worktree = request
266 .payload
267 .worktree
268 .as_mut()
269 .ok_or_else(|| anyhow!("missing worktree"))?;
270 let entries = mem::take(&mut worktree.entries)
271 .into_iter()
272 .map(|entry| (entry.id, entry))
273 .collect();
274 state.worktrees.insert(
275 worktree_id,
276 Worktree {
277 host_connection_id: Some(request.sender_id),
278 guest_connection_ids: Default::default(),
279 active_replica_ids: Default::default(),
280 access_token: access_token.clone(),
281 root_name: mem::take(&mut worktree.root_name),
282 entries,
283 },
284 );
285
286 self.peer
287 .respond(
288 request.receipt(),
289 proto::ShareWorktreeResponse {
290 worktree_id,
291 access_token,
292 },
293 )
294 .await?;
295 Ok(())
296 }
297
298 async fn join_worktree(
299 self: Arc<Server>,
300 request: TypedEnvelope<proto::OpenWorktree>,
301 ) -> tide::Result<()> {
302 let worktree_id = request.payload.worktree_id;
303 let access_token = &request.payload.access_token;
304
305 let mut state = self.state.write().await;
306 if let Some((peer_replica_id, worktree)) =
307 state.join_worktree(request.sender_id, worktree_id, access_token)
308 {
309 let mut peers = Vec::new();
310 if let Some(host_connection_id) = worktree.host_connection_id {
311 peers.push(proto::Peer {
312 peer_id: host_connection_id.0,
313 replica_id: 0,
314 });
315 }
316 for (peer_conn_id, peer_replica_id) in &worktree.guest_connection_ids {
317 if *peer_conn_id != request.sender_id {
318 peers.push(proto::Peer {
319 peer_id: peer_conn_id.0,
320 replica_id: *peer_replica_id as u32,
321 });
322 }
323 }
324
325 broadcast(request.sender_id, worktree.connection_ids(), |conn_id| {
326 self.peer.send(
327 conn_id,
328 proto::AddPeer {
329 worktree_id,
330 peer: Some(proto::Peer {
331 peer_id: request.sender_id.0,
332 replica_id: peer_replica_id as u32,
333 }),
334 },
335 )
336 })
337 .await?;
338 self.peer
339 .respond(
340 request.receipt(),
341 proto::OpenWorktreeResponse {
342 worktree_id,
343 worktree: Some(proto::Worktree {
344 root_name: worktree.root_name.clone(),
345 entries: worktree.entries.values().cloned().collect(),
346 }),
347 replica_id: peer_replica_id as u32,
348 peers,
349 },
350 )
351 .await?;
352 } else {
353 self.peer
354 .respond(
355 request.receipt(),
356 proto::OpenWorktreeResponse {
357 worktree_id,
358 worktree: None,
359 replica_id: 0,
360 peers: Vec::new(),
361 },
362 )
363 .await?;
364 }
365
366 Ok(())
367 }
368
369 async fn update_worktree(
370 self: Arc<Server>,
371 request: TypedEnvelope<proto::UpdateWorktree>,
372 ) -> tide::Result<()> {
373 {
374 let mut state = self.state.write().await;
375 let worktree = state.write_worktree(request.payload.worktree_id, request.sender_id)?;
376 for entry_id in &request.payload.removed_entries {
377 worktree.entries.remove(&entry_id);
378 }
379
380 for entry in &request.payload.updated_entries {
381 worktree.entries.insert(entry.id, entry.clone());
382 }
383 }
384
385 self.broadcast_in_worktree(request.payload.worktree_id, &request)
386 .await?;
387 Ok(())
388 }
389
390 async fn close_worktree(
391 self: Arc<Server>,
392 request: TypedEnvelope<proto::CloseWorktree>,
393 ) -> tide::Result<()> {
394 let connection_ids;
395 {
396 let mut state = self.state.write().await;
397 let worktree = state.write_worktree(request.payload.worktree_id, request.sender_id)?;
398 connection_ids = worktree.connection_ids();
399 if worktree.host_connection_id == Some(request.sender_id) {
400 worktree.host_connection_id = None;
401 } else if let Some(replica_id) =
402 worktree.guest_connection_ids.remove(&request.sender_id)
403 {
404 worktree.active_replica_ids.remove(&replica_id);
405 }
406 }
407
408 broadcast(request.sender_id, connection_ids, |conn_id| {
409 self.peer.send(
410 conn_id,
411 proto::RemovePeer {
412 worktree_id: request.payload.worktree_id,
413 peer_id: request.sender_id.0,
414 },
415 )
416 })
417 .await?;
418
419 Ok(())
420 }
421
422 async fn open_buffer(
423 self: Arc<Server>,
424 request: TypedEnvelope<proto::OpenBuffer>,
425 ) -> tide::Result<()> {
426 let receipt = request.receipt();
427 let worktree_id = request.payload.worktree_id;
428 let host_connection_id = self
429 .state
430 .read()
431 .await
432 .read_worktree(worktree_id, request.sender_id)?
433 .host_connection_id()?;
434
435 let response = self
436 .peer
437 .forward_request(request.sender_id, host_connection_id, request.payload)
438 .await?;
439 self.peer.respond(receipt, response).await?;
440 Ok(())
441 }
442
443 async fn close_buffer(
444 self: Arc<Server>,
445 request: TypedEnvelope<proto::CloseBuffer>,
446 ) -> tide::Result<()> {
447 let host_connection_id = self
448 .state
449 .read()
450 .await
451 .read_worktree(request.payload.worktree_id, request.sender_id)?
452 .host_connection_id()?;
453
454 self.peer
455 .forward_send(request.sender_id, host_connection_id, request.payload)
456 .await?;
457
458 Ok(())
459 }
460
461 async fn save_buffer(
462 self: Arc<Server>,
463 request: TypedEnvelope<proto::SaveBuffer>,
464 ) -> tide::Result<()> {
465 let host;
466 let guests;
467 {
468 let state = self.state.read().await;
469 let worktree = state.read_worktree(request.payload.worktree_id, request.sender_id)?;
470 host = worktree.host_connection_id()?;
471 guests = worktree
472 .guest_connection_ids
473 .keys()
474 .copied()
475 .collect::<Vec<_>>();
476 }
477
478 let sender = request.sender_id;
479 let receipt = request.receipt();
480 let response = self
481 .peer
482 .forward_request(sender, host, request.payload.clone())
483 .await?;
484
485 broadcast(host, guests, |conn_id| {
486 let response = response.clone();
487 let peer = &self.peer;
488 async move {
489 if conn_id == sender {
490 peer.respond(receipt, response).await
491 } else {
492 peer.forward_send(host, conn_id, response).await
493 }
494 }
495 })
496 .await?;
497
498 Ok(())
499 }
500
501 async fn update_buffer(
502 self: Arc<Server>,
503 request: TypedEnvelope<proto::UpdateBuffer>,
504 ) -> tide::Result<()> {
505 self.broadcast_in_worktree(request.payload.worktree_id, &request)
506 .await
507 }
508
509 async fn buffer_saved(
510 self: Arc<Server>,
511 request: TypedEnvelope<proto::BufferSaved>,
512 ) -> tide::Result<()> {
513 self.broadcast_in_worktree(request.payload.worktree_id, &request)
514 .await
515 }
516
517 async fn get_channels(
518 self: Arc<Server>,
519 request: TypedEnvelope<proto::GetChannels>,
520 ) -> tide::Result<()> {
521 let user_id = self
522 .state
523 .read()
524 .await
525 .user_id_for_connection(request.sender_id)?;
526 let channels = self.app_state.db.get_accessible_channels(user_id).await?;
527 self.peer
528 .respond(
529 request.receipt(),
530 proto::GetChannelsResponse {
531 channels: channels
532 .into_iter()
533 .map(|chan| proto::Channel {
534 id: chan.id.to_proto(),
535 name: chan.name,
536 })
537 .collect(),
538 },
539 )
540 .await?;
541 Ok(())
542 }
543
544 async fn get_users(
545 self: Arc<Server>,
546 request: TypedEnvelope<proto::GetUsers>,
547 ) -> tide::Result<()> {
548 let user_id = self
549 .state
550 .read()
551 .await
552 .user_id_for_connection(request.sender_id)?;
553 let receipt = request.receipt();
554 let user_ids = request.payload.user_ids.into_iter().map(UserId::from_proto);
555 let users = self
556 .app_state
557 .db
558 .get_users_by_ids(user_id, user_ids)
559 .await?
560 .into_iter()
561 .map(|user| proto::User {
562 id: user.id.to_proto(),
563 github_login: user.github_login,
564 avatar_url: String::new(),
565 })
566 .collect();
567 self.peer
568 .respond(receipt, proto::GetUsersResponse { users })
569 .await?;
570 Ok(())
571 }
572
573 async fn join_channel(
574 self: Arc<Self>,
575 request: TypedEnvelope<proto::JoinChannel>,
576 ) -> tide::Result<()> {
577 let user_id = self
578 .state
579 .read()
580 .await
581 .user_id_for_connection(request.sender_id)?;
582 let channel_id = ChannelId::from_proto(request.payload.channel_id);
583 if !self
584 .app_state
585 .db
586 .can_user_access_channel(user_id, channel_id)
587 .await?
588 {
589 Err(anyhow!("access denied"))?;
590 }
591
592 self.state
593 .write()
594 .await
595 .join_channel(request.sender_id, channel_id);
596 let messages = self
597 .app_state
598 .db
599 .get_channel_messages(channel_id, MESSAGE_COUNT_PER_PAGE, None)
600 .await?
601 .into_iter()
602 .map(|msg| proto::ChannelMessage {
603 id: msg.id.to_proto(),
604 body: msg.body,
605 timestamp: msg.sent_at.unix_timestamp() as u64,
606 sender_id: msg.sender_id.to_proto(),
607 })
608 .collect::<Vec<_>>();
609 self.peer
610 .respond(
611 request.receipt(),
612 proto::JoinChannelResponse {
613 done: messages.len() < MESSAGE_COUNT_PER_PAGE,
614 messages,
615 },
616 )
617 .await?;
618 Ok(())
619 }
620
621 async fn leave_channel(
622 self: Arc<Self>,
623 request: TypedEnvelope<proto::LeaveChannel>,
624 ) -> tide::Result<()> {
625 let user_id = self
626 .state
627 .read()
628 .await
629 .user_id_for_connection(request.sender_id)?;
630 let channel_id = ChannelId::from_proto(request.payload.channel_id);
631 if !self
632 .app_state
633 .db
634 .can_user_access_channel(user_id, channel_id)
635 .await?
636 {
637 Err(anyhow!("access denied"))?;
638 }
639
640 self.state
641 .write()
642 .await
643 .leave_channel(request.sender_id, channel_id);
644
645 Ok(())
646 }
647
648 async fn send_channel_message(
649 self: Arc<Self>,
650 request: TypedEnvelope<proto::SendChannelMessage>,
651 ) -> tide::Result<()> {
652 let receipt = request.receipt();
653 let channel_id = ChannelId::from_proto(request.payload.channel_id);
654 let user_id;
655 let connection_ids;
656 {
657 let state = self.state.read().await;
658 user_id = state.user_id_for_connection(request.sender_id)?;
659 if let Some(channel) = state.channels.get(&channel_id) {
660 connection_ids = channel.connection_ids();
661 } else {
662 return Ok(());
663 }
664 }
665
666 // Validate the message body.
667 let body = request.payload.body.trim().to_string();
668 if body.len() > MAX_MESSAGE_LEN {
669 self.peer
670 .respond_with_error(
671 receipt,
672 proto::Error {
673 message: "message is too long".to_string(),
674 },
675 )
676 .await?;
677 return Ok(());
678 }
679 if body.is_empty() {
680 self.peer
681 .respond_with_error(
682 receipt,
683 proto::Error {
684 message: "message can't be blank".to_string(),
685 },
686 )
687 .await?;
688 return Ok(());
689 }
690
691 let timestamp = OffsetDateTime::now_utc();
692 let message_id = self
693 .app_state
694 .db
695 .create_channel_message(channel_id, user_id, &body, timestamp)
696 .await?
697 .to_proto();
698 let message = proto::ChannelMessageSent {
699 channel_id: channel_id.to_proto(),
700 message: Some(proto::ChannelMessage {
701 sender_id: user_id.to_proto(),
702 id: message_id,
703 body,
704 timestamp: timestamp.unix_timestamp() as u64,
705 }),
706 };
707 broadcast(request.sender_id, connection_ids, |conn_id| {
708 self.peer.send(conn_id, message.clone())
709 })
710 .await?;
711 self.peer
712 .respond(
713 receipt,
714 proto::SendChannelMessageResponse {
715 message_id,
716 timestamp: timestamp.unix_timestamp() as u64,
717 },
718 )
719 .await?;
720 Ok(())
721 }
722
723 async fn get_channel_messages(
724 self: Arc<Self>,
725 request: TypedEnvelope<proto::GetChannelMessages>,
726 ) -> tide::Result<()> {
727 let user_id = self
728 .state
729 .read()
730 .await
731 .user_id_for_connection(request.sender_id)?;
732 let channel_id = ChannelId::from_proto(request.payload.channel_id);
733 if !self
734 .app_state
735 .db
736 .can_user_access_channel(user_id, channel_id)
737 .await?
738 {
739 Err(anyhow!("access denied"))?;
740 }
741
742 let messages = self
743 .app_state
744 .db
745 .get_channel_messages(
746 channel_id,
747 MESSAGE_COUNT_PER_PAGE,
748 Some(MessageId::from_proto(request.payload.before_message_id)),
749 )
750 .await?
751 .into_iter()
752 .map(|msg| proto::ChannelMessage {
753 id: msg.id.to_proto(),
754 body: msg.body,
755 timestamp: msg.sent_at.unix_timestamp() as u64,
756 sender_id: msg.sender_id.to_proto(),
757 })
758 .collect::<Vec<_>>();
759 self.peer
760 .respond(
761 request.receipt(),
762 proto::GetChannelMessagesResponse {
763 done: messages.len() < MESSAGE_COUNT_PER_PAGE,
764 messages,
765 },
766 )
767 .await?;
768 Ok(())
769 }
770
771 async fn broadcast_in_worktree<T: proto::EnvelopedMessage>(
772 &self,
773 worktree_id: u64,
774 message: &TypedEnvelope<T>,
775 ) -> tide::Result<()> {
776 let connection_ids = self
777 .state
778 .read()
779 .await
780 .read_worktree(worktree_id, message.sender_id)?
781 .connection_ids();
782
783 broadcast(message.sender_id, connection_ids, |conn_id| {
784 self.peer
785 .forward_send(message.sender_id, conn_id, message.payload.clone())
786 })
787 .await?;
788
789 Ok(())
790 }
791}
792
793pub async fn broadcast<F, T>(
794 sender_id: ConnectionId,
795 receiver_ids: Vec<ConnectionId>,
796 mut f: F,
797) -> anyhow::Result<()>
798where
799 F: FnMut(ConnectionId) -> T,
800 T: Future<Output = anyhow::Result<()>>,
801{
802 let futures = receiver_ids
803 .into_iter()
804 .filter(|id| *id != sender_id)
805 .map(|id| f(id));
806 futures::future::try_join_all(futures).await?;
807 Ok(())
808}
809
810impl ServerState {
811 fn join_channel(&mut self, connection_id: ConnectionId, channel_id: ChannelId) {
812 if let Some(connection) = self.connections.get_mut(&connection_id) {
813 connection.channels.insert(channel_id);
814 self.channels
815 .entry(channel_id)
816 .or_default()
817 .connection_ids
818 .insert(connection_id);
819 }
820 }
821
822 fn leave_channel(&mut self, connection_id: ConnectionId, channel_id: ChannelId) {
823 if let Some(connection) = self.connections.get_mut(&connection_id) {
824 connection.channels.remove(&channel_id);
825 if let hash_map::Entry::Occupied(mut entry) = self.channels.entry(channel_id) {
826 entry.get_mut().connection_ids.remove(&connection_id);
827 if entry.get_mut().connection_ids.is_empty() {
828 entry.remove();
829 }
830 }
831 }
832 }
833
834 fn user_id_for_connection(&self, connection_id: ConnectionId) -> tide::Result<UserId> {
835 Ok(self
836 .connections
837 .get(&connection_id)
838 .ok_or_else(|| anyhow!("unknown connection"))?
839 .user_id)
840 }
841
842 // Add the given connection as a guest of the given worktree
843 fn join_worktree(
844 &mut self,
845 connection_id: ConnectionId,
846 worktree_id: u64,
847 access_token: &str,
848 ) -> Option<(ReplicaId, &Worktree)> {
849 if let Some(worktree) = self.worktrees.get_mut(&worktree_id) {
850 if access_token == worktree.access_token {
851 if let Some(connection) = self.connections.get_mut(&connection_id) {
852 connection.worktrees.insert(worktree_id);
853 }
854
855 let mut replica_id = 1;
856 while worktree.active_replica_ids.contains(&replica_id) {
857 replica_id += 1;
858 }
859 worktree.active_replica_ids.insert(replica_id);
860 worktree
861 .guest_connection_ids
862 .insert(connection_id, replica_id);
863 Some((replica_id, worktree))
864 } else {
865 None
866 }
867 } else {
868 None
869 }
870 }
871
872 fn read_worktree(
873 &self,
874 worktree_id: u64,
875 connection_id: ConnectionId,
876 ) -> tide::Result<&Worktree> {
877 let worktree = self
878 .worktrees
879 .get(&worktree_id)
880 .ok_or_else(|| anyhow!("worktree not found"))?;
881
882 if worktree.host_connection_id == Some(connection_id)
883 || worktree.guest_connection_ids.contains_key(&connection_id)
884 {
885 Ok(worktree)
886 } else {
887 Err(anyhow!(
888 "{} is not a member of worktree {}",
889 connection_id,
890 worktree_id
891 ))?
892 }
893 }
894
895 fn write_worktree(
896 &mut self,
897 worktree_id: u64,
898 connection_id: ConnectionId,
899 ) -> tide::Result<&mut Worktree> {
900 let worktree = self
901 .worktrees
902 .get_mut(&worktree_id)
903 .ok_or_else(|| anyhow!("worktree not found"))?;
904
905 if worktree.host_connection_id == Some(connection_id)
906 || worktree.guest_connection_ids.contains_key(&connection_id)
907 {
908 Ok(worktree)
909 } else {
910 Err(anyhow!(
911 "{} is not a member of worktree {}",
912 connection_id,
913 worktree_id
914 ))?
915 }
916 }
917}
918
919impl Worktree {
920 pub fn connection_ids(&self) -> Vec<ConnectionId> {
921 self.guest_connection_ids
922 .keys()
923 .copied()
924 .chain(self.host_connection_id)
925 .collect()
926 }
927
928 fn host_connection_id(&self) -> tide::Result<ConnectionId> {
929 Ok(self
930 .host_connection_id
931 .ok_or_else(|| anyhow!("host disconnected from worktree"))?)
932 }
933}
934
935impl Channel {
936 fn connection_ids(&self) -> Vec<ConnectionId> {
937 self.connection_ids.iter().copied().collect()
938 }
939}
940
941pub fn add_routes(app: &mut tide::Server<Arc<AppState>>, rpc: &Arc<Peer>) {
942 let server = Server::new(app.state().clone(), rpc.clone(), None);
943 app.at("/rpc").with(auth::VerifyToken).get(move |request: Request<Arc<AppState>>| {
944 let user_id = request.ext::<UserId>().copied();
945 let server = server.clone();
946 async move {
947 const WEBSOCKET_GUID: &str = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
948
949 let connection_upgrade = header_contains_ignore_case(&request, CONNECTION, "upgrade");
950 let upgrade_to_websocket = header_contains_ignore_case(&request, UPGRADE, "websocket");
951 let upgrade_requested = connection_upgrade && upgrade_to_websocket;
952
953 if !upgrade_requested {
954 return Ok(Response::new(StatusCode::UpgradeRequired));
955 }
956
957 let header = match request.header("Sec-Websocket-Key") {
958 Some(h) => h.as_str(),
959 None => return Err(anyhow!("expected sec-websocket-key"))?,
960 };
961
962 let mut response = Response::new(StatusCode::SwitchingProtocols);
963 response.insert_header(UPGRADE, "websocket");
964 response.insert_header(CONNECTION, "Upgrade");
965 let hash = Sha1::new().chain(header).chain(WEBSOCKET_GUID).finalize();
966 response.insert_header("Sec-Websocket-Accept", base64::encode(&hash[..]));
967 response.insert_header("Sec-Websocket-Version", "13");
968
969 let http_res: &mut tide::http::Response = response.as_mut();
970 let upgrade_receiver = http_res.recv_upgrade().await;
971 let addr = request.remote().unwrap_or("unknown").to_string();
972 let user_id = user_id.ok_or_else(|| anyhow!("user_id is not present on request. ensure auth::VerifyToken middleware is present"))?;
973 task::spawn(async move {
974 if let Some(stream) = upgrade_receiver.await {
975 let stream = WebSocketStream::from_raw_socket(stream, Role::Server, None).await;
976 server.handle_connection(stream, addr, user_id).await;
977 }
978 });
979
980 Ok(response)
981 }
982 });
983}
984
985fn header_contains_ignore_case<T>(
986 request: &tide::Request<T>,
987 header_name: HeaderName,
988 value: &str,
989) -> bool {
990 request
991 .header(header_name)
992 .map(|h| {
993 h.as_str()
994 .split(',')
995 .any(|s| s.trim().eq_ignore_ascii_case(value.trim()))
996 })
997 .unwrap_or(false)
998}
999
1000#[cfg(test)]
1001mod tests {
1002 use super::*;
1003 use crate::{
1004 auth,
1005 db::{tests::TestDb, UserId},
1006 github, AppState, Config,
1007 };
1008 use async_std::{sync::RwLockReadGuard, task};
1009 use gpui::TestAppContext;
1010 use postage::mpsc;
1011 use serde_json::json;
1012 use sqlx::types::time::OffsetDateTime;
1013 use std::{path::Path, sync::Arc, time::Duration};
1014 use zed::{
1015 channel::{Channel, ChannelDetails, ChannelList},
1016 editor::{Editor, Insert},
1017 fs::{FakeFs, Fs as _},
1018 language::LanguageRegistry,
1019 rpc::Client,
1020 settings, test,
1021 user::UserStore,
1022 worktree::Worktree,
1023 };
1024 use zrpc::Peer;
1025
1026 #[gpui::test]
1027 async fn test_share_worktree(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1028 let (window_b, _) = cx_b.add_window(|_| EmptyView);
1029 let settings = cx_b.read(settings::test).1;
1030 let lang_registry = Arc::new(LanguageRegistry::new());
1031
1032 // Connect to a server as 2 clients.
1033 let mut server = TestServer::start().await;
1034 let (_, client_a) = server.create_client(&mut cx_a, "user_a").await;
1035 let (_, client_b) = server.create_client(&mut cx_b, "user_b").await;
1036
1037 cx_a.foreground().forbid_parking();
1038
1039 // Share a local worktree as client A
1040 let fs = Arc::new(FakeFs::new());
1041 fs.insert_tree(
1042 "/a",
1043 json!({
1044 "a.txt": "a-contents",
1045 "b.txt": "b-contents",
1046 }),
1047 )
1048 .await;
1049 let worktree_a = Worktree::open_local(
1050 "/a".as_ref(),
1051 lang_registry.clone(),
1052 fs,
1053 &mut cx_a.to_async(),
1054 )
1055 .await
1056 .unwrap();
1057 worktree_a
1058 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1059 .await;
1060 let (worktree_id, worktree_token) = worktree_a
1061 .update(&mut cx_a, |tree, cx| {
1062 tree.as_local_mut().unwrap().share(client_a.clone(), cx)
1063 })
1064 .await
1065 .unwrap();
1066
1067 // Join that worktree as client B, and see that a guest has joined as client A.
1068 let worktree_b = Worktree::open_remote(
1069 client_b.clone(),
1070 worktree_id,
1071 worktree_token,
1072 lang_registry.clone(),
1073 &mut cx_b.to_async(),
1074 )
1075 .await
1076 .unwrap();
1077 let replica_id_b = worktree_b.read_with(&cx_b, |tree, _| tree.replica_id());
1078 worktree_a
1079 .condition(&cx_a, |tree, _| {
1080 tree.peers()
1081 .values()
1082 .any(|replica_id| *replica_id == replica_id_b)
1083 })
1084 .await;
1085
1086 // Open the same file as client B and client A.
1087 let buffer_b = worktree_b
1088 .update(&mut cx_b, |worktree, cx| worktree.open_buffer("b.txt", cx))
1089 .await
1090 .unwrap();
1091 buffer_b.read_with(&cx_b, |buf, _| assert_eq!(buf.text(), "b-contents"));
1092 worktree_a.read_with(&cx_a, |tree, cx| assert!(tree.has_open_buffer("b.txt", cx)));
1093 let buffer_a = worktree_a
1094 .update(&mut cx_a, |tree, cx| tree.open_buffer("b.txt", cx))
1095 .await
1096 .unwrap();
1097
1098 // Create a selection set as client B and see that selection set as client A.
1099 let editor_b = cx_b.add_view(window_b, |cx| Editor::for_buffer(buffer_b, settings, cx));
1100 buffer_a
1101 .condition(&cx_a, |buffer, _| buffer.selection_sets().count() == 1)
1102 .await;
1103
1104 // Edit the buffer as client B and see that edit as client A.
1105 editor_b.update(&mut cx_b, |editor, cx| {
1106 editor.insert(&Insert("ok, ".into()), cx)
1107 });
1108 buffer_a
1109 .condition(&cx_a, |buffer, _| buffer.text() == "ok, b-contents")
1110 .await;
1111
1112 // Remove the selection set as client B, see those selections disappear as client A.
1113 cx_b.update(move |_| drop(editor_b));
1114 buffer_a
1115 .condition(&cx_a, |buffer, _| buffer.selection_sets().count() == 0)
1116 .await;
1117
1118 // Close the buffer as client A, see that the buffer is closed.
1119 drop(buffer_a);
1120 worktree_a
1121 .condition(&cx_a, |tree, cx| !tree.has_open_buffer("b.txt", cx))
1122 .await;
1123
1124 // Dropping the worktree removes client B from client A's peers.
1125 cx_b.update(move |_| drop(worktree_b));
1126 worktree_a
1127 .condition(&cx_a, |tree, _| tree.peers().is_empty())
1128 .await;
1129 }
1130
1131 #[gpui::test]
1132 async fn test_propagate_saves_and_fs_changes_in_shared_worktree(
1133 mut cx_a: TestAppContext,
1134 mut cx_b: TestAppContext,
1135 mut cx_c: TestAppContext,
1136 ) {
1137 cx_a.foreground().forbid_parking();
1138 let lang_registry = Arc::new(LanguageRegistry::new());
1139
1140 // Connect to a server as 3 clients.
1141 let mut server = TestServer::start().await;
1142 let (_, client_a) = server.create_client(&mut cx_a, "user_a").await;
1143 let (_, client_b) = server.create_client(&mut cx_b, "user_b").await;
1144 let (_, client_c) = server.create_client(&mut cx_c, "user_c").await;
1145
1146 let fs = Arc::new(FakeFs::new());
1147
1148 // Share a worktree as client A.
1149 fs.insert_tree(
1150 "/a",
1151 json!({
1152 "file1": "",
1153 "file2": ""
1154 }),
1155 )
1156 .await;
1157
1158 let worktree_a = Worktree::open_local(
1159 "/a".as_ref(),
1160 lang_registry.clone(),
1161 fs.clone(),
1162 &mut cx_a.to_async(),
1163 )
1164 .await
1165 .unwrap();
1166 worktree_a
1167 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1168 .await;
1169 let (worktree_id, worktree_token) = worktree_a
1170 .update(&mut cx_a, |tree, cx| {
1171 tree.as_local_mut().unwrap().share(client_a.clone(), cx)
1172 })
1173 .await
1174 .unwrap();
1175
1176 // Join that worktree as clients B and C.
1177 let worktree_b = Worktree::open_remote(
1178 client_b.clone(),
1179 worktree_id,
1180 worktree_token.clone(),
1181 lang_registry.clone(),
1182 &mut cx_b.to_async(),
1183 )
1184 .await
1185 .unwrap();
1186 let worktree_c = Worktree::open_remote(
1187 client_c.clone(),
1188 worktree_id,
1189 worktree_token,
1190 lang_registry.clone(),
1191 &mut cx_c.to_async(),
1192 )
1193 .await
1194 .unwrap();
1195
1196 // Open and edit a buffer as both guests B and C.
1197 let buffer_b = worktree_b
1198 .update(&mut cx_b, |tree, cx| tree.open_buffer("file1", cx))
1199 .await
1200 .unwrap();
1201 let buffer_c = worktree_c
1202 .update(&mut cx_c, |tree, cx| tree.open_buffer("file1", cx))
1203 .await
1204 .unwrap();
1205 buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "i-am-b, ", cx));
1206 buffer_c.update(&mut cx_c, |buf, cx| buf.edit([0..0], "i-am-c, ", cx));
1207
1208 // Open and edit that buffer as the host.
1209 let buffer_a = worktree_a
1210 .update(&mut cx_a, |tree, cx| tree.open_buffer("file1", cx))
1211 .await
1212 .unwrap();
1213
1214 buffer_a
1215 .condition(&mut cx_a, |buf, _| buf.text() == "i-am-c, i-am-b, ")
1216 .await;
1217 buffer_a.update(&mut cx_a, |buf, cx| {
1218 buf.edit([buf.len()..buf.len()], "i-am-a", cx)
1219 });
1220
1221 // Wait for edits to propagate
1222 buffer_a
1223 .condition(&mut cx_a, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1224 .await;
1225 buffer_b
1226 .condition(&mut cx_b, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1227 .await;
1228 buffer_c
1229 .condition(&mut cx_c, |buf, _| buf.text() == "i-am-c, i-am-b, i-am-a")
1230 .await;
1231
1232 // Edit the buffer as the host and concurrently save as guest B.
1233 let save_b = buffer_b.update(&mut cx_b, |buf, cx| buf.save(cx).unwrap());
1234 buffer_a.update(&mut cx_a, |buf, cx| buf.edit([0..0], "hi-a, ", cx));
1235 save_b.await.unwrap();
1236 assert_eq!(
1237 fs.load("/a/file1".as_ref()).await.unwrap(),
1238 "hi-a, i-am-c, i-am-b, i-am-a"
1239 );
1240 buffer_a.read_with(&cx_a, |buf, _| assert!(!buf.is_dirty()));
1241 buffer_b.read_with(&cx_b, |buf, _| assert!(!buf.is_dirty()));
1242 buffer_c.condition(&cx_c, |buf, _| !buf.is_dirty()).await;
1243
1244 // Make changes on host's file system, see those changes on the guests.
1245 fs.rename("/a/file2".as_ref(), "/a/file3".as_ref())
1246 .await
1247 .unwrap();
1248 fs.insert_file(Path::new("/a/file4"), "4".into())
1249 .await
1250 .unwrap();
1251
1252 worktree_b
1253 .condition(&cx_b, |tree, _| tree.file_count() == 3)
1254 .await;
1255 worktree_c
1256 .condition(&cx_c, |tree, _| tree.file_count() == 3)
1257 .await;
1258 worktree_b.read_with(&cx_b, |tree, _| {
1259 assert_eq!(
1260 tree.paths()
1261 .map(|p| p.to_string_lossy())
1262 .collect::<Vec<_>>(),
1263 &["file1", "file3", "file4"]
1264 )
1265 });
1266 worktree_c.read_with(&cx_c, |tree, _| {
1267 assert_eq!(
1268 tree.paths()
1269 .map(|p| p.to_string_lossy())
1270 .collect::<Vec<_>>(),
1271 &["file1", "file3", "file4"]
1272 )
1273 });
1274 }
1275
1276 #[gpui::test]
1277 async fn test_buffer_conflict_after_save(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1278 cx_a.foreground().forbid_parking();
1279 let lang_registry = Arc::new(LanguageRegistry::new());
1280
1281 // Connect to a server as 2 clients.
1282 let mut server = TestServer::start().await;
1283 let (_, client_a) = server.create_client(&mut cx_a, "user_a").await;
1284 let (_, client_b) = server.create_client(&mut cx_b, "user_b").await;
1285
1286 // Share a local worktree as client A
1287 let fs = Arc::new(FakeFs::new());
1288 fs.save(Path::new("/a.txt"), &"a-contents".into())
1289 .await
1290 .unwrap();
1291 let worktree_a = Worktree::open_local(
1292 "/".as_ref(),
1293 lang_registry.clone(),
1294 fs,
1295 &mut cx_a.to_async(),
1296 )
1297 .await
1298 .unwrap();
1299 worktree_a
1300 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1301 .await;
1302 let (worktree_id, worktree_token) = worktree_a
1303 .update(&mut cx_a, |tree, cx| {
1304 tree.as_local_mut().unwrap().share(client_a.clone(), cx)
1305 })
1306 .await
1307 .unwrap();
1308
1309 // Join that worktree as client B, and see that a guest has joined as client A.
1310 let worktree_b = Worktree::open_remote(
1311 client_b.clone(),
1312 worktree_id,
1313 worktree_token,
1314 lang_registry.clone(),
1315 &mut cx_b.to_async(),
1316 )
1317 .await
1318 .unwrap();
1319
1320 let buffer_b = worktree_b
1321 .update(&mut cx_b, |worktree, cx| worktree.open_buffer("a.txt", cx))
1322 .await
1323 .unwrap();
1324 let mtime = buffer_b.read_with(&cx_b, |buf, _| buf.file().unwrap().mtime);
1325
1326 buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "world ", cx));
1327 buffer_b.read_with(&cx_b, |buf, _| {
1328 assert!(buf.is_dirty());
1329 assert!(!buf.has_conflict());
1330 });
1331
1332 buffer_b
1333 .update(&mut cx_b, |buf, cx| buf.save(cx))
1334 .unwrap()
1335 .await
1336 .unwrap();
1337 worktree_b
1338 .condition(&cx_b, |_, cx| {
1339 buffer_b.read(cx).file().unwrap().mtime != mtime
1340 })
1341 .await;
1342 buffer_b.read_with(&cx_b, |buf, _| {
1343 assert!(!buf.is_dirty());
1344 assert!(!buf.has_conflict());
1345 });
1346
1347 buffer_b.update(&mut cx_b, |buf, cx| buf.edit([0..0], "hello ", cx));
1348 buffer_b.read_with(&cx_b, |buf, _| {
1349 assert!(buf.is_dirty());
1350 assert!(!buf.has_conflict());
1351 });
1352 }
1353
1354 #[gpui::test]
1355 async fn test_editing_while_guest_opens_buffer(
1356 mut cx_a: TestAppContext,
1357 mut cx_b: TestAppContext,
1358 ) {
1359 cx_a.foreground().forbid_parking();
1360 let lang_registry = Arc::new(LanguageRegistry::new());
1361
1362 // Connect to a server as 2 clients.
1363 let mut server = TestServer::start().await;
1364 let (_, client_a) = server.create_client(&mut cx_a, "user_a").await;
1365 let (_, client_b) = server.create_client(&mut cx_b, "user_b").await;
1366
1367 // Share a local worktree as client A
1368 let fs = Arc::new(FakeFs::new());
1369 fs.save(Path::new("/a.txt"), &"a-contents".into())
1370 .await
1371 .unwrap();
1372 let worktree_a = Worktree::open_local(
1373 "/".as_ref(),
1374 lang_registry.clone(),
1375 fs,
1376 &mut cx_a.to_async(),
1377 )
1378 .await
1379 .unwrap();
1380 worktree_a
1381 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1382 .await;
1383 let (worktree_id, worktree_token) = worktree_a
1384 .update(&mut cx_a, |tree, cx| {
1385 tree.as_local_mut().unwrap().share(client_a.clone(), cx)
1386 })
1387 .await
1388 .unwrap();
1389
1390 // Join that worktree as client B, and see that a guest has joined as client A.
1391 let worktree_b = Worktree::open_remote(
1392 client_b.clone(),
1393 worktree_id,
1394 worktree_token,
1395 lang_registry.clone(),
1396 &mut cx_b.to_async(),
1397 )
1398 .await
1399 .unwrap();
1400
1401 let buffer_a = worktree_a
1402 .update(&mut cx_a, |tree, cx| tree.open_buffer("a.txt", cx))
1403 .await
1404 .unwrap();
1405 let buffer_b = cx_b
1406 .background()
1407 .spawn(worktree_b.update(&mut cx_b, |worktree, cx| worktree.open_buffer("a.txt", cx)));
1408
1409 task::yield_now().await;
1410 buffer_a.update(&mut cx_a, |buf, cx| buf.edit([0..0], "z", cx));
1411
1412 let text = buffer_a.read_with(&cx_a, |buf, _| buf.text());
1413 let buffer_b = buffer_b.await.unwrap();
1414 buffer_b.condition(&cx_b, |buf, _| buf.text() == text).await;
1415 }
1416
1417 #[gpui::test]
1418 async fn test_peer_disconnection(mut cx_a: TestAppContext, cx_b: TestAppContext) {
1419 cx_a.foreground().forbid_parking();
1420 let lang_registry = Arc::new(LanguageRegistry::new());
1421
1422 // Connect to a server as 2 clients.
1423 let mut server = TestServer::start().await;
1424 let (_, client_a) = server.create_client(&mut cx_a, "user_a").await;
1425 let (_, client_b) = server.create_client(&mut cx_a, "user_b").await;
1426
1427 // Share a local worktree as client A
1428 let fs = Arc::new(FakeFs::new());
1429 fs.insert_tree(
1430 "/a",
1431 json!({
1432 "a.txt": "a-contents",
1433 "b.txt": "b-contents",
1434 }),
1435 )
1436 .await;
1437 let worktree_a = Worktree::open_local(
1438 "/a".as_ref(),
1439 lang_registry.clone(),
1440 fs,
1441 &mut cx_a.to_async(),
1442 )
1443 .await
1444 .unwrap();
1445 worktree_a
1446 .read_with(&cx_a, |tree, _| tree.as_local().unwrap().scan_complete())
1447 .await;
1448 let (worktree_id, worktree_token) = worktree_a
1449 .update(&mut cx_a, |tree, cx| {
1450 tree.as_local_mut().unwrap().share(client_a.clone(), cx)
1451 })
1452 .await
1453 .unwrap();
1454
1455 // Join that worktree as client B, and see that a guest has joined as client A.
1456 let _worktree_b = Worktree::open_remote(
1457 client_b.clone(),
1458 worktree_id,
1459 worktree_token,
1460 lang_registry.clone(),
1461 &mut cx_b.to_async(),
1462 )
1463 .await
1464 .unwrap();
1465 worktree_a
1466 .condition(&cx_a, |tree, _| tree.peers().len() == 1)
1467 .await;
1468
1469 // Drop client B's connection and ensure client A observes client B leaving the worktree.
1470 client_b.disconnect().await.unwrap();
1471 worktree_a
1472 .condition(&cx_a, |tree, _| tree.peers().len() == 0)
1473 .await;
1474 }
1475
1476 #[gpui::test]
1477 async fn test_basic_chat(mut cx_a: TestAppContext, mut cx_b: TestAppContext) {
1478 cx_a.foreground().forbid_parking();
1479
1480 // Connect to a server as 2 clients.
1481 let mut server = TestServer::start().await;
1482 let (user_id_a, client_a) = server.create_client(&mut cx_a, "user_a").await;
1483 let (user_id_b, client_b) = server.create_client(&mut cx_b, "user_b").await;
1484
1485 // Create an org that includes these 2 users.
1486 let db = &server.app_state.db;
1487 let org_id = db.create_org("Test Org", "test-org").await.unwrap();
1488 db.add_org_member(org_id, user_id_a, false).await.unwrap();
1489 db.add_org_member(org_id, user_id_b, false).await.unwrap();
1490
1491 // Create a channel that includes all the users.
1492 let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
1493 db.add_channel_member(channel_id, user_id_a, false)
1494 .await
1495 .unwrap();
1496 db.add_channel_member(channel_id, user_id_b, false)
1497 .await
1498 .unwrap();
1499 db.create_channel_message(
1500 channel_id,
1501 user_id_b,
1502 "hello A, it's B.",
1503 OffsetDateTime::now_utc(),
1504 )
1505 .await
1506 .unwrap();
1507
1508 let user_store_a = Arc::new(UserStore::new(client_a.clone()));
1509 let channels_a = cx_a.add_model(|cx| ChannelList::new(user_store_a, client_a, cx));
1510 channels_a
1511 .condition(&mut cx_a, |list, _| list.available_channels().is_some())
1512 .await;
1513 channels_a.read_with(&cx_a, |list, _| {
1514 assert_eq!(
1515 list.available_channels().unwrap(),
1516 &[ChannelDetails {
1517 id: channel_id.to_proto(),
1518 name: "test-channel".to_string()
1519 }]
1520 )
1521 });
1522 let channel_a = channels_a.update(&mut cx_a, |this, cx| {
1523 this.get_channel(channel_id.to_proto(), cx).unwrap()
1524 });
1525 channel_a.read_with(&cx_a, |channel, _| assert!(channel.messages().is_empty()));
1526 channel_a
1527 .condition(&cx_a, |channel, _| {
1528 channel_messages(channel)
1529 == [("user_b".to_string(), "hello A, it's B.".to_string())]
1530 })
1531 .await;
1532
1533 let user_store_b = Arc::new(UserStore::new(client_b.clone()));
1534 let channels_b = cx_b.add_model(|cx| ChannelList::new(user_store_b, client_b, cx));
1535 channels_b
1536 .condition(&mut cx_b, |list, _| list.available_channels().is_some())
1537 .await;
1538 channels_b.read_with(&cx_b, |list, _| {
1539 assert_eq!(
1540 list.available_channels().unwrap(),
1541 &[ChannelDetails {
1542 id: channel_id.to_proto(),
1543 name: "test-channel".to_string()
1544 }]
1545 )
1546 });
1547
1548 let channel_b = channels_b.update(&mut cx_b, |this, cx| {
1549 this.get_channel(channel_id.to_proto(), cx).unwrap()
1550 });
1551 channel_b.read_with(&cx_b, |channel, _| assert!(channel.messages().is_empty()));
1552 channel_b
1553 .condition(&cx_b, |channel, _| {
1554 channel_messages(channel)
1555 == [("user_b".to_string(), "hello A, it's B.".to_string())]
1556 })
1557 .await;
1558
1559 channel_a
1560 .update(&mut cx_a, |channel, cx| {
1561 channel
1562 .send_message("oh, hi B.".to_string(), cx)
1563 .unwrap()
1564 .detach();
1565 let task = channel.send_message("sup".to_string(), cx).unwrap();
1566 assert_eq!(
1567 channel
1568 .pending_messages()
1569 .iter()
1570 .map(|m| &m.body)
1571 .collect::<Vec<_>>(),
1572 &["oh, hi B.", "sup"]
1573 );
1574 task
1575 })
1576 .await
1577 .unwrap();
1578
1579 channel_a
1580 .condition(&cx_a, |channel, _| channel.pending_messages().is_empty())
1581 .await;
1582 channel_b
1583 .condition(&cx_b, |channel, _| {
1584 channel_messages(channel)
1585 == [
1586 ("user_b".to_string(), "hello A, it's B.".to_string()),
1587 ("user_a".to_string(), "oh, hi B.".to_string()),
1588 ("user_a".to_string(), "sup".to_string()),
1589 ]
1590 })
1591 .await;
1592
1593 assert_eq!(
1594 server.state().await.channels[&channel_id]
1595 .connection_ids
1596 .len(),
1597 2
1598 );
1599 cx_b.update(|_| drop(channel_b));
1600 server
1601 .condition(|state| state.channels[&channel_id].connection_ids.len() == 1)
1602 .await;
1603
1604 cx_a.update(|_| drop(channel_a));
1605 server
1606 .condition(|state| !state.channels.contains_key(&channel_id))
1607 .await;
1608
1609 fn channel_messages(channel: &Channel) -> Vec<(String, String)> {
1610 channel
1611 .messages()
1612 .cursor::<(), ()>()
1613 .map(|m| (m.sender.github_login.clone(), m.body.clone()))
1614 .collect()
1615 }
1616 }
1617
1618 #[gpui::test]
1619 async fn test_chat_message_validation(mut cx_a: TestAppContext) {
1620 cx_a.foreground().forbid_parking();
1621
1622 let mut server = TestServer::start().await;
1623 let (user_id_a, client_a) = server.create_client(&mut cx_a, "user_a").await;
1624
1625 let db = &server.app_state.db;
1626 let org_id = db.create_org("Test Org", "test-org").await.unwrap();
1627 let channel_id = db.create_org_channel(org_id, "test-channel").await.unwrap();
1628 db.add_org_member(org_id, user_id_a, false).await.unwrap();
1629 db.add_channel_member(channel_id, user_id_a, false)
1630 .await
1631 .unwrap();
1632
1633 let user_store_a = Arc::new(UserStore::new(client_a.clone()));
1634 let channels_a = cx_a.add_model(|cx| ChannelList::new(user_store_a, client_a, cx));
1635 channels_a
1636 .condition(&mut cx_a, |list, _| list.available_channels().is_some())
1637 .await;
1638 let channel_a = channels_a.update(&mut cx_a, |this, cx| {
1639 this.get_channel(channel_id.to_proto(), cx).unwrap()
1640 });
1641
1642 // Messages aren't allowed to be too long.
1643 channel_a
1644 .update(&mut cx_a, |channel, cx| {
1645 let long_body = "this is long.\n".repeat(1024);
1646 channel.send_message(long_body, cx).unwrap()
1647 })
1648 .await
1649 .unwrap_err();
1650
1651 // Messages aren't allowed to be blank.
1652 channel_a
1653 .update(&mut cx_a, |channel, cx| {
1654 channel.send_message(String::new(), cx).unwrap()
1655 })
1656 .await
1657 .unwrap_err();
1658
1659 // Leading and trailing whitespace are trimmed.
1660 channel_a
1661 .update(&mut cx_a, |channel, cx| {
1662 channel
1663 .send_message("\n surrounded by whitespace \n".to_string(), cx)
1664 .unwrap()
1665 })
1666 .await
1667 .unwrap();
1668 assert_eq!(
1669 db.get_channel_messages(channel_id, 10, None)
1670 .await
1671 .unwrap()
1672 .iter()
1673 .map(|m| &m.body)
1674 .collect::<Vec<_>>(),
1675 &["surrounded by whitespace"]
1676 );
1677 }
1678
1679 struct TestServer {
1680 peer: Arc<Peer>,
1681 app_state: Arc<AppState>,
1682 server: Arc<Server>,
1683 notifications: mpsc::Receiver<()>,
1684 _test_db: TestDb,
1685 }
1686
1687 impl TestServer {
1688 async fn start() -> Self {
1689 let test_db = TestDb::new();
1690 let app_state = Self::build_app_state(&test_db).await;
1691 let peer = Peer::new();
1692 let notifications = mpsc::channel(128);
1693 let server = Server::new(app_state.clone(), peer.clone(), Some(notifications.0));
1694 Self {
1695 peer,
1696 app_state,
1697 server,
1698 notifications: notifications.1,
1699 _test_db: test_db,
1700 }
1701 }
1702
1703 async fn create_client(
1704 &mut self,
1705 cx: &mut TestAppContext,
1706 name: &str,
1707 ) -> (UserId, Arc<Client>) {
1708 let user_id = self.app_state.db.create_user(name, false).await.unwrap();
1709 let client = Client::new();
1710 let (client_conn, server_conn) = test::Channel::bidirectional();
1711 cx.background()
1712 .spawn(
1713 self.server
1714 .handle_connection(server_conn, name.to_string(), user_id),
1715 )
1716 .detach();
1717 client
1718 .add_connection(user_id.to_proto(), client_conn, cx.to_async())
1719 .await
1720 .unwrap();
1721 (user_id, client)
1722 }
1723
1724 async fn build_app_state(test_db: &TestDb) -> Arc<AppState> {
1725 let mut config = Config::default();
1726 config.session_secret = "a".repeat(32);
1727 config.database_url = test_db.url.clone();
1728 let github_client = github::AppClient::test();
1729 Arc::new(AppState {
1730 db: test_db.db().clone(),
1731 handlebars: Default::default(),
1732 auth_client: auth::build_client("", ""),
1733 repo_client: github::RepoClient::test(&github_client),
1734 github_client,
1735 config,
1736 })
1737 }
1738
1739 async fn state<'a>(&'a self) -> RwLockReadGuard<'a, ServerState> {
1740 self.server.state.read().await
1741 }
1742
1743 async fn condition<F>(&mut self, mut predicate: F)
1744 where
1745 F: FnMut(&ServerState) -> bool,
1746 {
1747 async_std::future::timeout(Duration::from_millis(500), async {
1748 while !(predicate)(&*self.server.state.read().await) {
1749 self.notifications.recv().await;
1750 }
1751 })
1752 .await
1753 .expect("condition timed out");
1754 }
1755 }
1756
1757 impl Drop for TestServer {
1758 fn drop(&mut self) {
1759 task::block_on(self.peer.reset());
1760 }
1761 }
1762
1763 struct EmptyView;
1764
1765 impl gpui::Entity for EmptyView {
1766 type Event = ();
1767 }
1768
1769 impl gpui::View for EmptyView {
1770 fn ui_name() -> &'static str {
1771 "empty view"
1772 }
1773
1774 fn render(&mut self, _: &mut gpui::RenderContext<Self>) -> gpui::ElementBox {
1775 gpui::Element::boxed(gpui::elements::Empty)
1776 }
1777 }
1778}