1use crate::{ErrorCode, ErrorCodeExt, ErrorExt, RpcError};
2
3use super::{
4 proto::{self, AnyTypedEnvelope, EnvelopedMessage, MessageStream, PeerId, RequestMessage},
5 Connection,
6};
7use anyhow::{anyhow, Context, Result};
8use collections::HashMap;
9use futures::{
10 channel::{mpsc, oneshot},
11 stream::BoxStream,
12 FutureExt, SinkExt, Stream, StreamExt, TryFutureExt,
13};
14use parking_lot::{Mutex, RwLock};
15use serde::{ser::SerializeStruct, Serialize};
16use std::{
17 fmt, future,
18 future::Future,
19 marker::PhantomData,
20 sync::atomic::Ordering::SeqCst,
21 sync::{
22 atomic::{self, AtomicU32},
23 Arc,
24 },
25 time::Duration,
26 time::Instant,
27};
28use tracing::instrument;
29
30#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Serialize)]
31pub struct ConnectionId {
32 pub owner_id: u32,
33 pub id: u32,
34}
35
36impl Into<PeerId> for ConnectionId {
37 fn into(self) -> PeerId {
38 PeerId {
39 owner_id: self.owner_id,
40 id: self.id,
41 }
42 }
43}
44
45impl From<PeerId> for ConnectionId {
46 fn from(peer_id: PeerId) -> Self {
47 Self {
48 owner_id: peer_id.owner_id,
49 id: peer_id.id,
50 }
51 }
52}
53
54impl fmt::Display for ConnectionId {
55 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56 write!(f, "{}/{}", self.owner_id, self.id)
57 }
58}
59
60pub struct Receipt<T> {
61 pub sender_id: ConnectionId,
62 pub message_id: u32,
63 payload_type: PhantomData<T>,
64}
65
66impl<T> Clone for Receipt<T> {
67 fn clone(&self) -> Self {
68 *self
69 }
70}
71
72impl<T> Copy for Receipt<T> {}
73
74#[derive(Clone, Debug)]
75pub struct TypedEnvelope<T> {
76 pub sender_id: ConnectionId,
77 pub original_sender_id: Option<PeerId>,
78 pub message_id: u32,
79 pub payload: T,
80 pub received_at: Instant,
81}
82
83impl<T> TypedEnvelope<T> {
84 pub fn original_sender_id(&self) -> Result<PeerId> {
85 self.original_sender_id
86 .ok_or_else(|| anyhow!("missing original_sender_id"))
87 }
88}
89
90impl<T: RequestMessage> TypedEnvelope<T> {
91 pub fn receipt(&self) -> Receipt<T> {
92 Receipt {
93 sender_id: self.sender_id,
94 message_id: self.message_id,
95 payload_type: PhantomData,
96 }
97 }
98}
99
100pub struct Peer {
101 epoch: AtomicU32,
102 pub connections: RwLock<HashMap<ConnectionId, ConnectionState>>,
103 next_connection_id: AtomicU32,
104}
105
106#[derive(Clone, Serialize)]
107pub struct ConnectionState {
108 #[serde(skip)]
109 outgoing_tx: mpsc::UnboundedSender<proto::Message>,
110 next_message_id: Arc<AtomicU32>,
111 #[allow(clippy::type_complexity)]
112 #[serde(skip)]
113 response_channels: Arc<
114 Mutex<
115 Option<
116 HashMap<
117 u32,
118 oneshot::Sender<(proto::Envelope, std::time::Instant, oneshot::Sender<()>)>,
119 >,
120 >,
121 >,
122 >,
123 #[allow(clippy::type_complexity)]
124 #[serde(skip)]
125 stream_response_channels: Arc<
126 Mutex<
127 Option<
128 HashMap<u32, mpsc::UnboundedSender<(Result<proto::Envelope>, oneshot::Sender<()>)>>,
129 >,
130 >,
131 >,
132}
133
134const KEEPALIVE_INTERVAL: Duration = Duration::from_secs(1);
135const WRITE_TIMEOUT: Duration = Duration::from_secs(2);
136pub const RECEIVE_TIMEOUT: Duration = Duration::from_secs(10);
137
138impl Peer {
139 pub fn new(epoch: u32) -> Arc<Self> {
140 Arc::new(Self {
141 epoch: AtomicU32::new(epoch),
142 connections: Default::default(),
143 next_connection_id: Default::default(),
144 })
145 }
146
147 pub fn epoch(&self) -> u32 {
148 self.epoch.load(SeqCst)
149 }
150
151 #[instrument(skip_all)]
152 pub fn add_connection<F, Fut, Out>(
153 self: &Arc<Self>,
154 connection: Connection,
155 create_timer: F,
156 ) -> (
157 ConnectionId,
158 impl Future<Output = anyhow::Result<()>> + Send,
159 BoxStream<'static, Box<dyn AnyTypedEnvelope>>,
160 )
161 where
162 F: Send + Fn(Duration) -> Fut,
163 Fut: Send + Future<Output = Out>,
164 Out: Send,
165 {
166 // For outgoing messages, use an unbounded channel so that application code
167 // can always send messages without yielding. For incoming messages, use a
168 // bounded channel so that other peers will receive backpressure if they send
169 // messages faster than this peer can process them.
170 #[cfg(any(test, feature = "test-support"))]
171 const INCOMING_BUFFER_SIZE: usize = 1;
172 #[cfg(not(any(test, feature = "test-support")))]
173 const INCOMING_BUFFER_SIZE: usize = 256;
174 let (mut incoming_tx, incoming_rx) = mpsc::channel(INCOMING_BUFFER_SIZE);
175 let (outgoing_tx, mut outgoing_rx) = mpsc::unbounded();
176
177 let connection_id = ConnectionId {
178 owner_id: self.epoch.load(SeqCst),
179 id: self.next_connection_id.fetch_add(1, SeqCst),
180 };
181 let connection_state = ConnectionState {
182 outgoing_tx,
183 next_message_id: Default::default(),
184 response_channels: Arc::new(Mutex::new(Some(Default::default()))),
185 stream_response_channels: Arc::new(Mutex::new(Some(Default::default()))),
186 };
187 let mut writer = MessageStream::new(connection.tx);
188 let mut reader = MessageStream::new(connection.rx);
189
190 let this = self.clone();
191 let response_channels = connection_state.response_channels.clone();
192 let stream_response_channels = connection_state.stream_response_channels.clone();
193
194 let handle_io = async move {
195 tracing::trace!(%connection_id, "handle io future: start");
196
197 let _end_connection = util::defer(|| {
198 response_channels.lock().take();
199 if let Some(channels) = stream_response_channels.lock().take() {
200 for channel in channels.values() {
201 let _ = channel.unbounded_send((
202 Err(anyhow!("connection closed")),
203 oneshot::channel().0,
204 ));
205 }
206 }
207 this.connections.write().remove(&connection_id);
208 tracing::trace!(%connection_id, "handle io future: end");
209 });
210
211 // Send messages on this frequency so the connection isn't closed.
212 let keepalive_timer = create_timer(KEEPALIVE_INTERVAL).fuse();
213 futures::pin_mut!(keepalive_timer);
214
215 // Disconnect if we don't receive messages at least this frequently.
216 let receive_timeout = create_timer(RECEIVE_TIMEOUT).fuse();
217 futures::pin_mut!(receive_timeout);
218
219 loop {
220 tracing::trace!(%connection_id, "outer loop iteration start");
221 let read_message = reader.read().fuse();
222 futures::pin_mut!(read_message);
223
224 loop {
225 tracing::trace!(%connection_id, "inner loop iteration start");
226 futures::select_biased! {
227 outgoing = outgoing_rx.next().fuse() => match outgoing {
228 Some(outgoing) => {
229 tracing::trace!(%connection_id, "outgoing rpc message: writing");
230 futures::select_biased! {
231 result = writer.write(outgoing).fuse() => {
232 tracing::trace!(%connection_id, "outgoing rpc message: done writing");
233 result.context("failed to write RPC message")?;
234 tracing::trace!(%connection_id, "keepalive interval: resetting after sending message");
235 keepalive_timer.set(create_timer(KEEPALIVE_INTERVAL).fuse());
236 }
237 _ = create_timer(WRITE_TIMEOUT).fuse() => {
238 tracing::trace!(%connection_id, "outgoing rpc message: writing timed out");
239 Err(anyhow!("timed out writing message"))?;
240 }
241 }
242 }
243 None => {
244 tracing::trace!(%connection_id, "outgoing rpc message: channel closed");
245 return Ok(())
246 },
247 },
248 _ = keepalive_timer => {
249 tracing::trace!(%connection_id, "keepalive interval: pinging");
250 futures::select_biased! {
251 result = writer.write(proto::Message::Ping).fuse() => {
252 tracing::trace!(%connection_id, "keepalive interval: done pinging");
253 result.context("failed to send keepalive")?;
254 tracing::trace!(%connection_id, "keepalive interval: resetting after pinging");
255 keepalive_timer.set(create_timer(KEEPALIVE_INTERVAL).fuse());
256 }
257 _ = create_timer(WRITE_TIMEOUT).fuse() => {
258 tracing::trace!(%connection_id, "keepalive interval: pinging timed out");
259 Err(anyhow!("timed out sending keepalive"))?;
260 }
261 }
262 }
263 incoming = read_message => {
264 let incoming = incoming.context("error reading rpc message from socket")?;
265 tracing::trace!(%connection_id, "incoming rpc message: received");
266 tracing::trace!(%connection_id, "receive timeout: resetting");
267 receive_timeout.set(create_timer(RECEIVE_TIMEOUT).fuse());
268 if let (proto::Message::Envelope(incoming), received_at) = incoming {
269 tracing::trace!(%connection_id, "incoming rpc message: processing");
270 futures::select_biased! {
271 result = incoming_tx.send((incoming, received_at)).fuse() => match result {
272 Ok(_) => {
273 tracing::trace!(%connection_id, "incoming rpc message: processed");
274 }
275 Err(_) => {
276 tracing::trace!(%connection_id, "incoming rpc message: channel closed");
277 return Ok(())
278 }
279 },
280 _ = create_timer(WRITE_TIMEOUT).fuse() => {
281 tracing::trace!(%connection_id, "incoming rpc message: processing timed out");
282 Err(anyhow!("timed out processing incoming message"))?
283 }
284 }
285 }
286 break;
287 },
288 _ = receive_timeout => {
289 tracing::trace!(%connection_id, "receive timeout: delay between messages too long");
290 Err(anyhow!("delay between messages too long"))?
291 }
292 }
293 }
294 }
295 };
296
297 let response_channels = connection_state.response_channels.clone();
298 let stream_response_channels = connection_state.stream_response_channels.clone();
299 self.connections
300 .write()
301 .insert(connection_id, connection_state);
302
303 let incoming_rx = incoming_rx.filter_map(move |(incoming, received_at)| {
304 let response_channels = response_channels.clone();
305 let stream_response_channels = stream_response_channels.clone();
306 async move {
307 let message_id = incoming.id;
308 tracing::trace!(?incoming, "incoming message future: start");
309 let _end = util::defer(move || {
310 tracing::trace!(%connection_id, message_id, "incoming message future: end");
311 });
312
313 if let Some(responding_to) = incoming.responding_to {
314 tracing::trace!(
315 %connection_id,
316 message_id,
317 responding_to,
318 "incoming response: received"
319 );
320 let response_channel =
321 response_channels.lock().as_mut()?.remove(&responding_to);
322 let stream_response_channel = stream_response_channels
323 .lock()
324 .as_ref()?
325 .get(&responding_to)
326 .cloned();
327
328 if let Some(tx) = response_channel {
329 let requester_resumed = oneshot::channel();
330 if let Err(error) = tx.send((incoming, received_at, requester_resumed.0)) {
331 tracing::trace!(
332 %connection_id,
333 message_id,
334 responding_to = responding_to,
335 ?error,
336 "incoming response: request future dropped",
337 );
338 }
339
340 tracing::trace!(
341 %connection_id,
342 message_id,
343 responding_to,
344 "incoming response: waiting to resume requester"
345 );
346 let _ = requester_resumed.1.await;
347 tracing::trace!(
348 %connection_id,
349 message_id,
350 responding_to,
351 "incoming response: requester resumed"
352 );
353 } else if let Some(tx) = stream_response_channel {
354 let requester_resumed = oneshot::channel();
355 if let Err(error) = tx.unbounded_send((Ok(incoming), requester_resumed.0)) {
356 tracing::debug!(
357 %connection_id,
358 message_id,
359 responding_to = responding_to,
360 ?error,
361 "incoming stream response: request future dropped",
362 );
363 }
364
365 tracing::debug!(
366 %connection_id,
367 message_id,
368 responding_to,
369 "incoming stream response: waiting to resume requester"
370 );
371 let _ = requester_resumed.1.await;
372 tracing::debug!(
373 %connection_id,
374 message_id,
375 responding_to,
376 "incoming stream response: requester resumed"
377 );
378 } else {
379 let message_type =
380 proto::build_typed_envelope(connection_id, received_at, incoming)
381 .map(|p| p.payload_type_name());
382 tracing::warn!(
383 %connection_id,
384 message_id,
385 responding_to,
386 message_type,
387 "incoming response: unknown request"
388 );
389 }
390
391 None
392 } else {
393 tracing::trace!(%connection_id, message_id, "incoming message: received");
394 proto::build_typed_envelope(connection_id, received_at, incoming).or_else(
395 || {
396 tracing::error!(
397 %connection_id,
398 message_id,
399 "unable to construct a typed envelope"
400 );
401 None
402 },
403 )
404 }
405 }
406 });
407 (connection_id, handle_io, incoming_rx.boxed())
408 }
409
410 #[cfg(any(test, feature = "test-support"))]
411 pub fn add_test_connection(
412 self: &Arc<Self>,
413 connection: Connection,
414 executor: gpui::BackgroundExecutor,
415 ) -> (
416 ConnectionId,
417 impl Future<Output = anyhow::Result<()>> + Send,
418 BoxStream<'static, Box<dyn AnyTypedEnvelope>>,
419 ) {
420 let executor = executor.clone();
421 self.add_connection(connection, move |duration| executor.timer(duration))
422 }
423
424 pub fn disconnect(&self, connection_id: ConnectionId) {
425 self.connections.write().remove(&connection_id);
426 }
427
428 #[cfg(any(test, feature = "test-support"))]
429 pub fn reset(&self, epoch: u32) {
430 self.next_connection_id.store(0, SeqCst);
431 self.epoch.store(epoch, SeqCst);
432 }
433
434 pub fn teardown(&self) {
435 self.connections.write().clear();
436 }
437
438 pub fn request<T: RequestMessage>(
439 &self,
440 receiver_id: ConnectionId,
441 request: T,
442 ) -> impl Future<Output = Result<T::Response>> {
443 self.request_internal(None, receiver_id, request)
444 .map_ok(|envelope| envelope.payload)
445 }
446
447 pub fn request_envelope<T: RequestMessage>(
448 &self,
449 receiver_id: ConnectionId,
450 request: T,
451 ) -> impl Future<Output = Result<TypedEnvelope<T::Response>>> {
452 self.request_internal(None, receiver_id, request)
453 }
454
455 pub fn forward_request<T: RequestMessage>(
456 &self,
457 sender_id: ConnectionId,
458 receiver_id: ConnectionId,
459 request: T,
460 ) -> impl Future<Output = Result<T::Response>> {
461 self.request_internal(Some(sender_id), receiver_id, request)
462 .map_ok(|envelope| envelope.payload)
463 }
464
465 pub fn request_internal<T: RequestMessage>(
466 &self,
467 original_sender_id: Option<ConnectionId>,
468 receiver_id: ConnectionId,
469 request: T,
470 ) -> impl Future<Output = Result<TypedEnvelope<T::Response>>> {
471 let (tx, rx) = oneshot::channel();
472 let send = self.connection_state(receiver_id).and_then(|connection| {
473 let message_id = connection.next_message_id.fetch_add(1, SeqCst);
474 connection
475 .response_channels
476 .lock()
477 .as_mut()
478 .ok_or_else(|| anyhow!("connection was closed"))?
479 .insert(message_id, tx);
480 connection
481 .outgoing_tx
482 .unbounded_send(proto::Message::Envelope(request.into_envelope(
483 message_id,
484 None,
485 original_sender_id.map(Into::into),
486 )))
487 .map_err(|_| anyhow!("connection was closed"))?;
488 Ok(())
489 });
490 async move {
491 send?;
492 let (response, received_at, _barrier) =
493 rx.await.map_err(|_| anyhow!("connection was closed"))?;
494
495 if let Some(proto::envelope::Payload::Error(error)) = &response.payload {
496 Err(RpcError::from_proto(&error, T::NAME))
497 } else {
498 Ok(TypedEnvelope {
499 message_id: response.id,
500 sender_id: receiver_id,
501 original_sender_id: response.original_sender_id,
502 payload: T::Response::from_envelope(response)
503 .ok_or_else(|| anyhow!("received response of the wrong type"))?,
504 received_at,
505 })
506 }
507 }
508 }
509
510 pub fn request_stream<T: RequestMessage>(
511 &self,
512 receiver_id: ConnectionId,
513 request: T,
514 ) -> impl Future<Output = Result<impl Unpin + Stream<Item = Result<T::Response>>>> {
515 let (tx, rx) = mpsc::unbounded();
516 let send = self.connection_state(receiver_id).and_then(|connection| {
517 let message_id = connection.next_message_id.fetch_add(1, SeqCst);
518 let stream_response_channels = connection.stream_response_channels.clone();
519 stream_response_channels
520 .lock()
521 .as_mut()
522 .ok_or_else(|| anyhow!("connection was closed"))?
523 .insert(message_id, tx);
524 connection
525 .outgoing_tx
526 .unbounded_send(proto::Message::Envelope(
527 request.into_envelope(message_id, None, None),
528 ))
529 .map_err(|_| anyhow!("connection was closed"))?;
530 Ok((message_id, stream_response_channels))
531 });
532
533 async move {
534 let (message_id, stream_response_channels) = send?;
535 let stream_response_channels = Arc::downgrade(&stream_response_channels);
536
537 Ok(rx.filter_map(move |(response, _barrier)| {
538 let stream_response_channels = stream_response_channels.clone();
539 future::ready(match response {
540 Ok(response) => {
541 if let Some(proto::envelope::Payload::Error(error)) = &response.payload {
542 Some(Err(anyhow!(
543 "RPC request {} failed - {}",
544 T::NAME,
545 error.message
546 )))
547 } else if let Some(proto::envelope::Payload::EndStream(_)) =
548 &response.payload
549 {
550 // Remove the transmitting end of the response channel to end the stream.
551 if let Some(channels) = stream_response_channels.upgrade() {
552 if let Some(channels) = channels.lock().as_mut() {
553 channels.remove(&message_id);
554 }
555 }
556 None
557 } else {
558 Some(
559 T::Response::from_envelope(response)
560 .ok_or_else(|| anyhow!("received response of the wrong type")),
561 )
562 }
563 }
564 Err(error) => Some(Err(error)),
565 })
566 }))
567 }
568 }
569
570 pub fn send<T: EnvelopedMessage>(&self, receiver_id: ConnectionId, message: T) -> Result<()> {
571 let connection = self.connection_state(receiver_id)?;
572 let message_id = connection
573 .next_message_id
574 .fetch_add(1, atomic::Ordering::SeqCst);
575 connection
576 .outgoing_tx
577 .unbounded_send(proto::Message::Envelope(
578 message.into_envelope(message_id, None, None),
579 ))?;
580 Ok(())
581 }
582
583 pub fn forward_send<T: EnvelopedMessage>(
584 &self,
585 sender_id: ConnectionId,
586 receiver_id: ConnectionId,
587 message: T,
588 ) -> Result<()> {
589 let connection = self.connection_state(receiver_id)?;
590 let message_id = connection
591 .next_message_id
592 .fetch_add(1, atomic::Ordering::SeqCst);
593 connection
594 .outgoing_tx
595 .unbounded_send(proto::Message::Envelope(message.into_envelope(
596 message_id,
597 None,
598 Some(sender_id.into()),
599 )))?;
600 Ok(())
601 }
602
603 pub fn respond<T: RequestMessage>(
604 &self,
605 receipt: Receipt<T>,
606 response: T::Response,
607 ) -> Result<()> {
608 let connection = self.connection_state(receipt.sender_id)?;
609 let message_id = connection
610 .next_message_id
611 .fetch_add(1, atomic::Ordering::SeqCst);
612 connection
613 .outgoing_tx
614 .unbounded_send(proto::Message::Envelope(response.into_envelope(
615 message_id,
616 Some(receipt.message_id),
617 None,
618 )))?;
619 Ok(())
620 }
621
622 pub fn end_stream<T: RequestMessage>(&self, receipt: Receipt<T>) -> Result<()> {
623 let connection = self.connection_state(receipt.sender_id)?;
624 let message_id = connection
625 .next_message_id
626 .fetch_add(1, atomic::Ordering::SeqCst);
627
628 let message = proto::EndStream {};
629
630 connection
631 .outgoing_tx
632 .unbounded_send(proto::Message::Envelope(message.into_envelope(
633 message_id,
634 Some(receipt.message_id),
635 None,
636 )))?;
637 Ok(())
638 }
639
640 pub fn respond_with_error<T: RequestMessage>(
641 &self,
642 receipt: Receipt<T>,
643 response: proto::Error,
644 ) -> Result<()> {
645 let connection = self.connection_state(receipt.sender_id)?;
646 let message_id = connection
647 .next_message_id
648 .fetch_add(1, atomic::Ordering::SeqCst);
649 connection
650 .outgoing_tx
651 .unbounded_send(proto::Message::Envelope(response.into_envelope(
652 message_id,
653 Some(receipt.message_id),
654 None,
655 )))?;
656 Ok(())
657 }
658
659 pub fn respond_with_unhandled_message(
660 &self,
661 envelope: Box<dyn AnyTypedEnvelope>,
662 ) -> Result<()> {
663 let connection = self.connection_state(envelope.sender_id())?;
664 let response = ErrorCode::Internal
665 .message(format!(
666 "message {} was not handled",
667 envelope.payload_type_name()
668 ))
669 .to_proto();
670 let message_id = connection
671 .next_message_id
672 .fetch_add(1, atomic::Ordering::SeqCst);
673 connection
674 .outgoing_tx
675 .unbounded_send(proto::Message::Envelope(response.into_envelope(
676 message_id,
677 Some(envelope.message_id()),
678 None,
679 )))?;
680 Ok(())
681 }
682
683 fn connection_state(&self, connection_id: ConnectionId) -> Result<ConnectionState> {
684 let connections = self.connections.read();
685 let connection = connections
686 .get(&connection_id)
687 .ok_or_else(|| anyhow!("no such connection: {}", connection_id))?;
688 Ok(connection.clone())
689 }
690}
691
692impl Serialize for Peer {
693 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
694 where
695 S: serde::Serializer,
696 {
697 let mut state = serializer.serialize_struct("Peer", 2)?;
698 state.serialize_field("connections", &*self.connections.read())?;
699 state.end()
700 }
701}
702
703#[cfg(test)]
704mod tests {
705 use super::*;
706 use crate::TypedEnvelope;
707 use async_tungstenite::tungstenite::Message as WebSocketMessage;
708 use gpui::TestAppContext;
709
710 fn init_logger() {
711 if std::env::var("RUST_LOG").is_ok() {
712 env_logger::init();
713 }
714 }
715
716 #[gpui::test(iterations = 50)]
717 async fn test_request_response(cx: &mut TestAppContext) {
718 init_logger();
719
720 let executor = cx.executor();
721
722 // create 2 clients connected to 1 server
723 let server = Peer::new(0);
724 let client1 = Peer::new(0);
725 let client2 = Peer::new(0);
726
727 let (client1_to_server_conn, server_to_client_1_conn, _kill) =
728 Connection::in_memory(cx.executor());
729 let (client1_conn_id, io_task1, client1_incoming) =
730 client1.add_test_connection(client1_to_server_conn, cx.executor());
731 let (_, io_task2, server_incoming1) =
732 server.add_test_connection(server_to_client_1_conn, cx.executor());
733
734 let (client2_to_server_conn, server_to_client_2_conn, _kill) =
735 Connection::in_memory(cx.executor());
736 let (client2_conn_id, io_task3, client2_incoming) =
737 client2.add_test_connection(client2_to_server_conn, cx.executor());
738 let (_, io_task4, server_incoming2) =
739 server.add_test_connection(server_to_client_2_conn, cx.executor());
740
741 executor.spawn(io_task1).detach();
742 executor.spawn(io_task2).detach();
743 executor.spawn(io_task3).detach();
744 executor.spawn(io_task4).detach();
745 executor
746 .spawn(handle_messages(server_incoming1, server.clone()))
747 .detach();
748 executor
749 .spawn(handle_messages(client1_incoming, client1.clone()))
750 .detach();
751 executor
752 .spawn(handle_messages(server_incoming2, server.clone()))
753 .detach();
754 executor
755 .spawn(handle_messages(client2_incoming, client2.clone()))
756 .detach();
757
758 assert_eq!(
759 client1
760 .request(client1_conn_id, proto::Ping {},)
761 .await
762 .unwrap(),
763 proto::Ack {}
764 );
765
766 assert_eq!(
767 client2
768 .request(client2_conn_id, proto::Ping {},)
769 .await
770 .unwrap(),
771 proto::Ack {}
772 );
773
774 assert_eq!(
775 client1
776 .request(client1_conn_id, proto::Test { id: 1 },)
777 .await
778 .unwrap(),
779 proto::Test { id: 1 }
780 );
781
782 assert_eq!(
783 client2
784 .request(client2_conn_id, proto::Test { id: 2 })
785 .await
786 .unwrap(),
787 proto::Test { id: 2 }
788 );
789
790 client1.disconnect(client1_conn_id);
791 client2.disconnect(client1_conn_id);
792
793 async fn handle_messages(
794 mut messages: BoxStream<'static, Box<dyn AnyTypedEnvelope>>,
795 peer: Arc<Peer>,
796 ) -> Result<()> {
797 while let Some(envelope) = messages.next().await {
798 let envelope = envelope.into_any();
799 if let Some(envelope) = envelope.downcast_ref::<TypedEnvelope<proto::Ping>>() {
800 let receipt = envelope.receipt();
801 peer.respond(receipt, proto::Ack {})?
802 } else if let Some(envelope) = envelope.downcast_ref::<TypedEnvelope<proto::Test>>()
803 {
804 peer.respond(envelope.receipt(), envelope.payload.clone())?
805 } else {
806 panic!("unknown message type");
807 }
808 }
809
810 Ok(())
811 }
812 }
813
814 #[gpui::test(iterations = 50)]
815 async fn test_order_of_response_and_incoming(cx: &mut TestAppContext) {
816 let executor = cx.executor();
817 let server = Peer::new(0);
818 let client = Peer::new(0);
819
820 let (client_to_server_conn, server_to_client_conn, _kill) =
821 Connection::in_memory(executor.clone());
822 let (client_to_server_conn_id, io_task1, mut client_incoming) =
823 client.add_test_connection(client_to_server_conn, executor.clone());
824
825 let (server_to_client_conn_id, io_task2, mut server_incoming) =
826 server.add_test_connection(server_to_client_conn, executor.clone());
827
828 executor.spawn(io_task1).detach();
829 executor.spawn(io_task2).detach();
830
831 executor
832 .spawn(async move {
833 let future = server_incoming.next().await;
834 let request = future
835 .unwrap()
836 .into_any()
837 .downcast::<TypedEnvelope<proto::Ping>>()
838 .unwrap();
839
840 server
841 .send(
842 server_to_client_conn_id,
843 ErrorCode::Internal
844 .message("message 1".to_string())
845 .to_proto(),
846 )
847 .unwrap();
848 server
849 .send(
850 server_to_client_conn_id,
851 ErrorCode::Internal
852 .message("message 2".to_string())
853 .to_proto(),
854 )
855 .unwrap();
856 server.respond(request.receipt(), proto::Ack {}).unwrap();
857
858 // Prevent the connection from being dropped
859 server_incoming.next().await;
860 })
861 .detach();
862
863 let events = Arc::new(Mutex::new(Vec::new()));
864
865 let response = client.request(client_to_server_conn_id, proto::Ping {});
866 let response_task = executor.spawn({
867 let events = events.clone();
868 async move {
869 response.await.unwrap();
870 events.lock().push("response".to_string());
871 }
872 });
873
874 executor
875 .spawn({
876 let events = events.clone();
877 async move {
878 let incoming1 = client_incoming
879 .next()
880 .await
881 .unwrap()
882 .into_any()
883 .downcast::<TypedEnvelope<proto::Error>>()
884 .unwrap();
885 events.lock().push(incoming1.payload.message);
886 let incoming2 = client_incoming
887 .next()
888 .await
889 .unwrap()
890 .into_any()
891 .downcast::<TypedEnvelope<proto::Error>>()
892 .unwrap();
893 events.lock().push(incoming2.payload.message);
894
895 // Prevent the connection from being dropped
896 client_incoming.next().await;
897 }
898 })
899 .detach();
900
901 response_task.await;
902 assert_eq!(
903 &*events.lock(),
904 &[
905 "message 1".to_string(),
906 "message 2".to_string(),
907 "response".to_string()
908 ]
909 );
910 }
911
912 #[gpui::test(iterations = 50)]
913 async fn test_dropping_request_before_completion(cx: &mut TestAppContext) {
914 let executor = cx.executor();
915 let server = Peer::new(0);
916 let client = Peer::new(0);
917
918 let (client_to_server_conn, server_to_client_conn, _kill) =
919 Connection::in_memory(cx.executor());
920 let (client_to_server_conn_id, io_task1, mut client_incoming) =
921 client.add_test_connection(client_to_server_conn, cx.executor());
922 let (server_to_client_conn_id, io_task2, mut server_incoming) =
923 server.add_test_connection(server_to_client_conn, cx.executor());
924
925 executor.spawn(io_task1).detach();
926 executor.spawn(io_task2).detach();
927
928 executor
929 .spawn(async move {
930 let request1 = server_incoming
931 .next()
932 .await
933 .unwrap()
934 .into_any()
935 .downcast::<TypedEnvelope<proto::Ping>>()
936 .unwrap();
937 let request2 = server_incoming
938 .next()
939 .await
940 .unwrap()
941 .into_any()
942 .downcast::<TypedEnvelope<proto::Ping>>()
943 .unwrap();
944
945 server
946 .send(
947 server_to_client_conn_id,
948 ErrorCode::Internal
949 .message("message 1".to_string())
950 .to_proto(),
951 )
952 .unwrap();
953 server
954 .send(
955 server_to_client_conn_id,
956 ErrorCode::Internal
957 .message("message 2".to_string())
958 .to_proto(),
959 )
960 .unwrap();
961 server.respond(request1.receipt(), proto::Ack {}).unwrap();
962 server.respond(request2.receipt(), proto::Ack {}).unwrap();
963
964 // Prevent the connection from being dropped
965 server_incoming.next().await;
966 })
967 .detach();
968
969 let events = Arc::new(Mutex::new(Vec::new()));
970
971 let request1 = client.request(client_to_server_conn_id, proto::Ping {});
972 let request1_task = executor.spawn(request1);
973 let request2 = client.request(client_to_server_conn_id, proto::Ping {});
974 let request2_task = executor.spawn({
975 let events = events.clone();
976 async move {
977 request2.await.unwrap();
978 events.lock().push("response 2".to_string());
979 }
980 });
981
982 executor
983 .spawn({
984 let events = events.clone();
985 async move {
986 let incoming1 = client_incoming
987 .next()
988 .await
989 .unwrap()
990 .into_any()
991 .downcast::<TypedEnvelope<proto::Error>>()
992 .unwrap();
993 events.lock().push(incoming1.payload.message);
994 let incoming2 = client_incoming
995 .next()
996 .await
997 .unwrap()
998 .into_any()
999 .downcast::<TypedEnvelope<proto::Error>>()
1000 .unwrap();
1001 events.lock().push(incoming2.payload.message);
1002
1003 // Prevent the connection from being dropped
1004 client_incoming.next().await;
1005 }
1006 })
1007 .detach();
1008
1009 // Allow the request to make some progress before dropping it.
1010 cx.executor().simulate_random_delay().await;
1011 drop(request1_task);
1012
1013 request2_task.await;
1014 assert_eq!(
1015 &*events.lock(),
1016 &[
1017 "message 1".to_string(),
1018 "message 2".to_string(),
1019 "response 2".to_string()
1020 ]
1021 );
1022 }
1023
1024 #[gpui::test(iterations = 50)]
1025 async fn test_disconnect(cx: &mut TestAppContext) {
1026 let executor = cx.executor();
1027
1028 let (client_conn, mut server_conn, _kill) = Connection::in_memory(executor.clone());
1029
1030 let client = Peer::new(0);
1031 let (connection_id, io_handler, mut incoming) =
1032 client.add_test_connection(client_conn, executor.clone());
1033
1034 let (io_ended_tx, io_ended_rx) = oneshot::channel();
1035 executor
1036 .spawn(async move {
1037 io_handler.await.ok();
1038 io_ended_tx.send(()).unwrap();
1039 })
1040 .detach();
1041
1042 let (messages_ended_tx, messages_ended_rx) = oneshot::channel();
1043 executor
1044 .spawn(async move {
1045 incoming.next().await;
1046 messages_ended_tx.send(()).unwrap();
1047 })
1048 .detach();
1049
1050 client.disconnect(connection_id);
1051
1052 let _ = io_ended_rx.await;
1053 let _ = messages_ended_rx.await;
1054 assert!(server_conn
1055 .send(WebSocketMessage::Binary(vec![]))
1056 .await
1057 .is_err());
1058 }
1059
1060 #[gpui::test(iterations = 50)]
1061 async fn test_io_error(cx: &mut TestAppContext) {
1062 let executor = cx.executor();
1063 let (client_conn, mut server_conn, _kill) = Connection::in_memory(executor.clone());
1064
1065 let client = Peer::new(0);
1066 let (connection_id, io_handler, mut incoming) =
1067 client.add_test_connection(client_conn, executor.clone());
1068 executor.spawn(io_handler).detach();
1069 executor
1070 .spawn(async move { incoming.next().await })
1071 .detach();
1072
1073 let response = executor.spawn(client.request(connection_id, proto::Ping {}));
1074 let _request = server_conn.rx.next().await.unwrap().unwrap();
1075
1076 drop(server_conn);
1077 assert_eq!(
1078 response.await.unwrap_err().to_string(),
1079 "connection was closed"
1080 );
1081 }
1082}