use std::convert::Infallible;
use std::time::Duration;
use axum::http::{header, HeaderName, HeaderValue};
use axum::response::{IntoResponse, Response};
use futures_core::Stream;
pub use axum::response::sse::{Event, KeepAlive, Sse};
const DEFAULT_KEEP_ALIVE_SECS: u64 = 15;
const X_ACCEL_BUFFERING: HeaderName = HeaderName::from_static("x-accel-buffering");
pub fn sse<S>(stream: S) -> Response
where
S: Stream<Item = Result<Event, Infallible>> + Send + 'static,
{
sse_with_keep_alive(stream, Duration::from_secs(DEFAULT_KEEP_ALIVE_SECS))
}
pub fn sse_with_keep_alive<S>(stream: S, interval: Duration) -> Response
where
S: Stream<Item = Result<Event, Infallible>> + Send + 'static,
{
let mut resp = if interval.is_zero() {
Sse::new(stream).into_response()
} else {
Sse::new(stream)
.keep_alive(KeepAlive::new().interval(interval))
.into_response()
};
let headers = resp.headers_mut();
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("text/event-stream; charset=utf-8"),
);
headers.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-cache"));
headers.insert(X_ACCEL_BUFFERING, HeaderValue::from_static("no"));
resp
}
#[cfg(test)]
mod tests {
use super::*;
use axum::http::StatusCode;
fn probe(interval: Duration) -> Response {
sse_with_keep_alive(
tokio_stream::iter(vec![Ok::<_, Infallible>(
Event::default().event("message").data("hi"),
)]),
interval,
)
}
#[tokio::test]
async fn sse_sets_stream_headers() {
let resp = probe(Duration::from_secs(15));
assert_eq!(resp.status(), StatusCode::OK);
let headers = resp.headers();
let ct = headers.get(header::CONTENT_TYPE).unwrap().to_str().unwrap();
assert!(ct.starts_with("text/event-stream"), "{}", ct);
assert!(ct.contains("charset=utf-8"), "{}", ct);
assert_eq!(headers.get(header::CACHE_CONTROL).unwrap(), "no-cache");
assert_eq!(headers.get(X_ACCEL_BUFFERING).unwrap(), "no");
}
#[tokio::test]
async fn sse_writes_event_frames() {
let resp = probe(Duration::ZERO);
let body = resp.into_body();
let bytes = axum::body::to_bytes(body, 1024).await.unwrap();
let text = String::from_utf8_lossy(&bytes);
assert!(text.contains("event: message"), "{}", text);
assert!(text.contains("data: hi"), "{}", text);
assert!(text.lines().all(|l| !l.starts_with(':')), "{}", text);
}
#[tokio::test]
async fn default_sse_uses_nonzero_keep_alive() {
let resp = sse(tokio_stream::iter(Vec::<Result<Event, Infallible>>::new()));
assert_eq!(resp.status(), StatusCode::OK);
}
}