Skip to main content

hyperlane_plugin_sse/
impl.rs

1use super::*;
2
3/// Implements [`Hasher`] for [`FxHasher`] with zero heap allocations and 8-byte word mixing.
4impl Hasher for FxHasher {
5    /// Finalizes the 64-bit hash state.
6    ///
7    /// # Returns
8    ///
9    /// - `u64` - Finalized 64-bit hash.
10    #[inline(always)]
11    fn finish(&self) -> u64 {
12        let Self { state } = *self;
13        state
14    }
15
16    /// Mixes `bytes` into the hash state 8 bytes at a time without heap allocation.
17    ///
18    /// # Arguments
19    ///
20    /// - `&[u8]` - Input byte slice.
21    #[inline(always)]
22    fn write(&mut self, bytes: &[u8]) {
23        let Self { state } = self;
24        let mut h: u64 = *state;
25        let (chunks, rem): (&[[u8; 8]], &[u8]) = bytes.as_chunks::<8>();
26        for chunk in chunks {
27            h = (h.rotate_left(5) ^ u64::from_ne_bytes(*chunk)).wrapping_mul(FX_HASH_K);
28        }
29        let mut tail: &[u8] = rem;
30        if tail.len() >= 4 {
31            let word: u32 = u32::from_ne_bytes([tail[0], tail[1], tail[2], tail[3]]);
32            h = (h.rotate_left(5) ^ u64::from(word)).wrapping_mul(FX_HASH_K);
33            tail = &tail[4..];
34        }
35        if tail.len() >= 2 {
36            let half: u16 = u16::from_ne_bytes([tail[0], tail[1]]);
37            h = (h.rotate_left(5) ^ u64::from(half)).wrapping_mul(FX_HASH_K);
38            tail = &tail[2..];
39        }
40        if let Some(&b) = tail.first() {
41            h = (h.rotate_left(5) ^ u64::from(b)).wrapping_mul(FX_HASH_K);
42        }
43        *state = h;
44    }
45
46    /// Mixes a single `u8` byte directly into the hash state.
47    ///
48    /// # Arguments
49    ///
50    /// - `u8` - Input byte.
51    #[inline(always)]
52    fn write_u8(&mut self, i: u8) {
53        let Self { state } = self;
54        *state = (state.rotate_left(5) ^ u64::from(i)).wrapping_mul(FX_HASH_K);
55    }
56}
57
58/// Formatting / debug-printing for [`SseError`].
59impl Display for SseError {
60    /// Formats the [`SseError`] via the supplied formatter.
61    ///
62    /// # Arguments
63    ///
64    /// - `&mut Formatter<'_>` - The formatter receiving the formatted output.
65    ///
66    /// # Returns
67    ///
68    /// - `fmt::Result` - A `fmt::Result` value.
69    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
70        match self {
71            Self::TopicLimitReached => f.write_str(ERR_TOPIC_LIMIT),
72            Self::ChannelClosed => f.write_str(ERR_CHANNEL_CLOSED),
73            Self::Lagged(skipped) => write!(f, "SSE subscriber lagged by {skipped} events"),
74            Self::Transport(msg) => f.write_str(msg),
75        }
76    }
77}
78
79/// Implements [`Error`] for [`SseError`].
80impl Error for SseError {}
81
82/// Default construction for [`SseConfig`].
83impl Default for SseConfig {
84    /// Constructs a default [`SseConfig`] value.
85    fn default() -> Self {
86        Self {
87            heartbeat_ms: DEFAULT_SSE_HEARTBEAT_MS,
88            retry_ms: DEFAULT_SSE_RETRY_MS,
89            replay_capacity: DEFAULT_SSE_REPLAY_CAPACITY,
90            channel_capacity: DEFAULT_SSE_CHANNEL_CAPACITY,
91            max_topics: DEFAULT_SSE_MAX_TOPICS,
92        }
93    }
94}
95
96/// Inherent implementation of [`SseConfig`].
97impl SseConfig {
98    /// Sets the heartbeat comment interval in milliseconds (`0` disables heartbeats).
99    ///
100    /// # Arguments
101    ///
102    /// - `u64` - Heartbeat interval in milliseconds.
103    ///
104    /// # Returns
105    ///
106    /// - `Self` - Updated configuration.
107    pub fn with_heartbeat_ms(mut self, heartbeat_ms: u64) -> Self {
108        self.set_heartbeat_ms(heartbeat_ms);
109        self
110    }
111
112    /// Sets the client reconnect retry hint in milliseconds (`0` omits `retry:`).
113    ///
114    /// # Arguments
115    ///
116    /// - `u64` - Reconnect hint in milliseconds.
117    ///
118    /// # Returns
119    ///
120    /// - `Self` - Updated configuration.
121    pub fn with_retry_ms(mut self, retry_ms: u64) -> Self {
122        self.set_retry_ms(retry_ms);
123        self
124    }
125
126    /// Sets the bounded per-topic replay buffer capacity for `Last-Event-ID`.
127    ///
128    /// # Arguments
129    ///
130    /// - `usize` - Number of recent events retained per topic (`0` disables replay).
131    ///
132    /// # Returns
133    ///
134    /// - `Self` - Updated configuration.
135    pub fn with_replay_capacity(mut self, replay_capacity: usize) -> Self {
136        self.set_replay_capacity(replay_capacity);
137        self
138    }
139
140    /// Sets the per-topic broadcast channel buffer capacity.
141    ///
142    /// # Arguments
143    ///
144    /// - `usize` - Broadcast ring size per topic.
145    ///
146    /// # Returns
147    ///
148    /// - `Self` - Updated configuration.
149    pub fn with_channel_capacity(mut self, channel_capacity: usize) -> Self {
150        self.set_channel_capacity(channel_capacity);
151        self
152    }
153
154    /// Sets the maximum number of concurrent distinct topics tracked by an [`SseHub`].
155    ///
156    /// # Arguments
157    ///
158    /// - `usize` - Maximum topic cap.
159    ///
160    /// # Returns
161    ///
162    /// - `Self` - Updated configuration.
163    pub fn with_max_topics(mut self, max_topics: usize) -> Self {
164        self.set_max_topics(max_topics);
165        self
166    }
167}
168
169/// Inherent implementation of [`SseEvent`].
170impl SseEvent {
171    /// Creates a new SSE event carrying `data`.
172    ///
173    /// # Arguments
174    ///
175    /// - `D` - Payload text convertible into `String`.
176    ///
177    /// # Returns
178    ///
179    /// - `Self` - Event with empty metadata and the provided payload.
180    pub fn new<D>(data: D) -> Self
181    where
182        D: Into<String>,
183    {
184        Self {
185            id: None,
186            event: None,
187            data: data.into(),
188            retry: None,
189            comment: None,
190        }
191    }
192
193    /// Creates a comment-only SSE keep-alive frame (`: <comment>\n\n`).
194    ///
195    /// # Arguments
196    ///
197    /// - `C` - Comment text convertible into `String`.
198    ///
199    /// # Returns
200    ///
201    /// - `Self` - Comment-only SSE event.
202    pub fn comment_only<C>(comment: C) -> Self
203    where
204        C: Into<String>,
205    {
206        Self {
207            id: None,
208            event: None,
209            data: String::new(),
210            retry: None,
211            comment: Some(comment.into()),
212        }
213    }
214
215    /// Attaches an `id:` field to this event.
216    ///
217    /// # Arguments
218    ///
219    /// - `I` - Identifier text convertible into `String`.
220    ///
221    /// # Returns
222    ///
223    /// - `Self` - Updated event.
224    pub fn with_id<I>(mut self, id: I) -> Self
225    where
226        I: Into<String>,
227    {
228        self.set_id(Some(id.into()));
229        self
230    }
231
232    /// Attaches an `event:` type field to this event.
233    ///
234    /// # Arguments
235    ///
236    /// - `E` - Event type convertible into `String`.
237    ///
238    /// # Returns
239    ///
240    /// - `Self` - Updated event.
241    pub fn with_event<E>(mut self, event: E) -> Self
242    where
243        E: Into<String>,
244    {
245        self.set_event(Some(event.into()));
246        self
247    }
248
249    /// Attaches a `retry:` millisecond reconnection hint to this event.
250    ///
251    /// # Arguments
252    ///
253    /// - `u64` - Reconnect delay in milliseconds.
254    ///
255    /// # Returns
256    ///
257    /// - `Self` - Updated event.
258    pub fn with_retry(mut self, retry_ms: u64) -> Self {
259        self.set_retry(Some(retry_ms));
260        self
261    }
262
263    /// Encodes this event directly into `out` using SWAR line-break scanning with zero intermediate allocations.
264    ///
265    /// # Arguments
266    ///
267    /// - `&mut Vec<u8>` - Reusable wire buffer (cleared before writing).
268    #[inline]
269    pub fn encode_into(&self, out: &mut Vec<u8>) {
270        let Self {
271            id,
272            event,
273            data,
274            retry,
275            comment,
276        } = self;
277        out.clear();
278        let est: usize = data.len()
279            + id.as_ref().map_or(0, |s: &String| s.len() + 6)
280            + event.as_ref().map_or(0, |s: &String| s.len() + 8)
281            + comment.as_ref().map_or(0, |s: &String| s.len() + 4)
282            + if retry.is_some() { 28 } else { 0 }
283            + 16;
284        out.reserve(est);
285        if let Some(comment_text) = comment.as_deref() {
286            out.extend_from_slice(SSE_COMMENT_PREFIX.as_bytes());
287            write_sanitized_sse_bytes(comment_text, out);
288            out.push(BYTE_LF);
289        }
290        if let Some(id_text) = id.as_deref() {
291            out.extend_from_slice(SSE_FIELD_ID.as_bytes());
292            write_sanitized_sse_bytes(id_text, out);
293            out.push(BYTE_LF);
294        }
295        if let Some(event_text) = event.as_deref() {
296            out.extend_from_slice(SSE_FIELD_EVENT.as_bytes());
297            write_sanitized_sse_bytes(event_text, out);
298            out.push(BYTE_LF);
299        }
300        if let Some(retry_ms) = *retry {
301            out.extend_from_slice(SSE_FIELD_RETRY.as_bytes());
302            write_u64_decimal(retry_ms, out);
303            out.push(BYTE_LF);
304        }
305        let has_data: bool = !data.is_empty() || comment.is_none();
306        if has_data {
307            let mut rest: &[u8] = data.as_bytes();
308            let data_prefix: &[u8] = SSE_FIELD_DATA.as_bytes();
309            loop {
310                match find_line_break(rest) {
311                    None => {
312                        out.extend_from_slice(data_prefix);
313                        out.extend_from_slice(rest);
314                        out.push(BYTE_LF);
315                        break;
316                    }
317                    Some(pos) => {
318                        out.extend_from_slice(data_prefix);
319                        out.extend_from_slice(&rest[..pos]);
320                        out.push(BYTE_LF);
321                        let advance: usize = if rest[pos] == BYTE_CR
322                            && pos + 1 < rest.len()
323                            && rest[pos + 1] == BYTE_LF
324                        {
325                            pos + 2
326                        } else {
327                            pos + 1
328                        };
329                        rest = &rest[advance..];
330                    }
331                }
332            }
333        }
334        out.push(BYTE_LF);
335    }
336
337    /// Encodes this event directly into fixed stack buffer `buf` with zero heap allocations.
338    ///
339    /// # Arguments
340    ///
341    /// - `&mut [u8; SSE_EVENT_STACK_CAP]` - Stack wire output buffer.
342    ///
343    /// # Returns
344    ///
345    /// - `Option<usize>` - Total wire bytes written when the frame fits in `buf`.
346    #[inline]
347    pub(crate) fn encode_into_stack(&self, buf: &mut [u8; SSE_EVENT_STACK_CAP]) -> Option<usize> {
348        let Self {
349            id,
350            event,
351            data,
352            retry,
353            comment,
354        } = self;
355        let mut pos: usize = 0;
356        if let Some(comment_text) = comment.as_deref() {
357            let pfx: &[u8] = SSE_COMMENT_PREFIX.as_bytes();
358            if pos + pfx.len() >= SSE_EVENT_STACK_CAP {
359                return None;
360            }
361            buf[pos..pos + pfx.len()].copy_from_slice(pfx);
362            pos = write_sanitized_sse_slice(comment_text, buf, pos + pfx.len())?;
363            if pos >= SSE_EVENT_STACK_CAP {
364                return None;
365            }
366            buf[pos] = BYTE_LF;
367            pos += 1;
368        }
369        if let Some(id_text) = id.as_deref() {
370            let pfx: &[u8] = SSE_FIELD_ID.as_bytes();
371            if pos + pfx.len() >= SSE_EVENT_STACK_CAP {
372                return None;
373            }
374            buf[pos..pos + pfx.len()].copy_from_slice(pfx);
375            pos = write_sanitized_sse_slice(id_text, buf, pos + pfx.len())?;
376            if pos >= SSE_EVENT_STACK_CAP {
377                return None;
378            }
379            buf[pos] = BYTE_LF;
380            pos += 1;
381        }
382        if let Some(event_text) = event.as_deref() {
383            let pfx: &[u8] = SSE_FIELD_EVENT.as_bytes();
384            if pos + pfx.len() >= SSE_EVENT_STACK_CAP {
385                return None;
386            }
387            buf[pos..pos + pfx.len()].copy_from_slice(pfx);
388            pos = write_sanitized_sse_slice(event_text, buf, pos + pfx.len())?;
389            if pos >= SSE_EVENT_STACK_CAP {
390                return None;
391            }
392            buf[pos] = BYTE_LF;
393            pos += 1;
394        }
395        if let Some(retry_ms) = *retry {
396            let pfx: &[u8] = SSE_FIELD_RETRY.as_bytes();
397            if pos + pfx.len() >= SSE_EVENT_STACK_CAP {
398                return None;
399            }
400            buf[pos..pos + pfx.len()].copy_from_slice(pfx);
401            pos = write_u64_decimal_slice(retry_ms, buf, pos + pfx.len())?;
402            if pos >= SSE_EVENT_STACK_CAP {
403                return None;
404            }
405            buf[pos] = BYTE_LF;
406            pos += 1;
407        }
408        let has_data: bool = !data.is_empty() || comment.is_none();
409        if has_data {
410            let mut rest: &[u8] = data.as_bytes();
411            let pfx: &[u8] = SSE_FIELD_DATA.as_bytes();
412            loop {
413                match find_line_break(rest) {
414                    None => {
415                        let next: usize = pos + pfx.len() + rest.len() + 1;
416                        if next >= SSE_EVENT_STACK_CAP {
417                            return None;
418                        }
419                        buf[pos..pos + pfx.len()].copy_from_slice(pfx);
420                        let d_start: usize = pos + pfx.len();
421                        buf[d_start..d_start + rest.len()].copy_from_slice(rest);
422                        buf[next - 1] = BYTE_LF;
423                        pos = next;
424                        break;
425                    }
426                    Some(lb) => {
427                        let next: usize = pos + pfx.len() + lb + 1;
428                        if next >= SSE_EVENT_STACK_CAP {
429                            return None;
430                        }
431                        buf[pos..pos + pfx.len()].copy_from_slice(pfx);
432                        let d_start: usize = pos + pfx.len();
433                        buf[d_start..d_start + lb].copy_from_slice(&rest[..lb]);
434                        buf[next - 1] = BYTE_LF;
435                        pos = next;
436                        let advance: usize = if rest[lb] == BYTE_CR
437                            && lb + 1 < rest.len()
438                            && rest[lb + 1] == BYTE_LF
439                        {
440                            lb + 2
441                        } else {
442                            lb + 1
443                        };
444                        rest = &rest[advance..];
445                    }
446                }
447            }
448        }
449        if pos >= SSE_EVENT_STACK_CAP {
450            return None;
451        }
452        buf[pos] = BYTE_LF;
453        Some(pos + 1)
454    }
455
456    /// Encodes this event into WHATWG EventSource wire bytes with CRLF injection sanitization.
457    ///
458    /// # Returns
459    ///
460    /// - `Vec<u8>` - Complete SSE frame terminated by `\n\n`.
461    pub fn encode(&self) -> Vec<u8> {
462        let mut out: Vec<u8> = Vec::with_capacity(self.get_data().len() + 64);
463        self.encode_into(&mut out);
464        out
465    }
466}
467
468/// Inherent implementation of [`SharedSseEvent`].
469impl SharedSseEvent {
470    /// Wraps `event` for zero-copy fan-out across replay rings and broadcast subscribers.
471    ///
472    /// # Arguments
473    ///
474    /// - `SseEvent` - Owned event payload.
475    ///
476    /// # Returns
477    ///
478    /// - `Self` - Shared event wrapper.
479    #[inline]
480    pub(crate) fn new(event: SseEvent) -> Self {
481        Self {
482            event,
483            encoded: OnceLock::new(),
484        }
485    }
486
487    /// Returns lazily cached WHATWG wire bytes shared across all subscribers of this event.
488    ///
489    /// # Returns
490    ///
491    /// - `&[u8]` - Pre-encoded wire bytes.
492    #[inline]
493    pub(crate) fn encoded_bytes(&self) -> &[u8] {
494        let Self { event, encoded } = self;
495        encoded
496            .get_or_init(|| event.encode().into_boxed_slice())
497            .as_ref()
498    }
499}
500
501/// Recycles the borrowed coalesce buffer back to the worker pool on drop.
502impl Drop for SseScratchBuf {
503    /// Returns the owned scratch buffer to the thread-local pool.
504    fn drop(&mut self) {
505        let Self { buf } = self;
506        return_sse_coalesce_buf(take(buf));
507    }
508}
509
510/// Inherent implementation of [`SseTopicRing`].
511impl SseTopicRing {
512    /// Creates an empty, zero-allocation live broadcast ring capped at `capacity`.
513    ///
514    /// # Arguments
515    ///
516    /// - `usize` - Maximum unread entries retained before evicting oldest messages.
517    ///
518    /// # Returns
519    ///
520    /// - `Self` - Empty topic ring holding zero heap bytes while idle.
521    #[inline]
522    pub(crate) fn new(capacity: usize) -> Self {
523        Self {
524            entries: VecDeque::new(),
525            head_seq: 0,
526            next_seq: 0,
527            subscribers: 0,
528            capacity: capacity.max(1),
529            closed: false,
530        }
531    }
532
533    /// Reclaims any front entries already read by all subscribers and frees empty backing storage.
534    #[inline]
535    fn reclaim_consumed_front(&mut self) {
536        let Self {
537            entries,
538            head_seq,
539            next_seq,
540            ..
541        } = self;
542        while entries
543            .front()
544            .is_some_and(|entry: &SseRingEntry| entry.unread == 0)
545        {
546            let _: Option<SseRingEntry> = entries.pop_front();
547        }
548        *head_seq = entries
549            .front()
550            .map_or(*next_seq, |entry: &SseRingEntry| entry.seq);
551        if entries.is_empty() && entries.capacity() > 0 {
552            *entries = VecDeque::new();
553        }
554    }
555
556    /// Registers a new live subscriber positioned at the current ring tail.
557    ///
558    /// # Returns
559    ///
560    /// - `u64` - Initial delivery cursor for future published events.
561    #[inline]
562    pub(crate) fn subscribe(&mut self) -> u64 {
563        let Self {
564            subscribers,
565            next_seq,
566            ..
567        } = self;
568        *subscribers += 1;
569        *next_seq
570    }
571
572    /// Appends one shared event when active subscribers exist and the topic is open.
573    ///
574    /// # Arguments
575    ///
576    /// - `Arc<SharedSseEvent>` - Event to fan out zero-copy to active subscribers.
577    ///
578    /// # Returns
579    ///
580    /// - `bool` - `true` when enqueued and waiting subscribers should be notified.
581    #[inline]
582    pub(crate) fn push(&mut self, event: Arc<SharedSseEvent>) -> bool {
583        let Self {
584            entries,
585            head_seq,
586            next_seq,
587            subscribers,
588            capacity,
589            closed,
590        } = self;
591        if *subscribers == 0 || *closed {
592            return false;
593        }
594        if entries.len() >= *capacity {
595            let _: Option<SseRingEntry> = entries.pop_front();
596            *head_seq = entries
597                .front()
598                .map_or(*next_seq, |entry: &SseRingEntry| entry.seq);
599        }
600        let seq: u64 = *next_seq;
601        if entries.is_empty() {
602            *head_seq = seq;
603        }
604        entries.push_back(SseRingEntry {
605            seq,
606            event,
607            unread: *subscribers,
608        });
609        *next_seq = seq + 1;
610        true
611    }
612
613    /// Pops the next event for `cursor`, reporting lag or topic closure when applicable.
614    ///
615    /// # Arguments
616    ///
617    /// - `&mut u64` - Subscriber delivery cursor advanced on read or lag recovery.
618    ///
619    /// # Returns
620    ///
621    /// - `Option<Result<Arc<SharedSseEvent>, SseError>>` - Ready event/error, or `None` when caught up.
622    #[inline]
623    pub(crate) fn try_pop(
624        &mut self,
625        cursor: &mut u64,
626    ) -> Option<Result<Arc<SharedSseEvent>, SseError>> {
627        let Self {
628            entries,
629            head_seq,
630            next_seq,
631            closed,
632            ..
633        } = self;
634        if *cursor < *head_seq {
635            let skipped: u64 = *head_seq - *cursor;
636            *cursor = *head_seq;
637            return Some(Err(SseError::Lagged(skipped)));
638        }
639        if *cursor >= *next_seq {
640            if *closed {
641                return Some(Err(SseError::ChannelClosed));
642            }
643            return None;
644        }
645        let offset: usize = (*cursor - *head_seq) as usize;
646        let event: Arc<SharedSseEvent> = Arc::clone(&entries[offset].event);
647        entries[offset].unread = entries[offset].unread.saturating_sub(1);
648        *cursor += 1;
649        if offset == 0 && entries[0].unread == 0 {
650            self.reclaim_consumed_front();
651        }
652        Some(Ok(event))
653    }
654
655    /// Unregisters a disconnecting subscriber and releases unread references it will never consume.
656    ///
657    /// # Arguments
658    ///
659    /// - `u64` - Subscriber's last unconsumed delivery cursor.
660    #[inline]
661    pub(crate) fn unsubscribe(&mut self, cursor: u64) {
662        let Self {
663            entries,
664            head_seq,
665            next_seq,
666            subscribers,
667            ..
668        } = self;
669        *subscribers = subscribers.saturating_sub(1);
670        let start_seq: u64 = cursor.max(*head_seq);
671        if start_seq < *next_seq {
672            let start_idx: usize = (start_seq - *head_seq) as usize;
673            for entry in entries.iter_mut().skip(start_idx) {
674                entry.unread = entry.unread.saturating_sub(1);
675            }
676            self.reclaim_consumed_front();
677        }
678    }
679
680    /// Marks the ring closed so idle subscribers wake and observe [`SseError::ChannelClosed`].
681    #[inline]
682    pub(crate) fn close(&mut self) {
683        let Self { closed, .. } = self;
684        *closed = true;
685    }
686}
687
688/// Inherent implementation of [`SseHeartbeatWheel`].
689impl SseHeartbeatWheel {
690    /// Creates a new staggered heartbeat wheel with `bucket_count` independent watch channels.
691    ///
692    /// # Arguments
693    ///
694    /// - `usize` - Number of phase buckets (`1` or [`SSE_HEARTBEAT_BUCKETS`]).
695    ///
696    /// # Returns
697    ///
698    /// - `Self` - Initialized active heartbeat wheel.
699    pub(crate) fn new(bucket_count: usize) -> Self {
700        let mut buckets: Vec<Sender<u64>> = Vec::with_capacity(bucket_count);
701        for _ in 0..bucket_count {
702            let (tx, _): (Sender<u64>, Receiver<u64>) = watch::channel(0u64);
703            buckets.push(tx);
704        }
705        Self {
706            buckets: buckets.into_boxed_slice(),
707            phase: AtomicUsize::new(0),
708            alive: AtomicBool::new(true),
709        }
710    }
711
712    /// Subscribes to the bucket farthest from the next tick so the first heartbeat waits ~1 full period.
713    ///
714    /// # Returns
715    ///
716    /// - `Receiver<u64>` - Watch receiver positioned on the most recently ticked phase bucket.
717    #[inline]
718    pub(crate) fn subscribe_staggered(&self) -> Receiver<u64> {
719        let Self { buckets, phase, .. } = self;
720        let len: usize = buckets.len();
721        let cur: usize = phase.load(Ordering::Acquire);
722        let bucket_idx: usize = (cur.wrapping_add(len - 1)) % len;
723        let mut rx: Receiver<u64> = buckets[bucket_idx].subscribe();
724        let _: u64 = *rx.borrow_and_update();
725        rx
726    }
727
728    /// Counts active heartbeat receivers across all buckets.
729    ///
730    /// # Returns
731    ///
732    /// - `usize` - Sum of live receivers across all wheel buckets.
733    #[inline]
734    pub(crate) fn total_receivers(&self) -> usize {
735        let Self { buckets, .. } = self;
736        let mut total: usize = 0;
737        for bucket in buckets.iter() {
738            total += bucket.receiver_count();
739        }
740        total
741    }
742}
743
744/// Inherent implementation of [`SseHubInner`].
745impl SseHubInner {
746    /// Subscribes to a runtime-scoped shared staggered heartbeat bucket for `heartbeat_ms`.
747    ///
748    /// # Arguments
749    ///
750    /// - `&Arc<Self>` - Shared hub interior state.
751    /// - `u64` - Desired heartbeat interval in milliseconds.
752    ///
753    /// # Returns
754    ///
755    /// - `Receiver<u64>` - Watch receiver firing once every `heartbeat_ms` without per-connection timers.
756    pub(crate) fn subscribe_heartbeat(self: &Arc<Self>, heartbeat_ms: u64) -> Receiver<u64> {
757        let Self { heartbeats, .. } = self.as_ref();
758        let key: (Id, u64) = (Handle::current().id(), heartbeat_ms);
759        let Ok(mut map) = heartbeats.lock() else {
760            let (tx, rx): (Sender<u64>, Receiver<u64>) = watch::channel(0u64);
761            drop(tx);
762            return rx;
763        };
764        if let Some(existing) = map.get(&key)
765            && existing.alive.load(Ordering::Acquire)
766        {
767            return existing.subscribe_staggered();
768        }
769        let bucket_count: usize = if heartbeat_ms >= SSE_HEARTBEAT_MULTI_BUCKET_MIN_MS {
770            SSE_HEARTBEAT_BUCKETS
771        } else {
772            1
773        };
774        let wheel: Arc<SseHeartbeatWheel> = Arc::new(SseHeartbeatWheel::new(bucket_count));
775        let rx: Receiver<u64> = wheel.subscribe_staggered();
776        let _: Option<Arc<SseHeartbeatWheel>> = map.insert(key, Arc::clone(&wheel));
777        let step_micros: u64 = heartbeat_ms
778            .saturating_mul(SSE_MICROS_PER_MS)
779            .checked_div(bucket_count as u64)
780            .unwrap_or(SSE_HEARTBEAT_MIN_STEP_MICROS)
781            .max(SSE_HEARTBEAT_MIN_STEP_MICROS);
782        let step: Duration = Duration::from_micros(step_micros);
783        let hub_weak: Weak<SseHubInner> = Arc::downgrade(self);
784        let _: JoinHandle<()> = spawn(drive_sse_heartbeat_wheel(hub_weak, key, wheel, step));
785        rx
786    }
787}
788
789/// Inherent implementation of [`SseHub`].
790impl SseHub {
791    /// Creates a new 64-shard [`SseHub`] governed by `config`.
792    ///
793    /// # Arguments
794    ///
795    /// - `SseConfig` - Hub capacity and replay configuration.
796    ///
797    /// # Returns
798    ///
799    /// - `Self` - Ready multi-topic SSE hub.
800    pub fn new(config: SseConfig) -> Self {
801        let shards: Box<[SseShard; SSE_SHARD_COUNT]> = Box::new(from_fn(|_: usize| SseShard {
802            map: RwLock::new(HashMap::default()),
803        }));
804        Self {
805            inner: Arc::new(SseHubInner {
806                config,
807                next_seq: AtomicU64::new(1),
808                active_topics: AtomicUsize::new(0),
809                shards,
810                heartbeats: Mutex::new(HashMap::new()),
811            }),
812        }
813    }
814
815    /// Returns a reference to the hub configuration.
816    ///
817    /// # Returns
818    ///
819    /// - `&SseConfig` - Active hub configuration.
820    pub fn get_config(&self) -> &SseConfig {
821        let Self { inner } = self;
822        &inner.config
823    }
824
825    /// Looks up or inserts the shared topic key and [`TopicState`] using read-fast sharding.
826    ///
827    /// # Arguments
828    ///
829    /// - `&str` - Topic name.
830    ///
831    /// # Returns
832    ///
833    /// - `Result<(Arc<str>, Arc<TopicState>), SseError>` - Shared topic key and state, or [`SseError::TopicLimitReached`].
834    #[inline]
835    fn get_or_create_topic(
836        &self,
837        topic_name: &str,
838    ) -> Result<(Arc<str>, Arc<TopicState>), SseError> {
839        let Self { inner } = self;
840        let shard_idx: usize = sse_shard_index(topic_name);
841        let shard: &RwLock<SseShardMap> = &inner.shards[shard_idx].map;
842        if let Ok(read_map) = shard.read()
843            && let Some((existing_key, existing_state)) = read_map.get_key_value(topic_name)
844        {
845            return Ok((Arc::clone(existing_key), Arc::clone(existing_state)));
846        }
847        let Ok(mut write_map) = shard.write() else {
848            return Err(SseError::ChannelClosed);
849        };
850        if let Some((existing_key, existing_state)) = write_map.get_key_value(topic_name) {
851            return Ok((Arc::clone(existing_key), Arc::clone(existing_state)));
852        }
853        let max_topics: usize = inner.config.get_max_topics();
854        let mut current: usize = inner.active_topics.load(Ordering::Acquire);
855        loop {
856            if current >= max_topics {
857                return Err(SseError::TopicLimitReached);
858            }
859            match inner.active_topics.compare_exchange_weak(
860                current,
861                current + 1,
862                Ordering::AcqRel,
863                Ordering::Acquire,
864            ) {
865                Ok(_) => break,
866                Err(actual) => current = actual,
867            }
868        }
869        let chan_cap: usize = inner.config.get_channel_capacity().max(1);
870        let state: Arc<TopicState> = Arc::new(TopicState {
871            subscribers: AtomicUsize::new(0),
872            notify: Notify::new(),
873            ring: Mutex::new(SseTopicRing::new(chan_cap)),
874            replay: Mutex::new(VecDeque::new()),
875        });
876        let topic_key: Arc<str> = Arc::from(topic_name);
877        let _: Option<Arc<TopicState>> =
878            write_map.insert(Arc::clone(&topic_key), Arc::clone(&state));
879        Ok((topic_key, state))
880    }
881
882    /// Publishes an event to `topic`, assigning a monotonic id if absent and appending to replay history.
883    ///
884    /// # Arguments
885    ///
886    /// - `T` - Topic name convertible into `String`.
887    /// - `SseEvent` - Event to fan out to active subscribers.
888    ///
889    /// # Returns
890    ///
891    /// - `Result<u64, SseError>` - Assigned sequence identifier, or [`SseError::TopicLimitReached`].
892    pub fn publish<T>(&self, topic: T, mut event: SseEvent) -> Result<u64, SseError>
893    where
894        T: Into<String>,
895    {
896        let Self { inner } = self;
897        let topic_name: String = topic.into();
898        let (_, state): (Arc<str>, Arc<TopicState>) = self.get_or_create_topic(&topic_name)?;
899        let seq: u64 = inner.next_seq.fetch_add(1, Ordering::Relaxed);
900        let replay_cap: usize = inner.config.get_replay_capacity();
901        let has_subs: bool = state.subscribers.load(Ordering::Acquire) > 0;
902        if replay_cap == 0 && !has_subs {
903            return Ok(seq);
904        }
905        let SseEvent { id, .. } = &mut event;
906        if id.is_none() {
907            *id = Some(format_u64_string(seq));
908        }
909        let shared: Arc<SharedSseEvent> = Arc::new(SharedSseEvent::new(event));
910        if replay_cap > 0 {
911            if has_subs {
912                if let Ok(mut replay) = state.replay.lock() {
913                    if replay.len() >= replay_cap {
914                        let _: Option<(u64, Arc<SharedSseEvent>)> = replay.pop_front();
915                    }
916                    replay.push_back((seq, Arc::clone(&shared)));
917                }
918                let pushed: bool = state
919                    .ring
920                    .lock()
921                    .is_ok_and(|mut ring: MutexGuard<'_, SseTopicRing>| ring.push(shared));
922                if pushed {
923                    state.notify.notify_waiters();
924                }
925            } else if let Ok(mut replay) = state.replay.lock() {
926                if replay.len() >= replay_cap {
927                    let _: Option<(u64, Arc<SharedSseEvent>)> = replay.pop_front();
928                }
929                replay.push_back((seq, shared));
930            }
931        } else {
932            let pushed: bool = state
933                .ring
934                .lock()
935                .is_ok_and(|mut ring: MutexGuard<'_, SseTopicRing>| ring.push(shared));
936            if pushed {
937                state.notify.notify_waiters();
938            }
939        }
940        Ok(seq)
941    }
942
943    /// Publishes a batch of events to `topic` in order, returning the last assigned sequence id.
944    ///
945    /// # Arguments
946    ///
947    /// - `T` - Topic name convertible into `String`.
948    /// - `I` - Iterator yielding [`SseEvent`] items.
949    ///
950    /// # Returns
951    ///
952    /// - `Result<Option<u64>, SseError>` - Last assigned sequence id, or `None` when empty.
953    pub fn publish_many<T, I>(&self, topic: T, events: I) -> Result<Option<u64>, SseError>
954    where
955        T: Into<String>,
956        I: IntoIterator<Item = SseEvent>,
957    {
958        let Self { inner } = self;
959        let mut iter: I::IntoIter = events.into_iter();
960        let (lower, upper): (usize, Option<usize>) = iter.size_hint();
961        let Some(first_event) = iter.next() else {
962            return Ok(None);
963        };
964        let topic_name: String = topic.into();
965        let (_, state): (Arc<str>, Arc<TopicState>) = self.get_or_create_topic(&topic_name)?;
966        let replay_cap: usize = inner.config.get_replay_capacity();
967        let has_subs: bool = state.subscribers.load(Ordering::Acquire) > 0;
968        let exact_batch_base: Option<u64> = if upper == Some(lower) && lower > 0 {
969            Some(inner.next_seq.fetch_add(lower as u64, Ordering::Relaxed))
970        } else {
971            None
972        };
973        let mut replay_guard: Option<MutexGuard<'_, SseReplayQueue>> = if replay_cap > 0 {
974            state.replay.lock().ok()
975        } else {
976            None
977        };
978        let mut ring_guard: Option<MutexGuard<'_, SseTopicRing>> = if has_subs {
979            state.ring.lock().ok()
980        } else {
981            None
982        };
983        let mut pushed_any: bool = false;
984        let mut idx: u64 = 0;
985        let mut last_seq: u64 = 0;
986        let mut current: Option<SseEvent> = Some(first_event);
987        while let Some(mut event) = current {
988            let seq: u64 = match exact_batch_base {
989                Some(base) => base + idx,
990                None => inner.next_seq.fetch_add(1, Ordering::Relaxed),
991            };
992            idx += 1;
993            last_seq = seq;
994            if replay_cap > 0 || has_subs {
995                let SseEvent { id, .. } = &mut event;
996                if id.is_none() {
997                    *id = Some(format_u64_string(seq));
998                }
999                let shared: Arc<SharedSseEvent> = Arc::new(SharedSseEvent::new(event));
1000                if let Some(ring) = ring_guard.as_mut() {
1001                    if let Some(replay) = replay_guard.as_mut() {
1002                        if replay.len() >= replay_cap {
1003                            let _: Option<(u64, Arc<SharedSseEvent>)> = replay.pop_front();
1004                        }
1005                        replay.push_back((seq, Arc::clone(&shared)));
1006                    }
1007                    if ring.push(shared) {
1008                        pushed_any = true;
1009                    }
1010                } else if let Some(replay) = replay_guard.as_mut() {
1011                    if replay.len() >= replay_cap {
1012                        let _: Option<(u64, Arc<SharedSseEvent>)> = replay.pop_front();
1013                    }
1014                    replay.push_back((seq, shared));
1015                }
1016            }
1017            current = iter.next();
1018        }
1019        drop(ring_guard);
1020        drop(replay_guard);
1021        if pushed_any {
1022            state.notify.notify_waiters();
1023        }
1024        Ok(Some(last_seq))
1025    }
1026
1027    /// Subscribes to `topic`, replaying retained events newer than `last_event_id` via binary search.
1028    ///
1029    /// # Arguments
1030    ///
1031    /// - `T` - Topic name convertible into `String`.
1032    /// - `Option<&str>` - Optional `Last-Event-ID` header value for catch-up replay.
1033    ///
1034    /// # Returns
1035    ///
1036    /// - `Result<SseSubscription, SseError>` - Active subscription or [`SseError::TopicLimitReached`].
1037    pub fn subscribe<T>(
1038        &self,
1039        topic: T,
1040        last_event_id: Option<&str>,
1041    ) -> Result<SseSubscription, SseError>
1042    where
1043        T: Into<String>,
1044    {
1045        let Self { inner } = self;
1046        let topic_name: String = topic.into();
1047        let after_seq: Option<u64> = parse_last_event_id(last_event_id);
1048        let (topic_key, state): (Arc<str>, Arc<TopicState>) =
1049            self.get_or_create_topic(&topic_name)?;
1050        let cursor: u64 = match state.ring.lock() {
1051            Ok(mut ring) => ring.subscribe(),
1052            Err(_) => return Err(SseError::ChannelClosed),
1053        };
1054        state.subscribers.fetch_add(1, Ordering::Release);
1055        let mut replayed: Option<Box<SseReplayBatch>> = None;
1056        if let Some(last_id) = after_seq
1057            && let Ok(replay) = state.replay.lock()
1058        {
1059            let start_idx: usize =
1060                replay.partition_point(|(seq, _): &(u64, Arc<SharedSseEvent>)| *seq <= last_id);
1061            let count: usize = replay.len().saturating_sub(start_idx);
1062            if count > 0 {
1063                let mut items: Vec<Arc<SharedSseEvent>> = Vec::with_capacity(count);
1064                for (_, ev) in replay.range(start_idx..) {
1065                    items.push(Arc::clone(ev));
1066                }
1067                replayed = Some(Box::new(SseReplayBatch {
1068                    items: items.into_boxed_slice(),
1069                    next: 0,
1070                }));
1071            }
1072        }
1073        Ok(SseSubscription {
1074            topic: topic_key,
1075            state,
1076            hub: Arc::clone(inner),
1077            replayed,
1078            cursor,
1079        })
1080    }
1081
1082    /// Explicitly removes `topic` from the hub registry.
1083    ///
1084    /// # Arguments
1085    ///
1086    /// - `&str` - Topic name to evict.
1087    ///
1088    /// # Returns
1089    ///
1090    /// - `bool` - `true` if the topic existed and was removed.
1091    pub fn remove_topic(&self, topic: &str) -> bool {
1092        let Self { inner } = self;
1093        let shard_idx: usize = sse_shard_index(topic);
1094        let removed: Option<Arc<TopicState>> =
1095            inner.shards[shard_idx].map.write().ok().and_then(
1096                |mut write_map: RwLockWriteGuard<'_, SseShardMap>| write_map.remove(topic),
1097            );
1098        if let Some(state) = removed {
1099            inner.active_topics.fetch_sub(1, Ordering::AcqRel);
1100            if let Ok(mut ring) = state.ring.lock() {
1101                ring.close();
1102            }
1103            state.notify.notify_waiters();
1104            return true;
1105        }
1106        false
1107    }
1108
1109    /// Returns all currently active topic names across all shards.
1110    ///
1111    /// # Returns
1112    ///
1113    /// - `Vec<String>` - Snapshot of active topic names.
1114    pub fn topic_names(&self) -> Vec<String> {
1115        let Self { inner } = self;
1116        let mut names: Vec<String> = Vec::with_capacity(self.topic_count());
1117        for shard in inner.shards.iter() {
1118            if let Ok(read_map) = shard.map.read() {
1119                names.extend(
1120                    read_map
1121                        .keys()
1122                        .map(|key: &Arc<str>| key.as_ref().to_owned()),
1123                );
1124            }
1125        }
1126        names
1127    }
1128
1129    /// Returns the number of active topics currently tracked by this hub in `O(1)`.
1130    ///
1131    /// # Returns
1132    ///
1133    /// - `usize` - Count of tracked topics.
1134    pub fn topic_count(&self) -> usize {
1135        let Self { inner } = self;
1136        inner.active_topics.load(Ordering::Acquire)
1137    }
1138
1139    /// Returns the number of active subscribers currently listening to `topic`.
1140    ///
1141    /// # Arguments
1142    ///
1143    /// - `&str` - Topic name to inspect.
1144    ///
1145    /// # Returns
1146    ///
1147    /// - `usize` - Active subscriber count (`0` when topic does not exist).
1148    pub fn subscriber_count(&self, topic: &str) -> usize {
1149        let Self { inner } = self;
1150        let shard_idx: usize = sse_shard_index(topic);
1151        inner.shards[shard_idx]
1152            .map
1153            .read()
1154            .ok()
1155            .and_then(|map: RwLockReadGuard<'_, SseShardMap>| {
1156                map.get(topic)
1157                    .map(|state: &Arc<TopicState>| state.subscribers.load(Ordering::Acquire))
1158            })
1159            .unwrap_or(0)
1160    }
1161}
1162
1163/// Default construction for [`SseHub`].
1164impl Default for SseHub {
1165    /// Constructs a default [`SseHub`] value.
1166    fn default() -> Self {
1167        Self::new(SseConfig::default())
1168    }
1169}
1170
1171/// Inherent implementation of [`SseSubscription`].
1172impl SseSubscription {
1173    /// Returns the topic name associated with this subscription.
1174    ///
1175    /// # Returns
1176    ///
1177    /// - `&str` - Subscribed topic name.
1178    pub fn topic(&self) -> &str {
1179        let Self { topic, .. } = self;
1180        topic
1181    }
1182
1183    /// Pops one buffered `Last-Event-ID` replay event and frees the replay batch once drained.
1184    ///
1185    /// # Returns
1186    ///
1187    /// - `Option<Arc<SharedSseEvent>>` - Next buffered replay event, or `None`.
1188    #[inline]
1189    fn pop_replayed(&mut self) -> Option<Arc<SharedSseEvent>> {
1190        let Self { replayed, .. } = self;
1191        let batch: &mut SseReplayBatch = replayed.as_deref_mut()?;
1192        let item: Arc<SharedSseEvent> = Arc::clone(&batch.items[batch.next]);
1193        batch.next += 1;
1194        if batch.next >= batch.items.len() {
1195            *replayed = None;
1196        }
1197        Some(item)
1198    }
1199
1200    /// Receives the next shared event handle without cloning the underlying `SseEvent`.
1201    ///
1202    /// # Returns
1203    ///
1204    /// - `Result<Arc<SharedSseEvent>, SseError>` - Next shared SSE event or channel error.
1205    pub(crate) async fn recv_shared(&mut self) -> Result<Arc<SharedSseEvent>, SseError> {
1206        if let Some(shared) = self.pop_replayed() {
1207            return Ok(shared);
1208        }
1209        let Self { state, cursor, .. } = self;
1210        loop {
1211            if let Some(res) = match state.ring.lock() {
1212                Ok(mut ring) => ring.try_pop(cursor),
1213                Err(_) => Some(Err(SseError::ChannelClosed)),
1214            } {
1215                return res;
1216            }
1217            let notified: Notified<'_> = state.notify.notified();
1218            let mut pinned: Pin<&mut Notified<'_>> = pin!(notified);
1219            pinned.as_mut().enable();
1220            if let Some(res) = match state.ring.lock() {
1221                Ok(mut ring) => ring.try_pop(cursor),
1222                Err(_) => Some(Err(SseError::ChannelClosed)),
1223            } {
1224                return res;
1225            }
1226            pinned.await;
1227        }
1228    }
1229
1230    /// Attempts to receive one live event from the topic ring without awaiting.
1231    ///
1232    /// # Returns
1233    ///
1234    /// - `Option<Result<Arc<SharedSseEvent>, SseError>>` - Ready event/error, or `None` if idle.
1235    #[inline]
1236    fn try_recv_live(&mut self) -> Option<Result<Arc<SharedSseEvent>, SseError>> {
1237        let Self { state, cursor, .. } = self;
1238        match state.ring.lock() {
1239            Ok(mut ring) => ring.try_pop(cursor),
1240            Err(_) => Some(Err(SseError::ChannelClosed)),
1241        }
1242    }
1243
1244    /// Attempts to receive an already-queued shared event without awaiting for wire batch coalescing.
1245    ///
1246    /// # Returns
1247    ///
1248    /// - `Option<Result<Arc<SharedSseEvent>, SseError>>` - Ready event/error, or `None` if empty.
1249    #[inline]
1250    pub(crate) fn try_recv_shared(&mut self) -> Option<Result<Arc<SharedSseEvent>, SseError>> {
1251        if let Some(shared) = self.pop_replayed() {
1252            return Some(Ok(shared));
1253        }
1254        self.try_recv_live()
1255    }
1256
1257    /// Drains additional already-queued events into `out` under a single ring lock up to `max_bytes`.
1258    ///
1259    /// # Arguments
1260    ///
1261    /// - `&mut Vec<u8>` - Destination wire coalesce buffer.
1262    /// - `usize` - Maximum total bytes to accumulate in `out`.
1263    ///
1264    /// # Returns
1265    ///
1266    /// - `Result<bool, SseError>` - `Ok(true)` if the topic closed after draining, `Ok(false)` otherwise.
1267    #[inline]
1268    pub(crate) fn drain_queued_into(
1269        &mut self,
1270        out: &mut Vec<u8>,
1271        max_bytes: usize,
1272    ) -> Result<bool, SseError> {
1273        while out.len() < max_bytes {
1274            let Some(ev) = self.pop_replayed() else {
1275                break;
1276            };
1277            out.extend_from_slice(ev.encoded_bytes());
1278        }
1279        if out.len() >= max_bytes {
1280            return Ok(false);
1281        }
1282        let Self { state, cursor, .. } = self;
1283        let Ok(mut ring) = state.ring.lock() else {
1284            return Ok(true);
1285        };
1286        while out.len() < max_bytes {
1287            match ring.try_pop(cursor) {
1288                Some(Ok(ev)) => out.extend_from_slice(ev.encoded_bytes()),
1289                Some(Err(SseError::Lagged(_))) => continue,
1290                Some(Err(SseError::ChannelClosed)) => return Ok(true),
1291                Some(Err(err)) => return Err(err),
1292                None => break,
1293            }
1294        }
1295        Ok(false)
1296    }
1297
1298    /// Receives the next event (draining `Last-Event-ID` replay entries before live broadcasts).
1299    ///
1300    /// # Returns
1301    ///
1302    /// - `Result<SseEvent, SseError>` - Next SSE event or channel error.
1303    pub async fn recv(&mut self) -> Result<SseEvent, SseError> {
1304        let shared: Arc<SharedSseEvent> = self.recv_shared().await?;
1305        Ok(shared.event.clone())
1306    }
1307}
1308
1309/// Implements [`Drop`] for [`SseSubscription`].
1310impl Drop for SseSubscription {
1311    /// Releases unread ring slots and evicts empty ephemeral topics when the last subscriber disconnects.
1312    fn drop(&mut self) {
1313        let Self {
1314            hub,
1315            topic,
1316            state,
1317            cursor,
1318            ..
1319        } = self;
1320        if let Ok(mut ring) = state.ring.lock() {
1321            ring.unsubscribe(*cursor);
1322        }
1323        if state.subscribers.fetch_sub(1, Ordering::AcqRel) > 1 {
1324            return;
1325        }
1326        if state
1327            .replay
1328            .lock()
1329            .is_ok_and(|replay: MutexGuard<'_, SseReplayQueue>| !replay.is_empty())
1330        {
1331            return;
1332        }
1333        let shard_idx: usize = sse_shard_index(topic);
1334        if let Ok(mut write_map) = hub.shards[shard_idx].map.write()
1335            && let Some(current) = write_map.get(topic.as_ref())
1336            && Arc::ptr_eq(current, state)
1337            && current.subscribers.load(Ordering::Acquire) == 0
1338            && current
1339                .replay
1340                .lock()
1341                .is_ok_and(|replay: MutexGuard<'_, SseReplayQueue>| replay.is_empty())
1342        {
1343            let _: Option<Arc<TopicState>> = write_map.remove(topic.as_ref());
1344            hub.active_topics.fetch_sub(1, Ordering::AcqRel);
1345        }
1346    }
1347}
1348
1349/// Inherent implementation of [`SseStream`].
1350impl SseStream {
1351    /// Configures standard SSE response headers on `ctx` without closing the stream.
1352    ///
1353    /// # Arguments
1354    ///
1355    /// - `&mut Context` - Active Hyperlane request context.
1356    pub fn prepare(ctx: &mut Context) {
1357        ctx.get_mut_response()
1358            .set_header(CONTENT_TYPE, SSE_CONTENT_TYPE)
1359            .set_header(CACHE_CONTROL, SSE_CACHE_CONTROL)
1360            .set_header(SSE_ACCEL_BUFFERING_HEADER, SSE_ACCEL_BUFFERING_VALUE);
1361    }
1362
1363    /// Writes one [`SseEvent`] frame directly onto `stream`, using a zero-allocation stack buffer for frames `<= 512` bytes.
1364    ///
1365    /// # Arguments
1366    ///
1367    /// - `&mut Stream` - Active Hyperlane client stream.
1368    /// - `&SseEvent` - Event to encode and flush.
1369    ///
1370    /// # Returns
1371    ///
1372    /// - `Result<(), SseError>` - `Ok(())` on successful write, or [`SseError::Transport`].
1373    #[inline]
1374    pub async fn send_event(stream: &mut Stream, event: &SseEvent) -> Result<(), SseError> {
1375        let mut stack: [u8; SSE_EVENT_STACK_CAP] = [0u8; SSE_EVENT_STACK_CAP];
1376        if let Some(len) = event.encode_into_stack(&mut stack) {
1377            return stream
1378                .try_send(&stack[..len])
1379                .await
1380                .map_err(|err: ResponseError| SseError::Transport(err.to_string()));
1381        }
1382        let bytes: Vec<u8> = event.encode();
1383        stream
1384            .try_send(&bytes)
1385            .await
1386            .map_err(|err: ResponseError| SseError::Transport(err.to_string()))
1387    }
1388
1389    /// Encodes `event` into a reusable `scratch` buffer and writes it onto `stream`.
1390    ///
1391    /// # Arguments
1392    ///
1393    /// - `&mut Stream` - Active Hyperlane client stream.
1394    /// - `&SseEvent` - Event to encode and flush.
1395    /// - `&mut Vec<u8>` - Reusable frame encoding buffer.
1396    ///
1397    /// # Returns
1398    ///
1399    /// - `Result<(), SseError>` - `Ok(())` on successful write, or [`SseError::Transport`].
1400    pub async fn send_event_buffered(
1401        stream: &mut Stream,
1402        event: &SseEvent,
1403        scratch: &mut Vec<u8>,
1404    ) -> Result<(), SseError> {
1405        event.encode_into(scratch);
1406        stream
1407            .try_send(scratch)
1408            .await
1409            .map_err(|err: ResponseError| SseError::Transport(err.to_string()))
1410    }
1411
1412    /// Writes a single SSE comment / heartbeat line directly onto `stream` with zero heap allocations when `<= 252` bytes.
1413    ///
1414    /// # Arguments
1415    ///
1416    /// - `&mut Stream` - Active Hyperlane client stream.
1417    /// - `&str` - Comment text.
1418    ///
1419    /// # Returns
1420    ///
1421    /// - `Result<(), SseError>` - `Ok(())` on successful write, or [`SseError::Transport`].
1422    #[inline]
1423    pub async fn send_comment(stream: &mut Stream, comment: &str) -> Result<(), SseError> {
1424        let pfx: &[u8] = SSE_COMMENT_PREFIX.as_bytes();
1425        if pfx.len() + comment.len() + 2 <= SSE_COMMENT_STACK_CAP {
1426            let mut stack: [u8; SSE_COMMENT_STACK_CAP] = [0u8; SSE_COMMENT_STACK_CAP];
1427            stack[..pfx.len()].copy_from_slice(pfx);
1428            if let Some(pos) = write_sanitized_sse_slice(comment, &mut stack, pfx.len())
1429                && pos + 2 <= SSE_COMMENT_STACK_CAP
1430            {
1431                stack[pos] = BYTE_LF;
1432                stack[pos + 1] = BYTE_LF;
1433                return stream
1434                    .try_send(&stack[..pos + 2])
1435                    .await
1436                    .map_err(|err: ResponseError| SseError::Transport(err.to_string()));
1437            }
1438        }
1439        let mut buf: Vec<u8> = Vec::with_capacity(comment.len() + 4);
1440        buf.extend_from_slice(pfx);
1441        write_sanitized_sse_bytes(comment, &mut buf);
1442        buf.push(BYTE_LF);
1443        buf.push(BYTE_LF);
1444        stream
1445            .try_send(&buf)
1446            .await
1447            .map_err(|err: ResponseError| SseError::Transport(err.to_string()))
1448    }
1449
1450    /// Coalesces two or more ready events into a pooled scratch buffer and writes them in one send.
1451    ///
1452    /// # Arguments
1453    ///
1454    /// - `&mut Stream` - Active Hyperlane client stream.
1455    /// - `&mut SseSubscription` - Active topic subscription.
1456    /// - `Arc<SharedSseEvent>` - First received event.
1457    /// - `Arc<SharedSseEvent>` - Second already-ready event.
1458    ///
1459    /// # Returns
1460    ///
1461    /// - `Result<bool, SseError>` - `Ok(true)` if the channel closed after draining, `Ok(false)` otherwise.
1462    #[cold]
1463    async fn send_coalesced_burst(
1464        stream: &mut Stream,
1465        subscription: &mut SseSubscription,
1466        first: Arc<SharedSseEvent>,
1467        second: Arc<SharedSseEvent>,
1468    ) -> Result<bool, SseError> {
1469        let mut scratch: SseScratchBuf = take_sse_coalesce_buf();
1470        scratch.buf.extend_from_slice(first.encoded_bytes());
1471        drop(first);
1472        scratch.buf.extend_from_slice(second.encoded_bytes());
1473        drop(second);
1474        let closed_after: bool =
1475            subscription.drain_queued_into(&mut scratch.buf, SSE_COALESCE_MAX_BYTES)?;
1476        stream
1477            .try_send(&scratch.buf)
1478            .await
1479            .map_err(|err: ResponseError| SseError::Transport(err.to_string()))?;
1480        Ok(closed_after)
1481    }
1482
1483    /// Sends one already-received shared event plus any queued events coalesced through a pooled buffer.
1484    ///
1485    /// # Arguments
1486    ///
1487    /// - `&mut Stream` - Active Hyperlane client stream.
1488    /// - `&mut SseSubscription` - Active topic subscription.
1489    /// - `Arc<SharedSseEvent>` - First received event.
1490    ///
1491    /// # Returns
1492    ///
1493    /// - `Result<bool, SseError>` - `Ok(true)` if the channel closed after draining, `Ok(false)` to keep streaming.
1494    async fn send_coalesced_events(
1495        stream: &mut Stream,
1496        subscription: &mut SseSubscription,
1497        first: Arc<SharedSseEvent>,
1498    ) -> Result<bool, SseError> {
1499        let first_bytes: &[u8] = first.encoded_bytes();
1500        let mut closed_after: bool = false;
1501        let mut next_ready: Option<Arc<SharedSseEvent>> = None;
1502        if first_bytes.len() < SSE_COALESCE_MAX_BYTES {
1503            loop {
1504                match subscription.try_recv_shared() {
1505                    Some(Ok(ev)) => {
1506                        next_ready = Some(ev);
1507                        break;
1508                    }
1509                    Some(Err(SseError::Lagged(_))) => continue,
1510                    Some(Err(SseError::ChannelClosed)) => {
1511                        closed_after = true;
1512                        break;
1513                    }
1514                    Some(Err(err)) => return Err(err),
1515                    None => break,
1516                }
1517            }
1518        }
1519        let Some(second) = next_ready else {
1520            stream
1521                .try_send(first_bytes)
1522                .await
1523                .map_err(|err: ResponseError| SseError::Transport(err.to_string()))?;
1524            return Ok(closed_after);
1525        };
1526        Box::pin(Self::send_coalesced_burst(
1527            stream,
1528            subscription,
1529            first,
1530            second,
1531        ))
1532        .await
1533    }
1534
1535    /// Sends the prepared SSE HTTP response head and optional reconnect hint in one write.
1536    ///
1537    /// # Arguments
1538    ///
1539    /// - `&mut Stream` - Active Hyperlane client stream.
1540    /// - `&mut Context` - Active Hyperlane request context.
1541    /// - `u64` - Optional reconnect retry hint in milliseconds.
1542    ///
1543    /// # Returns
1544    ///
1545    /// - `Result<(), SseError>` - `Ok(())` when sent, or [`SseError::Transport`].
1546    async fn send_initial_head(
1547        stream: &mut Stream,
1548        ctx: &mut Context,
1549        retry_ms: u64,
1550    ) -> Result<(), SseError> {
1551        let head: Vec<u8> = build_initial_sse_head(ctx, retry_ms);
1552        stream
1553            .try_send(&head)
1554            .await
1555            .map_err(|err: ResponseError| SseError::Transport(err.to_string()))
1556    }
1557
1558    /// Prepares headers, sends the HTTP head, and pumps `subscription` with shared heartbeats until disconnect.
1559    ///
1560    /// # Arguments
1561    ///
1562    /// - `&mut Stream` - Active Hyperlane client stream.
1563    /// - `&mut Context` - Active Hyperlane request context.
1564    /// - `SseSubscription` - Topic subscription to stream.
1565    /// - `&SseConfig` - Heartbeat and reconnect configuration.
1566    ///
1567    /// # Returns
1568    ///
1569    /// - `Result<(), SseError>` - Terminates cleanly when the channel closes or client disconnects.
1570    pub async fn serve_subscription(
1571        stream: &mut Stream,
1572        ctx: &mut Context,
1573        mut subscription: SseSubscription,
1574        config: &SseConfig,
1575    ) -> Result<(), SseError> {
1576        let retry_ms: u64 = config.get_retry_ms();
1577        let heartbeat_ms: u64 = config.get_heartbeat_ms();
1578        Self::send_initial_head(stream, ctx, retry_ms).await?;
1579        let mut heartbeat: Option<Receiver<u64>> = if heartbeat_ms > 0 {
1580            Some(subscription.hub.subscribe_heartbeat(heartbeat_ms))
1581        } else {
1582            None
1583        };
1584        loop {
1585            match next_sse_action(&mut subscription, &mut heartbeat).await? {
1586                SseLoopAction::Event(shared) => {
1587                    if Self::send_coalesced_events(stream, &mut subscription, shared).await? {
1588                        stream.set_closed(true);
1589                        return Ok(());
1590                    }
1591                }
1592                SseLoopAction::Heartbeat => {
1593                    stream
1594                        .try_send(SSE_HEARTBEAT_FRAME)
1595                        .await
1596                        .map_err(|err: ResponseError| SseError::Transport(err.to_string()))?;
1597                }
1598                SseLoopAction::Closed => {
1599                    stream.set_closed(true);
1600                    return Ok(());
1601                }
1602            }
1603        }
1604    }
1605}
1606
1607/// Inherent implementation of [`SsePlugin`].
1608impl SsePlugin {
1609    /// Initializes the global [`SsePlugin`] once with `config`.
1610    ///
1611    /// # Arguments
1612    ///
1613    /// - `SseConfig` - SSE plugin configuration.
1614    ///
1615    /// # Returns
1616    ///
1617    /// - `&'static Self` - Reference to the initialized global plugin instance.
1618    pub fn init(config: SseConfig) -> &'static Self {
1619        SSE_PLUGIN.get_or_init(|| Self {
1620            hub: SseHub::new(config.clone()),
1621            config,
1622        })
1623    }
1624
1625    /// Returns the initialized global [`SsePlugin`], if [`SsePlugin::init`] was called.
1626    ///
1627    /// # Returns
1628    ///
1629    /// - `Option<&'static Self>` - Reference to the global plugin, or `None`.
1630    pub fn get() -> Option<&'static Self> {
1631        SSE_PLUGIN.get()
1632    }
1633
1634    /// Returns the plugin's [`SseConfig`].
1635    ///
1636    /// # Returns
1637    ///
1638    /// - `&SseConfig` - Active configuration.
1639    pub fn get_config(&self) -> &SseConfig {
1640        let Self { config, .. } = self;
1641        config
1642    }
1643
1644    /// Returns the plugin's shared [`SseHub`].
1645    ///
1646    /// # Returns
1647    ///
1648    /// - `&SseHub` - Process-wide SSE topic hub.
1649    pub fn get_hub(&self) -> &SseHub {
1650        let Self { hub, .. } = self;
1651        hub
1652    }
1653}