Skip to main content

schedr_client/
stream.rs

1//! Streamed answers: a response body read as it comes ([`Chunks`]), and server-sent events
2//! read from one ([`EventReader`]), for `GET /api/v1/changes`.
3
4use tokio::sync::mpsc;
5
6use crate::ClientError;
7
8#[cfg(test)]
9mod tests;
10
11/// A response body as it arrives, chunk by chunk.
12#[derive(Debug)]
13pub struct Chunks {
14    receiver: mpsc::Receiver<Result<Vec<u8>, ClientError>>,
15}
16
17impl Chunks {
18    /// Chunks handed over through a channel (by a task reading the body), and its sending end.
19    #[must_use]
20    pub fn channel() -> (mpsc::Sender<Result<Vec<u8>, ClientError>>, Self) {
21        let (sender, receiver) = mpsc::channel(16);
22        (sender, Self { receiver })
23    }
24
25    /// The next chunk; `None` at the end of the body.
26    pub async fn next(&mut self) -> Option<Result<Vec<u8>, ClientError>> {
27        self.receiver.recv().await
28    }
29}
30
31/// A server-sent event.
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct ServerEvent {
34    /// Its name (`message` when the server gave none).
35    pub name: String,
36    /// Its data, its `data:` lines joined by newlines.
37    pub data: String,
38}
39
40/// Server-sent events read from a stream (the event-stream format: `event:` and `data:`
41/// lines, a blank line ending each event, `:` comments skipped).
42#[derive(Debug)]
43pub struct EventReader {
44    chunks: Chunks,
45    /// Bytes read and not yet parsed (an event's start, possibly a character cut in two).
46    pending: Vec<u8>,
47}
48
49impl EventReader {
50    /// Events from `chunks`.
51    #[must_use]
52    pub const fn new(chunks: Chunks) -> Self {
53        Self {
54            chunks,
55            pending: Vec::new(),
56        }
57    }
58
59    /// The next event; `None` when the stream ends.
60    pub async fn next(&mut self) -> Option<Result<ServerEvent, ClientError>> {
61        loop {
62            if let Some(event) = self.parse_one() {
63                return Some(Ok(event));
64            }
65            match self.chunks.next().await? {
66                Ok(chunk) => self.pending.extend_from_slice(&chunk),
67                Err(error) => return Some(Err(error)),
68            }
69        }
70    }
71
72    /// The first whole event in what is pending, taken out; blocks of comments only are
73    /// dropped on the way.
74    fn parse_one(&mut self) -> Option<ServerEvent> {
75        loop {
76            let end = blank_line(&self.pending)?;
77            let block: Vec<u8> = self.pending.drain(..end.1).take(end.0).collect();
78            let text = String::from_utf8_lossy(&block);
79            let mut name = None;
80            let mut data: Option<String> = None;
81            for line in text.split('\n').map(|l| l.strip_suffix('\r').unwrap_or(l)) {
82                let (field, value) = line.split_once(':').unwrap_or((line, ""));
83                let value = value.strip_prefix(' ').unwrap_or(value);
84                match field {
85                    "event" => name = Some(value.to_owned()),
86                    "data" => match &mut data {
87                        Some(data) => {
88                            data.push('\n');
89                            data.push_str(value);
90                        }
91                        None => data = Some(value.to_owned()),
92                    },
93                    _ => {}
94                }
95            }
96            if name.is_some() || data.is_some() {
97                return Some(ServerEvent {
98                    name: name.unwrap_or_else(|| "message".to_owned()),
99                    data: data.unwrap_or_default(),
100                });
101            }
102        }
103    }
104}
105
106/// Where the first event in `bytes` ends: its length, and its length with the blank line
107/// after it (`\n\n` or `\r\n\r\n`).
108fn blank_line(bytes: &[u8]) -> Option<(usize, usize)> {
109    (0..bytes.len()).find_map(|i| {
110        if bytes[i..].starts_with(b"\n\n") {
111            Some((i, i + 2))
112        } else if bytes[i..].starts_with(b"\r\n\r\n") {
113            Some((i, i + 4))
114        } else {
115            None
116        }
117    })
118}