Skip to main content

causa_protocol/translation/sse_parser/
parser.rs

1use causa_kernel::{ModelInvokeError, ModelInvokeErrorKind};
2
3const DEFAULT_LIMIT: usize = 32 * 1024 * 1024;
4
5/// A complete SSE event, delimited by an empty line.
6#[derive(Debug, Clone, PartialEq, Eq)]
7#[non_exhaustive]
8pub struct SseEvent {
9    /// Explicit event name; absent or empty means the SSE default `message`.
10    pub event: Option<String>,
11    /// Data fields joined with one newline, including empty data fields.
12    pub data: String,
13}
14impl SseEvent {
15    /// An event with an optional name and its data.
16    pub fn new(event: Option<String>, data: impl Into<String>) -> Self {
17        Self {
18            event,
19            data: data.into(),
20        }
21    }
22}
23
24/// A bounded byte decoder with no event queue or input history.
25///
26/// UTF-8 is validated as lines become complete, so a chunk may end inside a
27/// character. LF, CRLF and CR terminate lines; a leading UTF-8 BOM is ignored.
28/// Comments and unknown fields are ignored but count against the event limit.
29/// Errors latch: after an error, discard the parser. There is no lossy decode,
30/// oversized-event truncation, or implicit EOF dispatch.
31///
32/// ```
33/// use causa_protocol::SseParser;
34/// let mut parser = SseParser::new();
35/// let mut bytes = b"data: hello\n\ndata: world\n\n".as_slice();
36/// assert_eq!(parser.decode(&mut bytes)?.unwrap().data, "hello");
37/// assert_eq!(parser.decode(&mut bytes)?.unwrap().data, "world");
38/// assert!(parser.decode(&mut bytes)?.is_none());
39/// parser.finish()?;
40/// # Ok::<(), causa_kernel::ModelInvokeError>(())
41/// ```
42#[derive(Debug)]
43pub struct SseParser {
44    line: Vec<u8>,
45    event_name: Option<String>,
46    data: String,
47    has_data: bool,
48    first_line: bool,
49    after_cr: bool,
50    event_bytes: usize,
51    max_line_bytes: usize,
52    max_event_bytes: usize,
53    failed: bool,
54    finished: bool,
55}
56
57impl Default for SseParser {
58    fn default() -> Self {
59        Self::new()
60    }
61}
62
63impl SseParser {
64    /// Create a decoder with 32 MiB line and event limits.
65    pub fn new() -> Self {
66        Self {
67            line: Vec::new(),
68            event_name: None,
69            data: String::new(),
70            has_data: false,
71            first_line: true,
72            after_cr: false,
73            event_bytes: 0,
74            max_line_bytes: DEFAULT_LIMIT,
75            max_event_bytes: DEFAULT_LIMIT,
76            failed: false,
77            finished: false,
78        }
79    }
80
81    /// Set raw line and event byte limits before decoding.
82    ///
83    /// A line excludes its terminator. An event includes its lines, ignored
84    /// fields and delimiters. A CRLF counts as CR plus a skipped LF; the LF
85    /// does not belong to the next event. Zero limits reject nonempty input.
86    pub fn with_limits(mut self, max_line_bytes: usize, max_event_bytes: usize) -> Self {
87        self.max_line_bytes = max_line_bytes;
88        self.max_event_bytes = max_event_bytes;
89        self
90    }
91
92    /// Consume bytes through at most one complete event.
93    ///
94    /// The caller retains the remaining slice and should call again, including
95    /// when multiple events arrived in one HTTP chunk. `None` means all supplied
96    /// bytes were consumed without completing a data event. Completed comments
97    /// and unknown fields do not emit events. Calls after successful `finish`
98    /// reject nonempty input.
99    pub fn decode(&mut self, input: &mut &[u8]) -> Result<Option<SseEvent>, ModelInvokeError> {
100        if self.failed {
101            return Err(misused("SSE parser is in a failed state"));
102        }
103        if self.finished {
104            return if input.is_empty() {
105                Ok(None)
106            } else {
107                self.fail(misused("SSE input received after EOF"))
108            };
109        }
110        match self.decode_inner(input) {
111            Ok(event) => Ok(event),
112            Err(error) => self.fail(error),
113        }
114    }
115
116    /// Validate EOF without emitting an unfinished event.
117    ///
118    /// Invalid or truncated UTF-8 is `Undecodable`; a valid unterminated line or
119    /// event is `UnknownOutcome`. A clean SSE boundary succeeds, but does not
120    /// prove that the enclosing model protocol supplied its terminal event.
121    pub fn finish(&mut self) -> Result<(), ModelInvokeError> {
122        if self.failed {
123            return Err(misused("SSE parser is in a failed state"));
124        }
125        if std::str::from_utf8(&self.line).is_err() {
126            return self.fail(undecodable("SSE input ended with invalid UTF-8"));
127        }
128        if !self.line.is_empty() || self.has_data || self.event_name.is_some() {
129            return self.fail(ModelInvokeError::new(
130                ModelInvokeErrorKind::UnknownOutcome,
131                "SSE input ended before an event delimiter",
132            ));
133        }
134        self.finished = true;
135        Ok(())
136    }
137
138    fn decode_inner(&mut self, input: &mut &[u8]) -> Result<Option<SseEvent>, ModelInvokeError> {
139        while !input.is_empty() {
140            if self.after_cr {
141                self.after_cr = false;
142                if input[0] == b'\n' {
143                    *input = &input[1..];
144                    // The CR has already ended the line (possibly the event).
145                    continue;
146                }
147            }
148            let length = input
149                .iter()
150                .position(|byte| matches!(byte, b'\r' | b'\n'))
151                .unwrap_or(input.len());
152            if self.line.len().saturating_add(length) > self.max_line_bytes {
153                return Err(undecodable("SSE line exceeds its byte limit"));
154            }
155            self.count_bytes(length)?;
156            self.line.extend_from_slice(&input[..length]);
157            *input = &input[length..];
158            if input.is_empty() {
159                return Ok(None);
160            }
161            self.count_bytes(1)?;
162            self.after_cr = input[0] == b'\r';
163            *input = &input[1..];
164            if let Some(event) = self.complete_line()? {
165                return Ok(Some(event));
166            }
167        }
168        Ok(None)
169    }
170
171    fn count_bytes(&mut self, count: usize) -> Result<(), ModelInvokeError> {
172        self.event_bytes = self
173            .event_bytes
174            .checked_add(count)
175            .filter(|bytes| *bytes <= self.max_event_bytes)
176            .ok_or_else(|| undecodable("SSE event exceeds its byte limit"))?;
177        Ok(())
178    }
179
180    fn complete_line(&mut self) -> Result<Option<SseEvent>, ModelInvokeError> {
181        let bytes = std::mem::take(&mut self.line);
182        let raw = std::str::from_utf8(&bytes)
183            .map_err(|_| undecodable("SSE line contains invalid UTF-8"))?;
184        let line = if self.first_line {
185            self.first_line = false;
186            raw.strip_prefix('\u{feff}').unwrap_or(raw)
187        } else {
188            raw
189        };
190        if line.is_empty() {
191            let event = self.has_data.then(|| SseEvent {
192                event: self.event_name.take().filter(|name| !name.is_empty()),
193                data: std::mem::take(&mut self.data),
194            });
195            self.event_name = None;
196            self.data.clear();
197            self.has_data = false;
198            self.event_bytes = 0;
199            return Ok(event);
200        }
201        if line.starts_with(':') {
202            return Ok(None);
203        }
204        let (field, value) = line.split_once(':').unwrap_or((line, ""));
205        let value = value.strip_prefix(' ').unwrap_or(value);
206        match field {
207            "data" => {
208                if self.has_data {
209                    self.data.push('\n');
210                }
211                self.data.push_str(value);
212                self.has_data = true;
213            }
214            "event" => self.event_name = Some(value.to_owned()),
215            _ => {}
216        }
217        Ok(None)
218    }
219
220    fn fail<T>(&mut self, error: ModelInvokeError) -> Result<T, ModelInvokeError> {
221        self.failed = true;
222        self.line = Vec::new();
223        self.event_name = None;
224        self.data = String::new();
225        Err(error)
226    }
227}
228
229fn undecodable(message: &str) -> ModelInvokeError {
230    ModelInvokeError::new(ModelInvokeErrorKind::Undecodable, message)
231}
232
233/// The caller broke the parser's contract; nothing the provider sent is at fault.
234fn misused(message: &str) -> ModelInvokeError {
235    ModelInvokeError::new(ModelInvokeErrorKind::InvalidRequest, message)
236}