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
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
//! firehose codec - com.atproto.sync.subscribeRepos
//!
//! encode and decode AT Protocol firehose events over WebSocket. messages are
//! DAG-CBOR encoded (unlike jetstream, which is JSON). includes frame encoding/
//! decoding, CAR block packing, and CID creation for records.
//!
//! wire format per frame:
//! [DAG-CBOR header: {op, t}] [DAG-CBOR payload: {seq, repo, ops, blocks, ...}]
//!
//! see: https://atproto.com/specs/event-stream
const std = @import("std");
const cbor = @import("../repo/cbor.zig");
const car = @import("../repo/car.zig");
const mst = @import("../repo/mst.zig");
const sync = @import("sync.zig");
const Did = @import("../syntax/did.zig").Did;
const Nsid = @import("../syntax/nsid.zig").Nsid;
const Rkey = @import("../syntax/rkey.zig").Rkey;
const Tid = @import("../syntax/tid.zig").Tid;
const mem = std.mem;
const Allocator = mem.Allocator;
const keepalive = @import("keepalive.zig");
const Io = std.Io;
const log = std.log.scoped(.zat);
pub const CommitAction = sync.CommitAction;
pub const AccountStatus = sync.AccountStatus;
pub const default_hosts = [_][]const u8{
"bsky.network",
"northamerica.firehose.network",
"europe.firehose.network",
"asia.firehose.network",
};
pub const Options = struct {
/// stream endpoints (relays for FirehoseClient, labelers for
/// LabelClient), as full URLs following ecosystem norms (atmos
/// streaming.Options.URL, jetstream --relay-url): the scheme carries
/// tls and the port rides in the URL, e.g. "wss://bsky.network" or
/// "ws://localhost:7777". any path is ignored — each stream's method
/// path is fixed by the protocol. bare hostnames are implicit wss.
hosts: []const []const u8 = &default_hosts,
cursor: ?i64 = null,
/// Fail over after this many milliseconds with no WebSocket frames.
/// Catches a host that holds the socket open but goes silent, which TCP
/// keepalive never fires on (the socket is healthy; the stream behind it
/// stalled). Mirrors JetstreamClient's option of the same name. A live
/// relay emits continuously, so even a few seconds of total silence is
/// anomalous — but the default stays off: reconnect policy belongs to
/// the consumer.
idle_timeout_ms: ?u32 = null,
max_message_size: usize = 5 * 1024 * 1024, // 5MB — firehose frames can be large
};
/// a parsed relay endpoint (see Options.hosts for the accepted forms)
pub const Endpoint = struct {
host: []const u8,
port: u16,
tls: bool,
pub fn parse(url: []const u8) error{InvalidEndpoint}!Endpoint {
var rest = url;
var tls = true;
if (mem.startsWith(u8, rest, "wss://")) {
rest = rest["wss://".len..];
} else if (mem.startsWith(u8, rest, "ws://")) {
tls = false;
rest = rest["ws://".len..];
} else if (mem.indexOf(u8, rest, "://") != null) {
return error.InvalidEndpoint;
}
if (mem.indexOfScalar(u8, rest, '/')) |i| rest = rest[0..i];
if (mem.indexOfScalar(u8, rest, '?')) |i| rest = rest[0..i];
var port: u16 = if (tls) 443 else 80;
var host = rest;
if (mem.indexOfScalar(u8, rest, ':')) |i| {
host = rest[0..i];
port = std.fmt.parseInt(u16, rest[i + 1 ..], 10) catch return error.InvalidEndpoint;
}
if (host.len == 0) return error.InvalidEndpoint;
return .{ .host = host, .port = port, .tls = tls };
}
fn isDefaultPort(self: Endpoint) bool {
return self.port == if (self.tls) @as(u16, 443) else 80;
}
};
/// decoded firehose event
pub const Event = union(enum) {
commit: CommitEvent,
sync: SyncEvent,
identity: IdentityEvent,
account: AccountEvent,
info: InfoEvent,
pub fn seq(self: Event) ?i64 {
return switch (self) {
.commit => |c| c.seq,
.sync => |s| s.seq,
.identity => |i| i.seq,
.account => |a| a.seq,
.info => null,
};
}
};
pub const CommitEvent = struct {
seq: i64,
repo: []const u8, // DID
rev: []const u8, // TID — revision of the commit
time: []const u8, // datetime — when event was received
since: ?[]const u8 = null, // TID — rev of preceding commit (null = full repo export)
commit: ?cbor.Cid = null, // CID of the commit object
blocks: []const u8 = &.{}, // raw CAR diff bytes
ops: []const RepoOp,
prev_data: ?cbor.Cid = null, // MST root CID of the previous revision
blobs: []const cbor.Cid = &.{}, // new blobs referenced by records in this commit
rebase: bool = false,
too_big: bool = false,
pub fn toMstOperations(self: CommitEvent, allocator: Allocator) Allocator.Error![]mst.Operation {
var ops: std.ArrayList(mst.Operation) = .empty;
errdefer ops.deinit(allocator);
for (self.ops) |op| {
const path = if (op.path.len != 0)
try allocator.dupe(u8, op.path)
else
try std.fmt.allocPrint(allocator, "{s}/{s}", .{ op.collection, op.rkey });
try ops.append(allocator, .{
.path = path,
.value = if (op.cid) |cid| cid.raw else null,
.prev = if (op.prev) |prev| prev.raw else null,
});
}
return ops.toOwnedSlice(allocator);
}
};
pub const RepoOp = struct {
action: CommitAction,
path: []const u8 = "",
collection: []const u8,
rkey: []const u8,
cid: ?cbor.Cid = null, // CID of the record (null for deletes)
prev: ?cbor.Cid = null, // CID of the previous record for updates/deletes
record: ?cbor.Value = null, // decoded DAG-CBOR record from CAR block
};
pub const CommitEventOp = struct {
action: CommitAction,
collection: []const u8,
rkey: []const u8,
cid: ?cbor.Cid = null,
prev: ?cbor.Cid = null,
};
pub const CommitEventParams = struct {
seq: i64,
repo_did: []const u8,
commit_cid: cbor.Cid,
rev: []const u8,
since_rev: ?[]const u8 = null,
prev_data: ?cbor.Cid = null,
blocks: []const u8,
ops: []const CommitEventOp,
blobs: []const cbor.Cid = &.{},
time: []const u8,
rebase: bool = false,
too_big: bool = false,
};
pub const SyncEvent = struct {
seq: i64,
did: []const u8,
rev: []const u8,
time: []const u8,
blocks: []const u8, // raw CAR bytes containing the current commit object
};
pub const IdentityEvent = struct {
seq: i64,
did: []const u8,
time: []const u8, // datetime — when event was received
handle: ?[]const u8 = null,
};
pub const AccountEvent = struct {
seq: i64,
did: []const u8,
time: []const u8, // datetime — when event was received
active: bool = true,
status: ?AccountStatus = null,
};
pub const InfoEvent = struct {
name: ?[]const u8 = null,
message: ?[]const u8 = null,
};
/// frame header from the wire
const FrameHeader = struct {
op: i64,
t: ?[]const u8 = null,
};
const FrameOp = enum(i64) {
message = 1,
err = -1,
};
pub const DecodeError = error{
InvalidFrame,
InvalidHeader,
UnexpectedEof,
MissingField,
InvalidRepoPath,
UnknownOp,
UnknownEventType,
} || cbor.DecodeError || car.CarError;
pub const ValidateCommitError = error{
MissingCommitCid,
InvalidRepoDid,
InvalidRev,
InvalidSince,
InvalidRepoPath,
MissingRecordCid,
UnexpectedRecordCid,
UnexpectedPrevRecordCid,
};
/// cheaply extract the seq from a raw frame without CAR hydration.
/// returns null for frames without a seq (#info, errors, malformed).
pub fn peekSeq(allocator: Allocator, data: []const u8) ?i64 {
var arena = std.heap.ArenaAllocator.init(allocator);
defer arena.deinit();
const header_result = cbor.decode(arena.allocator(), data) catch return null;
if ((header_result.value.getInt("op") orelse return null) != 1) return null;
const payload = cbor.decodeAll(arena.allocator(), data[header_result.consumed..]) catch return null;
return payload.getInt("seq");
}
/// decode a raw WebSocket binary frame into a firehose Event
pub fn decodeFrame(allocator: Allocator, data: []const u8) DecodeError!Event {
// frame = [CBOR header] [CBOR payload] concatenated
const header_result = try cbor.decode(allocator, data);
const header_val = header_result.value;
const payload_data = data[header_result.consumed..];
// parse header
const op = header_val.getInt("op") orelse return error.InvalidHeader;
if (op == -1) return error.UnknownOp; // error frame
const t = header_val.getString("t") orelse return error.InvalidHeader;
// decode payload
const payload = try cbor.decodeAll(allocator, payload_data);
if (mem.eql(u8, t, "#commit")) {
return try decodeCommit(allocator, payload);
} else if (mem.eql(u8, t, "#sync")) {
return decodeSync(payload);
} else if (mem.eql(u8, t, "#identity")) {
return decodeIdentity(payload);
} else if (mem.eql(u8, t, "#account")) {
return decodeAccount(payload);
} else if (mem.eql(u8, t, "#info")) {
return .{ .info = .{
.name = payload.getString("name"),
.message = payload.getString("message"),
} };
}
return error.UnknownEventType;
}
fn decodeCommit(allocator: Allocator, payload: cbor.Value) DecodeError!Event {
const seq_val = payload.getInt("seq") orelse return error.MissingField;
const repo = payload.getString("repo") orelse return error.MissingField;
const rev = payload.getString("rev") orelse return error.MissingField;
const time = payload.getString("time") orelse return error.MissingField;
const commit_cid = payload.getCid("commit") orelse return error.MissingField;
const blocks_bytes = payload.getBytes("blocks") orelse return error.MissingField;
const prev_data = try optionalCid(payload, "prevData");
// parse blobs array (array of CID links)
var blobs: std.ArrayList(cbor.Cid) = .empty;
if (payload.getArray("blobs")) |blob_values| {
for (blob_values) |blob_val| {
switch (blob_val) {
.cid => |c| try blobs.append(allocator, c),
else => {},
}
}
}
// parse CAR blocks for record hydration. CAR verification failure should not
// hide the wire event; consumers can reject by verifying `blocks` explicitly.
const parsed_car: ?car.Car = car.read(allocator, blocks_bytes) catch null;
// parse ops
const ops_array = payload.getArray("ops");
var ops: std.ArrayList(RepoOp) = .empty;
if (ops_array) |op_values| {
for (op_values) |op_val| {
const action_str = op_val.getString("action") orelse continue;
const action = CommitAction.parse(action_str) orelse continue;
const path = op_val.getString("path") orelse continue;
// Decoding preserves hostile/noncanonical paths so downstream
// ingest policy can drop one bad op without losing its valid
// siblings. Structural validation remains available through
// validateCommitEvent and encoding still calls it.
const repo_path = splitRepoPath(path);
// extract CID from op and look up record from CAR blocks
var op_cid: ?cbor.Cid = null;
var op_prev: ?cbor.Cid = null;
var record: ?cbor.Value = null;
if (op_val.get("cid")) |cid_val| {
switch (cid_val) {
.cid => |cid| {
op_cid = cid;
if (parsed_car) |c| {
if (car.findBlock(c, cid.raw)) |block_data| {
record = cbor.decodeAll(allocator, block_data) catch null;
}
}
},
else => {},
}
}
if (op_val.get("prev")) |prev_val| {
switch (prev_val) {
.cid => |cid| op_prev = cid,
else => {},
}
}
try ops.append(allocator, .{
.action = action,
.path = path,
.collection = repo_path.collection,
.rkey = repo_path.rkey,
.cid = op_cid,
.prev = op_prev,
.record = record,
});
}
}
return .{ .commit = .{
.seq = seq_val,
.repo = repo,
.rev = rev,
.time = time,
.since = payload.getString("since"),
.commit = commit_cid,
.blocks = blocks_bytes,
.ops = try ops.toOwnedSlice(allocator),
.prev_data = prev_data,
.blobs = try blobs.toOwnedSlice(allocator),
.rebase = payload.getBool("rebase") orelse false,
.too_big = payload.getBool("tooBig") orelse false,
} };
}
/// Validate the structural shape of a decoded commit event.
///
/// This is intentionally lighter than repo verification: it checks event
/// vocabulary, identifier syntax, repo op paths, and op CID nullability. It
/// does not parse CAR blocks, verify commit signatures, or prove MST roots.
pub fn validateCommitEvent(commit: CommitEvent) ValidateCommitError!void {
if (Did.parse(commit.repo) == null) return error.InvalidRepoDid;
if (Tid.parse(commit.rev) == null) return error.InvalidRev;
if (commit.since) |since| {
if (Tid.parse(since) == null) return error.InvalidSince;
}
if (commit.commit == null) return error.MissingCommitCid;
for (commit.ops) |op| {
try validateRepoOpPath(op);
switch (op.action) {
.create => {
if (op.cid == null) return error.MissingRecordCid;
if (op.prev != null) return error.UnexpectedPrevRecordCid;
},
.update => {
if (op.cid == null) return error.MissingRecordCid;
},
.delete => {
if (op.cid != null) return error.UnexpectedRecordCid;
},
}
}
}
fn commitEvent(allocator: Allocator, params: CommitEventParams) (Allocator.Error || ValidateCommitError)!CommitEvent {
var ops: std.ArrayList(RepoOp) = .empty;
errdefer ops.deinit(allocator);
for (params.ops) |op| {
try ops.append(allocator, .{
.action = op.action,
.path = "",
.collection = op.collection,
.rkey = op.rkey,
.cid = op.cid,
.prev = op.prev,
});
}
const event: CommitEvent = .{
.seq = params.seq,
.repo = params.repo_did,
.rev = params.rev,
.time = params.time,
.since = params.since_rev,
.commit = params.commit_cid,
.blocks = params.blocks,
.ops = try ops.toOwnedSlice(allocator),
.prev_data = params.prev_data,
.blobs = params.blobs,
.rebase = params.rebase,
.too_big = params.too_big,
};
errdefer allocator.free(event.ops);
try validateCommitEvent(event);
return event;
}
pub fn encodeCommitEvent(allocator: Allocator, params: CommitEventParams) ![]u8 {
var arena = std.heap.ArenaAllocator.init(allocator);
defer arena.deinit();
const event = try commitEvent(arena.allocator(), params);
return encodeFrame(allocator, .{ .commit = event });
}
/// encode an `#identity` frame
pub fn encodeIdentityEvent(allocator: Allocator, event: IdentityEvent) ![]u8 {
if (Did.parse(event.did) == null) return error.InvalidDid;
return encodeFrame(allocator, .{ .identity = event });
}
/// encode an `#account` frame. `status` gives the reason an account is
/// inactive, so an active account may not carry one.
pub fn encodeAccountEvent(allocator: Allocator, event: AccountEvent) ![]u8 {
if (Did.parse(event.did) == null) return error.InvalidDid;
if (event.active and event.status != null) return error.StatusOnActiveAccount;
return encodeFrame(allocator, .{ .account = event });
}
/// encode an `#info` frame. the lexicon requires `name`.
pub fn encodeInfoEvent(allocator: Allocator, event: InfoEvent) ![]u8 {
if (event.name == null) return error.MissingField;
return encodeFrame(allocator, .{ .info = event });
}
pub const SyncEventParams = struct {
seq: i64,
/// the signed commit block, as stored
commit: []const u8,
time: []const u8,
};
/// encode a `#sync` frame. `did` and `rev` are read from the commit block,
/// so they match it as the lexicon requires, and `blocks` is a CAR holding
/// that block with its CID as the first root.
pub fn encodeSyncEvent(allocator: Allocator, params: SyncEventParams) ![]u8 {
var arena = std.heap.ArenaAllocator.init(allocator);
defer arena.deinit();
const a = arena.allocator();
const commit = cbor.decodeAll(a, params.commit) catch return error.InvalidCommit;
const did = commit.getString("did") orelse return error.InvalidCommit;
const rev = commit.getString("rev") orelse return error.InvalidCommit;
if (Did.parse(did) == null) return error.InvalidCommit;
if (Tid.parse(rev) == null) return error.InvalidCommit;
const cid = try cbor.Cid.forDagCbor(a, params.commit);
const blocks = try car.writeAlloc(a, .{
.roots = &.{cid},
.blocks = &.{.{ .cid_raw = cid.raw, .data = params.commit }},
});
return encodeFrame(allocator, .{ .sync = .{
.seq = params.seq,
.did = did,
.rev = rev,
.time = params.time,
.blocks = blocks,
} });
}
/// encode an error frame: header `{op: -1}` with no `t`, then
/// `{error, message?}`. `error_name` is a name from the subscription's
/// lexicon, e.g. "FutureCursor" or "ConsumerTooSlow"; the stream closes after
/// it is sent.
pub fn encodeErrorFrame(allocator: Allocator, error_name: []const u8, message: ?[]const u8) Allocator.Error![]u8 {
var aw: std.Io.Writer.Allocating = .init(allocator);
errdefer aw.deinit();
const header: cbor.Value = .{ .map = &.{.{ .key = "op", .value = .{ .negative = -1 } }} };
const payload: cbor.Value = if (message) |m| .{ .map = &.{
.{ .key = "error", .value = .{ .text = error_name } },
.{ .key = "message", .value = .{ .text = m } },
} } else .{ .map = &.{
.{ .key = "error", .value = .{ .text = error_name } },
} };
cbor.encode(allocator, &aw.writer, header) catch return error.OutOfMemory;
cbor.encode(allocator, &aw.writer, payload) catch return error.OutOfMemory;
return try aw.toOwnedSlice();
}
const RepoPath = struct {
collection: []const u8,
rkey: []const u8,
};
fn splitRepoPath(path: []const u8) RepoPath {
const slash = mem.indexOfScalar(u8, path, '/') orelse return .{
.collection = path,
.rkey = "",
};
return .{
.collection = path[0..slash],
.rkey = path[slash + 1 ..],
};
}
fn parseRepoPath(path: []const u8) error{InvalidRepoPath}!RepoPath {
const slash = mem.indexOfScalar(u8, path, '/') orelse return error.InvalidRepoPath;
if (mem.indexOfScalarPos(u8, path, slash + 1, '/') != null) return error.InvalidRepoPath;
const result = splitRepoPath(path);
if (Nsid.parse(result.collection) == null) return error.InvalidRepoPath;
if (Rkey.parse(result.rkey) == null) return error.InvalidRepoPath;
return result;
}
fn validateRepoOpPath(op: RepoOp) error{InvalidRepoPath}!void {
if (op.path.len != 0) {
_ = try parseRepoPath(op.path);
return;
}
if (Nsid.parse(op.collection) == null) return error.InvalidRepoPath;
if (Rkey.parse(op.rkey) == null) return error.InvalidRepoPath;
}
fn optionalCid(value: cbor.Value, key: []const u8) DecodeError!?cbor.Cid {
const found = value.get(key) orelse return null;
return switch (found) {
.cid => |cid| cid,
.null => null,
else => error.MissingField,
};
}
test "optional CID accepts omitted and explicit null fields" {
try std.testing.expect(try optionalCid(.{ .map = &.{} }, "prevData") == null);
try std.testing.expect(try optionalCid(.{ .map = &.{.{
.key = "prevData",
.value = .null,
}} }, "prevData") == null);
try std.testing.expectError(error.MissingField, optionalCid(.{ .map = &.{.{
.key = "prevData",
.value = .{ .text = "not-a-cid" },
}} }, "prevData"));
}
fn decodeSync(payload: cbor.Value) DecodeError!Event {
return .{ .sync = .{
.seq = payload.getInt("seq") orelse return error.MissingField,
.did = payload.getString("did") orelse return error.MissingField,
.rev = payload.getString("rev") orelse return error.MissingField,
.time = payload.getString("time") orelse return error.MissingField,
.blocks = payload.getBytes("blocks") orelse return error.MissingField,
} };
}
fn decodeIdentity(payload: cbor.Value) DecodeError!Event {
return .{ .identity = .{
.seq = payload.getInt("seq") orelse return error.MissingField,
.did = payload.getString("did") orelse return error.MissingField,
.time = payload.getString("time") orelse return error.MissingField,
.handle = payload.getString("handle"),
} };
}
fn decodeAccount(payload: cbor.Value) DecodeError!Event {
const status_str = payload.getString("status");
return .{ .account = .{
.seq = payload.getInt("seq") orelse return error.MissingField,
.did = payload.getString("did") orelse return error.MissingField,
.time = payload.getString("time") orelse return error.MissingField,
.active = payload.getBool("active") orelse true,
.status = if (status_str) |s| AccountStatus.parse(s) else null,
} };
}
// === encoder ===
/// encode a firehose Event into a wire frame: [DAG-CBOR header] [DAG-CBOR payload]
fn encodeFrame(allocator: Allocator, event: Event) ![]u8 {
var aw: std.Io.Writer.Allocating = .init(allocator);
errdefer aw.deinit();
const tag = switch (event) {
.commit => "#commit",
.sync => "#sync",
.identity => "#identity",
.account => "#account",
.info => "#info",
};
// encode header: {op: 1, t: "#..."}
const header: cbor.Value = .{ .map = &.{
.{ .key = "op", .value = .{ .unsigned = 1 } },
.{ .key = "t", .value = .{ .text = tag } },
} };
try cbor.encode(allocator, &aw.writer, header);
// encode payload based on event type
switch (event) {
.commit => |commit| try encodeCommitPayload(allocator, &aw.writer, commit),
.sync => |sync_event| try encodeSyncPayload(allocator, &aw.writer, sync_event),
.identity => |id| try encodeIdentityPayload(allocator, &aw.writer, id),
.account => |acct| try encodeAccountPayload(allocator, &aw.writer, acct),
.info => |inf| try encodeInfoPayload(allocator, &aw.writer, inf),
}
return try aw.toOwnedSlice();
}
fn encodeCommitPayload(allocator: Allocator, writer: anytype, commit: CommitEvent) !void {
// build ops array and CAR blocks simultaneously
var op_values: std.ArrayList(cbor.Value) = .empty;
defer op_values.deinit(allocator);
var car_blocks: std.ArrayList(car.Block) = .empty;
defer car_blocks.deinit(allocator);
var root_cids: std.ArrayList(cbor.Cid) = .empty;
defer root_cids.deinit(allocator);
if (commit.commit) |commit_cid| try root_cids.append(allocator, commit_cid);
for (commit.ops) |op| {
const action_str: []const u8 = @tagName(op.action);
const path = if (op.path.len != 0)
op.path
else
try std.fmt.allocPrint(allocator, "{s}/{s}", .{ op.collection, op.rkey });
_ = try parseRepoPath(path);
if (op.record) |record| {
// encode record, create CID, add to CAR blocks
const record_bytes = try cbor.encodeAlloc(allocator, record);
const cid = try cbor.Cid.forDagCbor(allocator, record_bytes);
try car_blocks.append(allocator, .{
.cid_raw = cid.raw,
.data = record_bytes,
});
if (root_cids.items.len == 0) {
try root_cids.append(allocator, cid);
}
var op_entries: std.ArrayList(cbor.Value.MapEntry) = .empty;
defer op_entries.deinit(allocator);
try op_entries.append(allocator, .{ .key = "action", .value = .{ .text = action_str } });
try op_entries.append(allocator, .{ .key = "cid", .value = .{ .cid = cid } });
try op_entries.append(allocator, .{ .key = "path", .value = .{ .text = path } });
if (op.prev) |prev| {
try op_entries.append(allocator, .{ .key = "prev", .value = .{ .cid = prev } });
}
try op_values.append(allocator, .{ .map = try op_entries.toOwnedSlice(allocator) });
} else {
var op_entries: std.ArrayList(cbor.Value.MapEntry) = .empty;
defer op_entries.deinit(allocator);
try op_entries.append(allocator, .{ .key = "action", .value = .{ .text = action_str } });
try op_entries.append(allocator, .{ .key = "cid", .value = if (op.cid) |cid| .{ .cid = cid } else .null });
try op_entries.append(allocator, .{ .key = "path", .value = .{ .text = path } });
if (op.prev) |prev| {
try op_entries.append(allocator, .{ .key = "prev", .value = .{ .cid = prev } });
}
try op_values.append(allocator, .{ .map = try op_entries.toOwnedSlice(allocator) });
}
}
const blocks_bytes = if (commit.blocks.len != 0) commit.blocks else blk: {
const car_data = car.Car{
.roots = root_cids.items,
.blocks = car_blocks.items,
};
break :blk try car.writeAlloc(allocator, car_data);
};
// build blobs array
var blob_values: std.ArrayList(cbor.Value) = .empty;
defer blob_values.deinit(allocator);
for (commit.blobs) |blob| {
try blob_values.append(allocator, .{ .cid = blob });
}
// build payload entries
var entries: std.ArrayList(cbor.Value.MapEntry) = .empty;
defer entries.deinit(allocator);
try entries.append(allocator, .{ .key = "blocks", .value = .{ .bytes = blocks_bytes } });
if (commit.commit) |commit_cid| {
try entries.append(allocator, .{ .key = "commit", .value = .{ .cid = commit_cid } });
}
try entries.append(allocator, .{ .key = "blobs", .value = .{ .array = blob_values.items } });
try entries.append(allocator, .{ .key = "ops", .value = .{ .array = op_values.items } });
try entries.append(allocator, .{ .key = "prevData", .value = if (commit.prev_data) |prev_data| .{ .cid = prev_data } else .null });
try entries.append(allocator, .{ .key = "rebase", .value = .{ .boolean = commit.rebase } });
try entries.append(allocator, .{ .key = "repo", .value = .{ .text = commit.repo } });
try entries.append(allocator, .{ .key = "rev", .value = .{ .text = commit.rev } });
try entries.append(allocator, .{ .key = "seq", .value = .{ .unsigned = @intCast(commit.seq) } });
try entries.append(allocator, .{ .key = "since", .value = if (commit.since) |s| .{ .text = s } else .null });
try entries.append(allocator, .{ .key = "time", .value = .{ .text = commit.time } });
try entries.append(allocator, .{ .key = "tooBig", .value = .{ .boolean = commit.too_big } });
try cbor.encode(allocator, writer, .{ .map = entries.items });
}
fn encodeSyncPayload(allocator: Allocator, writer: anytype, sync_event: SyncEvent) !void {
var entries: std.ArrayList(cbor.Value.MapEntry) = .empty;
defer entries.deinit(allocator);
try entries.append(allocator, .{ .key = "blocks", .value = .{ .bytes = sync_event.blocks } });
try entries.append(allocator, .{ .key = "did", .value = .{ .text = sync_event.did } });
try entries.append(allocator, .{ .key = "rev", .value = .{ .text = sync_event.rev } });
try entries.append(allocator, .{ .key = "seq", .value = .{ .unsigned = @intCast(sync_event.seq) } });
try entries.append(allocator, .{ .key = "time", .value = .{ .text = sync_event.time } });
try cbor.encode(allocator, writer, .{ .map = entries.items });
}
fn encodeIdentityPayload(allocator: Allocator, writer: anytype, identity: IdentityEvent) !void {
var entries: std.ArrayList(cbor.Value.MapEntry) = .empty;
defer entries.deinit(allocator);
try entries.append(allocator, .{ .key = "did", .value = .{ .text = identity.did } });
if (identity.handle) |h| {
try entries.append(allocator, .{ .key = "handle", .value = .{ .text = h } });
}
try entries.append(allocator, .{ .key = "seq", .value = .{ .unsigned = @intCast(identity.seq) } });
try entries.append(allocator, .{ .key = "time", .value = .{ .text = identity.time } });
try cbor.encode(allocator, writer, .{ .map = entries.items });
}
fn encodeAccountPayload(allocator: Allocator, writer: anytype, account: AccountEvent) !void {
var entries: std.ArrayList(cbor.Value.MapEntry) = .empty;
defer entries.deinit(allocator);
try entries.append(allocator, .{ .key = "active", .value = .{ .boolean = account.active } });
try entries.append(allocator, .{ .key = "did", .value = .{ .text = account.did } });
try entries.append(allocator, .{ .key = "seq", .value = .{ .unsigned = @intCast(account.seq) } });
if (account.status) |s| {
try entries.append(allocator, .{ .key = "status", .value = .{ .text = @tagName(s) } });
}
try entries.append(allocator, .{ .key = "time", .value = .{ .text = account.time } });
try cbor.encode(allocator, writer, .{ .map = entries.items });
}
fn encodeInfoPayload(allocator: Allocator, writer: anytype, info: InfoEvent) !void {
var entries: std.ArrayList(cbor.Value.MapEntry) = .empty;
defer entries.deinit(allocator);
if (info.message) |m| {
try entries.append(allocator, .{ .key = "message", .value = .{ .text = m } });
}
if (info.name) |n| {
try entries.append(allocator, .{ .key = "name", .value = .{ .text = n } });
}
try cbor.encode(allocator, writer, .{ .map = entries.items });
}
/// The repo event stream: `com.atproto.sync.subscribeRepos`.
pub const RepoStream = struct {
pub const nsid = "com.atproto.sync.subscribeRepos";
pub const StreamEvent = Event;
pub const decode = decodeFrame;
};
pub const FirehoseClient = SubscriptionClient(RepoStream);
/// A reconnecting reader for one XRPC event stream. `S` names the stream:
/// `S.nsid` is its method, `S.StreamEvent` its decoded event (exposing
/// `seq() ?i64`) and `S.decode(allocator, frame)` its frame decoder.
pub fn SubscriptionClient(comptime S: type) type {
return struct {
const Self = @This();
pub const Stream = S;
io: Io,
allocator: Allocator,
options: Options,
last_seq: ?i64 = null,
/// set once the websocket handshake for the current attempt succeeds.
/// An endpoint that accepted a connection is a working endpoint, however
/// the connection later ended, so the reconnect backoff starts over
/// rather than compounding.
connected_this_attempt: bool = false,
/// frames delivered on the current connection; written by the reader
/// task and read by the idle watchdog, hence atomic.
frames_this_connection: std.atomic.Value(usize) = .init(0),
pub fn init(io: Io, allocator: Allocator, options: Options) Self {
return .{
.io = io,
.allocator = allocator,
.options = options,
.last_seq = if (options.cursor) |c| c else null,
};
}
pub fn deinit(_: *Self) void {}
/// subscribe with a user-provided handler.
/// handler must implement: fn onEvent(*@TypeOf(handler), S.StreamEvent) void
/// optional: fn onError(*@TypeOf(handler), anyerror) void
/// optional: fn onConnect(*@TypeOf(handler), []const u8) void — called
/// after the websocket handshake succeeds and before frame delivery
/// optional: fn onReconnect(*@TypeOf(handler)) void — called immediately
/// before every connection attempt after the initial attempt.
/// optional: fn onRawFrame(*@TypeOf(handler), []const u8) void or !void —
/// when declared, raw websocket frames are delivered INSTEAD of decoded
/// events (the caller owns decoding). Cursor tracking advances only
/// after the callback accepts the frame; a fallible callback can reject
/// work without making a reconnect skip it. This matters for bounded
/// downstream pipelines which may close or fail while the socket lives.
/// optional: fn shouldStop(*@TypeOf(handler)) bool — checked before
/// every frame delivery and around every reconnect. returning true
/// makes subscribe return cleanly (bounded consumers: bootstrap
/// capture, tests, graceful shutdown). without it, an interrupted
/// read is indistinguishable from a connection error and the
/// reconnect loop absorbs it forever; pair a stop flag with
/// future.cancel to unblock an idle read.
/// blocks until shouldStop (forever without it) — reconnects with
/// exponential backoff on disconnect. rotates through hosts on each
/// reconnect attempt.
pub fn subscribe(self: *Self, handler: anytype) Io.Cancelable!void {
var backoff: u64 = 1;
var host_index: usize = 0;
const max_backoff: u64 = 60;
var prev_host_index: usize = 0;
while (!stopRequested(handler)) {
if (host_index > 0 and comptime @hasDecl(@TypeOf(handler.*), "onReconnect"))
handler.onReconnect();
const host = self.options.hosts[host_index % self.options.hosts.len];
const effective_index = host_index % self.options.hosts.len;
// reset backoff on host switch (fresh host deserves a fresh chance)
if (host_index > 0 and effective_index != prev_host_index) {
backoff = 1;
}
// ...and after a connection that was actually established. Backoff
// exists to spare an endpoint that is refusing us; an endpoint that
// accepted a connection and later closed it is not that. Without
// this a single-host consumer never resets — effective_index is
// always 0, so the host-switch branch above can never fire — and
// the delay climbs to max_backoff and stays there for the life of
// the process. Observed on a relay that closed every ~113s: every
// reconnect paid the full 60s, leaving the tail down 33% of the
// time while each individual connection was perfectly healthy.
//
// Keyed on the handshake, matching jcalabro/atmos
// (streaming/client.go: "Reset backoff after successful
// connection"). Keying it on delivered frames instead would leave
// a connection that is open but idle compounding its backoff —
// which for a filtered jetstream consumer is an ordinary state,
// not a fault.
if (self.connected_this_attempt) backoff = 1;
log.info("connecting to host {d}/{d}: {s}", .{ effective_index + 1, self.options.hosts.len, host });
self.connectAndRead(host, handler) catch |err| {
// a stop-interrupted read surfaces as a connection error;
// don't report it as one
if (stopRequested(handler)) return;
if (comptime @hasDecl(@TypeOf(handler.*), "onError")) {
handler.onError(err);
} else {
log.err("{s} error: {s}, reconnecting in {d}s...", .{ S.nsid, @errorName(err), backoff });
}
};
if (stopRequested(handler)) return;
prev_host_index = effective_index;
host_index += 1;
self.io.sleep(Io.Duration.fromSeconds(@intCast(backoff)), .awake) catch |err| switch (err) {
// Closing the socket can race the next cancellable operation
// on some Io backends. That cancellation belongs to the dead
// connection, not to the reconnect loop; an explicit handler
// stop remains the only clean termination condition.
error.Canceled => {
if (stopRequested(handler)) return;
continue;
},
};
backoff = @min(backoff * 2, max_backoff);
}
}
fn connectAndRead(self: *Self, host: []const u8, handler: anytype) !void {
self.connected_this_attempt = false;
const ep = try Endpoint.parse(host);
var path_buf: [256]u8 = undefined;
var w: std.Io.Writer = .fixed(&path_buf);
try w.writeAll("/xrpc/" ++ S.nsid);
if (self.last_seq) |cursor| {
try w.print("?cursor={d}", .{cursor});
}
const path = w.buffered();
log.info("connecting to {s}://{s}:{d}{s}", .{ if (ep.tls) "wss" else "ws", ep.host, ep.port, path });
const websocket = @import("websocket");
var client = try websocket.Client.init(self.io, self.allocator, .{
.host = ep.host,
.port = ep.port,
.tls = ep.tls,
.max_size = self.options.max_message_size,
});
defer client.deinit();
// Host header carries the port only when non-default (RFC 9110 §7.2)
var host_header_buf: [256]u8 = undefined;
const host_header = if (ep.isDefaultPort())
std.fmt.bufPrint(&host_header_buf, "Host: {s}\r\n", .{ep.host}) catch ep.host
else
std.fmt.bufPrint(&host_header_buf, "Host: {s}:{d}\r\n", .{ ep.host, ep.port }) catch ep.host;
try client.handshake(path, .{ .headers = host_header });
keepalive.configure(client.stream.stream.socket.handle);
self.connected_this_attempt = true;
log.info("{s} connected to {s}", .{ S.nsid, ep.host });
if (comptime @hasDecl(@TypeOf(handler.*), "onConnect")) {
handler.onConnect(host);
}
var ws_handler = WsHandler(Self, @TypeOf(handler.*)){
.allocator = self.allocator,
.handler = handler,
.client_state = self,
};
if (self.options.idle_timeout_ms) |timeout_ms| {
// A socket-level receive timeout (SO_RCVTIMEO) is off the table:
// std.Io.Threaded treats the resulting EAGAIN on a blocking
// socket as a programmer bug and panics in debug builds. Instead
// the blocking readLoop runs as a concurrent task and a watchdog
// here compares the frame counter across quiet windows,
// cancelling the read when a full window passes with no frames.
// Fires between timeout and 2x timeout after the last frame.
self.frames_this_connection.store(0, .monotonic);
var done: Io.Event = .unset;
var read_err: ?anyerror = null;
const Reader = struct {
fn run(
io: Io,
ws_client: *websocket.Client,
h: *WsHandler(Self, @TypeOf(handler.*)),
done_ev: *Io.Event,
err_out: *?anyerror,
) void {
ws_client.readLoop(h) catch |err| {
err_out.* = err;
};
done_ev.set(io);
}
};
var future = try self.io.concurrent(Reader.run, .{ self.io, &client, &ws_handler, &done, &read_err });
var joined = false;
defer if (!joined) future.cancel(self.io);
var last_frames: usize = 0;
while (true) {
done.waitTimeout(self.io, .{ .duration = .{ .raw = Io.Duration.fromMilliseconds(@intCast(timeout_ms)), .clock = .awake } }) catch |err| switch (err) {
error.Timeout => {
const frames = self.frames_this_connection.load(.monotonic);
if (frames == last_frames) return error.IdleTimeout;
last_frames = frames;
continue;
},
error.Canceled => return error.Canceled,
};
// readLoop finished on its own (close frame, socket error, stop)
future.await(self.io);
joined = true;
if (read_err) |err| return err;
return;
}
} else {
try client.readLoop(&ws_handler);
}
}
};
}
/// true iff the handler declares shouldStop and it currently returns true
fn stopRequested(handler: anytype) bool {
if (comptime @hasDecl(@TypeOf(handler.*), "shouldStop")) {
return handler.shouldStop();
}
return false;
}
fn WsHandler(comptime Client: type, comptime H: type) type {
return struct {
allocator: Allocator,
handler: *H,
client_state: *Client,
const Self = @This();
pub fn serverMessage(self: *Self, data: []const u8) !void {
_ = self.client_state.frames_this_connection.fetchAdd(1, .monotonic);
if (comptime @hasDecl(H, "shouldStop")) {
// breaks the read loop; subscribe sees the stop and returns
if (self.handler.shouldStop()) return error.SubscriptionStopped;
}
if (comptime @hasDecl(H, "onRawFrame")) {
// A frame is reconnect-safe only after the downstream accepts
// it. Peeking before the callback is cheap, but publishing the
// cursor before a bounded/fallible pipeline accepts the frame
// can turn a local failure into silent upstream data loss.
const seq = peekSeq(self.allocator, data);
const result = self.handler.onRawFrame(data);
if (comptime @TypeOf(result) != void) try result;
if (seq) |s| self.client_state.last_seq = s;
return;
}
var arena = std.heap.ArenaAllocator.init(self.allocator);
defer arena.deinit();
const event = Client.Stream.decode(arena.allocator(), data) catch |err| {
log.debug("frame decode error: {s}", .{@errorName(err)});
return;
};
if (event.seq()) |s| {
self.client_state.last_seq = s;
}
self.handler.onEvent(event);
}
pub fn close(_: *Self) void {
log.info("firehose connection closed", .{});
}
};
}
// === tests ===
test "decode frame header" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
// simulate a frame: header {op: 1, t: "#info"} + payload {name: "OutdatedCursor"}
const header_bytes = [_]u8{
0xa2, // map(2)
0x61, 't', 0x65, '#', 'i', 'n', 'f', 'o', // "t": "#info"
0x62, 'o', 'p', 0x01, // "op": 1
};
const payload_bytes = [_]u8{
0xa1, // map(1)
0x64, 'n', 'a', 'm', 'e', // "name"
0x6e, 'O', 'u', 't', 'd', 'a', 't', 'e', 'd', 'C', 'u', 'r', 's', 'o', 'r', // "OutdatedCursor"
};
var frame: [header_bytes.len + payload_bytes.len]u8 = undefined;
@memcpy(frame[0..header_bytes.len], &header_bytes);
@memcpy(frame[header_bytes.len..], &payload_bytes);
const event = try decodeFrame(alloc, &frame);
const info = event.info;
try std.testing.expectEqualStrings("OutdatedCursor", info.name.?);
}
test "decode identity frame" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
// build frame via encoder for cleaner test
const original = Event{ .identity = .{
.seq = 42,
.did = "did:plc:test",
.time = "2024-01-15T10:30:00Z",
} };
const frame = try encodeFrame(alloc, original);
const event = try decodeFrame(alloc, frame);
const identity = event.identity;
try std.testing.expectEqual(@as(i64, 42), identity.seq);
try std.testing.expectEqualStrings("did:plc:test", identity.did);
try std.testing.expectEqualStrings("2024-01-15T10:30:00Z", identity.time);
}
test "Event.seq works" {
const info_event = Event{ .info = .{ .name = "test" } };
try std.testing.expect(info_event.seq() == null);
const identity_event = Event{ .identity = .{
.seq = 42,
.did = "did:plc:test",
.time = "2024-01-15T10:30:00Z",
} };
try std.testing.expectEqual(@as(i64, 42), identity_event.seq().?);
}
// === encoder tests ===
test "encode → decode info frame" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
const original = Event{ .info = .{
.name = "OutdatedCursor",
.message = "cursor is behind",
} };
const frame = try encodeFrame(alloc, original);
const decoded = try decodeFrame(alloc, frame);
try std.testing.expectEqualStrings("OutdatedCursor", decoded.info.name.?);
try std.testing.expectEqualStrings("cursor is behind", decoded.info.message.?);
}
test "encode → decode identity frame" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
const original = Event{ .identity = .{
.seq = 42,
.did = "did:plc:test123",
.time = "2024-01-15T10:30:00Z",
.handle = "alice.bsky.social",
} };
const frame = try encodeFrame(alloc, original);
const decoded = try decodeFrame(alloc, frame);
const id = decoded.identity;
try std.testing.expectEqual(@as(i64, 42), id.seq);
try std.testing.expectEqualStrings("did:plc:test123", id.did);
try std.testing.expectEqualStrings("2024-01-15T10:30:00Z", id.time);
try std.testing.expectEqualStrings("alice.bsky.social", id.handle.?);
}
test "encode → decode account frame" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
const original = Event{ .account = .{
.seq = 100,
.did = "did:plc:suspended",
.time = "2024-01-15T10:30:00Z",
.active = false,
.status = .suspended,
} };
const frame = try encodeFrame(alloc, original);
const decoded = try decodeFrame(alloc, frame);
const acct = decoded.account;
try std.testing.expectEqual(@as(i64, 100), acct.seq);
try std.testing.expectEqualStrings("did:plc:suspended", acct.did);
try std.testing.expectEqualStrings("2024-01-15T10:30:00Z", acct.time);
try std.testing.expectEqual(false, acct.active);
try std.testing.expectEqual(AccountStatus.suspended, acct.status.?);
}
test "encode → decode commit frame with record" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
const record: cbor.Value = .{ .map = &.{
.{ .key = "$type", .value = .{ .text = "app.bsky.feed.post" } },
.{ .key = "text", .value = .{ .text = "hello firehose" } },
} };
const commit_cid = try cbor.Cid.forDagCbor(alloc, "commit");
const prev_data = try cbor.Cid.forDagCbor(alloc, "prev-data");
const original = Event{ .commit = .{
.seq = 999,
.repo = "did:plc:poster",
.rev = "3k2abc000000",
.time = "2024-01-15T10:30:00Z",
.since = "3k2abd000000",
.commit = commit_cid,
.prev_data = prev_data,
.ops = &.{.{
.action = .create,
.collection = "app.bsky.feed.post",
.rkey = "3k2abc",
.record = record,
}},
} };
const frame = try encodeFrame(alloc, original);
const decoded = try decodeFrame(alloc, frame);
const commit = decoded.commit;
try std.testing.expectEqual(@as(i64, 999), commit.seq);
try std.testing.expectEqualStrings("did:plc:poster", commit.repo);
try std.testing.expectEqualStrings("3k2abc000000", commit.rev);
try std.testing.expectEqualStrings("2024-01-15T10:30:00Z", commit.time);
try std.testing.expectEqualStrings("3k2abd000000", commit.since.?);
try std.testing.expectEqualSlices(u8, commit_cid.raw, commit.commit.?.raw);
try std.testing.expect(commit.blocks.len > 0);
try std.testing.expectEqualSlices(u8, prev_data.raw, commit.prev_data.?.raw);
try std.testing.expectEqual(@as(usize, 0), commit.blobs.len);
try std.testing.expectEqual(@as(usize, 1), commit.ops.len);
const op = commit.ops[0];
try std.testing.expectEqual(CommitAction.create, op.action);
try std.testing.expectEqualStrings("app.bsky.feed.post/3k2abc", op.path);
try std.testing.expectEqualStrings("app.bsky.feed.post", op.collection);
try std.testing.expectEqualStrings("3k2abc", op.rkey);
try std.testing.expect(op.cid != null);
// record should be decoded from the CAR blocks
const rec = op.record.?;
try std.testing.expectEqualStrings("hello firehose", rec.getString("text").?);
try std.testing.expectEqualStrings("app.bsky.feed.post", rec.getString("$type").?);
const mst_ops = try commit.toMstOperations(alloc);
try std.testing.expectEqual(@as(usize, 1), mst_ops.len);
try std.testing.expectEqualStrings("app.bsky.feed.post/3k2abc", mst_ops[0].path);
try std.testing.expectEqualSlices(u8, op.cid.?.raw, mst_ops[0].value.?);
try std.testing.expect(mst_ops[0].prev == null);
}
test "encoded commit CAR lists the commit CID as its first root" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
const commit_cid = try cbor.Cid.forDagCbor(alloc, "commit");
const with_record = try encodeFrame(alloc, .{ .commit = .{
.seq = 1,
.repo = "did:plc:poster",
.rev = "3k2abc000000",
.time = "2024-01-15T10:30:00Z",
.commit = commit_cid,
.ops = &.{.{
.action = .create,
.collection = "app.bsky.feed.post",
.rkey = "3k2abc",
.record = .{ .map = &.{.{ .key = "text", .value = .{ .text = "hi" } }} },
}},
} });
const decoded = try decodeFrame(alloc, with_record);
const parsed = try car.read(alloc, decoded.commit.blocks);
try std.testing.expectEqualSlices(u8, commit_cid.raw, parsed.roots[0].raw);
try std.testing.expectEqualStrings("hi", decoded.commit.ops[0].record.?.getString("text").?);
const without_ops = try encodeCommitEvent(alloc, .{
.seq = 2,
.repo_did = "did:plc:poster",
.commit_cid = commit_cid,
.rev = "2222222222222",
.blocks = "",
.ops = &.{},
.time = "2024-01-15T10:30:00Z",
});
const empty = try car.read(alloc, (try decodeFrame(alloc, without_ops)).commit.blocks);
try std.testing.expectEqualSlices(u8, commit_cid.raw, empty.roots[0].raw);
try std.testing.expectEqual(@as(usize, 0), empty.blocks.len);
}
test "encode → decode commit with delete (no record)" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
const commit_cid = try cbor.Cid.forDagCbor(alloc, "commit");
const prev_data = try cbor.Cid.forDagCbor(alloc, "prev-data");
const prev_record = try cbor.Cid.forDagCbor(alloc, "prev-record");
const original = Event{ .commit = .{
.seq = 500,
.repo = "did:plc:deleter",
.rev = "3k2xyz000000",
.time = "2024-01-15T10:30:00Z",
.commit = commit_cid,
.prev_data = prev_data,
.ops = &.{.{
.action = .delete,
.collection = "app.bsky.feed.post",
.rkey = "abc123",
.prev = prev_record,
.record = null,
}},
} };
const frame = try encodeFrame(alloc, original);
const decoded = try decodeFrame(alloc, frame);
try std.testing.expectEqual(@as(i64, 500), decoded.commit.seq);
try std.testing.expectEqualStrings("3k2xyz000000", decoded.commit.rev);
try std.testing.expectEqualStrings("2024-01-15T10:30:00Z", decoded.commit.time);
try std.testing.expectEqual(@as(usize, 1), decoded.commit.ops.len);
try std.testing.expectEqual(CommitAction.delete, decoded.commit.ops[0].action);
try std.testing.expect(decoded.commit.ops[0].cid == null);
try std.testing.expectEqualSlices(u8, prev_record.raw, decoded.commit.ops[0].prev.?.raw);
try std.testing.expect(decoded.commit.ops[0].record == null);
}
test "encode → decode commit with null prevData" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
const commit_cid = try cbor.Cid.forDagCbor(alloc, "commit");
const original = Event{ .commit = .{
.seq = 501,
.repo = "did:plc:initial",
.rev = "3k2xyz000001",
.time = "2024-01-15T10:30:00Z",
.since = null,
.commit = commit_cid,
.blocks = "car bytes",
.prev_data = null,
.ops = &.{},
} };
const frame = try encodeFrame(alloc, original);
const decoded = try decodeFrame(alloc, frame);
try std.testing.expectEqual(@as(i64, 501), decoded.commit.seq);
try std.testing.expectEqualStrings("did:plc:initial", decoded.commit.repo);
try std.testing.expectEqualStrings("3k2xyz000001", decoded.commit.rev);
try std.testing.expect(decoded.commit.since == null);
try std.testing.expect(decoded.commit.prev_data == null);
try std.testing.expectEqualStrings("car bytes", decoded.commit.blocks);
}
test "commit op paths are validated" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
const commit_cid = try cbor.Cid.forDagCbor(alloc, "commit");
const event = Event{ .commit = .{
.seq = 502,
.repo = "did:plc:badpath",
.rev = "3k2xyz000002",
.time = "2024-01-15T10:30:00Z",
.commit = commit_cid,
.blocks = "car bytes",
.prev_data = null,
.ops = &.{.{
.action = .create,
.path = "app.bsky.feed.post/not/one/rkey",
.collection = "app.bsky.feed.post",
.rkey = "unused",
}},
} };
try std.testing.expectError(error.InvalidRepoPath, encodeFrame(alloc, event));
}
test "repo path decoding preserves invalid paths for downstream policy" {
const no_slash = splitRepoPath("nosslashatall");
try std.testing.expectEqualStrings("nosslashatall", no_slash.collection);
try std.testing.expectEqualStrings("", no_slash.rkey);
const extra_slash = splitRepoPath("app.bsky.feed.post/bad/key");
try std.testing.expectEqualStrings("app.bsky.feed.post", extra_slash.collection);
try std.testing.expectEqualStrings("bad/key", extra_slash.rkey);
try std.testing.expectError(error.InvalidRepoPath, parseRepoPath("nosslashatall"));
try std.testing.expectError(error.InvalidRepoPath, parseRepoPath("app.bsky.feed.post/bad/key"));
}
test "validate commit event accepts structurally valid event" {
const alloc = std.testing.allocator;
const commit_cid = try cbor.Cid.forDagCbor(alloc, "commit");
defer alloc.free(commit_cid.raw);
const record_cid = try cbor.Cid.forDagCbor(alloc, "record");
defer alloc.free(record_cid.raw);
const prev_record_cid = try cbor.Cid.forDagCbor(alloc, "prev-record");
defer alloc.free(prev_record_cid.raw);
const rev = Tid.fromTimestamp(1704067200000000, 1);
const since = Tid.fromTimestamp(1704067100000000, 1);
try validateCommitEvent(.{
.seq = 600,
.repo = "did:plc:validator",
.rev = &rev.str(),
.time = "2024-01-15T10:30:00Z",
.since = &since.str(),
.commit = commit_cid,
.blocks = "car bytes",
.ops = &.{
.{
.action = .create,
.path = "app.bsky.feed.post/3k2valid",
.collection = "unused.invalid.value",
.rkey = "unused",
.cid = record_cid,
},
.{
.action = .update,
.collection = "app.bsky.feed.post",
.rkey = "3k2valid",
.cid = record_cid,
.prev = prev_record_cid,
},
.{
.action = .delete,
.collection = "app.bsky.feed.post",
.rkey = "3k2delete",
.prev = prev_record_cid,
},
},
});
}
test "validate commit event rejects commit CID in since" {
const alloc = std.testing.allocator;
const commit_cid = try cbor.Cid.forDagCbor(alloc, "commit");
defer alloc.free(commit_cid.raw);
const rev = Tid.fromTimestamp(1704067200000000, 1);
try std.testing.expectError(error.InvalidSince, validateCommitEvent(.{
.seq = 601,
.repo = "did:plc:validator",
.rev = &rev.str(),
.time = "2024-01-15T10:30:00Z",
.since = "bafyreihyrpefhacm2x43w6c5ylz6dibjtnfubn2noldubqefbzzrskc6sy",
.commit = commit_cid,
.blocks = "car bytes",
.ops = &.{},
}));
}
test "validate commit event enforces op CID nullability" {
const alloc = std.testing.allocator;
const commit_cid = try cbor.Cid.forDagCbor(alloc, "commit");
defer alloc.free(commit_cid.raw);
const record_cid = try cbor.Cid.forDagCbor(alloc, "record");
defer alloc.free(record_cid.raw);
const prev_record_cid = try cbor.Cid.forDagCbor(alloc, "prev-record");
defer alloc.free(prev_record_cid.raw);
const rev = Tid.fromTimestamp(1704067200000000, 1);
try std.testing.expectError(error.MissingRecordCid, validateCommitEvent(.{
.seq = 602,
.repo = "did:plc:validator",
.rev = &rev.str(),
.time = "2024-01-15T10:30:00Z",
.commit = commit_cid,
.ops = &.{.{
.action = .create,
.collection = "app.bsky.feed.post",
.rkey = "3k2missing",
}},
}));
try std.testing.expectError(error.UnexpectedRecordCid, validateCommitEvent(.{
.seq = 603,
.repo = "did:plc:validator",
.rev = &rev.str(),
.time = "2024-01-15T10:30:00Z",
.commit = commit_cid,
.ops = &.{.{
.action = .delete,
.collection = "app.bsky.feed.post",
.rkey = "3k2delete",
.cid = record_cid,
}},
}));
try std.testing.expectError(error.UnexpectedPrevRecordCid, validateCommitEvent(.{
.seq = 604,
.repo = "did:plc:validator",
.rev = &rev.str(),
.time = "2024-01-15T10:30:00Z",
.commit = commit_cid,
.ops = &.{.{
.action = .create,
.collection = "app.bsky.feed.post",
.rkey = "3k2create",
.cid = record_cid,
.prev = prev_record_cid,
}},
}));
}
test "commit event builder names since as since_rev" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
const commit_cid = try cbor.Cid.forDagCbor(alloc, "commit");
const record_cid = try cbor.Cid.forDagCbor(alloc, "record");
const rev = Tid.fromTimestamp(1704067200000000, 1);
const since = Tid.fromTimestamp(1704067100000000, 1);
const frame = try encodeCommitEvent(alloc, .{
.seq = 700,
.repo_did = "did:plc:builder",
.commit_cid = commit_cid,
.rev = &rev.str(),
.since_rev = &since.str(),
.prev_data = null,
.blocks = "car bytes",
.ops = &.{.{
.action = .create,
.collection = "app.bsky.feed.post",
.rkey = "3k2builder",
.cid = record_cid,
}},
.time = "2024-01-15T10:30:00Z",
.rebase = true,
});
const decoded = try decodeFrame(alloc, frame);
try std.testing.expectEqual(@as(i64, 700), decoded.commit.seq);
try std.testing.expectEqualStrings("did:plc:builder", decoded.commit.repo);
try std.testing.expectEqualStrings(&rev.str(), decoded.commit.rev);
try std.testing.expectEqualStrings(&since.str(), decoded.commit.since.?);
try std.testing.expect(decoded.commit.prev_data == null);
try std.testing.expect(decoded.commit.rebase);
try std.testing.expectEqual(@as(usize, 1), decoded.commit.ops.len);
try std.testing.expectEqualStrings("app.bsky.feed.post/3k2builder", decoded.commit.ops[0].path);
try std.testing.expectEqualSlices(u8, record_cid.raw, decoded.commit.ops[0].cid.?.raw);
}
test "commit event payload carries every field subscribeRepos requires" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
const commit_cid = try cbor.Cid.forDagCbor(alloc, "commit");
const rev = Tid.fromTimestamp(1704067200000000, 1);
const frame = try encodeCommitEvent(alloc, .{
.seq = 702,
.repo_did = "did:plc:builder",
.commit_cid = commit_cid,
.rev = &rev.str(),
.since_rev = null,
.prev_data = null,
.blocks = "car bytes",
.ops = &.{},
.time = "2024-01-15T10:30:00Z",
});
const header = try cbor.decode(alloc, frame);
const payload = try cbor.decodeAll(alloc, frame[header.consumed..]);
const required = [_][]const u8{ "seq", "rebase", "tooBig", "repo", "commit", "rev", "since", "blocks", "ops", "blobs", "time" };
for (required) |key| {
if (payload.get(key) == null) {
std.debug.print("missing required #commit field {s}\n", .{key});
return error.TestExpectedEqual;
}
}
try std.testing.expect(payload.get("since").? == .null);
try std.testing.expectEqual(false, payload.getBool("rebase").?);
try std.testing.expectEqual(false, payload.getBool("tooBig").?);
}
test "account event payload carries active when the account is active" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
const frame = try encodeFrame(alloc, .{ .account = .{
.seq = 703,
.did = "did:plc:builder",
.time = "2024-01-15T10:30:00Z",
} });
const header = try cbor.decode(alloc, frame);
const payload = try cbor.decodeAll(alloc, frame[header.consumed..]);
try std.testing.expectEqual(true, payload.getBool("active").?);
}
test "commit event builder rejects commit CID as since_rev" {
const alloc = std.testing.allocator;
const commit_cid = try cbor.Cid.forDagCbor(alloc, "commit");
defer alloc.free(commit_cid.raw);
const rev = Tid.fromTimestamp(1704067200000000, 1);
try std.testing.expectError(error.InvalidSince, encodeCommitEvent(alloc, .{
.seq = 701,
.repo_did = "did:plc:builder",
.commit_cid = commit_cid,
.rev = &rev.str(),
.since_rev = "bafyreihyrpefhacm2x43w6c5ylz6dibjtnfubn2noldubqefbzzrskc6sy",
.prev_data = null,
.blocks = "car bytes",
.ops = &.{},
.time = "2024-01-15T10:30:00Z",
}));
}
test "encode → decode sync frame" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
const original = Event{ .sync = .{
.seq = 777,
.did = "did:plc:sync",
.rev = "3k2sync00000",
.time = "2024-01-15T10:30:00Z",
.blocks = "car bytes",
} };
const frame = try encodeFrame(alloc, original);
const decoded = try decodeFrame(alloc, frame);
try std.testing.expectEqual(@as(i64, 777), decoded.sync.seq);
try std.testing.expectEqualStrings("did:plc:sync", decoded.sync.did);
try std.testing.expectEqualStrings("3k2sync00000", decoded.sync.rev);
try std.testing.expectEqualStrings("car bytes", decoded.sync.blocks);
}
test "identity event encoder round-trips and validates the DID" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
const with_handle = try decodeFrame(alloc, try encodeIdentityEvent(alloc, .{
.seq = 9,
.did = "did:plc:identity",
.time = "2024-01-15T10:30:00Z",
.handle = "alice.example.com",
}));
try std.testing.expectEqual(@as(i64, 9), with_handle.identity.seq);
try std.testing.expectEqualStrings("did:plc:identity", with_handle.identity.did);
try std.testing.expectEqualStrings("2024-01-15T10:30:00Z", with_handle.identity.time);
try std.testing.expectEqualStrings("alice.example.com", with_handle.identity.handle.?);
const frame = try encodeIdentityEvent(alloc, .{ .seq = 10, .did = "did:plc:identity", .time = "2024-01-15T10:30:00Z" });
try std.testing.expect((try decodeFrame(alloc, frame)).identity.handle == null);
const header = try cbor.decode(alloc, frame);
const payload = try cbor.decodeAll(alloc, frame[header.consumed..]);
try std.testing.expect(payload.get("handle") == null);
try std.testing.expectError(error.InvalidDid, encodeIdentityEvent(alloc, .{ .seq = 11, .did = "not-a-did", .time = "2024-01-15T10:30:00Z" }));
}
test "account event encoder round-trips and keeps status to inactive accounts" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
const active = (try decodeFrame(alloc, try encodeAccountEvent(alloc, .{
.seq = 20,
.did = "did:plc:account",
.time = "2024-01-15T10:30:00Z",
}))).account;
try std.testing.expectEqual(@as(i64, 20), active.seq);
try std.testing.expect(active.active);
try std.testing.expect(active.status == null);
const deleted = (try decodeFrame(alloc, try encodeAccountEvent(alloc, .{
.seq = 21,
.did = "did:plc:account",
.time = "2024-01-15T10:30:00Z",
.active = false,
.status = .deleted,
}))).account;
try std.testing.expect(!deleted.active);
try std.testing.expectEqual(AccountStatus.deleted, deleted.status.?);
try std.testing.expectError(error.StatusOnActiveAccount, encodeAccountEvent(alloc, .{
.seq = 22,
.did = "did:plc:account",
.time = "2024-01-15T10:30:00Z",
.status = .takendown,
}));
try std.testing.expectError(error.InvalidDid, encodeAccountEvent(alloc, .{ .seq = 23, .did = "", .time = "2024-01-15T10:30:00Z" }));
}
test "info event encoder requires a name" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
const info = (try decodeFrame(alloc, try encodeInfoEvent(alloc, .{ .name = "OutdatedCursor" }))).info;
try std.testing.expectEqualStrings("OutdatedCursor", info.name.?);
try std.testing.expect(info.message == null);
try std.testing.expectError(error.MissingField, encodeInfoEvent(alloc, .{ .message = "no name" }));
}
fn testCommitBlock(alloc: Allocator, did: []const u8, rev: []const u8) ![]u8 {
const data = try cbor.Cid.forDagCbor(alloc, "mst root");
return cbor.encodeAlloc(alloc, .{ .map = &.{
.{ .key = "did", .value = .{ .text = did } },
.{ .key = "rev", .value = .{ .text = rev } },
.{ .key = "sig", .value = .{ .bytes = &(@as([64]u8, @splat(7))) } },
.{ .key = "data", .value = .{ .cid = data } },
.{ .key = "prev", .value = .null },
.{ .key = "version", .value = .{ .unsigned = 3 } },
} });
}
test "sync event encoder roots its CAR at the commit" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
const rev = Tid.fromTimestamp(1704067200000000, 1);
const commit = try testCommitBlock(alloc, "did:plc:sync", &rev.str());
const frame = try encodeSyncEvent(alloc, .{ .seq = 30, .commit = commit, .time = "2024-01-15T10:30:00Z" });
const header = try cbor.decode(alloc, frame);
const payload = try cbor.decodeAll(alloc, frame[header.consumed..]);
for ([_][]const u8{ "seq", "did", "blocks", "rev", "time" }) |key| {
if (payload.get(key) == null) {
std.debug.print("missing required #sync field {s}\n", .{key});
return error.TestExpectedEqual;
}
}
const event = (try decodeFrame(alloc, frame)).sync;
try std.testing.expectEqual(@as(i64, 30), event.seq);
try std.testing.expectEqualStrings("did:plc:sync", event.did);
try std.testing.expectEqualStrings(&rev.str(), event.rev);
try std.testing.expectEqualStrings("2024-01-15T10:30:00Z", event.time);
const commit_cid = try cbor.Cid.forDagCbor(alloc, commit);
const blocks = try car.read(alloc, event.blocks);
try std.testing.expectEqualSlices(u8, commit_cid.raw, blocks.roots[0].raw);
try std.testing.expectEqual(@as(usize, 1), blocks.blocks.len);
try std.testing.expectEqualSlices(u8, commit, car.findBlock(blocks, commit_cid.raw).?);
}
test "sync event encoder rejects a block that is not a commit" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
const rev = Tid.fromTimestamp(1704067200000000, 1);
const no_did = try cbor.encodeAlloc(alloc, .{ .map = &.{.{ .key = "rev", .value = .{ .text = &rev.str() } }} });
const no_rev = try cbor.encodeAlloc(alloc, .{ .map = &.{.{ .key = "did", .value = .{ .text = "did:plc:sync" } }} });
const bad_did = try testCommitBlock(alloc, "did:sync", &rev.str());
const bad_rev = try testCommitBlock(alloc, "did:plc:sync", "not-a-tid");
for ([_][]const u8{ no_did, no_rev, bad_did, bad_rev, "", &.{0xff} }) |commit| {
try std.testing.expectError(error.InvalidCommit, encodeSyncEvent(alloc, .{ .seq = 31, .commit = commit, .time = "2024-01-15T10:30:00Z" }));
}
}
test "error frame has an op -1 header without t" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
const frame = try encodeErrorFrame(alloc, "FutureCursor", "Cursor in the future.");
try std.testing.expectError(error.UnknownOp, decodeFrame(alloc, frame));
const header = try cbor.decode(alloc, frame);
try std.testing.expectEqual(@as(i64, -1), header.value.getInt("op").?);
try std.testing.expect(header.value.get("t") == null);
const payload = try cbor.decodeAll(alloc, frame[header.consumed..]);
try std.testing.expectEqualStrings("FutureCursor", payload.getString("error").?);
try std.testing.expectEqualStrings("Cursor in the future.", payload.getString("message").?);
const canonical = [_]u8{ 0xa1, 0x62, 'o', 'p', 0x20, 0xa2, 0x65 } ++ "error".* ++ [_]u8{0x6c} ++ "FutureCursor".* ++
[_]u8{0x67} ++ "message".* ++ [_]u8{0x75} ++ "Cursor in the future.".*;
try std.testing.expectEqualSlices(u8, &canonical, frame);
const bare = try encodeErrorFrame(alloc, "ConsumerTooSlow", null);
const bare_header = try cbor.decode(alloc, bare);
const bare_payload = try cbor.decodeAll(alloc, bare[bare_header.consumed..]);
try std.testing.expectEqualStrings("ConsumerTooSlow", bare_payload.getString("error").?);
try std.testing.expect(bare_payload.get("message") == null);
}
test "Endpoint.parse accepts URLs and bare hostnames" {
const bare = try Endpoint.parse("bsky.network");
try std.testing.expectEqualStrings("bsky.network", bare.host);
try std.testing.expectEqual(@as(u16, 443), bare.port);
try std.testing.expect(bare.tls);
const wss = try Endpoint.parse("wss://bsky.network/xrpc/whatever?x=1");
try std.testing.expectEqualStrings("bsky.network", wss.host);
try std.testing.expectEqual(@as(u16, 443), wss.port);
try std.testing.expect(wss.tls);
const ws = try Endpoint.parse("ws://localhost:7777");
try std.testing.expectEqualStrings("localhost", ws.host);
try std.testing.expectEqual(@as(u16, 7777), ws.port);
try std.testing.expect(!ws.tls);
const ws_default = try Endpoint.parse("ws://localhost");
try std.testing.expectEqual(@as(u16, 80), ws_default.port);
try std.testing.expectError(error.InvalidEndpoint, Endpoint.parse("https://bsky.network"));
try std.testing.expectError(error.InvalidEndpoint, Endpoint.parse("wss://"));
try std.testing.expectError(error.InvalidEndpoint, Endpoint.parse("ws://host:notaport"));
}
test "peekSeq extracts seq without full decode" {
// header {op:1, t:"#commit"} + payload {seq: 42}
const frame = [_]u8{
0xa2, 0x62, 'o', 'p', 0x01, 0x61, 't', 0x67, '#', 'c', 'o', 'm', 'm', 'i', 't',
0xa1, 0x63, 's', 'e', 'q', 0x18, 0x2a,
};
try std.testing.expectEqual(@as(?i64, 42), peekSeq(std.testing.allocator, &frame));
try std.testing.expectEqual(@as(?i64, null), peekSeq(std.testing.allocator, "junk"));
}
test "raw frame cursor advances only after downstream acceptance" {
const frame = [_]u8{
0xa2, 0x62, 'o', 'p', 0x01, 0x61, 't', 0x67, '#', 'c', 'o', 'm', 'm', 'i', 't',
0xa1, 0x63, 's', 'e', 'q', 0x18, 0x2a,
};
var client = FirehoseClient.init(std.testing.io, std.testing.allocator, .{});
defer client.deinit();
const Rejecting = struct {
calls: usize = 0,
pub fn onRawFrame(self: *@This(), _: []const u8) !void {
self.calls += 1;
return error.PipelineClosed;
}
};
var rejecting: Rejecting = .{};
var rejecting_ws: WsHandler(FirehoseClient, Rejecting) = .{
.allocator = std.testing.allocator,
.handler = &rejecting,
.client_state = &client,
};
try std.testing.expectError(error.PipelineClosed, rejecting_ws.serverMessage(&frame));
try std.testing.expectEqual(@as(usize, 1), rejecting.calls);
try std.testing.expectEqual(@as(?i64, null), client.last_seq);
const Accepting = struct {
client: *FirehoseClient,
cursor_during_callback: ?i64 = null,
pub fn onRawFrame(self: *@This(), _: []const u8) !void {
self.cursor_during_callback = self.client.last_seq;
}
};
var accepting: Accepting = .{ .client = &client };
var accepting_ws: WsHandler(FirehoseClient, Accepting) = .{
.allocator = std.testing.allocator,
.handler = &accepting,
.client_state = &client,
};
try accepting_ws.serverMessage(&frame);
try std.testing.expectEqual(@as(?i64, null), accepting.cursor_during_callback);
try std.testing.expectEqual(@as(?i64, 42), client.last_seq);
}
test "shouldStop hook: subscribe returns cleanly instead of reconnecting" {
var threaded: Io.Threaded = .init(std.testing.allocator, .{});
defer threaded.deinit();
const io = threaded.io();
const StopHandler = struct {
stop: bool = false,
errors: usize = 0,
pub fn onEvent(_: *@This(), _: Event) void {}
pub fn shouldStop(self: *@This()) bool {
return self.stop;
}
pub fn onError(self: *@This(), _: anyerror) void {
// first failed connect (port 9, nothing listening) requests stop
self.errors += 1;
self.stop = true;
}
};
var client = FirehoseClient.init(io, std.testing.allocator, .{
.hosts = &.{"ws://127.0.0.1:9"},
});
defer client.deinit();
// stop set before the first connect: returns without dialing
var pre_stopped: StopHandler = .{ .stop = true };
try client.subscribe(&pre_stopped);
try std.testing.expectEqual(@as(usize, 0), pre_stopped.errors);
// stop set from onError: returns after the first failed connect,
// without sleeping into the reconnect backoff
var stops_on_error: StopHandler = .{};
try client.subscribe(&stops_on_error);
try std.testing.expectEqual(@as(usize, 1), stops_on_error.errors);
}
test "handlers without shouldStop never stop-request" {
const Plain = struct {
pub fn onEvent(_: *@This(), _: Event) void {}
};
var h: Plain = .{};
try std.testing.expect(!stopRequested(&h));
}
test "onReconnect runs at the retry attempt boundary" {
var threaded: Io.Threaded = .init(std.testing.allocator, .{});
defer threaded.deinit();
const io = threaded.io();
const Handler = struct {
stop: bool = false,
errors: usize = 0,
reconnects: usize = 0,
pub fn onEvent(_: *@This(), _: Event) void {}
pub fn shouldStop(self: *@This()) bool {
return self.stop;
}
pub fn onError(self: *@This(), _: anyerror) void {
self.errors += 1;
if (self.errors == 2) self.stop = true;
}
pub fn onReconnect(self: *@This()) void {
self.reconnects += 1;
}
};
var client = FirehoseClient.init(io, std.testing.allocator, .{
.hosts = &.{"ws://127.0.0.1:9"},
});
defer client.deinit();
var handler: Handler = .{};
try client.subscribe(&handler);
try std.testing.expectEqual(@as(usize, 2), handler.errors);
try std.testing.expectEqual(@as(usize, 1), handler.reconnects);
}