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