pub struct SseDecoder { /* private fields */ }Expand description
An incremental SSE decoder: push bytes, take complete events.
SseStream drives one over a byte stream; use it directly when the
bytes do not come as a Stream (a callback API, a test).
Decoding is linear: each byte is scanned for a line ending once, however
the chunks split the lines. A size cap
(max_event_size) bounds the line still waiting
for its ending, where memory grows from chunk to chunk, and the data an
event accumulates.
use allama_http::sse::SseDecoder;
let mut decoder = SseDecoder::new();
decoder.push(b"event: ping\r");
assert_eq!(decoder.next_event(), Ok(None));
decoder.push(b"\ndata: {}\r\n\r\n");
let event = decoder.next_event().unwrap().unwrap();
assert_eq!((event.event.as_str(), event.data.as_str()), ("ping", "{}"));
assert_eq!(decoder.next_event(), Ok(None));Implementations§
Source§impl SseDecoder
impl SseDecoder
Sourcepub const DEFAULT_MAX_EVENT_SIZE: usize
pub const DEFAULT_MAX_EVENT_SIZE: usize
The default max_event_size: 64 MiB.
Generous on purpose: a Responses response.completed event repeats
every output of the response, and streamed base64 images (OpenAI
partial images, Gemini inline data) can pass 16 MiB.
Sourcepub fn max_event_size(self, limit: usize) -> Self
pub fn max_event_size(self, limit: usize) -> Self
Set the size cap, in bytes (default
DEFAULT_MAX_EVENT_SIZE).
It bounds a line (its line ending excluded) and an event’s data (its
data: values, joined). push checks the line still
waiting for its ending before it buffers a chunk, so that line never
grows past the cap, not even briefly while the buffer reallocates.
Past the cap, next_event fails with
SseError::EventTooLarge, and decoding cannot go on: the decoder
drops what it holds, ignores later bytes and keeps returning the
error.
use allama_http::sse::{SseDecoder, SseError};
let mut decoder = SseDecoder::new().max_event_size(16);
decoder.push(b"data: 0123456789");
assert_eq!(decoder.next_event(), Ok(None));
// A 17th byte without a line ending.
decoder.push(b"a");
assert!(matches!(
decoder.next_event(),
Err(SseError::EventTooLarge { limit: 16, .. })
));Sourcepub fn push(&mut self, bytes: &[u8])
pub fn push(&mut self, bytes: &[u8])
Append received bytes. Chunk boundaries may fall anywhere, inside a
line, a CRLF or a UTF-8 sequence.
Bytes that would take the line still waiting for its ending past the
size cap are not buffered:
next_event returns the events completed before
that line, then fails.
Sourcepub fn next_event(&mut self) -> Result<Option<SseEvent>, SseError<Infallible>>
pub fn next_event(&mut self) -> Result<Option<SseEvent>, SseError<Infallible>>
The next complete event, or None until more bytes arrive.
§Errors
SseError::InvalidUtf8when a line is not valid UTF-8. The line is skipped, and decoding can go on, but the stream is corrupt:SseStreamends there.SseError::EventTooLargepast the size cap. Decoding cannot go on.
A decoder fails with no other error: it reads no transport.