nido-svc-common 0.1.0-alpha.1

Shared health, error, OpenAPI, SSE, and middleware primitives for nido-*-svc crates
Documentation
// SPDX-License-Identifier: Apache-2.0 OR MIT

//! SSE keepalive wrapper — Cilium-mandatory 15s interval.
//!
//! Without a keepalive, idle SSE connections hit Cilium's connection timeout
//! and are silently dropped.  All nido-*-svc SSE endpoints must use this
//! wrapper.

use axum::response::sse::{Event, KeepAlive, KeepAliveStream, Sse};
use futures::Stream;
use std::time::Duration;

/// Default keepalive interval required to survive Cilium connection timeouts.
pub const SSE_KEEPALIVE_SECS: u64 = 15;

/// Wrap a stream in `Sse` with the mandatory 15-second keepalive.
///
/// # Example
///
/// ```rust,no_run
/// # use futures::stream;
/// # use axum::response::sse::Event;
/// # use std::convert::Infallible;
/// use nido_svc_common::sse::sse_with_keepalive;
///
/// async fn events_handler() -> impl axum::response::IntoResponse {
///     let stream = stream::empty::<Result<Event, Infallible>>();
///     sse_with_keepalive(stream)
/// }
/// ```
pub fn sse_with_keepalive<S, E>(stream: S) -> Sse<KeepAliveStream<S>>
where
    S: Stream<Item = Result<Event, E>> + Send + 'static,
    E: std::error::Error + Send + Sync + 'static,
{
    Sse::new(stream).keep_alive(
        KeepAlive::new()
            .interval(Duration::from_secs(SSE_KEEPALIVE_SECS))
            .text("keep-alive"),
    )
}