hyperlane-plugin-sse 23.3.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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
use super::*;

/// Computes the shard index for `topic` with zero allocations.
///
/// # Arguments
///
/// - `&str` - Topic name to hash.
///
/// # Returns
///
/// - `usize` - Shard slot in `0..SSE_SHARD_COUNT`.
#[inline(always)]
pub(crate) fn sse_shard_index(topic: &str) -> usize {
    let mut hasher: FxHasher = FxHasher::default();
    hasher.write(topic.as_bytes());
    let h: u64 = hasher.finish();
    (((h >> 32) ^ h) as usize) & (SSE_SHARD_COUNT - 1)
}

/// Tests whether an 8-byte word contains any zero byte using SWAR bit-parallel arithmetic.
///
/// # Arguments
///
/// - `u64` - Input 8-byte word.
///
/// # Returns
///
/// - `bool` - `true` if any lane equals `0x00`.
#[inline(always)]
pub(crate) fn swar_has_zero(word: u64) -> bool {
    (word.wrapping_sub(SWAR_LO_ONES) & !word & SWAR_HI_BITS) != 0
}

/// Reports whether `bytes` contains any `\r`, `\n`, or NUL byte using 8-byte SWAR scanning.
///
/// # Arguments
///
/// - `&[u8]` - Input byte slice.
///
/// # Returns
///
/// - `bool` - `true` when any forbidden control byte is present.
#[inline]
pub(crate) fn has_forbidden_sse_byte(bytes: &[u8]) -> bool {
    let (chunks, rem): (&[[u8; 8]], &[u8]) = bytes.as_chunks::<8>();
    for chunk in chunks {
        let w: u64 = u64::from_ne_bytes(*chunk);
        if swar_has_zero(w) || swar_has_zero(w ^ SWAR_LF_MASK) || swar_has_zero(w ^ SWAR_CR_MASK) {
            return true;
        }
    }
    for &b in rem {
        if b == BYTE_LF || b == BYTE_CR || b == 0 {
            return true;
        }
    }
    false
}

/// Finds the first `\r` or `\n` offset within `bytes` using 8-byte SWAR scanning.
///
/// # Arguments
///
/// - `&[u8]` - Input payload byte slice.
///
/// # Returns
///
/// - `Option<usize>` - Byte index of the first line break, or `None` if single-line.
#[inline]
pub(crate) fn find_line_break(bytes: &[u8]) -> Option<usize> {
    let (chunks, rem): (&[[u8; 8]], &[u8]) = bytes.as_chunks::<8>();
    for (ci, chunk) in chunks.iter().enumerate() {
        let w: u64 = u64::from_ne_bytes(*chunk);
        let lf: u64 = w ^ SWAR_LF_MASK;
        let cr: u64 = w ^ SWAR_CR_MASK;
        let mask: u64 = ((lf.wrapping_sub(SWAR_LO_ONES) & !lf)
            | (cr.wrapping_sub(SWAR_LO_ONES) & !cr))
            & SWAR_HI_BITS;
        if mask != 0 {
            let base: usize = ci * 8;
            for (j, &b) in chunk.iter().enumerate() {
                if b == BYTE_LF || b == BYTE_CR {
                    return Some(base + j);
                }
            }
        }
    }
    let tail_base: usize = chunks.len() * 8;
    for (j, &b) in rem.iter().enumerate() {
        if b == BYTE_LF || b == BYTE_CR {
            return Some(tail_base + j);
        }
    }
    None
}

/// Writes sanitized single-line SSE header bytes directly into `out`, stripping `\r`, `\n`, and NUL.
///
/// # Arguments
///
/// - `&str` - Raw field text.
/// - `&mut Vec<u8>` - Destination wire buffer.
#[inline]
pub(crate) fn write_sanitized_sse_bytes(raw: &str, out: &mut Vec<u8>) {
    let bytes: &[u8] = raw.as_bytes();
    if !has_forbidden_sse_byte(bytes) {
        out.extend_from_slice(bytes);
        return;
    }
    for &b in bytes {
        if b != BYTE_CR && b != BYTE_LF && b != 0 {
            out.push(b);
        }
    }
}

