hyperlane-plugin-sse 23.2.0

A Server-Sent Events (SSE) streaming and topic pub/sub plugin for the Hyperlane framework with Last-Event-ID replay, heartbeat, and CRLF-safe event framing.
Documentation
use super::*;

/// One Server-Sent Event frame with optional id, event type, retry hint, comment, and data payload.
#[derive(Clone, Data, Debug, Default, Eq, PartialEq)]
pub struct SseEvent {
    /// Optional event identifier emitted as `id: <value>`.
    #[get(type(clone))]
    pub(crate) id: Option<String>,
    /// Optional event name emitted as `event: <value>`.
    #[get(type(clone))]
    pub(crate) event: Option<String>,
    /// Event payload emitted as one or more `data: <line>` lines.
    pub(crate) data: String,
    /// Optional client reconnection delay in milliseconds (`retry: <ms>`).
    #[get(type(copy))]
    pub(crate) retry: Option<u64>,
    /// Optional SSE comment line emitted as `: <comment>`.
    #[get(type(clone))]
    pub(crate) comment: Option<String>,
}

/// Configuration for [`SseHub`] and [`SseStream`].
#[derive(Clone, Data, Debug, Eq, PartialEq)]
pub struct SseConfig {
    /// Heartbeat comment interval in milliseconds (`0` disables heartbeats).
    #[get(type(copy))]
    pub(crate) heartbeat_ms: u64,
    /// Reconnection hint sent to clients in milliseconds (`0` omits `retry:`).
    #[get(type(copy))]
    pub(crate) retry_ms: u64,
    /// Maximum number of recent events retained per topic for `Last-Event-ID` replay.
    #[get(type(copy))]
    pub(crate) replay_capacity: usize,
    /// Broadcast channel buffer capacity per topic.
    #[get(type(copy))]
    pub(crate) channel_capacity: usize,
    /// Maximum concurrent distinct topics tracked by an [`SseHub`].
    #[get(type(copy))]
    pub(crate) max_topics: usize,
}

/// Zero-allocation multiplicative 64-bit hasher for SSE topic shard lookup.
#[derive(Clone, Copy, Default)]
pub(crate) struct FxHasher {
    /// Running 64-bit hash accumulator.
    pub(crate) state: u64,
}

/// Cache-line-aligned SSE topic shard avoiding cross-thread false sharing.
#[repr(align(64))]
pub(crate) struct SseShard {
    /// Per-shard read-write lock guarding active topic states.
    pub(crate) map: RwLock<SseShardMap>,
}

/// Shared SSE event carrying lazily pre-encoded wire bytes reused zero-copy across subscribers.
pub(crate) struct SharedSseEvent {
    /// Logical SSE event payload.
    pub(crate) event: SseEvent,
    /// Lazily encoded wire bytes shared across all streaming subscribers.
    pub(crate) encoded: OnceLock<Box<[u8]>>,
}

/// One live broadcast entry awaiting delivery to active SSE topic subscribers.
pub(crate) struct SseRingEntry {
    /// Strictly monotonic per-topic delivery sequence number.
    pub(crate) seq: u64,
    /// Shared zero-copy SSE event payload.
    pub(crate) event: Arc<SharedSseEvent>,
    /// Exact number of live subscribers with cursor `<= seq` that have not consumed this entry.
    pub(crate) unread: usize,
}

/// Lazily allocated, auto-reclaiming bounded ring buffer for one SSE topic.
pub(crate) struct SseTopicRing {
    /// Unread live entries (`VecDeque::new()` — zero heap bytes when idle or fully drained).
    pub(crate) entries: VecDeque<SseRingEntry>,
    /// Sequence number of `entries.front()`, or `next_seq` when empty.
    pub(crate) head_seq: u64,
    /// Next sequence number assigned on publish.
    pub(crate) next_seq: u64,
    /// Active subscriber count synchronized with `unread` entry counters.
    pub(crate) subscribers: usize,
    /// Maximum unread entries retained before evicting oldest messages.
    pub(crate) capacity: usize,
    /// Whether this topic has been explicitly removed and closed.
    pub(crate) closed: bool,
}

