Skip to main content

trusty_code/tui_client/
sse.rs

1//! [`SseLines`]: a minimal Server-Sent-Events line pump over a
2//! `reqwest::Response` body (issue #3415).
3//!
4//! Why: `CodeEngine` consumes two SSE routes
5//! (`GET /sessions/{id}/events`, `GET /workstreams/{id}/events`) that both
6//! frame their payloads as plain `data: <json>\n\n` lines (axum's
7//! `axum::response::sse::Event::default().json_data(..)`, see
8//! `crate::serve::http::sse_event_for`/`crate::workstreams::sse::sse_event_for`).
9//! Pulling in a full SSE client crate for "read `data:` lines from a byte
10//! stream" would be disproportionate; `crate::cli_client::stdio` already
11//! shows this crate's convention of hand-rolling the minimal wire parser
12//! for a trusted, in-house transport rather than adding a dependency for a
13//! few lines of line-splitting (mirrors
14//! `trusty_common::chat::openai_compat::sse_pump::pump_openai_sse`'s
15//! `buf.find('\n')` loop, adapted to this crate's own `data:` framing).
16//! What: [`SseLines::new`] wraps a `reqwest::Response`'s byte stream;
17//! [`SseLines::next_data`] returns the next non-empty `data:` payload
18//! (already stripped of the prefix and trimmed) as `Ok(Some(json_text))`,
19//! `Ok(None)` on a clean upstream close, or `Err` on a stream I/O failure.
20//! SSE comment lines (`:` keep-alive pings) and blank `data:` lines are
21//! silently skipped, never surfaced.
22//! Test: `sse_tests::*` against synthetic byte chunks (no network).
23
24use std::pin::Pin;
25
26use futures_util::{Stream, StreamExt};
27
28/// See module docs.
29pub struct SseLines {
30    stream: Pin<Box<dyn Stream<Item = reqwest::Result<Vec<u8>>> + Send>>,
31    buf: String,
32}
33
34impl SseLines {
35    /// Wrap `resp`'s body as an SSE line source.
36    pub fn new(resp: reqwest::Response) -> Self {
37        // `.map` converts each `bytes::Bytes` chunk to `Vec<u8>` so this
38        // module never needs to name the `bytes` crate's type directly (not
39        // otherwise a dependency of this crate).
40        let stream = resp.bytes_stream().map(|r| r.map(|b| b.to_vec()));
41        Self {
42            stream: Box::pin(stream),
43            buf: String::new(),
44        }
45    }
46
47    /// Return the next `data:` payload, reading more of the underlying byte
48    /// stream as needed.
49    ///
50    /// Why/What: see module docs.
51    /// Test: `sse_tests::next_data_skips_comments_and_blank_lines`,
52    /// `sse_tests::next_data_returns_none_on_clean_close`,
53    /// `sse_tests::next_data_on_empty_body_returns_none`.
54    pub async fn next_data(&mut self) -> Result<Option<String>, reqwest::Error> {
55        loop {
56            if let Some(idx) = self.buf.find('\n') {
57                let line: String = self.buf.drain(..=idx).collect();
58                let line = line.trim();
59                if let Some(payload) = line.strip_prefix("data:") {
60                    let payload = payload.trim();
61                    if !payload.is_empty() {
62                        return Ok(Some(payload.to_string()));
63                    }
64                }
65                // Every other line shape (blank keep-alive, `event:`,
66                // `id:`, `:comment`) is intentionally ignored — neither SSE
67                // route this client consumes uses named events or ids.
68                continue;
69            }
70            match self.stream.next().await {
71                Some(Ok(bytes)) => {
72                    if let Ok(text) = std::str::from_utf8(&bytes) {
73                        self.buf.push_str(text);
74                    }
75                    // Invalid UTF-8 mid-chunk is dropped rather than erroring
76                    // — SSE framing here is always JSON text; a malformed
77                    // chunk boundary is exceedingly unlikely and, if it
78                    // happens, the next chunk still resyncs on the next
79                    // `\n`.
80                }
81                Some(Err(e)) => return Err(e),
82                None => return Ok(None),
83            }
84        }
85    }
86}
87
88#[cfg(test)]
89mod sse_tests {
90    use super::*;
91    use wiremock::matchers::{method, path};
92    use wiremock::{Mock, MockServer, ResponseTemplate};
93
94    /// Build an `SseLines` whose byte stream comes from a `wiremock`
95    /// response body — the simplest way to get a REAL `reqwest::Response`
96    /// (needed for `.bytes_stream()`) without standing up a hand-rolled
97    /// hyper server.
98    async fn sse_lines_for_body(body: &str) -> SseLines {
99        let server = MockServer::start().await;
100        Mock::given(method("GET"))
101            .and(path("/events"))
102            .respond_with(
103                ResponseTemplate::new(200).set_body_raw(body.to_string(), "text/event-stream"),
104            )
105            .mount(&server)
106            .await;
107        let resp = reqwest::get(format!("{}/events", server.uri()))
108            .await
109            .expect("get");
110        SseLines::new(resp)
111    }
112
113    /// Comment lines (`: keep-alive`) and blank `data:` framing must be
114    /// skipped; only real payloads are returned, in order.
115    #[tokio::test]
116    async fn next_data_skips_comments_and_blank_lines() {
117        let mut lines =
118            sse_lines_for_body(": keep-alive\n\ndata: {\"a\":1}\n\ndata:\n\ndata: {\"a\":2}\n\n")
119                .await;
120        assert_eq!(
121            lines.next_data().await.expect("read"),
122            Some("{\"a\":1}".to_string())
123        );
124        assert_eq!(
125            lines.next_data().await.expect("read"),
126            Some("{\"a\":2}".to_string())
127        );
128        assert_eq!(lines.next_data().await.expect("read"), None);
129    }
130
131    /// A clean upstream close (no more bytes) must yield `Ok(None)`, not an
132    /// error — this is the normal "server finished the stream" case, not a
133    /// transport failure.
134    #[tokio::test]
135    async fn next_data_returns_none_on_clean_close() {
136        let mut lines = sse_lines_for_body("data: {\"only\":true}\n\n").await;
137        assert_eq!(
138            lines.next_data().await.expect("read"),
139            Some("{\"only\":true}".to_string())
140        );
141        assert_eq!(lines.next_data().await.expect("read"), None);
142    }
143
144    /// An empty body must yield `Ok(None)` on the very first call.
145    #[tokio::test]
146    async fn next_data_on_empty_body_returns_none() {
147        let mut lines = sse_lines_for_body("").await;
148        assert_eq!(lines.next_data().await.expect("read"), None);
149    }
150}