feat(sse): add Event::raw for fully custom payloads (#3829)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Dihan Nahdi · committed by GitHub · parent 46d4f02 · Browse files · 2 files·+153 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Trailers
- Co-authored-by: Jess Izen <44884346+jlizen@users.noreply.github.com>
Diff stats
2 files+153 added−0 removed
- other:+153 added−0 removed
Provenance
- Commit
9d18496- Tree
b390d2d- Author
Dihan Nahdi <90670352+dihannahdi@users.noreply.github.com>- Committer
GitHub <noreply@github.com>- Parent
46d4f02
2 files changed+153 added−0 removed
modified:axum/src/response/sse.rs+151 added
22 unmodified lines23 //! Sse::new(stream).keep_alive(KeepAlive::default())24 //! }25 //! # let _: Router = app;26 //! ```27+//!28+//! # Custom event payloads29+//!30+//! Sometimes a client expects a payload other than the standard `data: ` framing, such as31+//! a pre-serialized event, or a raw text chunk for a client that doesn't speak32+//! `EventSource` framing at all. [`Event::raw`] hands you full control over the bytes written33+//! to the wire for that event, while `Sse` still takes care of the response headers and, if34+//! 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 59 use crate::{60 body::{Bytes, HttpBody},61 BoxError,181 unmodified lines243 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 the251+ /// event needs to be understood by a standard [`EventSource`] client, the caller is252+ /// responsible for providing the complete event including its terminator, such as253+ /// `"data: hi\n\n"`.254+ ///255+ /// This is meant as an escape hatch for nonstandard event formats (such as clients that256+ /// don't accept the usual SSE framing) while still keeping [`Sse`]'s handling of the257+ /// `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 through260+ /// [`Sse::keep_alive`].261+ ///262+ /// Note that calling further builder methods, such as [`Event::comment`], after `raw` will263+ /// append their fields *after* the raw bytes and re-add a terminating newline. That's264+ /// allowed, but usually not what you want.265+ ///266+ /// [`EventSource`]: https://developer.mozilla.org/en-US/docs/Web/API/EventSource267+ ///268+ /// # Example269+ ///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) -> Self276+ where277+ 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` data285 /// - [`Self::json_data`] can be used as a shortcut to write `json` data522 unmodified lines808 b"data: {\rdata: \"foo\": \ndata: \rdata: \rdata: \"bar\\n\"\ndata: }\n\n"809 );810 }811 812+ #[test]813+ fn raw_event_round_trips_bytes_exactly() {814+ let event = Event::raw(b"data: hi\n\n".as_slice());815+ assert_eq!(&*event.finalize(), b"data: hi\n\n");816+817+ let empty = Event::raw(Bytes::new());818+ assert_eq!(&*empty.finalize(), b"");819+820+ // No trailing `\n` is appended, unlike an `Active` buffer.821+ let no_trailing_newline = Event::raw(b"data: hi".as_slice());822+ assert_eq!(&*no_trailing_newline.finalize(), b"data: hi");823+ }824+825+ #[test]826+ fn raw_event_then_comment_appends_and_reterminates() {827+ // Once further builder methods are called, the `Finalized` buffer is converted back828+ // into an `Active` one, so a trailing `\n` is added again on top of the appended field.829+ let event = Event::raw(b"data: hi\n\n".as_slice()).comment("x");830+ assert_eq!(&*event.finalize(), b"data: hi\n\n: x\n\n");831+ }832+833 #[crate::test]834 async fn basic() {835 let app = Router::new().route(836 "/",35 unmodified lines872 873 assert!(stream.chunk_text().await.is_none());874 }875 876+ #[crate::test]877+ async fn raw_events() {878+ let app = Router::new().route(879+ "/",880+ get(|| async {881+ let stream = stream::iter(vec![882+ Event::raw(Bytes::from_static(b"data: one\n\n")),883+ Event::raw(Bytes::from_static(b":raw two\n\n")),884+ ])885+ .map(Ok::<_, Infallible>);886+ Sse::new(stream)887+ }),888+ );889+890+ let client = TestClient::new(app);891+ let mut stream = client.get("/").await;892+893+ assert_eq!(stream.headers()["content-type"], "text/event-stream");894+ assert_eq!(stream.headers()["cache-control"], "no-cache");895+896+ // Chunks are received byte-exact: no `data:` framing or extra newline is added.897+ assert_eq!(stream.chunk_text().await.unwrap(), "data: one\n\n");898+ assert_eq!(stream.chunk_text().await.unwrap(), ":raw two\n\n");899+900+ assert!(stream.chunk_text().await.is_none());901+ }902+903 #[tokio::test(start_paused = true)]904 async fn keep_alive() {905 const DELAY: Duration = Duration::from_secs(5);906 29 unmodified lines936 }937 }938 939 #[tokio::test(start_paused = true)]940+ async fn keep_alive_with_raw_events() {941+ const DELAY: Duration = Duration::from_secs(5);942+943+ let app = Router::new().route(944+ "/",945+ get(|| async {946+ let stream =947+ stream::repeat_with(|| Event::raw(Bytes::from_static(b"data: raw\n\n")))948+ .map(Ok::<_, Infallible>)949+ .throttle(DELAY);950+951+ Sse::new(stream).keep_alive(952+ KeepAlive::new()953+ .interval(Duration::from_secs(1))954+ .text("keep-alive-text"),955+ )956+ }),957+ );958+959+ let client = TestClient::new(app);960+ let mut stream = client.get("/").await;961+962+ for _ in 0..5 {963+ // first message should be a raw event, sent byte-exact964+ assert_eq!(stream.chunk_text().await.unwrap(), "data: raw\n\n");965+966+ // then 4 seconds of keep-alive messages: a raw event resets the timer just like967+ // any other event968+ for _ in 0..4 {969+ tokio::time::sleep(Duration::from_secs(1)).await;970+ let event_fields = parse_event(&stream.chunk_text().await.unwrap());971+ assert_eq!(event_fields.get("comment").unwrap(), "keep-alive-text");972+ }973+ }974+ }975+976+ #[tokio::test(start_paused = true)]977 async fn keep_alive_ends_when_the_stream_ends() {978 const DELAY: Duration = Duration::from_secs(5);979 980 let app = Router::new().route(58 unmodified linesmodified:axum/CHANGELOG.md+2 added
19 unmodified lines20 tasks are spawned, enabling use cases like tracing and telemetry instrumentation ([#3704])21 - **added:** `IntoResponseParts` impl for `Redirect`, allowing it to be combined22 with a body in a response tuple ([#3721])23 - **added:** Add `RawPathParams::from_request_extensions` ([#3757])24+- **added:** `sse::Event::raw` for events with fully custom payloads ([#3829])25 - **changed:** `serve` has an additional generic argument and can now work with any response body26 type, not just `axum::body::Body` ([#3205])27 - **changed:** Reduced contention in `axum::serve` shutdown notification with many28 active connections ([#3867])16 unmodified lines45 [#3721]: https://github.com/tokio-rs/axum/pull/372146 [#3742]: https://github.com/tokio-rs/axum/pull/374247 [#3836]: https://github.com/tokio-rs/axum/pull/383648 [#3757]: https://github.com/tokio-rs/axum/pull/375749+[#3829]: https://github.com/tokio-rs/axum/pull/382950 [#3801]: https://github.com/tokio-rs/axum/pull/380151 [#3867]: https://github.com/tokio-rs/axum/pull/386752 53 # 0.8.92411 unmodified lines