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