redseat-api 0.3.0

Rust client for Redseat media servers
Documentation
//! Server-Sent Events parsing. Port of `@redseat/api-http` `sse-fetch.ts`
//! (`parseSSEBuffer`), plus an incremental decoder for byte chunks.

use std::collections::VecDeque;

use futures_util::{Stream, StreamExt};

use crate::error::Result;
use crate::transport::RawEvent;

/// Parses complete events out of `buffer` and returns them with the incomplete rest.
///
/// Follows the SSE spec: events are separated by blank lines, fields are
/// `field: value`, and `\r\n`, `\r` and `\n` all end a line. Comments (`:`) and
/// blocks without an `event` field are skipped, like the TS client.
pub fn parse_sse_buffer(buffer: &str) -> (Vec<RawEvent>, String) {
    let normalised = buffer.replace("\r\n", "\n").replace('\r', "\n");
    let mut events = Vec::new();
    let mut last_end = 0;

    while let Some(offset) = normalised[last_end..].find("\n\n") {
        let block = &normalised[last_end..last_end + offset];
        last_end += offset + 2;

        let mut event = RawEvent::default();
        let mut has_data = false;
        for line in block.split('\n') {
            if line.is_empty() || line.starts_with(':') {
                continue;
            }
            let Some((field, value)) = line.split_once(':') else {
                continue;
            };
            let value = value.strip_prefix(' ').unwrap_or(value);
            match field {
                "event" => event.event = value.to_owned(),
                "data" => {
                    if has_data {
                        event.data.push('\n');
                    }
                    event.data.push_str(value);
                    has_data = true;
                }
                "id" => event.id = Some(value.to_owned()),
                "retry" => event.retry = value.trim().parse().ok(),
                _ => {}
            }
        }
        if !event.event.is_empty() {
            events.push(event);
        }
    }

    (events, normalised[last_end..].to_owned())
}

/// Turns byte chunks of an event stream into events. Handles UTF-8 characters split
/// across chunks.
#[derive(Debug, Default)]
pub struct SseDecoder {
    bytes: Vec<u8>,
    text: String,
}

impl SseDecoder {
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds a chunk and returns the events it completes.
    pub fn push(&mut self, chunk: &[u8]) -> Vec<RawEvent> {
        self.bytes.extend_from_slice(chunk);
        let valid = match std::str::from_utf8(&self.bytes) {
            Ok(text) => text.len(),
            Err(error) if error.error_len().is_none() => error.valid_up_to(),
            // Invalid UTF-8, not just a cut character: replace it and move on.
            Err(_) => {
                let lossy = String::from_utf8_lossy(&self.bytes).into_owned();
                self.bytes.clear();
                self.text.push_str(&lossy);
                return self.drain();
            }
        };
        let rest = self.bytes.split_off(valid);
        // `valid` bytes are UTF-8: checked above.
        self.text
            .push_str(&String::from_utf8_lossy(&std::mem::replace(
                &mut self.bytes,
                rest,
            )));
        self.drain()
    }

    /// The last event when the stream ends without a trailing blank line.
    pub fn finish(mut self) -> Vec<RawEvent> {
        if !self.bytes.is_empty() {
            let rest = String::from_utf8_lossy(&self.bytes).into_owned();
            self.text.push_str(&rest);
        }
        if self.text.trim().is_empty() {
            return Vec::new();
        }
        self.text.push_str("\n\n");
        parse_sse_buffer(&self.text).0
    }

    fn drain(&mut self) -> Vec<RawEvent> {
        // A `\r` at the end may be the first half of a `\r\n` that the chunking cut:
        // keep it back until the next chunk, or it would count as a line of its own.
        let held_cr = self.text.ends_with('\r');
        if held_cr {
            self.text.pop();
        }
        let (events, mut rest) = parse_sse_buffer(&self.text);
        if held_cr {
            rest.push('\r');
        }
        self.text = rest;
        events
    }
}