/// Shared staggered multi-bucket heartbeat ticker driving thousands of idle SSE streams from one timer.
pub(crate) struct SseHeartbeatWheel {
    /// Staggered watch channels notified one bucket per step to eliminate thundering-herd flushes.
    pub(crate) buckets: Box<[Sender<u64>]>,
    /// Rotating phase cursor advanced once per step by the single background ticker task.
    pub(crate) phase: AtomicUsize,
    /// Indicates whether the background ticker task is still active.
    pub(crate) alive: AtomicBool,
}

/// RAII guard returning a worker-local coalesce scratch buffer on drop (including future cancellation).
pub(crate) struct SseScratchBuf {
    /// Borrowed scratch byte buffer.
    pub(crate) buf: Vec<u8>,
}

/// Per-topic zero-idle-ring pub/sub state and independently locked lazily grown replay ring.
pub(crate) struct TopicState {
    /// Lock-free active subscriber count avoiding ring lock probes when no subscribers exist.
    pub(crate) subscribers: AtomicUsize,
    /// Zero-allocation intrusive waiter list waking idle subscribers on publish or topic close.
    pub(crate) notify: Notify,
    /// Lazily allocated, auto-reclaiming bounded live delivery ring.
    pub(crate) ring: Mutex<SseTopicRing>,
    /// Lazily grown bounded FIFO replay buffer storing `(sequence_id, shared_event)`.
    pub(crate) replay: Mutex<SseReplayQueue>,
}

/// Shared sharded interior state of an [`SseHub`].
pub(crate) struct SseHubInner {
    /// Configuration limits governing this hub.
    pub(crate) config: SseConfig,
    /// Monotonic event sequence generator across all topics.
    pub(crate) next_seq: AtomicU64,
    /// Lock-free counter tracking total active topics across all shards.
    pub(crate) active_topics: AtomicUsize,
    /// 64-way lock-striped topic registry indexed by [`FxHasher`].
    pub(crate) shards: Box<[SseShard; SSE_SHARD_COUNT]>,
    /// Lazily created runtime-scoped staggered heartbeat wheels shared across idle SSE streams.
    pub(crate) heartbeats: Mutex<SseHeartbeatMap>,
}

/// Thread-safe sharded multi-topic Server-Sent Events pub/sub hub with `Last-Event-ID` replay.
#[derive(Clone)]
pub struct SseHub {
    /// Shared hub state.
    pub(crate) inner: Arc<SseHubInner>,
}

/// Compact cursor over `Last-Event-ID` replay events allocated only when catch-up replay is non-empty.
pub(crate) struct SseReplayBatch {
    /// Captured replay events ordered from oldest to newest.
    pub(crate) items: Box<[Arc<SharedSseEvent>]>,
    /// Index of the next unconsumed replay event.
    pub(crate) next: usize,
}

/// Active subscriber handle returned by [`SseHub::subscribe`].
pub struct SseSubscription {
    /// Shared topic name owned by this subscription for cleanup on drop.
    pub(crate) topic: Arc<str>,
    /// Cached topic state handle enabling lock-free fast-path drop checks.
    pub(crate) state: Arc<TopicState>,
    /// Reference to the parent hub for automatic empty-topic eviction and shared heartbeats.
    pub(crate) hub: Arc<SseHubInner>,
    /// Lazily allocated replay batch captured on subscribe when `Last-Event-ID` matched (`None` when empty).
    pub(crate) replayed: Option<Box<SseReplayBatch>>,
    /// Next per-topic live ring sequence number expected by this subscriber.
    pub(crate) cursor: u64,
}

/// Helper for configuring SSE response headers and streaming events over a Hyperlane [`Context`].
pub struct SseStream;

/// Process-wide [`SsePlugin`] registry storing an [`SseConfig`] and shared [`SseHub`].
#[derive(Clone)]
pub struct SsePlugin {
    /// Active plugin configuration.
    pub(crate) config: SseConfig,
    /// Shared process-wide SSE pub/sub hub.
    pub(crate) hub: SseHub,
}