Module sse

Module sse 

Source
Expand description

Server-Sent Events (SSE) response types for RustAPI

This module provides types for streaming Server-Sent Events to clients. SSE is ideal for real-time updates like notifications, live feeds, and progress updates.

§Example

use rustapi_core::sse::{Sse, SseEvent, KeepAlive};
use futures_util::stream;
use std::time::Duration;

async fn events() -> Sse<impl Stream<Item = Result<SseEvent, std::convert::Infallible>>> {
    let stream = stream::iter(vec![
        Ok(SseEvent::new("Hello")),
        Ok(SseEvent::new("World").event("greeting")),
    ]);
    Sse::new(stream)
        .keep_alive(KeepAlive::new().interval(Duration::from_secs(15)))
}

§Keep-Alive Support

SSE connections can be kept alive by sending periodic comments:

use rustapi_core::sse::{Sse, SseEvent, KeepAlive};
use std::time::Duration;

async fn events() -> impl IntoResponse {
    let stream = async_stream::stream! {
        for i in 0..10 {
            yield Ok::<_, std::convert::Infallible>(
                SseEvent::new(format!("Event {}", i))
            );
            tokio::time::sleep(Duration::from_secs(1)).await;
        }
    };

    Sse::new(stream)
        .keep_alive(KeepAlive::new()
            .interval(Duration::from_secs(30))
            .text("ping"))
}

Structs§

KeepAlive
Keep-alive configuration for SSE connections
Sse
Server-Sent Events response wrapper
SseEvent
A Server-Sent Event
SseStream
A stream that combines SSE events with keep-alive messages

Functions§

collect_sse_events
Collect all SSE events from a stream into a single response body
sse_from_iter
Helper function to create an SSE response from an iterator of events
sse_response
Create an SSE response from a synchronous iterator of events