Skip to main content

mojentic/realtime/
transport.rs

1//! Transport abstraction for the realtime subsystem.
2//!
3//! The gateway owns I/O against this interface so unit tests can swap
4//! the live WebSocket for a scripted, deterministic transport.
5
6use async_trait::async_trait;
7use std::fmt;
8use tokio::sync::mpsc;
9
10/// A duplex text-frame channel — minimal surface so providers can swap
11/// WebSocket for SSE, in-process loopback, etc.
12#[async_trait]
13pub trait RealtimeTransport: Send + Sync {
14    async fn send(&mut self, payload: &str) -> Result<(), TransportError>;
15    async fn close(&mut self) -> Result<(), TransportError>;
16    /// Returns the next text frame, or None on close.
17    async fn next_frame(&mut self) -> Option<Result<String, TransportError>>;
18}
19
20#[derive(Debug, Clone)]
21pub struct TransportError(pub String);
22
23impl fmt::Display for TransportError {
24    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
25        write!(f, "{}", self.0)
26    }
27}
28
29impl std::error::Error for TransportError {}
30
31/// Production transport — wraps `tokio_tungstenite` and pumps frames in
32/// a background task whose output flows through an mpsc receiver.
33pub struct WebSocketTransport {
34    outbound: mpsc::Sender<String>,
35    inbound: mpsc::Receiver<Result<String, TransportError>>,
36    close_signal: tokio::sync::watch::Sender<bool>,
37}
38
39impl WebSocketTransport {
40    /// Connect to a WebSocket URL with optional headers. Spawns a
41    /// pump task that lives until the inbound channel is dropped or
42    /// the connection closes.
43    pub async fn connect(url: &str, headers: &[(String, String)]) -> Result<Self, TransportError> {
44        use tokio_tungstenite::tungstenite::client::IntoClientRequest;
45        use tokio_tungstenite::tungstenite::http;
46
47        let mut req = url
48            .into_client_request()
49            .map_err(|e| TransportError(format!("invalid url: {e}")))?;
50        for (k, v) in headers {
51            let header_name = http::header::HeaderName::from_bytes(k.as_bytes())
52                .map_err(|e| TransportError(format!("bad header name: {e}")))?;
53            let header_value = http::HeaderValue::from_str(v)
54                .map_err(|e| TransportError(format!("bad header value: {e}")))?;
55            req.headers_mut().insert(header_name, header_value);
56        }
57
58        let (ws, _resp) = tokio_tungstenite::connect_async(req)
59            .await
60            .map_err(|e| TransportError(format!("ws connect failed: {e}")))?;
61
62        let (outbound_tx, mut outbound_rx) = mpsc::channel::<String>(64);
63        let (inbound_tx, inbound_rx) = mpsc::channel(64);
64        let (close_tx, mut close_rx) = tokio::sync::watch::channel(false);
65
66        use futures::stream::StreamExt;
67        use futures::SinkExt;
68
69        let (mut sink, mut stream) = ws.split();
70
71        tokio::spawn(async move {
72            loop {
73                tokio::select! {
74                    Some(out) = outbound_rx.recv() => {
75                        if let Err(err) = sink.send(tokio_tungstenite::tungstenite::Message::text(out)).await {
76                            let _ = inbound_tx.send(Err(TransportError(format!("ws send: {err}")))).await;
77                            break;
78                        }
79                    }
80                    maybe = stream.next() => {
81                        match maybe {
82                            Some(Ok(tokio_tungstenite::tungstenite::Message::Text(text))) => {
83                                if inbound_tx.send(Ok(text.to_string())).await.is_err() { break; }
84                            }
85                            Some(Ok(tokio_tungstenite::tungstenite::Message::Close(_))) => break,
86                            Some(Ok(_)) => continue,
87                            Some(Err(err)) => {
88                                let _ = inbound_tx.send(Err(TransportError(format!("ws recv: {err}")))).await;
89                                break;
90                            }
91                            None => break,
92                        }
93                    }
94                    _ = close_rx.changed() => {
95                        if *close_rx.borrow() { break; }
96                    }
97                }
98            }
99            let _ = sink.close().await;
100        });
101
102        Ok(Self {
103            outbound: outbound_tx,
104            inbound: inbound_rx,
105            close_signal: close_tx,
106        })
107    }
108}
109
110#[async_trait]
111impl RealtimeTransport for WebSocketTransport {
112    async fn send(&mut self, payload: &str) -> Result<(), TransportError> {
113        self.outbound
114            .send(payload.to_string())
115            .await
116            .map_err(|e| TransportError(format!("ws outbound: {e}")))
117    }
118
119    async fn close(&mut self) -> Result<(), TransportError> {
120        let _ = self.close_signal.send(true);
121        Ok(())
122    }
123
124    async fn next_frame(&mut self) -> Option<Result<String, TransportError>> {
125        self.inbound.recv().await
126    }
127}