Skip to main content

nitr_http/testing/
sse.rs

1// SPDX-License-Identifier: MIT OR Apache-2.0
2// This file is part of Nitr.
3// See https://nitrweb.com/ for more information
4// Copyright (C) 2024-present Jose Quintana <joseluisq.net>
5
6//! A parser for a collected `text/event-stream` body (`resp:sse()` in
7//! `nitr test`), following the WHATWG event-stream interpretation rules.
8
9/// One dispatched server-sent event.
10#[derive(Debug, Clone, Default, PartialEq, Eq)]
11pub struct SseEvent {
12    /// The `event:` field, when one was given.
13    pub event: Option<String>,
14    /// The `data:` lines, joined with `\n`.
15    pub data: String,
16    /// The `id:` field, when one was given.
17    pub id: Option<String>,
18    /// The `retry:` field, when it was a number.
19    pub retry: Option<u64>,
20}
21
22/// Parses a whole event-stream body into its events, in order.
23///
24/// Lines end in `\r\n`, `\n` or `\r`; a blank line dispatches the event
25/// being built, unless it has no `data` (which the spec discards); a line
26/// starting with `:` is a comment; `field:value` loses one space after the
27/// colon; a line without a colon is a field with an empty value; unknown
28/// fields and an `id` containing NUL are ignored. A final event without
29/// its blank line is not dispatched — a browser would not have seen it
30/// either. Linear in the input, one pass, no recursion.
31///
32/// One deliberate difference from a browser, for the sake of assertions:
33/// `id` and `retry` describe the event whose lines carried them, rather
34/// than the stream-wide last-event-id and reconnection delay a client
35/// keeps.
36pub fn parse_sse(body: &[u8]) -> Vec<SseEvent> {
37    let text = String::from_utf8_lossy(body);
38    let mut events = Vec::new();
39    let mut current = SseEvent::default();
40    let mut has_data = false;
41    let mut rest: &str = &text;
42    // A leading byte-order mark is stripped once, per the spec.
43    rest = rest.strip_prefix('\u{feff}').unwrap_or(rest);
44    while !rest.is_empty() {
45        let end = rest.find(['\r', '\n']).unwrap_or(rest.len());
46        let line = &rest[..end];
47        let mut next = &rest[end..];
48        if next.starts_with("\r\n") {
49            next = &next[2..];
50        } else if !next.is_empty() {
51            next = &next[1..];
52        } else {
53            // The last line had no terminator: it cannot complete an
54            // event, but its fields still accumulate.
55        }
56        rest = next;
57
58        if line.is_empty() {
59            if has_data {
60                events.push(std::mem::take(&mut current));
61            } else {
62                current = SseEvent::default();
63            }
64            has_data = false;
65            continue;
66        }
67        if line.starts_with(':') {
68            continue;
69        }
70        let (field, value) = match line.split_once(':') {
71            Some((field, value)) => (field, value.strip_prefix(' ').unwrap_or(value)),
72            None => (line, ""),
73        };
74        match field {
75            "event" => current.event = Some(value.to_string()),
76            "data" => {
77                if has_data {
78                    current.data.push('\n');
79                }
80                current.data.push_str(value);
81                has_data = true;
82            }
83            "id" if !value.contains('\0') => current.id = Some(value.to_string()),
84            "retry" if !value.is_empty() && value.bytes().all(|b| b.is_ascii_digit()) => {
85                current.retry = value.parse().ok();
86            }
87            _ => {}
88        }
89    }
90    events
91}
92
93#[cfg(test)]
94mod tests {
95    use super::*;
96
97    #[test]
98    fn events_parse_with_every_line_ending_and_field() {
99        let body = b"retry: 1500\r\n: a comment\r\nevent: tick\nid: 7\ndata: one\rdata:two\n\ndata: {\"n\":1}\n\n";
100        let events = parse_sse(body);
101        assert_eq!(
102            events,
103            vec![
104                SseEvent {
105                    event: Some("tick".into()),
106                    data: "one\ntwo".into(),
107                    id: Some("7".into()),
108                    retry: Some(1500),
109                },
110                SseEvent {
111                    event: None,
112                    data: "{\"n\":1}".into(),
113                    id: None,
114                    retry: None,
115                },
116            ]
117        );
118    }
119
120    #[test]
121    fn events_without_data_or_a_terminating_blank_line_are_not_dispatched() {
122        assert!(
123            parse_sse(b"event: ping\n\n").is_empty(),
124            "no data, no event"
125        );
126        assert!(parse_sse(b"data: cut off").is_empty());
127        assert!(parse_sse(b"").is_empty());
128        let events = parse_sse(b"data\n\n");
129        assert_eq!(events[0].data, "", "a bare field name has an empty value");
130        let events = parse_sse(b"retry: soon\nid: a\0b\ndata: x\n\n");
131        assert_eq!((events[0].retry, events[0].id.as_deref()), (None, None));
132    }
133
134    proptest::proptest! {
135        /// Property: a list of events serialized the way `nitr.sse` writes
136        /// them parses back to the same list.
137        #[test]
138        fn prop_sse_parser_events(
139            events in proptest::collection::vec(
140                (
141                    proptest::option::of("[a-z]{1,8}"),
142                    proptest::collection::vec("[ -~]{0,16}", 1..4),
143                    proptest::option::of("[a-z0-9]{1,8}"),
144                ),
145                0..8,
146            ),
147            crlf in proptest::bool::ANY,
148        ) {
149            let nl = if crlf { "\r\n" } else { "\n" };
150            let mut body = String::new();
151            let mut expected = Vec::new();
152            for (event, lines, id) in &events {
153                if let Some(event) = event {
154                    body.push_str(&format!("event: {event}{nl}"));
155                }
156                if let Some(id) = id {
157                    body.push_str(&format!("id: {id}{nl}"));
158                }
159                for line in lines {
160                    body.push_str(&format!("data: {line}{nl}"));
161                }
162                body.push_str(nl);
163                expected.push(SseEvent {
164                    event: event.clone(),
165                    data: lines.join("\n"),
166                    id: id.clone(),
167                    retry: None,
168                });
169            }
170            proptest::prop_assert_eq!(parse_sse(body.as_bytes()), expected);
171        }
172    }
173}