Skip to main content

gemini_genai_rs/transport/
ws.rs

1//! Transport abstraction — bidirectional message transport.
2//!
3//! The [`Transport`] trait defines a pluggable transport layer for sending and
4//! receiving raw bytes. The default implementation [`TungsteniteTransport`] wraps
5//! `tokio-tungstenite` for WebSocket connectivity. [`MockTransport`] enables
6//! deterministic unit testing without a network.
7
8use async_trait::async_trait;
9
10/// A bidirectional message transport.
11///
12/// The default is WebSocket ([`TungsteniteTransport`]); [`MockTransport`] enables
13/// unit testing without a real server.
14///
15/// # Implementors
16///
17/// - [`TungsteniteTransport`] -- Production WebSocket transport using `tokio-tungstenite`.
18///   Handles both Text and Binary frames (Vertex AI sends Binary).
19/// - [`MockTransport`] -- Deterministic test transport. Records sent data and replays
20///   scripted responses. When the queue is empty, `recv()` pends indefinitely.
21#[async_trait]
22pub trait Transport: Send + 'static {
23    /// The error type produced by this transport.
24    type Error: std::error::Error + Send + Sync + 'static;
25
26    /// Connect to the given URL with optional headers.
27    async fn connect(
28        &mut self,
29        url: &str,
30        headers: Vec<(String, String)>,
31    ) -> Result<(), Self::Error>;
32
33    /// Send raw bytes.
34    async fn send(&mut self, data: Vec<u8>) -> Result<(), Self::Error>;
35
36    /// Receive raw bytes. Returns `None` when the connection is closed.
37    async fn recv(&mut self) -> Result<Option<Vec<u8>>, Self::Error>;
38
39    /// Close the transport.
40    async fn close(&mut self) -> Result<(), Self::Error>;
41
42    /// Why the peer closed the connection, if it said.
43    ///
44    /// Read after [`recv`](Self::recv) returns `Ok(None)`. A server-initiated
45    /// close on the Live API carries a status code and a reason — a context
46    /// window exhausted, an invalid argument, a quota — and without this the
47    /// only thing that survives is the fact of the close. That is the difference
48    /// between a session that "just dropped" and one that dropped for a stated
49    /// reason: a governed voice evaluation lost several turns to a close whose
50    /// reason had been logged at `warn` and then discarded, so it was never
51    /// diagnosed.
52    ///
53    /// Defaults to `None` so an existing transport implementation keeps
54    /// compiling; it merely reports nothing.
55    fn close_reason(&self) -> Option<String> {
56        None
57    }
58}
59
60// ---------------------------------------------------------------------------
61// TungsteniteTransport — WebSocket transport using tokio-tungstenite
62// ---------------------------------------------------------------------------
63
64use futures_util::{SinkExt, StreamExt};
65use tokio_tungstenite::tungstenite::Message;
66use tokio_tungstenite::tungstenite::client::IntoClientRequest;
67
68type WsStream =
69    tokio_tungstenite::WebSocketStream<tokio_tungstenite::MaybeTlsStream<tokio::net::TcpStream>>;
70
71/// Bytes tungstenite reads from the socket per frame read.
72///
73/// Its default, 128 KiB, is allocated and zero-filled for every connection:
74/// over a thousand sessions that is 128 MB for buffers that hold one
75/// message at a time. 16 KiB still takes a 40 ms audio message (about
76/// 2.7 KB) or an 8 KB-PCM one (about 11 KB) in a single read; anything
77/// larger is read in more than one.
78const READ_BUFFER_SIZE: usize = 16 * 1024;
79
80/// WebSocket transport using `tokio-tungstenite`.
81pub struct TungsteniteTransport {
82    ws_write: Option<futures_util::stream::SplitSink<WsStream, Message>>,
83    ws_read: Option<futures_util::stream::SplitStream<WsStream>>,
84    /// Code and reason from the peer's close frame, kept so the session loop can
85    /// report *why* the connection ended rather than only that it did.
86    close_reason: Option<String>,
87}
88
89impl TungsteniteTransport {
90    /// Create a new, disconnected transport.
91    pub fn new() -> Self {
92        Self {
93            ws_write: None,
94            ws_read: None,
95            close_reason: None,
96        }
97    }
98}
99
100impl Default for TungsteniteTransport {
101    fn default() -> Self {
102        Self::new()
103    }
104}
105
106/// Errors from the [`TungsteniteTransport`].
107#[derive(Debug, thiserror::Error)]
108pub enum TungsteniteError {
109    /// The transport is not connected.
110    #[error("Not connected")]
111    NotConnected,
112
113    /// WebSocket protocol error from tungstenite.
114    #[error("WebSocket error: {0}")]
115    WebSocket(#[from] tokio_tungstenite::tungstenite::Error),
116
117    /// Failed to construct the HTTP request (e.g. bad URL or header).
118    #[error("Request error: {0}")]
119    Request(String),
120
121    /// A `wss://` URL was dialed but the crate was compiled with neither TLS
122    /// backend.
123    ///
124    /// Without `tls-native` or `tls-rustls`, `tokio-tungstenite` can open
125    /// plain `ws://` sockets only; the Live API is TLS-only, so this build
126    /// cannot reach it. The check runs before any socket is opened, so the
127    /// failure names the fix instead of surfacing as a generic handshake error
128    /// from deep inside the WebSocket stack.
129    #[error(
130        "cannot dial {url}: this build of gemini-genai-rs has no TLS backend; \
131         enable the `tls-native` (default) or `tls-rustls` feature"
132    )]
133    NoTlsBackend {
134        /// The URL that was refused.
135        url: String,
136    },
137}
138
139/// Whether a TLS backend was compiled in. `wss://` and `https://` need one.
140pub const HAS_TLS_BACKEND: bool = cfg!(any(feature = "tls-native", feature = "tls-rustls"));
141
142/// What one WebSocket message means to the session loop.
143#[derive(Debug, Clone, PartialEq, Eq)]
144pub enum FramePayload {
145    /// A frame carrying a server message, as bytes for the codec.
146    Data(Vec<u8>),
147    /// The peer closed the connection, with its close code and a reason
148    /// text (code, and the server's text when it gave one) when it sent a
149    /// close frame.
150    Close(Option<(u16, String)>),
151    /// A control frame (ping, pong, raw frame) the session loop ignores.
152    Skip,
153}
154
155/// The bytes a WebSocket message carries for the codec.
156///
157/// Google AI sends JSON in text frames; **Vertex AI sends the same JSON in
158/// binary frames**. Both become the same bytes here, which is what the
159/// session loop and the fuzz targets rely on: one decoder, two wire paths.
160/// A close frame becomes [`FramePayload::Close`] with the server's reason
161/// (code and text), and control frames are [`FramePayload::Skip`].
162pub fn frame_payload(message: Message) -> FramePayload {
163    match message {
164        Message::Text(t) => FramePayload::Data(bytes::Bytes::from(t).into()),
165        Message::Binary(b) => FramePayload::Data(b.into()),
166        Message::Close(frame) => FramePayload::Close(frame.map(|cf| {
167            let reason = if cf.reason.is_empty() {
168                format!("server closed the connection ({})", cf.code)
169            } else {
170                format!("server closed the connection ({}): {}", cf.code, cf.reason)
171            };
172            (u16::from(cf.code), reason)
173        })),
174        // Ping/Pong are handled internally by tungstenite; Frame is a
175        // low-level variant.
176        Message::Ping(_) | Message::Pong(_) | Message::Frame(_) => FramePayload::Skip,
177    }
178}
179
180#[async_trait]
181impl Transport for TungsteniteTransport {
182    type Error = TungsteniteError;
183
184    async fn connect(
185        &mut self,
186        url: &str,
187        headers: Vec<(String, String)>,
188    ) -> Result<(), Self::Error> {
189        if !HAS_TLS_BACKEND && url.trim_start().to_ascii_lowercase().starts_with("wss://") {
190            return Err(TungsteniteError::NoTlsBackend {
191                url: url.to_string(),
192            });
193        }
194
195        let mut request = url
196            .into_client_request()
197            .map_err(|e| TungsteniteError::Request(e.to_string()))?;
198
199        for (name, value) in headers {
200            let header_name: tokio_tungstenite::tungstenite::http::HeaderName =
201                name.parse().map_err(
202                    |e: tokio_tungstenite::tungstenite::http::header::InvalidHeaderName| {
203                        TungsteniteError::Request(format!("invalid header name: {e}"))
204                    },
205                )?;
206            let header_value: tokio_tungstenite::tungstenite::http::HeaderValue =
207                value.parse().map_err(
208                    |e: tokio_tungstenite::tungstenite::http::header::InvalidHeaderValue| {
209                        TungsteniteError::Request(format!("invalid header value: {e}"))
210                    },
211                )?;
212            request.headers_mut().insert(header_name, header_value);
213        }
214
215        let config = tokio_tungstenite::tungstenite::protocol::WebSocketConfig::default()
216            .read_buffer_size(READ_BUFFER_SIZE);
217        // Nagle off: audio goes out as a stream of small messages, and a
218        // small write must not wait for the previous one to be acknowledged.
219        let (ws_stream, _response) =
220            tokio_tungstenite::connect_async_with_config(request, Some(config), true).await?;
221        let (ws_write, ws_read) = ws_stream.split();
222        self.ws_write = Some(ws_write);
223        self.ws_read = Some(ws_read);
224        Ok(())
225    }
226
227    async fn send(&mut self, data: Vec<u8>) -> Result<(), Self::Error> {
228        let ws_write = self
229            .ws_write
230            .as_mut()
231            .ok_or(TungsteniteError::NotConnected)?;
232        // Convert bytes to a UTF-8 text frame. The wire protocol sends JSON as text.
233        let text = String::from_utf8(data)
234            .map_err(|e| TungsteniteError::Request(format!("invalid UTF-8: {e}")))?;
235        ws_write.send(Message::Text(text.into())).await?;
236        Ok(())
237    }
238
239    async fn recv(&mut self) -> Result<Option<Vec<u8>>, Self::Error> {
240        let ws_read = self
241            .ws_read
242            .as_mut()
243            .ok_or(TungsteniteError::NotConnected)?;
244        loop {
245            match ws_read.next().await {
246                Some(Ok(message)) => match frame_payload(message) {
247                    FramePayload::Data(bytes) => return Ok(Some(bytes)),
248                    FramePayload::Close(close) => {
249                        if let Some((code, reason)) = close {
250                            tracing::warn!(code, %reason, "WebSocket close frame received");
251                            // Kept, not merely logged: a `warn` is invisible
252                            // unless the application configured a subscriber,
253                            // and the reason is the only account of why the
254                            // session ended.
255                            self.close_reason = Some(reason);
256                        }
257                        return Ok(None);
258                    }
259                    FramePayload::Skip => continue,
260                },
261                Some(Err(e)) => return Err(e.into()),
262                None => return Ok(None),
263            }
264        }
265    }
266
267    async fn close(&mut self) -> Result<(), Self::Error> {
268        if let Some(ref mut ws_write) = self.ws_write {
269            ws_write.send(Message::Close(None)).await?;
270        }
271        self.ws_write = None;
272        self.ws_read = None;
273        Ok(())
274    }
275
276    fn close_reason(&self) -> Option<String> {
277        self.close_reason.clone()
278    }
279}
280
281// ---------------------------------------------------------------------------
282// MockTransport — for unit testing
283// ---------------------------------------------------------------------------
284
285/// Mock transport for unit testing.
286///
287/// Records sent data and replays scripted responses from a queue. When the
288/// queue is empty and the transport is connected, [`recv`](Transport::recv)
289/// will pend indefinitely — simulating a connected-but-idle transport.
290/// Call [`close`](Transport::close) to signal connection closure (returns `None`).
291pub struct MockTransport {
292    sent: Vec<Vec<u8>>,
293    recv_queue: std::collections::VecDeque<Vec<u8>>,
294    /// Whether connect() has been called (and close() has not).
295    connected: bool,
296    /// Scripted peer close reason, surfaced by [`Transport::close_reason`].
297    close_reason: Option<String>,
298}
299
300impl MockTransport {
301    /// Create a new, disconnected mock transport.
302    pub fn new() -> Self {
303        Self {
304            sent: Vec::new(),
305            recv_queue: std::collections::VecDeque::new(),
306            connected: false,
307            close_reason: None,
308        }
309    }
310
311    /// Queue a message to be returned by [`Transport::recv`].
312    pub fn script_recv(&mut self, data: Vec<u8>) {
313        self.recv_queue.push_back(data);
314    }
315
316    /// Script the reason the peer gives for closing, so a test can assert that
317    /// it reaches the application rather than being swallowed.
318    pub fn script_close_reason(&mut self, reason: impl Into<String>) {
319        self.close_reason = Some(reason.into());
320    }
321
322    /// Take all sent data (for assertions). Drains the internal buffer.
323    pub fn take_sent(&mut self) -> Vec<Vec<u8>> {
324        std::mem::take(&mut self.sent)
325    }
326}
327
328impl Default for MockTransport {
329    fn default() -> Self {
330        Self::new()
331    }
332}
333
334/// Errors from the [`MockTransport`].
335#[derive(Debug, thiserror::Error)]
336pub enum MockTransportError {
337    /// Operation attempted while not connected.
338    #[error("Not connected")]
339    NotConnected,
340
341    /// A custom error injected for testing.
342    #[error("Mock error: {0}")]
343    Custom(String),
344}
345
346#[async_trait]
347impl Transport for MockTransport {
348    type Error = MockTransportError;
349
350    async fn connect(
351        &mut self,
352        _url: &str,
353        _headers: Vec<(String, String)>,
354    ) -> Result<(), Self::Error> {
355        self.connected = true;
356        Ok(())
357    }
358
359    async fn send(&mut self, data: Vec<u8>) -> Result<(), Self::Error> {
360        if !self.connected {
361            return Err(MockTransportError::NotConnected);
362        }
363        self.sent.push(data);
364        Ok(())
365    }
366
367    async fn recv(&mut self) -> Result<Option<Vec<u8>>, Self::Error> {
368        if !self.connected {
369            return Err(MockTransportError::NotConnected);
370        }
371        // Yield to the scheduler so tests can observe intermediate states
372        // (phase transitions, events) before the next message is processed.
373        tokio::task::yield_now().await;
374
375        if let Some(data) = self.recv_queue.pop_front() {
376            return Ok(Some(data));
377        }
378
379        // Queue is empty: pend indefinitely, simulating a connected-but-idle
380        // transport waiting for the next message from the server.
381        // The connection loop uses `tokio::select!` so this future is dropped
382        // when a command (e.g., Disconnect) arrives on the command channel.
383        std::future::pending().await
384    }
385
386    async fn close(&mut self) -> Result<(), Self::Error> {
387        self.connected = false;
388        Ok(())
389    }
390
391    fn close_reason(&self) -> Option<String> {
392        self.close_reason.clone()
393    }
394}
395
396// ---------------------------------------------------------------------------
397// Tests
398// ---------------------------------------------------------------------------
399
400#[cfg(test)]
401mod tests {
402    use super::*;
403
404    /// The two wire paths carry the same bytes: Google AI's text frame and
405    /// Vertex AI's binary frame of the same JSON reach the codec identically.
406    #[test]
407    fn text_and_binary_frames_carry_the_same_bytes() {
408        let json = r#"{"setupComplete":{}}"#;
409        let text = frame_payload(Message::Text(json.into()));
410        let binary = frame_payload(Message::Binary(json.as_bytes().to_vec().into()));
411        assert_eq!(text, FramePayload::Data(json.as_bytes().to_vec()));
412        assert_eq!(text, binary);
413        // Bytes that are not UTF-8 can only arrive on the binary path, and
414        // they arrive untouched for the codec to refuse.
415        let raw = vec![0xff, 0xfe, b'{'];
416        assert_eq!(
417            frame_payload(Message::Binary(raw.clone().into())),
418            FramePayload::Data(raw)
419        );
420    }
421
422    #[test]
423    fn close_and_control_frames_never_reach_the_codec() {
424        use tokio_tungstenite::tungstenite::protocol::CloseFrame;
425        use tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode;
426        assert_eq!(
427            frame_payload(Message::Close(None)),
428            FramePayload::Close(None)
429        );
430        let close = frame_payload(Message::Close(Some(CloseFrame {
431            code: CloseCode::Policy,
432            reason: "quota exceeded".into(),
433        })));
434        assert_eq!(
435            close,
436            FramePayload::Close(Some((
437                1008,
438                "server closed the connection (1008): quota exceeded".into()
439            )))
440        );
441        let bare = frame_payload(Message::Close(Some(CloseFrame {
442            code: CloseCode::Normal,
443            reason: "".into(),
444        })));
445        assert_eq!(
446            bare,
447            FramePayload::Close(Some((1000, "server closed the connection (1000)".into())))
448        );
449        assert_eq!(
450            frame_payload(Message::Ping(vec![1].into())),
451            FramePayload::Skip
452        );
453        assert_eq!(
454            frame_payload(Message::Pong(vec![1].into())),
455            FramePayload::Skip
456        );
457    }
458
459    /// A transport that says nothing about why it closed still compiles and
460    /// still reports nothing — the default keeps third-party implementations
461    /// working rather than forcing them to answer a question they cannot.
462    #[test]
463    fn a_transport_that_says_nothing_reports_nothing() {
464        assert_eq!(MockTransport::new().close_reason(), None);
465    }
466
467    /// When the peer gives a reason, it survives to the caller.
468    ///
469    /// It used to be logged at `warn` and dropped: `recv` returned a bare
470    /// `Ok(None)` and the session loop turned that into the literal string
471    /// "Transport closed". A `warn` is invisible without a configured
472    /// subscriber, so in practice the only account of why a session ended was
473    /// discarded at the point it was produced — which is why a governed voice
474    /// evaluation lost turns to a close it could never diagnose.
475    #[test]
476    fn a_stated_close_reason_survives_to_the_caller() {
477        let mut transport = MockTransport::new();
478        transport.script_close_reason("server closed the connection (1011): quota exceeded");
479        assert_eq!(
480            transport.close_reason().as_deref(),
481            Some("server closed the connection (1011): quota exceeded")
482        );
483    }
484
485    /// Only meaningful in a build with no TLS backend (`--no-default-features`):
486    /// the `wss://` dial must fail before any socket is opened, with an error
487    /// that names the feature to enable.
488    #[cfg(not(any(feature = "tls-native", feature = "tls-rustls")))]
489    #[tokio::test]
490    async fn wss_without_tls_backend_fails_before_dialing() {
491        let mut transport = TungsteniteTransport::new();
492        let err = transport
493            .connect("wss://example.invalid/ws", vec![])
494            .await
495            .expect_err("no TLS backend compiled in");
496        assert!(matches!(err, TungsteniteError::NoTlsBackend { .. }));
497        let text = err.to_string();
498        assert!(text.contains("tls-native"), "{text}");
499        assert!(text.contains("tls-rustls"), "{text}");
500    }
501
502    #[test]
503    fn has_tls_backend_tracks_features() {
504        assert_eq!(
505            HAS_TLS_BACKEND,
506            cfg!(any(feature = "tls-native", feature = "tls-rustls"))
507        );
508    }
509
510    #[tokio::test]
511    async fn mock_transport_round_trip() {
512        let mut transport = MockTransport::new();
513        transport.script_recv(br#"{"setupComplete":{}}"#.to_vec());
514
515        transport
516            .connect("wss://example.com", vec![])
517            .await
518            .unwrap();
519        transport.send(b"hello".to_vec()).await.unwrap();
520        let data = transport.recv().await.unwrap();
521        assert!(data.is_some());
522        let text = String::from_utf8(data.unwrap()).unwrap();
523        assert!(text.contains("setupComplete"));
524    }
525
526    #[tokio::test]
527    async fn mock_transport_records_sent() {
528        let mut transport = MockTransport::new();
529        transport
530            .connect("wss://example.com", vec![])
531            .await
532            .unwrap();
533        transport.send(b"msg1".to_vec()).await.unwrap();
534        transport.send(b"msg2".to_vec()).await.unwrap();
535        let sent = transport.take_sent();
536        assert_eq!(sent.len(), 2);
537        assert_eq!(sent[0], b"msg1");
538    }
539
540    #[tokio::test]
541    async fn mock_transport_recv_pends_when_queue_empty() {
542        let mut transport = MockTransport::new();
543        transport
544            .connect("wss://example.com", vec![])
545            .await
546            .unwrap();
547        // recv() should pend when queue is empty (simulating idle transport)
548        let result =
549            tokio::time::timeout(std::time::Duration::from_millis(50), transport.recv()).await;
550        assert!(result.is_err(), "recv should pend when queue is empty");
551    }
552
553    #[tokio::test]
554    async fn mock_transport_recv_errors_when_not_connected() {
555        let mut transport = MockTransport::new();
556        // Not connected yet — recv should error
557        let result = transport.recv().await;
558        assert!(result.is_err());
559    }
560
561    #[tokio::test]
562    async fn mock_transport_not_connected_error() {
563        let mut transport = MockTransport::new();
564        let result = transport.send(b"data".to_vec()).await;
565        assert!(result.is_err());
566    }
567
568    #[test]
569    fn transport_trait_is_object_safe_check() {
570        // Transport has an associated type, so it's not directly object-safe
571        // but can be used as generic bounds. This test just verifies compilation.
572        fn _assert_transport<T: Transport>() {}
573        _assert_transport::<MockTransport>();
574    }
575}