/// Turns a stream of byte chunks into a stream of events. A chunk error is passed on
/// and ends the stream.
pub fn decode_event_stream<S, B>(chunks: S) -> impl Stream<Item = Result<RawEvent>>
where
    S: Stream<Item = Result<B>> + Unpin,
    B: AsRef<[u8]>,
{
    struct State<S> {
        chunks: S,
        decoder: Option<SseDecoder>,
        queue: VecDeque<RawEvent>,
    }
    let state = State {
        chunks,
        decoder: Some(SseDecoder::new()),
        queue: VecDeque::new(),
    };
    futures_util::stream::unfold(state, |mut state| async move {
        loop {
            if let Some(event) = state.queue.pop_front() {
                return Some((Ok(event), state));
            }
            state.decoder.as_ref()?;
            match state.chunks.next().await {
                Some(Ok(chunk)) => {
                    if let Some(decoder) = state.decoder.as_mut() {
                        state.queue.extend(decoder.push(chunk.as_ref()));
                    }
                }
                Some(Err(error)) => {
                    state.decoder = None;
                    return Some((Err(error), state));
                }
                None => {
                    if let Some(decoder) = state.decoder.take() {
                        state.queue.extend(decoder.finish());
                    }
                }
            }
        }
    })
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn decodes_a_chunk_stream_and_stops_at_an_error() {
        let chunks = futures_util::stream::iter(vec![
            Ok(b"event: a\ndata: 1\n\nevent: b\nda".to_vec()),
            Ok(b"ta: 2\n\n".to_vec()),
            Err(crate::Error::Cancelled {
                message: "gone".into(),
            }),
            Ok(b"event: c\ndata: 3\n\n".to_vec()),
        ]);
        let items: Vec<_> = decode_event_stream(chunks).collect().await;
        assert_eq!(items.len(), 3);
        assert_eq!(items[0].as_ref().unwrap().event, "a");
        assert_eq!(items[1].as_ref().unwrap().data, "2");
        assert!(items[2].is_err());
    }

    #[test]
    fn parses_events_and_keeps_the_rest() {
        let (events, rest) = parse_sse_buffer(
            "event: medias\ndata: {\"a\":1}\nid: 7\n\n: comment\n\nevent: heartbeat\r\ndata: {}\r\n\r\nevent: tags\ndata: {",
        );
        assert_eq!(events.len(), 2);
        assert_eq!(events[0].event, "medias");
        assert_eq!(events[0].data, "{\"a\":1}");
        assert_eq!(events[0].id.as_deref(), Some("7"));
        assert_eq!(events[1].event, "heartbeat");
        assert_eq!(rest, "event: tags\ndata: {");
    }

    #[test]
    fn joins_multi_line_data_and_reads_retry() {
        let (events, _) = parse_sse_buffer("event: x\ndata: a\ndata: b\nretry: 3000\n\n");
        assert_eq!(events[0].data, "a\nb");
        assert_eq!(events[0].retry, Some(3000));
    }

    #[test]
    fn decoder_handles_split_chunks_and_characters() {
        let text = "event: tags\ndata: {\"name\":\"été\"}\n\n".as_bytes();
        let mut decoder = SseDecoder::new();
        let mut events = Vec::new();
        for chunk in text.chunks(3) {
            events.extend(decoder.push(chunk));
        }
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].data, "{\"name\":\"été\"}");
    }

    #[test]
    fn decoder_keeps_a_crlf_cut_between_chunks() {
        // The case from the review: the chunk ends in the middle of `\r\n`.
        let mut decoder = SseDecoder::new();
        assert!(decoder.push(b"event: medias\r").is_empty());
        let events = decoder.push(b"\ndata: {\"medias\":[]}\r\n\r\n");
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].event, "medias");
        assert_eq!(events[0].data, "{\"medias\":[]}");

        // Any cut of a CRLF stream gives the same events as reading it whole.
        let text = b"event: a\r\ndata: 1\r\n\r\nevent: b\r\ndata: 2\r\ndata: 3\r\n\r\n";
        for size in 1..text.len() {
            let mut decoder = SseDecoder::new();
            let mut events = Vec::new();
            for chunk in text.chunks(size) {
                events.extend(decoder.push(chunk));
            }
            events.extend(decoder.finish());
            let read: Vec<_> = events
                .iter()
                .map(|e| (e.event.as_str(), e.data.as_str()))
                .collect();
            assert_eq!(read, [("a", "1"), ("b", "2\n3")], "chunks of {size} bytes");
        }
    }

    #[test]
    fn decoder_still_ends_lines_on_a_lone_cr() {
        let mut decoder = SseDecoder::new();
        let mut events = decoder.push(b"event: a\rdata: 1\r\r");
        events.extend(decoder.push(b"event: b\rdata: 2\r\r"));
        events.extend(decoder.finish());
        let read: Vec<_> = events
            .iter()
            .map(|e| (e.event.as_str(), e.data.as_str()))
            .collect();
        assert_eq!(read, [("a", "1"), ("b", "2")]);
    }

    #[test]
    fn decoder_flushes_the_last_event() {
        let mut decoder = SseDecoder::new();
        assert!(decoder.push(b"event: medias\ndata: {}").is_empty());
        let events = decoder.finish();
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].event, "medias");
    }
}