wordval-web 1.0.13

Wordval web layer: router, middleware, extractors, responses, session-based authentication
Documentation
//! SSE(Server-Sent Events)响应辅助
//!
//! 薄封装 axum 的 [`Sse`],统一补齐流式响应常见缺口:
//! - `Content-Type: text/event-stream; charset=utf-8`
//! - `Cache-Control: no-cache`
//! - `X-Accel-Buffering: no`(Nginx 等反向代理不缓冲,避免增量被攒批)
//! - 默认 keep-alive 心跳(穿透代理空闲超时)
//!
//! # 示例
//!
//! ```ignore
//! use wordval_web::sse::{sse, Event};
//! use tokio_stream::Iter;
//!
//! async fn stream_handler() -> axum::response::Response {
//!     let events = vec![
//!         Ok(Event::default().data("hello")),
//!         Ok(Event::default().data("world")),
//!     ];
//!     sse(tokio_stream::iter(events))
//! }
//! ```

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};

/// 默认 keep-alive 间隔(秒):多数反向代理/负载均衡的空闲超时为 60s
const DEFAULT_KEEP_ALIVE_SECS: u64 = 15;

const X_ACCEL_BUFFERING: HeaderName = HeaderName::from_static("x-accel-buffering");

/// 构造 SSE 响应(默认 15s keep-alive)
///
/// `stream` 的每个 `Ok(Event)` 会立即写入响应体;`Err` 类型固定为
/// [`Infallible`],业务侧用 `futures::stream::unfold` / channel 产出事件即可。
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))
}

/// 构造 SSE 响应并自定义 keep-alive 间隔
///
/// 传入 `Duration::ZERO` 关闭心跳。
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);
        // 关闭心跳时不应出现 keep-alive 注释帧(以 ':' 开头的行)
        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);
    }
}