1use super::*;
2
3impl Hasher for FxHasher {
5 #[inline(always)]
11 fn finish(&self) -> u64 {
12 let Self { state } = *self;
13 state
14 }
15
16 #[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 #[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
58impl Display for SseError {
60 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
79impl Error for SseError {}
81
82impl Default for SseConfig {
84 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
96impl SseConfig {
98 pub fn with_heartbeat_ms(mut self, heartbeat_ms: u64) -> Self {
108 self.set_heartbeat_ms(heartbeat_ms);
109 self
110 }
111
112 pub fn with_retry_ms(mut self, retry_ms: u64) -> Self {
122 self.set_retry_ms(retry_ms);
123 self
124 }
125
126 pub fn with_replay_capacity(mut self, replay_capacity: usize) -> Self {
136 self.set_replay_capacity(replay_capacity);
137 self
138 }
139
140 pub fn with_channel_capacity(mut self, channel_capacity: usize) -> Self {
150 self.set_channel_capacity(channel_capacity);
151 self
152 }
153
154 pub fn with_max_topics(mut self, max_topics: usize) -> Self {
164 self.set_max_topics(max_topics);
165 self
166 }
167}
168
169impl SseEvent {
171 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 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 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 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 pub fn with_retry(mut self, retry_ms: u64) -> Self {
259 self.set_retry(Some(retry_ms));
260 self
261 }
262
263 #[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 #[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 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
468impl SharedSseEvent {
470 #[inline]
480 pub(crate) fn new(event: SseEvent) -> Self {
481 Self {
482 event,
483 encoded: OnceLock::new(),
484 }
485 }
486
487 #[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
501impl Drop for SseScratchBuf {
503 fn drop(&mut self) {
505 let Self { buf } = self;
506 return_sse_coalesce_buf(take(buf));
507 }
508}
509
510impl SseTopicRing {
512 #[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 #[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 #[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 #[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 #[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 #[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 #[inline]
682 pub(crate) fn close(&mut self) {
683 let Self { closed, .. } = self;
684 *closed = true;
685 }
686}
687
688impl SseHeartbeatWheel {
690 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 #[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 #[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
744impl SseHubInner {
746 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
789impl SseHub {
791 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 pub fn get_config(&self) -> &SseConfig {
821 let Self { inner } = self;
822 &inner.config
823 }
824
825 #[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 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 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 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 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 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 pub fn topic_count(&self) -> usize {
1135 let Self { inner } = self;
1136 inner.active_topics.load(Ordering::Acquire)
1137 }
1138
1139 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
1163impl Default for SseHub {
1165 fn default() -> Self {
1167 Self::new(SseConfig::default())
1168 }
1169}
1170
1171impl SseSubscription {
1173 pub fn topic(&self) -> &str {
1179 let Self { topic, .. } = self;
1180 topic
1181 }
1182
1183 #[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 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 #[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 #[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 #[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 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
1309impl Drop for SseSubscription {
1311 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
1349impl SseStream {
1351 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 #[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 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 #[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 #[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 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 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 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
1607impl SsePlugin {
1609 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 pub fn get() -> Option<&'static Self> {
1631 SSE_PLUGIN.get()
1632 }
1633
1634 pub fn get_config(&self) -> &SseConfig {
1640 let Self { config, .. } = self;
1641 config
1642 }
1643
1644 pub fn get_hub(&self) -> &SseHub {
1650 let Self { hub, .. } = self;
1651 hub
1652 }
1653}