Skip to main content

next_rust_server/
sse.rs

1//! Server-Sent Events.
2
3use std::time::Duration;
4
5use bytes::Bytes;
6use futures_util::stream::{Stream, StreamExt};
7
8use crate::response::{Body, Response};
9
10/// One SSE message.
11#[derive(Debug, Clone, Default, PartialEq, Eq)]
12pub struct SseEvent {
13    pub event: Option<String>,
14    pub data: String,
15    pub id: Option<String>,
16    pub retry: Option<Duration>,
17}
18
19impl SseEvent {
20    pub fn data(data: impl Into<String>) -> Self {
21        SseEvent { data: data.into(), ..Default::default() }
22    }
23
24    /// Serialize `value` as JSON data.
25    pub fn json<T: serde::Serialize>(value: &T) -> Self {
26        SseEvent::data(serde_json::to_string(value).unwrap_or_default())
27    }
28
29    pub fn event(mut self, name: impl Into<String>) -> Self {
30        self.event = Some(name.into());
31        self
32    }
33
34    pub fn id(mut self, id: impl Into<String>) -> Self {
35        self.id = Some(id.into());
36        self
37    }
38
39    pub fn retry(mut self, d: Duration) -> Self {
40        self.retry = Some(d);
41        self
42    }
43
44    /// Wire format. Newlines in `event`/`id` are stripped so a value can
45    /// never inject additional fields.
46    pub fn to_wire(&self) -> String {
47        let clean = |s: &str| s.replace(['\r', '\n'], "");
48        let mut out = String::new();
49        if let Some(e) = &self.event {
50            out.push_str(&format!("event: {}\n", clean(e)));
51        }
52        if let Some(id) = &self.id {
53            out.push_str(&format!("id: {}\n", clean(id)));
54        }
55        if let Some(r) = self.retry {
56            out.push_str(&format!("retry: {}\n", r.as_millis()));
57        }
58        for line in self.data.replace("\r\n", "\n").replace('\r', "\n").split('\n') {
59            out.push_str("data: ");
60            out.push_str(line);
61            out.push('\n');
62        }
63        out.push('\n');
64        out
65    }
66}
67
68impl Response {
69    /// Stream server-sent events. A keep-alive comment is sent every 15
70    /// seconds of inactivity; the response ends when `events` ends.
71    pub fn sse<S>(events: S) -> Response
72    where
73        S: Stream<Item = SseEvent> + Send + 'static,
74    {
75        Response::sse_with_keep_alive(events, Duration::from_secs(15))
76    }
77
78    pub fn sse_with_keep_alive<S>(events: S, keep_alive: Duration) -> Response
79    where
80        S: Stream<Item = SseEvent> + Send + 'static,
81    {
82        let events = Box::pin(events);
83        let stream = futures_util::stream::unfold(Some(events), move |state| async move {
84            let mut events = state?;
85            tokio::select! {
86                next = events.next() => next.map(|ev| (Ok::<Bytes, crate::request::BoxError>(Bytes::from(ev.to_wire())), Some(events))),
87                _ = tokio::time::sleep(keep_alive) => Some((Ok(Bytes::from_static(b": keep-alive\n\n")), Some(events))),
88            }
89        });
90        let mut r = Response::new(http::StatusCode::OK, Body::Stream(Box::pin(stream)));
91        r.set_header("content-type", "text/event-stream");
92        r.set_header("cache-control", "no-cache");
93        r.set_header("x-accel-buffering", "no");
94        r
95    }
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101
102    #[test]
103    fn wire_format() {
104        let e = SseEvent::data("line1\nline2").event("up\ndate").id("7");
105        assert_eq!(e.to_wire(), "event: update\nid: 7\ndata: line1\ndata: line2\n\n");
106    }
107}