conn.rs

  1use async_tungstenite::tungstenite::Message as WebSocketMessage;
  2use futures::{SinkExt as _, StreamExt as _};
  3
  4pub struct Connection {
  5    pub(crate) tx:
  6        Box<dyn 'static + Send + Unpin + futures::Sink<WebSocketMessage, Error = anyhow::Error>>,
  7    pub(crate) rx: Box<
  8        dyn 'static
  9            + Send
 10            + Unpin
 11            + futures::Stream<Item = Result<WebSocketMessage, anyhow::Error>>,
 12    >,
 13}
 14
 15impl Connection {
 16    pub fn new<S>(stream: S) -> Self
 17    where
 18        S: 'static
 19            + Send
 20            + Unpin
 21            + futures::Sink<WebSocketMessage, Error = anyhow::Error>
 22            + futures::Stream<Item = Result<WebSocketMessage, anyhow::Error>>,
 23    {
 24        let (tx, rx) = stream.split();
 25        Self {
 26            tx: Box::new(tx),
 27            rx: Box::new(rx),
 28        }
 29    }
 30
 31    pub async fn send(&mut self, message: WebSocketMessage) -> Result<(), anyhow::Error> {
 32        self.tx.send(message).await
 33    }
 34
 35    #[cfg(any(test, feature = "test-support"))]
 36    pub fn in_memory(
 37        executor: gpui::BackgroundExecutor,
 38    ) -> (Self, Self, std::sync::Arc<std::sync::atomic::AtomicBool>) {
 39        use std::sync::{
 40            Arc,
 41            atomic::{AtomicBool, Ordering::SeqCst},
 42        };
 43
 44        let killed = Arc::new(AtomicBool::new(false));
 45        let (a_tx, a_rx) = channel(killed.clone(), executor.clone());
 46        let (b_tx, b_rx) = channel(killed.clone(), executor);
 47        return (
 48            Self { tx: a_tx, rx: b_rx },
 49            Self { tx: b_tx, rx: a_rx },
 50            killed,
 51        );
 52
 53        #[allow(clippy::type_complexity)]
 54        fn channel(
 55            killed: Arc<AtomicBool>,
 56            executor: gpui::BackgroundExecutor,
 57        ) -> (
 58            Box<dyn Send + Unpin + futures::Sink<WebSocketMessage, Error = anyhow::Error>>,
 59            Box<dyn Send + Unpin + futures::Stream<Item = Result<WebSocketMessage, anyhow::Error>>>,
 60        ) {
 61            use anyhow::anyhow;
 62            use futures::channel::mpsc;
 63            use std::io::{Error, ErrorKind};
 64
 65            let (tx, rx) = mpsc::unbounded::<WebSocketMessage>();
 66
 67            let tx = tx.sink_map_err(|error| anyhow!(error)).with({
 68                let killed = killed.clone();
 69                let executor = executor.clone();
 70                move |msg| {
 71                    let killed = killed.clone();
 72                    let executor = executor.clone();
 73                    Box::pin(async move {
 74                        executor.simulate_random_delay().await;
 75
 76                        // Writes to a half-open TCP connection will error.
 77                        if killed.load(SeqCst) {
 78                            std::io::Result::Err(Error::new(ErrorKind::Other, "connection lost"))?;
 79                        }
 80
 81                        Ok(msg)
 82                    })
 83                }
 84            });
 85
 86            let rx = rx.then({
 87                let executor = executor.clone();
 88                move |msg| {
 89                    let killed = killed.clone();
 90                    let executor = executor.clone();
 91                    Box::pin(async move {
 92                        executor.simulate_random_delay().await;
 93
 94                        // Reads from a half-open TCP connection will hang.
 95                        if killed.load(SeqCst) {
 96                            futures::future::pending::<()>().await;
 97                        }
 98
 99                        Ok(msg)
100                    })
101                }
102            });
103
104            (Box::new(tx), Box::new(rx))
105        }
106    }
107}