Skip to main content

axum/response/
sse.rs

1//! Server-Sent Events (SSE) responses.
2//!
3//! # Example
4//!
5//! ```
6//! use axum::{
7//!     Router,
8//!     routing::get,
9//!     response::sse::{Event, KeepAlive, Sse},
10//! };
11//! use std::{time::Duration, convert::Infallible};
12//! use tokio_stream::StreamExt as _ ;
13//! use futures_util::stream::{self, Stream};
14//!
15//! let app = Router::new().route("/sse", get(sse_handler));
16//!
17//! async fn sse_handler() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
18//!     // A `Stream` that repeats an event every second
19//!     let stream = stream::repeat_with(|| Event::default().data("hi!"))
20//!         .map(Ok)
21//!         .throttle(Duration::from_secs(1));
22//!
23//!     Sse::new(stream).keep_alive(KeepAlive::default())
24//! }
25//! # let _: Router = app;
26//! ```
27//!
28//! # Custom event payloads
29//!
30//! Sometimes a client expects a payload other than the standard `data: ` framing, such as
31//! a pre-serialized event, or a raw text chunk for a client that doesn't speak
32//! `EventSource` framing at all. [`Event::raw`] hands you full control over the bytes written
33//! to the wire for that event, while `Sse` still takes care of the response headers and, if
34//! configured, [`KeepAlive`]:
35//!
36//! ```
37//! use axum::{
38//!     Router,
39//!     routing::get,
40//!     response::sse::{Event, KeepAlive, Sse},
41//! };
42//! use std::{time::Duration, convert::Infallible};
43//! use tokio_stream::StreamExt as _ ;
44//! use futures_util::stream::{self, Stream};
45//!
46//! let app = Router::new().route("/sse", get(sse_handler));
47//!
48//! async fn sse_handler() -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
49//!     // A pre-serialized event, sent on the wire exactly as given.
50//!     let stream = stream::repeat_with(|| Event::raw("data: hi\n\n"))
51//!         .map(Ok)
52//!         .throttle(Duration::from_secs(1));
53//!
54//!     Sse::new(stream).keep_alive(KeepAlive::default())
55//! }
56//! # let _: Router = app;
57//! ```
58
59use crate::{
60    body::{Bytes, HttpBody},
61    BoxError,
62};
63use axum_core::{
64    body::Body,
65    response::{IntoResponse, Response},
66};
67use bytes::{BufMut, BytesMut};
68use futures_core::Stream;
69use futures_util::stream::TryStream;
70use http_body::Frame;
71use pin_project_lite::pin_project;
72use std::{
73    fmt::{self, Write as _},
74    io::Write as _,
75    mem,
76    pin::Pin,
77    task::{ready, Context, Poll},
78    time::Duration,
79};
80use sync_wrapper::SyncWrapper;
81
82/// An SSE response
83#[derive(Clone)]
84#[must_use]
85pub struct Sse<S> {
86    stream: S,
87}
88
89impl<S> Sse<S> {
90    /// Create a new [`Sse`] response that will respond with the given stream of
91    /// [`Event`]s.
92    ///
93    /// See the [module docs](self) for more details.
94    pub fn new(stream: S) -> Self
95    where
96        S: TryStream<Ok = Event> + Send + 'static,
97        S::Error: Into<BoxError>,
98    {
99        Self { stream }
100    }
101
102    /// Configure the interval between keep-alive messages.
103    ///
104    /// Defaults to no keep-alive messages.
105    #[cfg(feature = "tokio")]
106    pub fn keep_alive(self, keep_alive: KeepAlive) -> Sse<KeepAliveStream<S>> {
107        Sse {
108            stream: KeepAliveStream::new(keep_alive, self.stream),
109        }
110    }
111}
112
113impl<S> fmt::Debug for Sse<S> {
114    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115        f.debug_struct("Sse")
116            .field("stream", &format_args!("{}", std::any::type_name::<S>()))
117            .finish()
118    }
119}
120
121impl<S, E> IntoResponse for Sse<S>
122where
123    S: Stream<Item = Result<Event, E>> + Send + 'static,
124    E: Into<BoxError>,
125{
126    fn into_response(self) -> Response {
127        (
128            [
129                (http::header::CONTENT_TYPE, mime::TEXT_EVENT_STREAM.as_ref()),
130                (http::header::CACHE_CONTROL, "no-cache"),
131            ],
132            Body::new(SseBody {
133                event_stream: SyncWrapper::new(self.stream),
134            }),
135        )
136            .into_response()
137    }
138}
139
140pin_project! {
141    struct SseBody<S> {
142        #[pin]
143        event_stream: SyncWrapper<S>,
144    }
145}
146
147impl<S, E> HttpBody for SseBody<S>
148where
149    S: Stream<Item = Result<Event, E>>,
150{
151    type Data = Bytes;
152    type Error = E;
153
154    fn poll_frame(
155        self: Pin<&mut Self>,
156        cx: &mut Context<'_>,
157    ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
158        let this = self.project();
159
160        match ready!(this.event_stream.get_pin_mut().poll_next(cx)) {
161            Some(Ok(event)) => Poll::Ready(Some(Ok(Frame::data(event.finalize())))),
162            Some(Err(error)) => Poll::Ready(Some(Err(error))),
163            None => Poll::Ready(None),
164        }
165    }
166}
167
168/// The state of an event's buffer.
169///
170/// This type allows creating events in a `const` context
171/// by using a finalized buffer.
172///
173/// While the buffer is active, more bytes can be written to it.
174/// Once finalized, it's immutable and cheap to clone.
175/// The buffer is active during the event building, but eventually
176/// becomes finalized to send http body frames as [`Bytes`].
177#[derive(Debug, Clone)]
178enum Buffer {
179    Active(BytesMut),
180    Finalized(Bytes),
181}
182
183impl Buffer {
184    /// Returns a mutable reference to the internal buffer.
185    ///
186    /// If the buffer was finalized, this method creates
187    /// a new active buffer with the previous contents.
188    fn as_mut(&mut self) -> &mut BytesMut {
189        match self {
190            Self::Active(bytes_mut) => bytes_mut,
191            Self::Finalized(bytes) => {
192                *self = Self::Active(BytesMut::from(mem::take(bytes)));
193                match self {
194                    Self::Active(bytes_mut) => bytes_mut,
195                    Self::Finalized(_) => unreachable!(),
196                }
197            }
198        }
199    }
200}
201
202/// Server-sent event
203#[derive(Debug, Clone)]
204#[must_use]
205pub struct Event {
206    buffer: Buffer,
207    flags: EventFlags,
208}
209
210/// Expose [`Event`] as a [`std::fmt::Write`]
211/// such that any form of data can be written as data safely.
212///
213/// This also ensures that CRLF (`\r\n`), lone CR (`\r`), and lone LF (`\n`)
214/// line endings correctly trigger a split with a new `data: ` prefix. A CRLF
215/// pair is treated as a single line ending.
216///
217/// # Panics
218///
219/// Panics if any `data` has already been written prior to the first write
220/// of this [`EventDataWriter`] instance.
221#[derive(Debug)]
222#[must_use]
223pub struct EventDataWriter {
224    event: Event,
225
226    // Indicates if _this_ EventDataWriter has written data,
227    // this does not say anything about whether or not `event` contains
228    // data or not.
229    data_written: bool,
230
231    // A trailing CR might be followed by an LF in the next write. Defer the
232    // next `data: ` prefix until we know whether they form a CRLF pair.
233    pending_cr: bool,
234}
235
236impl Event {
237    /// Default keep-alive event
238    pub const DEFAULT_KEEP_ALIVE: Self = Self::finalized(Bytes::from_static(b":\n\n"));
239
240    const fn finalized(bytes: Bytes) -> Self {
241        Self {
242            buffer: Buffer::Finalized(bytes),
243            flags: EventFlags::from_bits(0),
244        }
245    }
246
247    /// Create an event whose payload is emitted on the wire exactly as provided.
248    ///
249    /// The given `bytes` are sent as a single body frame, verbatim: there is no `data: `
250    /// framing, no validation of field syntax, and no terminating empty line is added. If the
251    /// event needs to be understood by a standard [`EventSource`] client, the caller is
252    /// responsible for providing the complete event including its terminator, such as
253    /// `"data: hi\n\n"`.
254    ///
255    /// This is meant as an escape hatch for nonstandard event formats (such as clients that
256    /// don't accept the usual SSE framing) while still keeping [`Sse`]'s handling of the
257    /// `content-type`/`cache-control` headers and its [`KeepAlive`] support.
258    ///
259    /// Like any other event, a raw event resets the keep-alive timer when sent through
260    /// [`Sse::keep_alive`].
261    ///
262    /// Note that calling further builder methods, such as [`Event::comment`], after `raw` will
263    /// append their fields *after* the raw bytes and re-add a terminating newline. That's
264    /// allowed, but usually not what you want.
265    ///
266    /// [`EventSource`]: https://developer.mozilla.org/en-US/docs/Web/API/EventSource
267    ///
268    /// # Example
269    ///
270    /// ```
271    /// use axum::response::sse::Event;
272    ///
273    /// let event = Event::raw("data: hi\n\n");
274    /// ```
275    pub fn raw<T>(bytes: T) -> Self
276    where
277        T: Into<Bytes>,
278    {
279        Self::finalized(bytes.into())
280    }
281
282    /// Use this [`Event`] as a [`EventDataWriter`] to write custom data.
283    ///
284    /// - [`Self::data`] can be used as a shortcut to write `str` data
285    /// - [`Self::json_data`] can be used as a shortcut to write `json` data
286    ///
287    /// Turn it into an [`Event`] again using [`EventDataWriter::into_event`].
288    pub fn into_data_writer(self) -> EventDataWriter {
289        EventDataWriter {
290            event: self,
291            data_written: false,
292            pending_cr: false,
293        }
294    }
295
296    /// Set the event's data field(s) (`data: <content>`)
297    ///
298    /// Newlines in `data` will automatically be broken across `data: ` fields.
299    ///
300    /// This corresponds to [`MessageEvent`'s data field].
301    ///
302    /// Note that events with an empty data field will be ignored by the browser.
303    ///
304    /// # Panics
305    ///
306    /// Panics if any `data` has already been written before.
307    ///
308    /// [`MessageEvent`'s data field]: https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent/data
309    pub fn data<T>(self, data: T) -> Self
310    where
311        T: AsRef<str>,
312    {
313        let mut writer = self.into_data_writer();
314        let _ = writer.write_str(data.as_ref());
315        writer.into_event()
316    }
317
318    /// Set the event's data field to a value serialized as unformatted JSON (`data: <content>`).
319    ///
320    /// This corresponds to [`MessageEvent`'s data field].
321    ///
322    /// # Panics
323    ///
324    /// Panics if any `data` has already been written before.
325    ///
326    /// [`MessageEvent`'s data field]: https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent/data
327    #[cfg(feature = "json")]
328    pub fn json_data<T>(self, data: T) -> Result<Self, axum_core::Error>
329    where
330        T: serde_core::Serialize,
331    {
332        struct JsonWriter<'a>(&'a mut EventDataWriter);
333        impl std::io::Write for JsonWriter<'_> {
334            #[inline]
335            fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
336                Ok(self.0.write_buf(buf))
337            }
338            fn flush(&mut self) -> std::io::Result<()> {
339                Ok(())
340            }
341        }
342
343        let mut writer = self.into_data_writer();
344
345        let json_writer = JsonWriter(&mut writer);
346        serde_json::to_writer(json_writer, &data).map_err(axum_core::Error::new)?;
347
348        Ok(writer.into_event())
349    }
350
351    /// Set the event's comment field (`:<comment-text>`).
352    ///
353    /// This field will be ignored by most SSE clients.
354    ///
355    /// Unlike other functions, this function can be called multiple times to add many comments.
356    ///
357    /// # Panics
358    ///
359    /// Panics if `comment` contains any newlines or carriage returns, as they are not allowed in
360    /// comments.
361    pub fn comment<T>(mut self, comment: T) -> Self
362    where
363        T: AsRef<str>,
364    {
365        self.field("", comment.as_ref());
366        self
367    }
368
369    /// Set the event's name field (`event:<event-name>`).
370    ///
371    /// This corresponds to the `type` parameter given when calling `addEventListener` on an
372    /// [`EventSource`]. For example, `.event("update")` should correspond to
373    /// `.addEventListener("update", ...)`. If no event type is given, browsers will fire a
374    /// [`message` event] instead.
375    ///
376    /// [`EventSource`]: https://developer.mozilla.org/en-US/docs/Web/API/EventSource
377    /// [`message` event]: https://developer.mozilla.org/en-US/docs/Web/API/EventSource/message_event
378    ///
379    /// # Panics
380    ///
381    /// - Panics if `event` contains any newlines or carriage returns.
382    /// - Panics if this function has already been called on this event.
383    pub fn event<T>(mut self, event: T) -> Self
384    where
385        T: AsRef<str>,
386    {
387        if self.flags.contains(EventFlags::HAS_EVENT) {
388            panic!("Called `Event::event` multiple times");
389        }
390        self.flags.insert(EventFlags::HAS_EVENT);
391
392        self.field("event", event.as_ref());
393
394        self
395    }
396
397    /// Set the event's retry timeout field (`retry: <timeout>`).
398    ///
399    /// This sets how long clients will wait before reconnecting if they are disconnected from the
400    /// SSE endpoint. Note that this is just a hint: clients are free to wait for longer if they
401    /// wish, such as if they implement exponential backoff.
402    ///
403    /// # Panics
404    ///
405    /// Panics if this function has already been called on this event.
406    pub fn retry(mut self, duration: Duration) -> Self {
407        if self.flags.contains(EventFlags::HAS_RETRY) {
408            panic!("Called `Event::retry` multiple times");
409        }
410        self.flags.insert(EventFlags::HAS_RETRY);
411
412        let buffer = self.buffer.as_mut();
413        buffer.extend_from_slice(b"retry: ");
414
415        let secs = duration.as_secs();
416        let millis = duration.subsec_millis();
417
418        if secs > 0 {
419            // format seconds
420            buffer.extend_from_slice(itoa::Buffer::new().format(secs).as_bytes());
421
422            // pad milliseconds
423            if millis < 10 {
424                buffer.extend_from_slice(b"00");
425            } else if millis < 100 {
426                buffer.extend_from_slice(b"0");
427            }
428        }
429
430        // format milliseconds
431        buffer.extend_from_slice(itoa::Buffer::new().format(millis).as_bytes());
432
433        buffer.put_u8(b'\n');
434
435        self
436    }
437
438    /// Set the event's identifier field (`id:<identifier>`).
439    ///
440    /// This corresponds to [`MessageEvent`'s `lastEventId` field]. If no ID is in the event itself,
441    /// the browser will set that field to the last known message ID, starting with the empty
442    /// string.
443    ///
444    /// [`MessageEvent`'s `lastEventId` field]: https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent/lastEventId
445    ///
446    /// # Panics
447    ///
448    /// - Panics if `id` contains any newlines, carriage returns or null characters.
449    /// - Panics if this function has already been called on this event.
450    pub fn id<T>(mut self, id: T) -> Self
451    where
452        T: AsRef<str>,
453    {
454        if self.flags.contains(EventFlags::HAS_ID) {
455            panic!("Called `Event::id` multiple times");
456        }
457        self.flags.insert(EventFlags::HAS_ID);
458
459        let id = id.as_ref().as_bytes();
460        assert_eq!(
461            memchr::memchr(b'\0', id),
462            None,
463            "Event ID cannot contain null characters",
464        );
465
466        self.field("id", id);
467        self
468    }
469
470    fn field(&mut self, name: &str, value: impl AsRef<[u8]>) {
471        let value = value.as_ref();
472        assert_eq!(
473            memchr::memchr2(b'\r', b'\n', value),
474            None,
475            "SSE field value cannot contain newlines or carriage returns",
476        );
477
478        let buffer = self.buffer.as_mut();
479        buffer.extend_from_slice(name.as_bytes());
480        buffer.put_u8(b':');
481        buffer.put_u8(b' ');
482        buffer.extend_from_slice(value);
483        buffer.put_u8(b'\n');
484    }
485
486    /// Turns the event to `Bytes` ready to be sent
487    ///
488    /// If the events is already finalized just returns the `Bytes` again
489    pub fn finalize(self) -> Bytes {
490        match self.buffer {
491            Buffer::Finalized(bytes) => bytes,
492            Buffer::Active(mut bytes_mut) => {
493                bytes_mut.put_u8(b'\n');
494                bytes_mut.freeze()
495            }
496        }
497    }
498}
499
500impl EventDataWriter {
501    /// Consume the [`EventDataWriter`] and return the [`Event`] once again.
502    ///
503    /// In case any data was written by this instance
504    /// it will also write the trailing `\n` character.
505    pub fn into_event(self) -> Event {
506        let mut event = self.event;
507        if self.data_written {
508            let buffer = event.buffer.as_mut();
509            if self.pending_cr {
510                let _ = buffer.write_str("data: ");
511            }
512            let _ = buffer.write_char('\n');
513        }
514        event
515    }
516}
517
518impl EventDataWriter {
519    // Assumption: underlying writer never returns an error:
520    // <https://docs.rs/bytes/latest/src/bytes/buf/writer.rs.html#79-82>
521    fn write_buf(&mut self, buf: &[u8]) -> usize {
522        if buf.is_empty() {
523            return 0;
524        }
525
526        let pending_cr = mem::take(&mut self.pending_cr);
527        let buffer = self.event.buffer.as_mut();
528
529        if !std::mem::replace(&mut self.data_written, true) {
530            if self.event.flags.contains(EventFlags::HAS_DATA) {
531                panic!("Called `Event::data*` multiple times");
532            }
533
534            let _ = buffer.write_str("data: ");
535            self.event.flags.insert(EventFlags::HAS_DATA);
536        }
537
538        let mut writer = buffer.writer();
539
540        if pending_cr && buf[0] != b'\n' {
541            let _ = writer.write_all(b"data: ");
542        }
543
544        let mut last_split = 0;
545        for delimiter in memchr::memchr2_iter(b'\n', b'\r', buf) {
546            if buf[delimiter] == b'\r' && buf.get(delimiter + 1) == Some(&b'\n') {
547                continue;
548            }
549
550            let _ = writer.write_all(&buf[last_split..=delimiter]);
551            last_split = delimiter + 1;
552
553            if buf[delimiter] != b'\r' || last_split != buf.len() {
554                let _ = writer.write_all(b"data: ");
555            }
556        }
557        let _ = writer.write_all(&buf[last_split..]);
558
559        self.pending_cr = buf.last() == Some(&b'\r');
560
561        buf.len()
562    }
563}
564
565impl fmt::Write for EventDataWriter {
566    fn write_str(&mut self, s: &str) -> fmt::Result {
567        let _ = self.write_buf(s.as_bytes());
568        Ok(())
569    }
570}
571
572impl Default for Event {
573    fn default() -> Self {
574        Self {
575            buffer: Buffer::Active(BytesMut::new()),
576            flags: EventFlags::from_bits(0),
577        }
578    }
579}
580
581#[derive(Debug, Copy, Clone, PartialEq)]
582struct EventFlags(u8);
583
584impl EventFlags {
585    const HAS_DATA: Self = Self::from_bits(0b0001);
586    const HAS_EVENT: Self = Self::from_bits(0b0010);
587    const HAS_RETRY: Self = Self::from_bits(0b0100);
588    const HAS_ID: Self = Self::from_bits(0b1000);
589
590    const fn bits(self) -> u8 {
591        self.0
592    }
593
594    const fn from_bits(bits: u8) -> Self {
595        Self(bits)
596    }
597
598    const fn contains(self, other: Self) -> bool {
599        self.bits() & other.bits() == other.bits()
600    }
601
602    fn insert(&mut self, other: Self) {
603        *self = Self::from_bits(self.bits() | other.bits());
604    }
605}
606
607/// Configure the interval between keep-alive messages, the content
608/// of each message, and the associated stream.
609#[derive(Debug, Clone)]
610#[must_use]
611pub struct KeepAlive {
612    event: Event,
613    max_interval: Duration,
614}
615
616impl KeepAlive {
617    /// Create a new `KeepAlive`.
618    pub fn new() -> Self {
619        Self {
620            event: Event::DEFAULT_KEEP_ALIVE,
621            max_interval: Duration::from_secs(15),
622        }
623    }
624
625    /// Customize the interval between keep-alive messages.
626    ///
627    /// Default is 15 seconds.
628    pub fn interval(mut self, time: Duration) -> Self {
629        self.max_interval = time;
630        self
631    }
632
633    /// Customize the text of the keep-alive message.
634    ///
635    /// Default is an empty comment.
636    ///
637    /// # Panics
638    ///
639    /// Panics if `text` contains any newline or carriage returns, as they are not allowed in SSE
640    /// comments.
641    pub fn text<I>(self, text: I) -> Self
642    where
643        I: AsRef<str>,
644    {
645        self.event(Event::default().comment(text))
646    }
647
648    /// Customize the event of the keep-alive message.
649    ///
650    /// Default is an empty comment.
651    ///
652    /// # Panics
653    ///
654    /// Panics if `event` contains any newline or carriage returns, as they are not allowed in SSE
655    /// comments.
656    pub fn event(mut self, event: Event) -> Self {
657        self.event = Event::finalized(event.finalize());
658        self
659    }
660}
661
662impl Default for KeepAlive {
663    fn default() -> Self {
664        Self::new()
665    }
666}
667
668#[cfg(feature = "tokio")]
669pin_project! {
670    /// A wrapper around a stream that produces keep-alive events
671    #[derive(Debug)]
672    pub struct KeepAliveStream<S> {
673        #[pin]
674        alive_timer: tokio::time::Sleep,
675        #[pin]
676        inner: S,
677        keep_alive: KeepAlive,
678    }
679}
680
681#[cfg(feature = "tokio")]
682impl<S> KeepAliveStream<S> {
683    fn new(keep_alive: KeepAlive, inner: S) -> Self {
684        Self {
685            alive_timer: tokio::time::sleep(keep_alive.max_interval),
686            inner,
687            keep_alive,
688        }
689    }
690
691    fn reset(self: Pin<&mut Self>) {
692        let this = self.project();
693        this.alive_timer
694            .reset(tokio::time::Instant::now() + this.keep_alive.max_interval);
695    }
696}
697
698#[cfg(feature = "tokio")]
699impl<S, E> Stream for KeepAliveStream<S>
700where
701    S: Stream<Item = Result<Event, E>>,
702{
703    type Item = Result<Event, E>;
704
705    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
706        use std::future::Future;
707
708        let mut this = self.as_mut().project();
709
710        match this.inner.as_mut().poll_next(cx) {
711            Poll::Ready(Some(Ok(event))) => {
712                self.reset();
713
714                Poll::Ready(Some(Ok(event)))
715            }
716            Poll::Ready(Some(Err(error))) => Poll::Ready(Some(Err(error))),
717            Poll::Ready(None) => Poll::Ready(None),
718            Poll::Pending => {
719                ready!(this.alive_timer.poll(cx));
720
721                let event = this.keep_alive.event.clone();
722
723                self.reset();
724
725                Poll::Ready(Some(Ok(event)))
726            }
727        }
728    }
729}
730
731#[cfg(test)]
732mod tests {
733    use super::*;
734    use crate::{routing::get, test_helpers::*, Router};
735    use futures_util::stream;
736    use serde_json::value::RawValue;
737    use std::{collections::HashMap, convert::Infallible};
738    use tokio_stream::StreamExt as _;
739
740    #[test]
741    fn leading_space_is_not_stripped() {
742        let no_leading_space = Event::default().data("\tfoobar");
743        assert_eq!(&*no_leading_space.finalize(), b"data: \tfoobar\n\n");
744
745        let leading_space = Event::default().data(" foobar");
746        assert_eq!(&*leading_space.finalize(), b"data:  foobar\n\n");
747    }
748
749    #[test]
750    fn write_data_writer_str() {
751        // also confirm that nop writers do nothing :)
752        let mut writer = Event::default()
753            .into_data_writer()
754            .into_event()
755            .into_data_writer();
756        writer.write_str("").unwrap();
757        let mut writer = writer.into_event().into_data_writer();
758
759        writer.write_str("").unwrap();
760        writer.write_str("moon ").unwrap();
761        writer.write_str("star\nsun").unwrap();
762        writer.write_str("").unwrap();
763        writer.write_str("set").unwrap();
764        writer.write_str("").unwrap();
765        writer.write_str(" bye\r").unwrap();
766
767        let event = writer.into_event();
768
769        assert_eq!(
770            &*event.finalize(),
771            b"data: moon star\ndata: sunset bye\rdata: \n\n"
772        );
773    }
774
775    #[test]
776    fn crlf_is_one_line_ending() {
777        let event = Event::default().data("first\r\nsecond");
778
779        assert_eq!(&*event.finalize(), b"data: first\r\ndata: second\n\n");
780    }
781
782    #[test]
783    fn data_writer_output_is_independent_of_write_boundaries() {
784        let data = "first\r\nsecond\rthird\nfourth\r";
785        let expected = b"data: first\r\ndata: second\rdata: third\ndata: fourth\rdata: \n\n";
786
787        for first_split in 0..=data.len() {
788            for second_split in first_split..=data.len() {
789                let mut writer = Event::default().into_data_writer();
790                writer.write_str(&data[..first_split]).unwrap();
791                writer.write_str(&data[first_split..second_split]).unwrap();
792                writer.write_str(&data[second_split..]).unwrap();
793
794                assert_eq!(
795                    &*writer.into_event().finalize(),
796                    expected,
797                    "write boundaries at {first_split} and {second_split}"
798                );
799            }
800        }
801    }
802
803    #[test]
804    fn valid_json_raw_value_chars_handled() {
805        let json_string = "{\r\"foo\":  \n\r\r   \"bar\\n\"\n}";
806        let json_raw_value_event = Event::default()
807            .json_data(serde_json::from_str::<&RawValue>(json_string).unwrap())
808            .unwrap();
809        assert_eq!(
810            &*json_raw_value_event.finalize(),
811            b"data: {\rdata: \"foo\":  \ndata: \rdata: \rdata:    \"bar\\n\"\ndata: }\n\n"
812        );
813    }
814
815    #[test]
816    fn raw_event_round_trips_bytes_exactly() {
817        let event = Event::raw(b"data: hi\n\n".as_slice());
818        assert_eq!(&*event.finalize(), b"data: hi\n\n");
819
820        let empty = Event::raw(Bytes::new());
821        assert_eq!(&*empty.finalize(), b"");
822
823        // No trailing `\n` is appended, unlike an `Active` buffer.
824        let no_trailing_newline = Event::raw(b"data: hi".as_slice());
825        assert_eq!(&*no_trailing_newline.finalize(), b"data: hi");
826    }
827
828    #[test]
829    fn raw_event_then_comment_appends_and_reterminates() {
830        // Once further builder methods are called, the `Finalized` buffer is converted back
831        // into an `Active` one, so a trailing `\n` is added again on top of the appended field.
832        let event = Event::raw(b"data: hi\n\n".as_slice()).comment("x");
833        assert_eq!(&*event.finalize(), b"data: hi\n\n: x\n\n");
834    }
835
836    #[crate::test]
837    async fn basic() {
838        let app = Router::new().route(
839            "/",
840            get(|| async {
841                let stream = stream::iter(vec![
842                    Event::default().data("one").comment("this is a comment"),
843                    Event::default()
844                        .json_data(serde_json::json!({ "foo": "bar" }))
845                        .unwrap(),
846                    Event::default()
847                        .event("three")
848                        .retry(Duration::from_secs(30))
849                        .id("unique-id"),
850                ])
851                .map(Ok::<_, Infallible>);
852                Sse::new(stream)
853            }),
854        );
855
856        let client = TestClient::new(app);
857        let mut stream = client.get("/").await;
858
859        assert_eq!(stream.headers()["content-type"], "text/event-stream");
860        assert_eq!(stream.headers()["cache-control"], "no-cache");
861
862        let event_fields = parse_event(&stream.chunk_text().await.unwrap());
863        assert_eq!(event_fields.get("data").unwrap(), "one");
864        assert_eq!(event_fields.get("comment").unwrap(), "this is a comment");
865
866        let event_fields = parse_event(&stream.chunk_text().await.unwrap());
867        assert_eq!(event_fields.get("data").unwrap(), "{\"foo\":\"bar\"}");
868        assert!(!event_fields.contains_key("comment"));
869
870        let event_fields = parse_event(&stream.chunk_text().await.unwrap());
871        assert_eq!(event_fields.get("event").unwrap(), "three");
872        assert_eq!(event_fields.get("retry").unwrap(), "30000");
873        assert_eq!(event_fields.get("id").unwrap(), "unique-id");
874        assert!(!event_fields.contains_key("comment"));
875
876        assert!(stream.chunk_text().await.is_none());
877    }
878
879    #[crate::test]
880    async fn raw_events() {
881        let app = Router::new().route(
882            "/",
883            get(|| async {
884                let stream = stream::iter(vec![
885                    Event::raw(Bytes::from_static(b"data: one\n\n")),
886                    Event::raw(Bytes::from_static(b":raw two\n\n")),
887                ])
888                .map(Ok::<_, Infallible>);
889                Sse::new(stream)
890            }),
891        );
892
893        let client = TestClient::new(app);
894        let mut stream = client.get("/").await;
895
896        assert_eq!(stream.headers()["content-type"], "text/event-stream");
897        assert_eq!(stream.headers()["cache-control"], "no-cache");
898
899        // Chunks are received byte-exact: no `data:` framing or extra newline is added.
900        assert_eq!(stream.chunk_text().await.unwrap(), "data: one\n\n");
901        assert_eq!(stream.chunk_text().await.unwrap(), ":raw two\n\n");
902
903        assert!(stream.chunk_text().await.is_none());
904    }
905
906    #[tokio::test(start_paused = true)]
907    async fn keep_alive() {
908        const DELAY: Duration = Duration::from_secs(5);
909
910        let app = Router::new().route(
911            "/",
912            get(|| async {
913                let stream = stream::repeat_with(|| Event::default().data("msg"))
914                    .map(Ok::<_, Infallible>)
915                    .throttle(DELAY);
916
917                Sse::new(stream).keep_alive(
918                    KeepAlive::new()
919                        .interval(Duration::from_secs(1))
920                        .text("keep-alive-text"),
921                )
922            }),
923        );
924
925        let client = TestClient::new(app);
926        let mut stream = client.get("/").await;
927
928        for _ in 0..5 {
929            // first message should be an event
930            let event_fields = parse_event(&stream.chunk_text().await.unwrap());
931            assert_eq!(event_fields.get("data").unwrap(), "msg");
932
933            // then 4 seconds of keep-alive messages
934            for _ in 0..4 {
935                tokio::time::sleep(Duration::from_secs(1)).await;
936                let event_fields = parse_event(&stream.chunk_text().await.unwrap());
937                assert_eq!(event_fields.get("comment").unwrap(), "keep-alive-text");
938            }
939        }
940    }
941
942    #[tokio::test(start_paused = true)]
943    async fn keep_alive_with_raw_events() {
944        const DELAY: Duration = Duration::from_secs(5);
945
946        let app = Router::new().route(
947            "/",
948            get(|| async {
949                let stream =
950                    stream::repeat_with(|| Event::raw(Bytes::from_static(b"data: raw\n\n")))
951                        .map(Ok::<_, Infallible>)
952                        .throttle(DELAY);
953
954                Sse::new(stream).keep_alive(
955                    KeepAlive::new()
956                        .interval(Duration::from_secs(1))
957                        .text("keep-alive-text"),
958                )
959            }),
960        );
961
962        let client = TestClient::new(app);
963        let mut stream = client.get("/").await;
964
965        for _ in 0..5 {
966            // first message should be a raw event, sent byte-exact
967            assert_eq!(stream.chunk_text().await.unwrap(), "data: raw\n\n");
968
969            // then 4 seconds of keep-alive messages: a raw event resets the timer just like
970            // any other event
971            for _ in 0..4 {
972                tokio::time::sleep(Duration::from_secs(1)).await;
973                let event_fields = parse_event(&stream.chunk_text().await.unwrap());
974                assert_eq!(event_fields.get("comment").unwrap(), "keep-alive-text");
975            }
976        }
977    }
978
979    #[tokio::test(start_paused = true)]
980    async fn keep_alive_ends_when_the_stream_ends() {
981        const DELAY: Duration = Duration::from_secs(5);
982
983        let app = Router::new().route(
984            "/",
985            get(|| async {
986                let stream = stream::repeat_with(|| Event::default().data("msg"))
987                    .map(Ok::<_, Infallible>)
988                    .throttle(DELAY)
989                    .take(2);
990
991                Sse::new(stream).keep_alive(
992                    KeepAlive::new()
993                        .interval(Duration::from_secs(1))
994                        .text("keep-alive-text"),
995                )
996            }),
997        );
998
999        let client = TestClient::new(app);
1000        let mut stream = client.get("/").await;
1001
1002        // first message should be an event
1003        let event_fields = parse_event(&stream.chunk_text().await.unwrap());
1004        assert_eq!(event_fields.get("data").unwrap(), "msg");
1005
1006        // then 4 seconds of keep-alive messages
1007        for _ in 0..4 {
1008            tokio::time::sleep(Duration::from_secs(1)).await;
1009            let event_fields = parse_event(&stream.chunk_text().await.unwrap());
1010            assert_eq!(event_fields.get("comment").unwrap(), "keep-alive-text");
1011        }
1012
1013        // then the last event
1014        let event_fields = parse_event(&stream.chunk_text().await.unwrap());
1015        assert_eq!(event_fields.get("data").unwrap(), "msg");
1016
1017        // then no more events or keep-alive messages
1018        assert!(stream.chunk_text().await.is_none());
1019    }
1020
1021    fn parse_event(payload: &str) -> HashMap<String, String> {
1022        let mut fields = HashMap::new();
1023
1024        let mut lines = payload.lines().peekable();
1025        while let Some(line) = lines.next() {
1026            if line.is_empty() {
1027                assert!(lines.next().is_none());
1028                break;
1029            }
1030
1031            let (mut key, value) = line.split_once(':').unwrap();
1032            let value = value.trim();
1033            if key.is_empty() {
1034                key = "comment";
1035            }
1036            fields.insert(key.to_owned(), value.to_owned());
1037        }
1038
1039        fields
1040    }
1041}