Skip to main content

phoenix_http/
sse.rs

1//! Server-Sent Events response types.
2
3use std::{
4    convert::Infallible,
5    pin::Pin,
6    task::{Context, Poll},
7    time::Duration,
8};
9
10use bytes::Bytes;
11use futures_util::{Stream, StreamExt};
12use http::{HeaderName, HeaderValue, header};
13use serde::Serialize;
14use thiserror::Error;
15
16use crate::{
17    FromRequest, IntoResponse, Request, Response, ResponseBodyError, StatusCode, rejection_response,
18};
19
20const DEFAULT_SSE_EVENT_LIMIT: usize = 64 * 1024;
21const MAX_SSE_EVENT_LIMIT: usize = 1024 * 1024;
22const MAX_SSE_FIELD_LENGTH: usize = 1024;
23const MAX_KEEP_ALIVE_INTERVAL: Duration = Duration::from_hours(24);
24
25/// One validated Server-Sent Event.
26#[derive(Clone, Debug, Default, Eq, PartialEq)]
27pub struct SseEvent {
28    event: Option<String>,
29    id: Option<String>,
30    data: String,
31    retry: Option<Duration>,
32    comment: Option<String>,
33}
34
35impl SseEvent {
36    #[must_use]
37    pub fn new() -> Self {
38        Self::default()
39    }
40
41    /// Set the browser event type.
42    ///
43    /// # Errors
44    ///
45    /// Rejects empty, oversized, NUL, CR, or LF values.
46    pub fn event(mut self, event: impl Into<String>) -> Result<Self, InvalidSseField> {
47        self.event = Some(validate_sse_field("event", event.into(), false)?);
48        Ok(self)
49    }
50
51    /// Set the reconnection cursor sent back as `Last-Event-ID`.
52    ///
53    /// # Errors
54    ///
55    /// Rejects oversized, NUL, CR, or LF values.
56    pub fn id(mut self, id: impl Into<String>) -> Result<Self, InvalidSseField> {
57        self.id = Some(validate_sse_field("id", id.into(), true)?);
58        Ok(self)
59    }
60
61    #[must_use]
62    pub fn data(mut self, data: impl Into<String>) -> Self {
63        self.data = data.into();
64        self
65    }
66
67    /// Serialize structured data into one SSE data field.
68    ///
69    /// # Errors
70    ///
71    /// Returns the serializer error for unsupported values.
72    pub fn json_data<T>(mut self, data: &T) -> Result<Self, serde_json::Error>
73    where
74        T: Serialize,
75    {
76        self.data = serde_json::to_string(data)?;
77        Ok(self)
78    }
79
80    #[must_use]
81    pub const fn retry(mut self, retry: Duration) -> Self {
82        self.retry = Some(retry);
83        self
84    }
85
86    /// Add a single-line SSE comment before the event fields.
87    ///
88    /// # Errors
89    ///
90    /// Rejects oversized, NUL, CR, or LF values.
91    pub fn comment(mut self, comment: impl Into<String>) -> Result<Self, InvalidSseField> {
92        self.comment = Some(validate_sse_field("comment", comment.into(), true)?);
93        Ok(self)
94    }
95
96    fn encode(self, max_size: usize) -> Result<Bytes, ResponseBodyError> {
97        let mut output = String::new();
98        if let Some(comment) = self.comment {
99            output.push_str(": ");
100            output.push_str(&comment);
101            output.push('\n');
102        }
103        if let Some(event) = self.event {
104            output.push_str("event: ");
105            output.push_str(&event);
106            output.push('\n');
107        }
108        if let Some(id) = self.id {
109            output.push_str("id: ");
110            output.push_str(&id);
111            output.push('\n');
112        }
113        if let Some(retry) = self.retry {
114            output.push_str("retry: ");
115            output.push_str(
116                &u64::try_from(retry.as_millis())
117                    .unwrap_or(u64::MAX)
118                    .to_string(),
119            );
120            output.push('\n');
121        }
122        let data = self.data.replace("\r\n", "\n").replace('\r', "\n");
123        for line in data.split('\n') {
124            output.push_str("data: ");
125            output.push_str(line);
126            output.push('\n');
127        }
128        output.push('\n');
129        if output.len() > max_size {
130            return Err(ResponseBodyError);
131        }
132        Ok(Bytes::from(output))
133    }
134}
135
136/// Validated SSE keepalive policy.
137#[derive(Clone, Debug, Eq, PartialEq)]
138pub struct KeepAlive {
139    interval: Duration,
140    comment: String,
141}
142
143impl KeepAlive {
144    /// Configure a keepalive interval.
145    ///
146    /// # Errors
147    ///
148    /// Rejects zero or intervals above 24 hours.
149    pub fn new(interval: Duration) -> Result<Self, SseConfigError> {
150        if interval.is_zero() || interval > MAX_KEEP_ALIVE_INTERVAL {
151            return Err(SseConfigError::InvalidKeepAliveInterval);
152        }
153        Ok(Self {
154            interval,
155            comment: "keep-alive".to_owned(),
156        })
157    }
158
159    /// Set the single-line keepalive comment.
160    ///
161    /// # Errors
162    ///
163    /// Rejects oversized, NUL, CR, or LF values.
164    pub fn comment(mut self, comment: impl Into<String>) -> Result<Self, InvalidSseField> {
165        self.comment = validate_sse_field("comment", comment.into(), true)?;
166        Ok(self)
167    }
168}
169
170impl Default for KeepAlive {
171    fn default() -> Self {
172        Self {
173            interval: Duration::from_secs(15),
174            comment: "keep-alive".to_owned(),
175        }
176    }
177}
178
179type SseEventStream =
180    Pin<Box<dyn Stream<Item = Result<SseEvent, ResponseBodyError>> + Send + 'static>>;
181
182/// A backpressure-aware Server-Sent Events response.
183pub struct Sse {
184    events: SseEventStream,
185    keep_alive: Option<KeepAlive>,
186    max_event_size: usize,
187}
188
189impl Sse {
190    /// Build SSE from a fallible event source. Source errors are redacted at the wire boundary.
191    #[must_use]
192    pub fn new<S, E>(events: S) -> Self
193    where
194        S: Stream<Item = Result<SseEvent, E>> + Send + 'static,
195        E: Send + 'static,
196    {
197        Self {
198            events: Box::pin(events.map(|event| event.map_err(|_| ResponseBodyError))),
199            keep_alive: None,
200            max_event_size: DEFAULT_SSE_EVENT_LIMIT,
201        }
202    }
203
204    /// Build SSE from an infallible event source.
205    #[must_use]
206    pub fn from_events<S>(events: S) -> Self
207    where
208        S: Stream<Item = SseEvent> + Send + 'static,
209    {
210        Self::new(events.map(Ok::<_, Infallible>))
211    }
212
213    #[must_use]
214    pub fn keep_alive(mut self, keep_alive: KeepAlive) -> Self {
215        self.keep_alive = Some(keep_alive);
216        self
217    }
218
219    /// Override the encoded per-event byte limit.
220    ///
221    /// # Errors
222    ///
223    /// Rejects zero and values above 1 MiB.
224    pub fn max_event_size(mut self, bytes: usize) -> Result<Self, SseConfigError> {
225        if bytes == 0 || bytes > MAX_SSE_EVENT_LIMIT {
226            return Err(SseConfigError::InvalidEventSize);
227        }
228        self.max_event_size = bytes;
229        Ok(self)
230    }
231}
232
233impl std::fmt::Debug for Sse {
234    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
235        formatter
236            .debug_struct("Sse")
237            .field("keep_alive", &self.keep_alive)
238            .field("max_event_size", &self.max_event_size)
239            .finish_non_exhaustive()
240    }
241}
242
243impl IntoResponse for Sse {
244    fn into_response(self) -> Response {
245        let mut response = Response::try_stream(SseBodyStream::new(
246            self.events,
247            self.keep_alive,
248            self.max_event_size,
249        ));
250        response.headers_mut().insert(
251            header::CONTENT_TYPE,
252            HeaderValue::from_static("text/event-stream; charset=utf-8"),
253        );
254        response
255            .headers_mut()
256            .insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
257        response.headers_mut().insert(
258            HeaderName::from_static("x-accel-buffering"),
259            HeaderValue::from_static("no"),
260        );
261        response
262    }
263}
264
265struct SseBodyStream {
266    events: SseEventStream,
267    keep_alive: Option<KeepAlive>,
268    sleep: Option<Pin<Box<tokio::time::Sleep>>>,
269    max_event_size: usize,
270    finished: bool,
271}
272
273impl SseBodyStream {
274    fn new(events: SseEventStream, keep_alive: Option<KeepAlive>, max_event_size: usize) -> Self {
275        let sleep = keep_alive
276            .as_ref()
277            .map(|keep_alive| Box::pin(tokio::time::sleep(keep_alive.interval)));
278        Self {
279            events,
280            keep_alive,
281            sleep,
282            max_event_size,
283            finished: false,
284        }
285    }
286
287    fn reset_keep_alive(&mut self) {
288        if let (Some(keep_alive), Some(sleep)) = (&self.keep_alive, &mut self.sleep) {
289            sleep
290                .as_mut()
291                .reset(tokio::time::Instant::now() + keep_alive.interval);
292        }
293    }
294}
295
296impl Stream for SseBodyStream {
297    type Item = Result<Bytes, ResponseBodyError>;
298
299    fn poll_next(mut self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Option<Self::Item>> {
300        let this = self.as_mut().get_mut();
301        if this.finished {
302            return Poll::Ready(None);
303        }
304        match this.events.as_mut().poll_next(context) {
305            Poll::Ready(Some(Ok(event))) => {
306                this.reset_keep_alive();
307                let encoded = event.encode(this.max_event_size);
308                if encoded.is_err() {
309                    this.finished = true;
310                }
311                return Poll::Ready(Some(encoded));
312            }
313            Poll::Ready(Some(Err(error))) => {
314                this.finished = true;
315                return Poll::Ready(Some(Err(error)));
316            }
317            Poll::Ready(None) => {
318                this.finished = true;
319                return Poll::Ready(None);
320            }
321            Poll::Pending => {}
322        }
323
324        if this
325            .sleep
326            .as_mut()
327            .is_some_and(|sleep| sleep.as_mut().poll(context).is_ready())
328        {
329            let comment = this
330                .keep_alive
331                .as_ref()
332                .expect("a keepalive timer has a policy")
333                .comment
334                .clone();
335            this.reset_keep_alive();
336            return Poll::Ready(Some(Ok(Bytes::from(format!(": {comment}\n\n")))));
337        }
338        Poll::Pending
339    }
340}
341
342#[derive(Clone, Copy, Debug, Error, Eq, PartialEq)]
343#[error("The SSE {field} field is invalid.")]
344pub struct InvalidSseField {
345    field: &'static str,
346}
347
348#[derive(Clone, Copy, Debug, Error, Eq, PartialEq)]
349pub enum SseConfigError {
350    #[error("The SSE event size limit must be between 1 byte and 1 MiB.")]
351    InvalidEventSize,
352    #[error("The SSE keepalive interval must be greater than zero and at most 24 hours.")]
353    InvalidKeepAliveInterval,
354}
355
356fn validate_sse_field(
357    field: &'static str,
358    value: String,
359    allow_empty: bool,
360) -> Result<String, InvalidSseField> {
361    if (!allow_empty && value.is_empty())
362        || value.len() > MAX_SSE_FIELD_LENGTH
363        || value
364            .chars()
365            .any(|character| matches!(character, '\0' | '\r' | '\n'))
366    {
367        return Err(InvalidSseField { field });
368    }
369    Ok(value)
370}
371
372/// Optional browser reconnection cursor from the `Last-Event-ID` header.
373#[derive(Clone, Debug, Default, Eq, PartialEq)]
374pub struct LastEventId(Option<String>);
375
376impl LastEventId {
377    #[must_use]
378    pub fn as_deref(&self) -> Option<&str> {
379        self.0.as_deref()
380    }
381
382    #[must_use]
383    pub fn into_inner(self) -> Option<String> {
384        self.0
385    }
386}
387
388impl FromRequest for LastEventId {
389    type Rejection = LastEventIdRejection;
390
391    fn from_request(request: &Request) -> Result<Self, Self::Rejection> {
392        let Some(value) = request.headers().get("last-event-id") else {
393            return Ok(Self(None));
394        };
395        let value = value.to_str().map_err(|_| LastEventIdRejection)?.to_owned();
396        validate_sse_field("Last-Event-ID", value, true)
397            .map(|value| Self(Some(value)))
398            .map_err(|_| LastEventIdRejection)
399    }
400}
401
402#[derive(Clone, Copy, Debug, Error, Eq, PartialEq)]
403#[error("The Last-Event-ID header is invalid.")]
404pub struct LastEventIdRejection;
405
406impl IntoResponse for LastEventIdRejection {
407    fn into_response(self) -> Response {
408        rejection_response(StatusCode::BAD_REQUEST, &self.to_string())
409    }
410}
411
412#[cfg(test)]
413mod tests {
414    use std::time::Duration;
415
416    use futures_util::{StreamExt, stream};
417    use http::{HeaderValue, header};
418
419    use super::*;
420    use crate::{Method, Request, ResponseBody};
421
422    #[tokio::test]
423    async fn sse_encodes_validated_events_headers_limits_and_keepalives() {
424        let event = SseEvent::new()
425            .comment("snapshot")
426            .unwrap()
427            .event("member.updated")
428            .unwrap()
429            .id("42")
430            .unwrap()
431            .retry(Duration::from_millis(1_500))
432            .data("first\r\nsecond\rthird\n");
433        let response = Sse::from_events(stream::iter([event])).into_response();
434        assert_eq!(
435            response.headers()[header::CONTENT_TYPE],
436            "text/event-stream; charset=utf-8"
437        );
438        assert_eq!(response.headers()[header::CACHE_CONTROL], "no-cache");
439        assert_eq!(response.headers()["x-accel-buffering"], "no");
440        assert!(!response.headers().contains_key(header::CONNECTION));
441        let (_, _, body) = response.into_parts();
442        let ResponseBody::Stream(stream) = body else {
443            panic!("expected SSE stream");
444        };
445        let encoded = stream
446            .collect::<Vec<_>>()
447            .await
448            .into_iter()
449            .map(Result::unwrap)
450            .fold(Vec::new(), |mut output, chunk| {
451                output.extend_from_slice(&chunk);
452                output
453            });
454        assert_eq!(
455            encoded,
456            b": snapshot\nevent: member.updated\nid: 42\nretry: 1500\ndata: first\ndata: second\ndata: third\ndata: \n\n"
457        );
458
459        let keep_alive = KeepAlive::new(Duration::from_millis(10))
460            .unwrap()
461            .comment("heartbeat")
462            .unwrap();
463        let response = Sse::from_events(stream::pending()).keep_alive(keep_alive);
464        let (_, _, body) = response.into_response().into_parts();
465        let ResponseBody::Stream(mut stream) = body else {
466            panic!("expected SSE stream");
467        };
468        let heartbeat = tokio::time::timeout(Duration::from_millis(200), stream.next())
469            .await
470            .unwrap()
471            .unwrap()
472            .unwrap();
473        assert_eq!(heartbeat, ": heartbeat\n\n");
474
475        let response = Sse::from_events(stream::iter([SseEvent::new().data("too large")]))
476            .max_event_size(4)
477            .unwrap()
478            .into_response();
479        let (_, _, body) = response.into_parts();
480        let ResponseBody::Stream(mut stream) = body else {
481            panic!("expected SSE stream");
482        };
483        assert!(stream.next().await.unwrap().is_err());
484    }
485
486    #[test]
487    fn sse_fields_configuration_and_last_event_id_fail_closed() {
488        for invalid in ["bad\nevent", "bad\rid", "bad\0comment"] {
489            assert!(SseEvent::new().event(invalid).is_err());
490            assert!(SseEvent::new().id(invalid).is_err());
491            assert!(SseEvent::new().comment(invalid).is_err());
492        }
493        assert!(SseEvent::new().event("").is_err());
494        assert!(SseEvent::new().event("x".repeat(1_025)).is_err());
495        assert!(KeepAlive::new(Duration::ZERO).is_err());
496        assert!(KeepAlive::new(Duration::from_secs(24 * 60 * 60 + 1)).is_err());
497        assert!(Sse::from_events(stream::empty()).max_event_size(0).is_err());
498
499        let missing = Request::new(Method::GET, "/events".parse().unwrap());
500        assert_eq!(
501            LastEventId::from_request(&missing).unwrap().as_deref(),
502            None
503        );
504        let mut present = Request::new(Method::GET, "/events".parse().unwrap());
505        present
506            .headers_mut()
507            .insert("last-event-id", HeaderValue::from_static("cursor-42"));
508        assert_eq!(
509            LastEventId::from_request(&present).unwrap().as_deref(),
510            Some("cursor-42")
511        );
512        let mut invalid = Request::new(Method::GET, "/events".parse().unwrap());
513        invalid.headers_mut().insert(
514            "last-event-id",
515            HeaderValue::from_bytes(&vec![b'x'; 1_025]).unwrap(),
516        );
517        assert!(LastEventId::from_request(&invalid).is_err());
518    }
519}