hyperlane_plugin_sse/struct.rs
1use super::*;
2
3/// One Server-Sent Event frame with optional id, event type, retry hint, comment, and data payload.
4#[derive(Clone, Data, Debug, Default, Eq, PartialEq)]
5pub struct SseEvent {
6 /// Optional event identifier emitted as `id: <value>`.
7 #[get(type(clone))]
8 pub(crate) id: Option<String>,
9 /// Optional event name emitted as `event: <value>`.
10 #[get(type(clone))]
11 pub(crate) event: Option<String>,
12 /// Event payload emitted as one or more `data: <line>` lines.
13 pub(crate) data: String,
14 /// Optional client reconnection delay in milliseconds (`retry: <ms>`).
15 #[get(type(copy))]
16 pub(crate) retry: Option<u64>,
17 /// Optional SSE comment line emitted as `: <comment>`.
18 #[get(type(clone))]
19 pub(crate) comment: Option<String>,
20}
21
22/// Configuration for [`SseHub`] and [`SseStream`].
23#[derive(Clone, Data, Debug, Eq, PartialEq)]
24pub struct SseConfig {
25 /// Heartbeat comment interval in milliseconds (`0` disables heartbeats).
26 #[get(type(copy))]
27 pub(crate) heartbeat_ms: u64,
28 /// Reconnection hint sent to clients in milliseconds (`0` omits `retry:`).
29 #[get(type(copy))]
30 pub(crate) retry_ms: u64,
31 /// Maximum number of recent events retained per topic for `Last-Event-ID` replay.
32 #[get(type(copy))]
33 pub(crate) replay_capacity: usize,
34 /// Broadcast channel buffer capacity per topic.
35 #[get(type(copy))]
36 pub(crate) channel_capacity: usize,
37 /// Maximum concurrent distinct topics tracked by an [`SseHub`].
38 #[get(type(copy))]
39 pub(crate) max_topics: usize,
40}
41
42/// Zero-allocation multiplicative 64-bit hasher for SSE topic shard lookup.
43#[derive(Clone, Copy, Default)]
44pub(crate) struct FxHasher {
45 /// Running 64-bit hash accumulator.
46 pub(crate) state: u64,
47}
48
49/// Cache-line-aligned SSE topic shard avoiding cross-thread false sharing.
50#[repr(align(64))]
51pub(crate) struct SseShard {
52 /// Per-shard read-write lock guarding active topic states.
53 pub(crate) map: RwLock<SseShardMap>,
54}
55
56/// Shared SSE event carrying lazily pre-encoded wire bytes reused zero-copy across subscribers.
57pub(crate) struct SharedSseEvent {
58 /// Logical SSE event payload.
59 pub(crate) event: SseEvent,
60 /// Lazily encoded wire bytes shared across all streaming subscribers.
61 pub(crate) encoded: OnceLock<Box<[u8]>>,
62}
63
64/// One live broadcast entry awaiting delivery to active SSE topic subscribers.
65pub(crate) struct SseRingEntry {
66 /// Strictly monotonic per-topic delivery sequence number.
67 pub(crate) seq: u64,
68 /// Shared zero-copy SSE event payload.
69 pub(crate) event: Arc<SharedSseEvent>,
70 /// Exact number of live subscribers with cursor `<= seq` that have not consumed this entry.
71 pub(crate) unread: usize,
72}
73
74/// Lazily allocated, auto-reclaiming bounded ring buffer for one SSE topic.
75pub(crate) struct SseTopicRing {
76 /// Unread live entries (`VecDeque::new()` — zero heap bytes when idle or fully drained).
77 pub(crate) entries: VecDeque<SseRingEntry>,
78 /// Sequence number of `entries.front()`, or `next_seq` when empty.
79 pub(crate) head_seq: u64,
80 /// Next sequence number assigned on publish.
81 pub(crate) next_seq: u64,
82 /// Active subscriber count synchronized with `unread` entry counters.
83 pub(crate) subscribers: usize,
84 /// Maximum unread entries retained before evicting oldest messages.
85 pub(crate) capacity: usize,
86 /// Whether this topic has been explicitly removed and closed.
87 pub(crate) closed: bool,
88}
89
90/// Shared staggered multi-bucket heartbeat ticker driving thousands of idle SSE streams from one timer.
91pub(crate) struct SseHeartbeatWheel {
92 /// Staggered watch channels notified one bucket per step to eliminate thundering-herd flushes.
93 pub(crate) buckets: Box<[Sender<u64>]>,
94 /// Rotating phase cursor advanced once per step by the single background ticker task.
95 pub(crate) phase: AtomicUsize,
96 /// Indicates whether the background ticker task is still active.
97 pub(crate) alive: AtomicBool,
98}
99
100/// RAII guard returning a worker-local coalesce scratch buffer on drop (including future cancellation).
101pub(crate) struct SseScratchBuf {
102 /// Borrowed scratch byte buffer.
103 pub(crate) buf: Vec<u8>,
104}
105
106/// Per-topic zero-idle-ring pub/sub state and independently locked lazily grown replay ring.
107pub(crate) struct TopicState {
108 /// Lock-free active subscriber count avoiding ring lock probes when no subscribers exist.
109 pub(crate) subscribers: AtomicUsize,
110 /// Zero-allocation intrusive waiter list waking idle subscribers on publish or topic close.
111 pub(crate) notify: Notify,
112 /// Lazily allocated, auto-reclaiming bounded live delivery ring.
113 pub(crate) ring: Mutex<SseTopicRing>,
114 /// Lazily grown bounded FIFO replay buffer storing `(sequence_id, shared_event)`.
115 pub(crate) replay: Mutex<SseReplayQueue>,
116}
117
118/// Shared sharded interior state of an [`SseHub`].
119pub(crate) struct SseHubInner {
120 /// Configuration limits governing this hub.
121 pub(crate) config: SseConfig,
122 /// Monotonic event sequence generator across all topics.
123 pub(crate) next_seq: AtomicU64,
124 /// Lock-free counter tracking total active topics across all shards.
125 pub(crate) active_topics: AtomicUsize,
126 /// 64-way lock-striped topic registry indexed by [`FxHasher`].
127 pub(crate) shards: Box<[SseShard; SSE_SHARD_COUNT]>,
128 /// Lazily created runtime-scoped staggered heartbeat wheels shared across idle SSE streams.
129 pub(crate) heartbeats: Mutex<SseHeartbeatMap>,
130}
131
132/// Thread-safe sharded multi-topic Server-Sent Events pub/sub hub with `Last-Event-ID` replay.
133#[derive(Clone)]
134pub struct SseHub {
135 /// Shared hub state.
136 pub(crate) inner: Arc<SseHubInner>,
137}
138
139/// Compact cursor over `Last-Event-ID` replay events allocated only when catch-up replay is non-empty.
140pub(crate) struct SseReplayBatch {
141 /// Captured replay events ordered from oldest to newest.
142 pub(crate) items: Box<[Arc<SharedSseEvent>]>,
143 /// Index of the next unconsumed replay event.
144 pub(crate) next: usize,
145}
146
147/// Active subscriber handle returned by [`SseHub::subscribe`].
148pub struct SseSubscription {
149 /// Shared topic name owned by this subscription for cleanup on drop.
150 pub(crate) topic: Arc<str>,
151 /// Cached topic state handle enabling lock-free fast-path drop checks.
152 pub(crate) state: Arc<TopicState>,
153 /// Reference to the parent hub for automatic empty-topic eviction and shared heartbeats.
154 pub(crate) hub: Arc<SseHubInner>,
155 /// Lazily allocated replay batch captured on subscribe when `Last-Event-ID` matched (`None` when empty).
156 pub(crate) replayed: Option<Box<SseReplayBatch>>,
157 /// Next per-topic live ring sequence number expected by this subscriber.
158 pub(crate) cursor: u64,
159}
160
161/// Helper for configuring SSE response headers and streaming events over a Hyperlane [`Context`].
162pub struct SseStream;
163
164/// Process-wide [`SsePlugin`] registry storing an [`SseConfig`] and shared [`SseHub`].
165#[derive(Clone)]
166pub struct SsePlugin {
167 /// Active plugin configuration.
168 pub(crate) config: SseConfig,
169 /// Shared process-wide SSE pub/sub hub.
170 pub(crate) hub: SseHub,
171}