peer.rs

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