/// Writes sanitized single-line SSE bytes into fixed stack slice `buf` at `pos`, returning new offset.
///
/// # Arguments
///
/// - `&str` - Raw field text.
/// - `&mut [u8]` - Destination stack buffer.
/// - `usize` - Starting write offset.
///
/// # Returns
///
/// - `Option<usize>` - Updated write offset, or `None` on overflow.
#[inline]
pub(crate) fn write_sanitized_sse_slice(raw: &str, buf: &mut [u8], pos: usize) -> Option<usize> {
    let bytes: &[u8] = raw.as_bytes();
    if !has_forbidden_sse_byte(bytes) {
        let next: usize = pos + bytes.len();
        if next > buf.len() {
            return None;
        }
        buf[pos..next].copy_from_slice(bytes);
        return Some(next);
    }
    let mut cur: usize = pos;
    for &b in bytes {
        if b != BYTE_CR && b != BYTE_LF && b != 0 {
            if cur >= buf.len() {
                return None;
            }
            buf[cur] = b;
            cur += 1;
        }
    }
    Some(cur)
}

/// Writes an unsigned 64-bit decimal integer into a 20-byte stack array, returning the start index.
///
/// # Arguments
///
/// - `u64` - Unsigned integer to format.
/// - `&mut [u8; U64_DECIMAL_BUF_LEN]` - Destination digit array.
///
/// # Returns
///
/// - `usize` - Start index inside `digits` (`digits[idx..]` holds the formatted digits).
#[inline(always)]
pub(crate) fn format_u64_digits(mut value: u64, digits: &mut [u8; U64_DECIMAL_BUF_LEN]) -> usize {
    if value < 10 {
        let idx: usize = U64_DECIMAL_BUF_LEN - 1;
        digits[idx] = BYTE_ZERO + value as u8;
        return idx;
    }
    let mut idx: usize = U64_DECIMAL_BUF_LEN;
    while value >= 100 {
        let pair: usize = ((value % 100) as usize) * 2;
        value /= 100;
        idx -= 2;
        digits[idx] = DEC_DIGITS_LUT[pair];
        digits[idx + 1] = DEC_DIGITS_LUT[pair + 1];
    }
    if value >= 10 {
        let pair: usize = (value as usize) * 2;
        idx -= 2;
        digits[idx] = DEC_DIGITS_LUT[pair];
        digits[idx + 1] = DEC_DIGITS_LUT[pair + 1];
    } else {
        idx -= 1;
        digits[idx] = BYTE_ZERO + value as u8;
    }
    idx
}

/// Writes an unsigned 64-bit decimal integer directly into `out` without allocating.
///
/// # Arguments
///
/// - `u64` - Unsigned integer to format.
/// - `&mut Vec<u8>` - Destination wire buffer.
#[inline]
pub(crate) fn write_u64_decimal(value: u64, out: &mut Vec<u8>) {
    let mut digits: [u8; U64_DECIMAL_BUF_LEN] = [0u8; U64_DECIMAL_BUF_LEN];
    let pos: usize = format_u64_digits(value, &mut digits);
    out.extend_from_slice(&digits[pos..]);
}

/// Writes an unsigned 64-bit decimal integer into fixed stack slice `buf` at `pos`.
///
/// # Arguments
///
/// - `u64` - Unsigned integer to format.
/// - `&mut [u8]` - Destination stack buffer.
/// - `usize` - Starting write offset.
///
/// # Returns
///
/// - `Option<usize>` - Updated write offset, or `None` on overflow.
#[inline]
pub(crate) fn write_u64_decimal_slice(value: u64, buf: &mut [u8], pos: usize) -> Option<usize> {
    let mut digits: [u8; U64_DECIMAL_BUF_LEN] = [0u8; U64_DECIMAL_BUF_LEN];
    let start: usize = format_u64_digits(value, &mut digits);
    let slice: &[u8] = &digits[start..];
    let next: usize = pos + slice.len();
    if next > buf.len() {
        return None;
    }
    buf[pos..next].copy_from_slice(slice);
    Some(next)
}

