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: std::sync::Arc<gpui::executor::Background>,
38 ) -> (Self, Self, std::sync::Arc<std::sync::atomic::AtomicBool>) {
39 use std::sync::{
40 atomic::{AtomicBool, Ordering::SeqCst},
41 Arc,
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 fn channel(
54 killed: Arc<AtomicBool>,
55 executor: Arc<gpui::executor::Background>,
56 ) -> (
57 Box<dyn Send + Unpin + futures::Sink<WebSocketMessage, Error = anyhow::Error>>,
58 Box<dyn Send + Unpin + futures::Stream<Item = Result<WebSocketMessage, anyhow::Error>>>,
59 ) {
60 use anyhow::anyhow;
61 use futures::channel::mpsc;
62 use std::io::{Error, ErrorKind};
63
64 let (tx, rx) = mpsc::unbounded::<WebSocketMessage>();
65
66 let tx = tx.sink_map_err(|error| anyhow!(error)).with({
67 let killed = killed.clone();
68 let executor = Arc::downgrade(&executor);
69 move |msg| {
70 let killed = killed.clone();
71 let executor = executor.clone();
72 Box::pin(async move {
73 if let Some(executor) = executor.upgrade() {
74 executor.simulate_random_delay().await;
75 }
76
77 // Writes to a half-open TCP connection will error.
78 if killed.load(SeqCst) {
79 std::io::Result::Err(
80 Error::new(ErrorKind::Other, "connection lost").into(),
81 )?;
82 }
83
84 Ok(msg)
85 })
86 }
87 });
88
89 let rx = rx.then({
90 let killed = killed.clone();
91 let executor = Arc::downgrade(&executor);
92 move |msg| {
93 let killed = killed.clone();
94 let executor = executor.clone();
95 Box::pin(async move {
96 if let Some(executor) = executor.upgrade() {
97 executor.simulate_random_delay().await;
98 }
99
100 // Reads from a half-open TCP connection will hang.
101 if killed.load(SeqCst) {
102 futures::future::pending::<()>().await;
103 }
104
105 Ok(msg)
106 })
107 }
108 });
109
110 (Box::new(tx), Box::new(rx))
111 }
112 }
113}