ag_ui/client/transport/sse.rs
1//! Decoding `text/event-stream`.
2//!
3//! The encoder lives in `ag_ui::encode`; this is the other half. It is a wire
4//! format parser fed by a network, so it assumes nothing about what it is
5//! handed: bytes arrive in arbitrary chunks that split lines, split UTF-8
6//! sequences, and end without the terminating blank line the format calls for.
7//!
8//! What it handles, because real servers and proxies do all of it:
9//!
10//! - `data:` repeated over several lines, rejoined with `\n` — the format's own
11//! way of carrying a payload that contains newlines.
12//! - Comment lines (`: keep-alive`), which proxies inject to hold a connection
13//! open and which dispatch nothing.
14//! - A body that ends without a blank line: [`SseDecoder::finish`] dispatches
15//! the last frame rather than dropping it.
16//! - `\n`, `\r\n` and lone `\r` line endings, including a `\r\n` split across
17//! two chunks.
18//! - A leading UTF-8 byte-order mark.
19//! - A field with no colon, an empty field value, and unknown field names.
20//! - A frame with no `data` field, which the format says not to dispatch.
21//!
22//! What it refuses: invalid UTF-8, and a single frame larger than
23//! [`SseDecoder::max_frame_size`] — an unterminated line is otherwise an
24//! unbounded allocation driven by the other end. The cap is on the frame, not
25//! on the chunk: one read carrying a thousand complete frames is ordinary, and
26//! counting it against a per-frame limit would refuse a well-behaved server.
27//!
28//! ```
29//! use ag_ui::client::transport::SseDecoder;
30//!
31//! let mut decoder = SseDecoder::new();
32//! decoder.push(b": keep-alive\n\ndata: {\"type\":\"RUN_ERROR\",\"mes")?;
33//! assert!(decoder.next_frame()?.is_none());
34//!
35//! decoder.push(b"sage\":\"boom\"}\n\n")?;
36//! let frame = decoder.next_frame()?.expect("a complete frame");
37//! assert_eq!(frame.into_event()?.event_type().as_str(), "RUN_ERROR");
38//! # Ok::<(), ag_ui::client::Error>(())
39//! ```
40
41use std::collections::VecDeque;
42
43use crate::Event;
44use futures_core::Stream;
45use futures_util::StreamExt;
46use serde_json::Value;
47
48use crate::client::error::{Error, Result};
49
50/// The default cap on one frame, before the decoder gives up: 8 MiB.
51pub const DEFAULT_MAX_FRAME_SIZE: usize = 8 * 1024 * 1024;
52
53/// One decoded `text/event-stream` frame.
54#[derive(Clone, Debug, Default, PartialEq, Eq)]
55pub struct SseFrame {
56 /// The `event:` field, if the server sent one. AG-UI does not use it.
57 pub event: Option<String>,
58 /// The `data:` field, with the trailing newline removed and multiple
59 /// `data:` lines rejoined with `\n`.
60 pub data: String,
61 /// The `id:` field, if the server sent one.
62 pub id: Option<String>,
63 /// The `retry:` field, in milliseconds, if the server sent one.
64 pub retry: Option<u64>,
65}
66
67impl SseFrame {
68 /// Parses the frame payload as JSON without discarding any unknown fields.
69 pub fn into_raw_value(self) -> Result<Value> {
70 serde_json::from_str(&self.data).map_err(Error::from)
71 }
72
73 /// Parses one frame strictly, without the stream compatibility and
74 /// enforcement stages. Application streams use [`decode_events`].
75 pub fn into_event(self) -> Result<Event> {
76 serde_json::from_str(&self.data).map_err(Error::from)
77 }
78}
79
80/// An incremental `text/event-stream` decoder.
81///
82/// Push bytes, pull frames. It owns a buffer for the partial line at the end of
83/// each chunk, which is why it has to be a struct and not a function.
84#[derive(Clone, Debug)]
85pub struct SseDecoder {
86 buffer: Vec<u8>,
87 /// How much of `buffer` has already been handed out as lines.
88 ///
89 /// The consumed prefix is dropped on the next push rather than as each line
90 /// is taken: shifting the remainder once per read instead of once per line
91 /// is what keeps a chunk carrying a thousand frames linear.
92 consumed: usize,
93 /// A CR at the end of the last read already ended its line. If the
94 /// next nonempty read begins with LF, consume it as part of that CRLF.
95 skip_lf: bool,
96 /// First byte of the pending line not yet checked for a terminator.
97 scan_from: usize,
98 data: String,
99 event: Option<String>,
100 id: Option<String>,
101 retry: Option<u64>,
102 max_frame_size: usize,
103 frame_bytes: usize,
104 at_start: bool,
105}
106
107impl Default for SseDecoder {
108 fn default() -> Self {
109 Self::new()
110 }
111}
112
113impl SseDecoder {
114 /// A decoder with the default frame size cap.
115 pub fn new() -> Self {
116 Self {
117 buffer: Vec::new(),
118 consumed: 0,
119 skip_lf: false,
120 scan_from: 0,
121 data: String::new(),
122 event: None,
123 id: None,
124 retry: None,
125 max_frame_size: DEFAULT_MAX_FRAME_SIZE,
126 frame_bytes: 0,
127 at_start: true,
128 }
129 }
130
131 /// Sets the cap on a single frame, counting UTF-8 field and comment bytes
132 /// but excluding line terminators and the initial byte-order mark.
133 #[must_use]
134 pub fn with_max_frame_size(mut self, bytes: usize) -> Self {
135 self.max_frame_size = bytes;
136 self
137 }
138
139 /// The cap on a single frame, in bytes.
140 pub fn max_frame_size(&self) -> usize {
141 self.max_frame_size
142 }
143
144 /// Feeds the decoder a chunk of the response body.
145 ///
146 /// # Errors
147 ///
148 /// [`Error::Decode`] when the frame being assembled exceeds
149 /// [`SseDecoder::max_frame_size`] — a server that never sends a line break
150 /// would otherwise grow this buffer without bound.
151 pub fn push(&mut self, bytes: &[u8]) -> Result<()> {
152 if self.consumed > 0 {
153 self.buffer.drain(..self.consumed);
154 self.scan_from -= self.consumed;
155 self.consumed = 0;
156 }
157 let bytes = if self.skip_lf && !bytes.is_empty() {
158 self.skip_lf = false;
159 bytes.strip_prefix(b"\n").unwrap_or(bytes)
160 } else {
161 bytes
162 };
163 self.buffer.extend_from_slice(bytes);
164 // A complete line may dispatch an earlier frame. Leave later lines
165 // for next_frame so network chunking cannot hide a valid prefix.
166 if self.line_end().is_none() {
167 self.check_partial_line()?;
168 }
169 Ok(())
170 }
171
172 /// The bytes pushed but not yet handed out as lines.
173 fn pending(&self) -> &[u8] {
174 &self.buffer[self.consumed..]
175 }
176
177 fn line_end(&mut self) -> Option<usize> {
178 let rest = &self.buffer[self.scan_from..];
179 let scanned = rest
180 .iter()
181 .position(|b| matches!(b, b'\n' | b'\r'))
182 .unwrap_or(rest.len());
183 self.scan_from += scanned;
184 (self.scan_from < self.buffer.len()).then_some(self.scan_from)
185 }
186
187 fn check_partial_line(&self) -> Result<()> {
188 let pending = self.without_initial_bom(self.pending());
189 self.check_size(self.frame_bytes.saturating_add(pending.len()))
190 }
191
192 fn without_initial_bom<'a>(&self, pending: &'a [u8]) -> &'a [u8] {
193 if self.at_start {
194 if b"\xef\xbb\xbf".starts_with(pending) {
195 return &[];
196 }
197 pending.strip_prefix(b"\xef\xbb\xbf").unwrap_or(pending)
198 } else {
199 pending
200 }
201 }
202
203 fn check_size(&self, bytes: usize) -> Result<()> {
204 if bytes > self.max_frame_size {
205 return Err(Error::decode(format!(
206 "frame exceeded the {} byte limit across its data lines or fields",
207 self.max_frame_size
208 )));
209 }
210 Ok(())
211 }
212
213 fn checked_process(&mut self, line: &str) -> Result<Option<SseFrame>> {
214 if line.is_empty() {
215 self.frame_bytes = 0;
216 } else {
217 self.frame_bytes = self.frame_bytes.saturating_add(line.len());
218 self.check_size(self.frame_bytes)?;
219 }
220 Ok(self.process(line))
221 }
222
223 /// Pulls the next complete frame, if the bytes pushed so far contain one.
224 ///
225 /// # Errors
226 ///
227 /// [`Error::Decode`] when the bytes are not UTF-8 or the frame exceeds its cap.
228 pub fn next_frame(&mut self) -> Result<Option<SseFrame>> {
229 while let Some(line) = self.take_line(false)? {
230 if let Some(frame) = self.checked_process(&line)? {
231 return Ok(Some(frame));
232 }
233 }
234 self.check_partial_line()?;
235 Ok(None)
236 }
237
238 /// Drains the decoder at the end of the stream.
239 ///
240 /// A body that stops without the blank line that terminates its last frame
241 /// is common enough — a closed connection, a server that forgets — that
242 /// dropping the frame would lose real events. Anything still buffered is
243 /// dispatched here.
244 ///
245 /// # Errors
246 ///
247 /// [`Error::Decode`] when the trailing bytes are not UTF-8 or exceed the cap.
248 pub fn finish(&mut self) -> Result<Vec<SseFrame>> {
249 let mut frames = Vec::new();
250 while let Some(line) = self.take_line(true)? {
251 if let Some(frame) = self.checked_process(&line)? {
252 frames.push(frame);
253 }
254 }
255 if let Some(frame) = self.dispatch() {
256 frames.push(frame);
257 }
258 Ok(frames)
259 }
260
261 /// Takes one complete line, minus its terminator.
262 ///
263 /// At `eof` the trailing bytes count as a line even without a terminator.
264 /// A trailing CR is already a terminator, even if the next read never arrives.
265 fn take_line(&mut self, eof: bool) -> Result<Option<String>> {
266 let position = self.line_end().map(|end| end - self.consumed);
267 let pending = self.pending();
268 let Some(position) = position else {
269 if eof && !pending.is_empty() {
270 let line = pending.to_vec();
271 self.consumed = self.buffer.len();
272 return self.decode_line(line).map(Some);
273 }
274 return Ok(None);
275 };
276
277 let is_cr = pending[position] == b'\r';
278 let trailing_cr = is_cr && position + 1 == pending.len();
279 let width = if is_cr && pending.get(position + 1) == Some(&b'\n') {
280 2
281 } else {
282 1
283 };
284 let line = pending[..position].to_vec();
285 self.skip_lf = trailing_cr;
286 self.consumed += position + width;
287 self.scan_from = self.consumed;
288 self.decode_line(line).map(Some)
289 }
290
291 fn decode_line(&mut self, line: Vec<u8>) -> Result<String> {
292 let mut line = String::from_utf8(line)
293 .map_err(|error| Error::decode(format!("stream is not UTF-8: {error}")))?;
294 if self.at_start {
295 self.at_start = false;
296 if let Some(stripped) = line.strip_prefix('\u{feff}') {
297 line = stripped.to_owned();
298 }
299 }
300 Ok(line)
301 }
302
303 /// Applies one line to the frame being built, dispatching on a blank line.
304 fn process(&mut self, line: &str) -> Option<SseFrame> {
305 if line.is_empty() {
306 return self.dispatch();
307 }
308 if line.starts_with(':') {
309 // A comment. Heartbeats are the usual reason one is here.
310 return None;
311 }
312
313 let (field, value) = match line.find(':') {
314 Some(index) => (&line[..index], strip_one_space(&line[index + 1..])),
315 // A field name with no colon has an empty value.
316 None => (line, ""),
317 };
318
319 match field {
320 "data" => {
321 self.data.push_str(value);
322 self.data.push('\n');
323 }
324 "event" => self.event = Some(value.to_owned()),
325 "id" => self.id = Some(value.to_owned()),
326 "retry" => {
327 if let Ok(milliseconds) = value.parse() {
328 self.retry = Some(milliseconds);
329 }
330 }
331 // Unknown fields are ignored, as the format requires.
332 _ => {}
333 }
334 None
335 }
336
337 /// Emits the buffered frame, if it has a payload.
338 fn dispatch(&mut self) -> Option<SseFrame> {
339 self.frame_bytes = 0;
340 let event = self.event.take();
341 let id = self.id.take();
342 let retry = self.retry.take();
343 let mut data = std::mem::take(&mut self.data);
344 if data.is_empty() {
345 // No data field: the format says this dispatches nothing. A frame
346 // of pure comments or a stray blank line lands here.
347 return None;
348 }
349 data.pop();
350 Some(SseFrame {
351 event,
352 data,
353 id,
354 retry,
355 })
356 }
357}
358
359/// Removes the single optional space after a field's colon.
360fn strip_one_space(value: &str) -> &str {
361 value.strip_prefix(' ').unwrap_or(value)
362}
363
364/// Decodes a stream of byte chunks into a stream of events.
365///
366/// This is the adapter between a transport's body stream and the rest of the
367/// crate. Unknown additions are dropped, while malformed known fields and
368/// framing errors end the stream with an error item.
369pub fn decode_events<S, B, E>(chunks: S) -> impl Stream<Item = Result<Event>>
370where
371 S: Stream<Item = core::result::Result<B, E>>,
372 B: AsRef<[u8]>,
373 E: std::error::Error + Send + Sync + 'static,
374{
375 crate::client::enforce::stream(decode_raw_events(chunks))
376}
377
378/// Decodes SSE frames into raw JSON values. A transport hands these on as
379/// [`TransportStream::json`](super::TransportStream::json), so the common
380/// compatibility boundary runs on what the peer actually sent.
381pub fn decode_raw_events<S, B, E>(chunks: S) -> impl Stream<Item = Result<Value>>
382where
383 S: Stream<Item = core::result::Result<B, E>>,
384 B: AsRef<[u8]>,
385 E: std::error::Error + Send + Sync + 'static,
386{
387 let state = Decoding {
388 chunks: Some(Box::pin(chunks)),
389 decoder: SseDecoder::new(),
390 ready: VecDeque::new(),
391 };
392
393 futures_util::stream::unfold(state, |mut state| async move {
394 loop {
395 if let Some(item) = state.ready.pop_front() {
396 return Some((item, state));
397 }
398 match state.chunks.as_mut()?.next().await {
399 Some(Ok(bytes)) => {
400 if let Err(error) = state.decoder.push(bytes.as_ref()) {
401 state.chunks = None;
402 return Some((Err(error), state));
403 }
404 loop {
405 match state.decoder.next_frame() {
406 Ok(Some(frame)) => match frame.into_raw_value() {
407 Ok(value) => state.ready.push_back(Ok(value)),
408 Err(error) => {
409 state.ready.push_back(Err(error));
410 state.chunks = None;
411 break;
412 }
413 },
414 Ok(None) => break,
415 Err(error) => {
416 state.chunks = None;
417 state.ready.push_back(Err(error));
418 break;
419 }
420 }
421 }
422 }
423 Some(Err(error)) => {
424 state.chunks = None;
425 return Some((Err(Error::transport(error)), state));
426 }
427 None => {
428 state.chunks = None;
429 match state.decoder.finish() {
430 Ok(frames) => {
431 for frame in frames {
432 match frame.into_raw_value() {
433 Ok(value) => state.ready.push_back(Ok(value)),
434 Err(error) => {
435 state.ready.push_back(Err(error));
436 break;
437 }
438 }
439 }
440 }
441 Err(error) => state.ready.push_back(Err(error)),
442 }
443 }
444 }
445 }
446 })
447}
448
449/// The state [`decode_events`] carries between polls.
450struct Decoding<S> {
451 chunks: Option<std::pin::Pin<Box<S>>>,
452 decoder: SseDecoder,
453 ready: VecDeque<Result<Value>>,
454}
455
456#[cfg(test)]
457mod tests {
458 use super::SseDecoder;
459
460 /// A body of `frames` identical two-line frames, and the size of one.
461 fn body(frames: usize) -> (String, usize) {
462 let frame = "data: {\"type\":\"CUSTOM\"}\n\n";
463 (frame.repeat(frames), frame.len())
464 }
465
466 #[test]
467 fn taking_a_line_moves_the_cursor_instead_of_the_bytes_behind_it() {
468 // `take_line` used to `split_off` the remainder of the buffer, copying
469 // every byte still unread once per line. One read carrying a thousand
470 // frames — a fast agent filling a TCP window — then cost a thousand
471 // copies of a shrinking buffer, and the total grew with the square of
472 // the frame count. The cursor is what makes it linear, and the buffer
473 // holding still while frames come out of it is how that is visible
474 // without timing anything.
475 let (body, frame_size) = body(64);
476 let mut decoder = SseDecoder::new();
477 decoder.push(body.as_bytes()).expect("pushes");
478 let pushed = decoder.buffer.len();
479
480 for taken in 1..=32 {
481 decoder
482 .next_frame()
483 .expect("decodes")
484 .expect("64 frames went in");
485 assert_eq!(
486 decoder.buffer.len(),
487 pushed,
488 "the unread remainder was recopied after {taken} frames"
489 );
490 assert_eq!(decoder.consumed, taken * frame_size);
491 }
492
493 // The consumed prefix is dropped once, on the next push, rather than
494 // once per line.
495 decoder.push(b"data: x\n\n").expect("pushes");
496 assert_eq!(decoder.consumed, 0);
497 assert_eq!(decoder.buffer.len(), pushed - 32 * frame_size + 9);
498 }
499
500 #[test]
501 fn dropping_the_consumed_prefix_does_not_disturb_what_is_still_buffered() {
502 // That drop rewrites the offset every remaining byte sits at, so the
503 // frames either side of a push have to come out whole and in order.
504 let (body, _) = body(4);
505 let mut decoder = SseDecoder::new();
506 decoder.push(body.as_bytes()).expect("pushes");
507 decoder.next_frame().expect("decodes").expect("a frame");
508 decoder.next_frame().expect("decodes").expect("a frame");
509
510 decoder.push(b"data: last\n\n").expect("pushes");
511 let mut rest = Vec::new();
512 while let Some(frame) = decoder.next_frame().expect("decodes") {
513 rest.push(frame.data);
514 }
515 assert_eq!(
516 rest,
517 [r#"{"type":"CUSTOM"}"#, r#"{"type":"CUSTOM"}"#, "last"]
518 );
519 }
520}