/// Formats an unsigned 64-bit integer into a decimal `String` via a 2-digit LUT stack buffer.
///
/// # Arguments
///
/// - `u64` - Unsigned integer value.
///
/// # Returns
///
/// - `String` - Decimal string representation.
#[inline]
pub(crate) fn format_u64_string(value: u64) -> String {
    if value == 0 {
        return ZERO_STR.to_owned();
    }
    let mut digits: [u8; U64_DECIMAL_BUF_LEN] = [0u8; U64_DECIMAL_BUF_LEN];
    let pos: usize = format_u64_digits(value, &mut digits);
    from_utf8(&digits[pos..]).unwrap_or_default().to_owned()
}

/// Parses a `Last-Event-ID` string into a numeric sequence id when valid.
///
/// # Arguments
///
/// - `Option<&str>` - Raw `Last-Event-ID` header value.
///
/// # Returns
///
/// - `Option<u64>` - Parsed sequence id, or `None` when absent or non-numeric.
#[inline]
pub(crate) fn parse_last_event_id(raw: Option<&str>) -> Option<u64> {
    raw.and_then(|text: &str| text.trim().parse::<u64>().ok())
}

/// Takes a pooled scratch byte buffer for multi-event SSE wire coalescing.
///
/// # Returns
///
/// - `SseScratchBuf` - An empty scratch buffer returned to the worker pool on drop.
#[inline]
pub(crate) fn take_sse_coalesce_buf() -> SseScratchBuf {
    let buf: Vec<u8> = SSE_COALESCE_BUF_POOL.with(|pool: &RefCell<Vec<Vec<u8>>>| {
        let mut guard: RefMut<'_, Vec<Vec<u8>>> = pool.borrow_mut();
        match guard.pop() {
            Some(mut existing) => {
                existing.clear();
                existing
            }
            None => Vec::new(),
        }
    });
    SseScratchBuf { buf }
}

/// Returns a coalesce scratch buffer to the worker pool when within retention bounds.
///
/// # Arguments
///
/// - `Vec<u8>` - Scratch buffer to recycle.
#[inline]
pub(crate) fn return_sse_coalesce_buf(mut buf: Vec<u8>) {
    if buf.capacity() == 0 || buf.capacity() > SSE_COALESCE_MAX_RETAIN {
        return;
    }
    buf.clear();
    SSE_COALESCE_BUF_POOL.with(|pool: &RefCell<Vec<Vec<u8>>>| {
        let mut guard: RefMut<'_, Vec<Vec<u8>>> = pool.borrow_mut();
        if guard.len() < SSE_MAX_POOLED_COALESCE_BUFS {
            guard.push(buf);
        }
    });
}

/// Prepares SSE response headers and builds the initial response head plus optional retry hint.
///
/// Combining the HTTP head and initial reconnect comment into one buffer halves setup writes
/// and avoids retaining stack retry arrays across the long-lived streaming future.
///
/// # Arguments
///
/// - `&mut Context` - Active Hyperlane request context.
/// - `u64` - Optional reconnect retry hint in milliseconds (`0` omits the hint).
///
/// # Returns
///
/// - `Vec<u8>` - Complete initial wire bytes ready for a single stream write.
pub(crate) fn build_initial_sse_head(ctx: &mut Context, retry_ms: u64) -> Vec<u8> {
    SseStream::prepare(ctx);
    let mut head: Vec<u8> = ctx.get_mut_response().build_head();
    if retry_ms > 0 {
        head.reserve(SSE_RETRY_HINT_STACK_CAP);
        head.extend_from_slice(SSE_COMMENT_PREFIX.as_bytes());
        head.extend_from_slice(SSE_HEARTBEAT_COMMENT.as_bytes());
        head.push(BYTE_LF);
        head.extend_from_slice(SSE_FIELD_RETRY.as_bytes());
        write_u64_decimal(retry_ms, &mut head);
        head.push(BYTE_LF);
        head.push(BYTE_LF);
    }
    head
}

