slabs-realtime 0.2.0

Low-level pub/sub broadcast hub for SSE and WebSockets
Documentation
//! In-process topic broadcast hub for Server-Sent Events (SSE) and `WebSockets` in Slabs.
//!
//! [`Realtime`] maps string topic names to [`tokio::sync::broadcast`] channels so HTTP handlers
//! and background jobs can push live updates to connected browsers.
//!
//! # Delivery and lag semantics
//!
//! - Single-node and in-memory: messages stay inside one server process and are not persisted or
//!   replicated across nodes.
//! - Fire-and-forget: publishing to a topic with zero active subscribers drops the message and
//!   returns `0`.
//! - Bounded buffer: each topic holds 256 messages per channel. When a slow receiver falls more
//!   than 256 messages behind, `tokio::sync::broadcast` skips the oldest messages and reports lag.
//! - SSE resilience: [`Realtime::sse_stream`] ignores lag errors so slow clients stay connected,
//!   and sends a `"ping"` keep-alive comment every 15 seconds. Direct [`Realtime::subscribe`]
//!   callers (such as `WebSocket` loops) receive raw [`tokio::sync::broadcast::Receiver`] values
//!   and must handle `RecvError::Lagged` explicitly.
//!
//! # Usage
//!
//! ```rust,no_run
//! use serde::Serialize;
//! use slabs_realtime::Realtime;
//!
//! #[derive(Serialize)]
//! struct Ping {
//!     room_id: &'static str,
//! }
//!
//! fn push_updates(realtime: &Realtime) {
//!     realtime.publish_html("room:lobby", "message", "<p>Hello</p>");
//!     realtime.publish_json("room:lobby", "ping", &Ping { room_id: "lobby" });
//! }
//!
//! fn sse_handler(realtime: &Realtime) -> impl axum::response::IntoResponse {
//!     realtime.sse_stream("room:lobby")
//! }
//! ```

use axum::response::sse::{Event, KeepAlive, Sse};
use futures_util::Stream;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::convert::Infallible;
use std::sync::{Arc, RwLock};
use std::time::Duration;
use tokio::sync::broadcast;
use tokio_stream::wrappers::BroadcastStream;
use tokio_stream::StreamExt;

/// Message delivered over a realtime topic to SSE and `WebSocket` subscribers.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RealtimeMessage {
    /// Topic channel name the message was published on.
    pub topic: String,
    /// Named event type sent as the SSE `event:` field.
    pub event: String,
    /// Serialized message body (plain text, HTML fragment, or JSON).
    pub data: String,
}

/// Clonable, in-memory topic broadcast hub for SSE and `WebSockets`.
///
/// Topics are created lazily on first publish or subscribe with a 256-message ring buffer per
/// topic.
#[derive(Debug, Clone, Default)]
pub struct Realtime {
    topics: Arc<RwLock<HashMap<String, broadcast::Sender<RealtimeMessage>>>>,
}

impl Realtime {
    /// Create an empty in-memory broadcast hub.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    fn sender_for(&self, topic: &str) -> broadcast::Sender<RealtimeMessage> {
        {
            let guard = self.topics.read().expect("realtime rwlock poisoned");
            if let Some(tx) = guard.get(topic) {
                return tx.clone();
            }
        }
        let mut guard = self.topics.write().expect("realtime rwlock poisoned");
        guard
            .entry(topic.to_string())
            .or_insert_with(|| broadcast::channel(256).0)
            .clone()
    }

    /// Subscribe to raw broadcast messages on `topic` for custom SSE or `WebSocket` loops.
    ///
    /// Slow receivers that fall more than 256 messages behind receive `RecvError::Lagged`.
    pub fn subscribe(&self, topic: &str) -> broadcast::Receiver<RealtimeMessage> {
        self.sender_for(topic).subscribe()
    }

    /// Publish a text payload to `topic` under `event` and return the active subscriber count.
    ///
    /// Returns `0` and drops the message when `topic` has no active subscribers.
    pub fn publish_text(&self, topic: &str, event: &str, data: impl Into<String>) -> usize {
        let tx = self.sender_for(topic);
        let msg = RealtimeMessage {
            topic: topic.to_string(),
            event: event.to_string(),
            data: data.into(),
        };
        tx.send(msg).unwrap_or(0)
    }

    /// Serialize `payload` as JSON and publish it to `topic` under `event`.
    ///
    /// Falls back to `"{}"` if serialization fails. Returns the active subscriber count.
    pub fn publish_json<T: Serialize>(&self, topic: &str, event: &str, payload: &T) -> usize {
        let data = serde_json::to_string(payload).unwrap_or_else(|_| "{}".into());
        self.publish_text(topic, event, data)
    }

    /// Publish an HTML fragment to `topic` under `event` for HTMX `sse-swap="<event>"` listeners.
    ///
    /// Returns the active subscriber count.
    pub fn publish_html(&self, topic: &str, event: &str, html: impl Into<String>) -> usize {
        self.publish_text(topic, event, html)
    }

    /// Build an Axum SSE response subscribed to `topic` with a 15-second `"ping"` keep-alive.
    ///
    /// Lagged broadcast errors are skipped so slow clients remain connected.
    pub fn sse_stream(&self, topic: &str) -> Sse<impl Stream<Item = Result<Event, Infallible>>> {
        let rx = self.subscribe(topic);
        let stream = BroadcastStream::new(rx).filter_map(|item| match item {
            Ok(msg) => Some(Ok(Event::default().event(msg.event).data(msg.data))),
            Err(_) => None,
        });
        Sse::new(stream).keep_alive(
            KeepAlive::new()
                .interval(Duration::from_secs(15))
                .text("ping"),
        )
    }
}