/// Awaits the next SSE streaming action using biased event-first polling over the shared heartbeat wheel.
///
/// # Arguments
///
/// - `&mut SseSubscription` - Active SSE topic subscription.
/// - `&mut Option<Receiver<u64>>` - Optional shared staggered heartbeat receiver.
///
/// # Returns
///
/// - `Result<SseLoopAction, SseError>` - Next event, heartbeat tick, clean closure, or error.
pub(crate) async fn next_sse_action(
    subscription: &mut SseSubscription,
    heartbeat: &mut Option<Receiver<u64>>,
) -> Result<SseLoopAction, SseError> {
    loop {
        match heartbeat {
            None => match subscription.recv_shared().await {
                Ok(shared) => return Ok(SseLoopAction::Event(shared)),
                Err(SseError::Lagged(_)) => continue,
                Err(SseError::ChannelClosed) => return Ok(SseLoopAction::Closed),
                Err(err) => return Err(err),
            },
            Some(hb_rx) => {
                select! {
                    biased;
                    next = subscription.recv_shared() => match next {
                        Ok(shared) => return Ok(SseLoopAction::Event(shared)),
                        Err(SseError::Lagged(_)) => continue,
                        Err(SseError::ChannelClosed) => return Ok(SseLoopAction::Closed),
                        Err(err) => return Err(err),
                    },
                    tick = hb_rx.changed() => {
                        if tick.is_ok() {
                            return Ok(SseLoopAction::Heartbeat);
                        }
                    }
                }
            }
        }
    }
}

/// Drives one shared staggered heartbeat wheel until every subscribed SSE stream disconnects.
///
/// # Arguments
///
/// - `Weak<SseHubInner>` - Weak handle to the owning SSE hub for automatic registry eviction.
/// - `(Id, u64)` - Runtime-scoped `(runtime_id, heartbeat_ms)` registry key.
/// - `Arc<SseHeartbeatWheel>` - Shared bucketed heartbeat wheel to advance.
/// - `Duration` - Step period between consecutive bucket notifications.
pub(crate) async fn drive_sse_heartbeat_wheel(
    hub: Weak<SseHubInner>,
    key: (Id, u64),
    wheel: Arc<SseHeartbeatWheel>,
    step: Duration,
) {
    let mut ticker: Interval = interval(step);
    ticker.set_missed_tick_behavior(MissedTickBehavior::Delay);
    let _: Instant = ticker.tick().await;
    let bucket_count: usize = wheel.buckets.len();
    loop {
        let _: Instant = ticker.tick().await;
        if wheel.total_receivers() == 0 {
            let Some(hub_arc) = hub.upgrade() else {
                wheel.alive.store(false, Ordering::Release);
                return;
            };
            if let Ok(mut map) = hub_arc.heartbeats.lock()
                && wheel.total_receivers() == 0
            {
                wheel.alive.store(false, Ordering::Release);
                if map
                    .get(&key)
                    .is_some_and(|cur: &Arc<SseHeartbeatWheel>| Arc::ptr_eq(cur, &wheel))
                {
                    let _: Option<Arc<SseHeartbeatWheel>> = map.remove(&key);
                }
                return;
            }
        }
        let step_idx: usize = wheel.phase.fetch_add(1, Ordering::AcqRel) % bucket_count;
        wheel.buckets[step_idx].send_modify(|tick: &mut u64| {
            *tick = tick.wrapping_add(1);
        });
    }
}