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
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
//! backfill XRPC API — network.bsky.jetstream.{listSegments,getSegment,getBlock}
//!
//! serves the archive's sealed segments per upstream's lexicons: listSegments
//! returns JSON metadata (checksum hex == the getSegment ETag), getSegment
//! streams the raw .jss bytes, getBlock returns one block's raw stored zstd
//! frame (located via the footer's block index with positional reads — the
//! file is never loaded whole). the segment format is wire-visible contract;
//! upstream's client parses these bytes with its own segment package.
//!
//! getSegment and getBlock match upstream's http.ServeContent byte-range
//! contract, including multipart/byteranges and mixed overlap handling.
const std = @import("std");
const api_keys = @import("api_keys.zig");
const archive_mod = @import("../storage/archive.zig");
const segment = @import("../storage/segment.zig");
const import_manager = @import("../timestamp/manager.zig");
const import_jobs = @import("../timestamp/jobs.zig");
const http_time = @import("http_time.zig");
const metrics = @import("../runtime/metrics.zig");
const observability = @import("../runtime/observability.zig");
const time_format = @import("../ingest/backfill/resync.zig");
const zstd = @import("../storage/zstd.zig");
const Io = std.Io;
const Allocator = std.mem.Allocator;
const log = std.log.scoped(.stream);
pub const Preconditions = struct {
range: ?[]const u8 = null,
if_match: ?[]const u8 = null,
if_unmodified_since: ?[]const u8 = null,
if_none_match: ?[]const u8 = null,
if_modified_since: ?[]const u8 = null,
if_range: ?[]const u8 = null,
};
pub const PlanConfig = struct {
max_dids: usize = 1000,
max_collections: usize = 25,
max_entries: usize = 100_000,
whole_segment_threshold: f64 = 0.75,
};
pub const Api = struct {
allocator: Allocator,
io: Io,
archive: *archive_mod.Archive,
segment_cache_max_age_s: u64 = 0,
plan: PlanConfig = .{},
import: ?*import_manager.Manager = null,
import_token: []const u8 = "",
/// Gates the archive endpoints when non-empty, mirroring the hosted
/// Bluesky instances (Jetstream v2, 2026-08-13): live tail and
/// getZstdDictionary stay open, archive requests need a bearer key.
/// Empty = open archive — the operator's opt-in, since gating an
/// already-public surface must be a deliberate flip, not a default.
archive_api_key: []const u8 = "",
/// named, revocable, per-key-metered archive keys (api_keys.zig).
/// checked when the fleet key above does not match; null = ring
/// disabled and the single key is the only credential.
key_ring: ?*api_keys.KeyRing = null,
/// Keep one manifest planning pass in flight so public callers cannot
/// multiply CPU and response allocation with concurrent requests.
plan_mutex: Io.Mutex = .init,
/// route an /xrpc/network.bsky.jetstream.* request. returns false when
/// the path isn't ours (caller 404s).
pub fn handle(self: *Api, respond: anytype, http_method: []const u8, path: []const u8, query: []const u8, body: []const u8, authorization: ?[]const u8, preconditions: Preconditions) bool {
const prefix = "/xrpc/network.bsky.jetstream.";
if (!std.mem.startsWith(u8, path, prefix)) return false;
const method = path[prefix.len..];
const is_post = std.mem.eql(u8, http_method, "POST");
const is_get = std.mem.eql(u8, http_method, "GET");
if (std.mem.eql(u8, method, "importTimestamps")) {
if (!authorized(self.import_token, authorization)) {
respond.err(401, "AuthRequired", "invalid or missing bearer token");
return true;
}
if (!is_post) {
respond.err(405, "InvalidRequest", "importTimestamps is a procedure (POST)");
return true;
}
self.importTimestamps(respond, body);
return true;
}
if (std.mem.eql(u8, method, "getImportStatus")) {
if (!authorized(self.import_token, authorization)) {
respond.err(401, "AuthRequired", "invalid or missing bearer token");
return true;
}
if (!is_get) {
respond.err(405, "InvalidRequest", "getImportStatus is a query (GET)");
return true;
}
self.getImportStatus(respond, query);
return true;
}
const archive_method = std.mem.eql(u8, method, "planSnapshot") or
std.mem.eql(u8, method, "listSegments") or
std.mem.eql(u8, method, "getSegment") or
std.mem.eql(u8, method, "getBlock");
var metered: ?*api_keys.Entry = null;
var key_name: []const u8 = "open";
if (archive_method) {
const fleet_ok = self.archive_api_key.len > 0 and authorized(self.archive_api_key, authorization);
if (fleet_ok) key_name = "fleet";
const gated = self.archive_api_key.len > 0 or self.key_ring != null;
if (gated and !fleet_ok) {
const ring = self.key_ring orelse {
respond.unauthorized();
return true;
};
const now_us = nowUs(self.io);
metered = ring.authorize(self.io, authorization, now_us) orelse {
respond.unauthorized();
return true;
};
key_name = metered.?.name;
if (ring.precheck(self.io, metered.?, now_us)) |_| {
// the SDK's fetchWithRetry backs off on 429 (1s/2s/4s)
respond.err(429, "RateLimitExceeded", "per-key byte budget exhausted; retry shortly");
return true;
}
}
}
if (std.mem.eql(u8, method, "planSnapshot")) {
if (!is_post) {
respond.err(405, "InvalidRequest", "planSnapshot is a procedure (POST)");
return true;
}
planSnapshot(self, respond, body, key_name);
self.chargeMetered(respond, metered);
return true;
}
if (std.mem.eql(u8, method, "planBackfill")) {
// renamed upstream (655ecc5); a hard 400 naming the successor
// beats a silent 501 for the handful of pre-rename consumers
respond.err(400, "InvalidRequest", "planBackfill was renamed; call network.bsky.jetstream.planSnapshot");
return true;
}
if (!is_get) {
respond.err(405, "InvalidRequest", "queries are GET");
return true;
}
if (std.mem.eql(u8, method, "getZstdDictionary")) {
self.getZstdDictionary(respond, query, preconditions.if_none_match);
} else if (std.mem.eql(u8, method, "listSegments")) {
self.listSegments(respond, query);
} else if (std.mem.eql(u8, method, "getSegment")) {
self.getSegment(respond, query, preconditions);
} else if (std.mem.eql(u8, method, "getBlock")) {
self.getBlock(respond, query, preconditions);
} else {
respond.err(501, "MethodNotImplemented", method);
}
self.chargeMetered(respond, metered);
return true;
}
/// charge a metered key for the bytes the responder actually served.
/// post-hoc by design: the bucket may go negative and gates the NEXT
/// request, so one oversized response is always allowed through.
fn chargeMetered(self: *Api, respond: anytype, metered: ?*api_keys.Entry) void {
const entry = metered orelse return;
const ring = self.key_ring orelse return;
const bytes: u64 = if (comptime @hasDecl(@TypeOf(respond.*), "servedBytes")) respond.servedBytes() else 0;
ring.charge(self.io, entry, bytes, nowUs(self.io));
}
fn nowUs(io: Io) i64 {
return @intCast(@divTrunc(Io.Timestamp.now(io, .awake).nanoseconds, std.time.ns_per_us));
}
fn getZstdDictionary(_: *Api, respond: anytype, query: []const u8, if_none_match: ?[]const u8) void {
if (queryParam(query, "id")) |raw| {
const parsed = std.fmt.parseInt(i64, raw, 10) catch
return respond.err(400, "InvalidRequest", "id must be an integer zstd dictionary ID");
if (parsed <= 0 or parsed > std.math.maxInt(u32) or @as(u32, @intCast(parsed)) != zstd.v2_dictionary_id) {
var message: [160]u8 = undefined;
const out = std.fmt.bufPrint(&message, "no dictionary with id {d}; current dictionary id is {d}", .{ parsed, zstd.v2_dictionary_id }) catch unreachable;
return respond.err(404, "DictionaryNotFound", out);
}
}
var etag_buf: [48]u8 = undefined;
const etag = std.fmt.bufPrint(&etag_buf, "\"zstd-dict-{d}\"", .{zstd.v2_dictionary_id}) catch unreachable;
respond.dictionary(&zstd.v2_dictionary, zstd.v2_dictionary_id, etag, if_none_match != null and std.mem.eql(u8, if_none_match.?, etag));
}
fn importTimestamps(self: *Api, respond: anytype, body: []const u8) void {
const manager = self.import orelse return respond.err(503, "ImportNotReady", "timestamp import is not configured");
var parsed = std.json.parseFromSlice(std.json.Value, self.allocator, body, .{}) catch
return respond.err(400, "InvalidRequest", "malformed request body");
defer parsed.deinit();
if (parsed.value != .object) return respond.err(400, "InvalidRequest", "request body must be an object");
const path = parsed.value.object.get("path") orelse
return respond.err(400, "InvalidRequest", "missing path");
if (path != .string) return respond.err(400, "InvalidRequest", "path must be a string");
const id = manager.submit(path.string) catch |err| return switch (err) {
error.ImportJobInProgress => respond.err(409, "ImportInProgress", @errorName(err)),
error.ImportNotReady => respond.err(503, "ImportNotReady", @errorName(err)),
error.ImportPathRequired,
error.ImportPathEscape,
error.ImportPathNotFound,
error.ImportPathNotRegularFile,
=> respond.err(400, "InvalidPath", @errorName(err)),
else => respond.err(500, "InternalError", "failed to submit import"),
};
defer self.allocator.free(id);
var output: Io.Writer.Allocating = .init(self.allocator);
defer output.deinit();
var json: std.json.Stringify = .{ .writer = &output.writer };
json.write(.{ .job = id }) catch return respond.err(500, "InternalError", "failed to encode response");
respond.json(200, output.written());
}
fn getImportStatus(self: *Api, respond: anytype, query: []const u8) void {
const manager = self.import orelse return respond.err(503, "ImportNotReady", "timestamp import is not configured");
const requested = queryParam(query, "job");
var parsed = if (requested != null and requested.?.len > 0)
manager.status(requested.?) catch |err| return switch (err) {
error.ImportJobNotFound => respond.err(404, "JobNotFound", "job not found"),
else => respond.err(500, "InternalError", "failed to read import status"),
}
else
(manager.current() catch return respond.err(500, "InternalError", "failed to read import status")) orelse
return respond.err(404, "JobNotFound", "no import job has run");
defer parsed.deinit();
writeImportStatus(self.allocator, respond, parsed.value);
}
fn listSegments(self: *Api, respond: anytype, query: []const u8) void {
const limit = blk: {
const raw = queryParam(query, "limit") orelse break :blk 100;
const v = std.fmt.parseInt(usize, raw, 10) catch
return respond.err(400, "InvalidRequest", "limit must be an integer");
if (v < 1)
return respond.err(400, "InvalidRequest", "limit must be positive");
break :blk @min(v, 1000);
};
// cursor = last segment index already returned, as decimal text
const after: ?u64 = blk: {
const raw = queryParam(query, "cursor") orelse break :blk null;
break :blk std.fmt.parseInt(u64, raw, 10) catch
return respond.err(400, "InvalidRequest", "invalid cursor");
};
var arena = std.heap.ArenaAllocator.init(self.allocator);
defer arena.deinit();
const alloc = arena.allocator();
const summaries = self.archive.manifest.all(alloc) catch
return respond.err(500, "InternalError", "oom");
var out: Io.Writer.Allocating = .init(alloc);
renderSegments(summaries, limit, after, &out) catch
return respond.err(500, "InternalError", "oom");
respond.json(200, out.written());
}
fn getSegment(self: *Api, respond: anytype, query: []const u8, preconditions: Preconditions) void {
const name = queryParam(query, "name") orelse
return respond.err(400, "InvalidRequest", "missing name");
const idx = archive_mod.parseSegmentIndex(name) orelse
return respond.err(400, "InvalidRequest", "bad segment name");
_ = self.archive.manifest.segmentByIndex(idx) orelse
return respond.err(404, "SegmentNotFound", name);
// Validators, size, and bytes all come from this one freshly-opened
// descriptor. A compaction rename between manifest lookup and open
// can otherwise pair an old ETag with a new generation's bytes.
var file = self.archive.dir.openFile(self.io, name, .{}) catch
return respond.err(500, "InternalError", "failed to open segment");
defer file.close(self.io);
const stat = file.stat(self.io) catch
return respond.err(500, "InternalError", "failed to stat segment");
const header = segment.readHeaderFile(self.io, &file) catch
return respond.err(500, "InternalError", "failed to read segment header");
var hex_buf: [16]u8 = undefined;
const etag = checksumHex(&hex_buf, header.checksum);
const modified_s = stat.mtime.toSeconds();
respond.archiveModified(modified_s);
respond.archiveCacheMaxAge(self.segment_cache_max_age_s);
switch (checkPreconditions(preconditions, etag, modified_s)) {
.proceed => {},
.not_modified => return respond.notModified(etag),
.failed => return respond.preconditionFailed(etag),
}
// ServeContent-style single and multipart ranges. If-Range accepts
// either the strong ETag or the representation's exact mtime.
if (preconditions.range) |raw| range: {
if (preconditions.if_range) |candidate| {
if (!ifRangeMatches(candidate, etag, modified_s)) break :range;
}
const ranges = parseRanges(self.allocator, raw, stat.size) catch |err| switch (err) {
error.OutOfMemory => return respond.err(500, "InternalError", "oom"),
error.InvalidRange => return respond.rangeNotSatisfiable(stat.size, false),
error.NoOverlap => return respond.rangeNotSatisfiable(stat.size, true),
};
defer self.allocator.free(ranges);
if (sumRangeLengths(ranges) <= stat.size) switch (ranges.len) {
0 => break :range,
1 => {
const r = ranges[0];
respond.file(self.io, file, etag, r.start, r.end(), stat.size, true);
return;
},
else => {
var entropy: [30]u8 = undefined;
self.io.randomSecure(&entropy) catch
return respond.err(500, "InternalError", "failed to generate multipart boundary");
const boundary = std.fmt.bytesToHex(entropy, .lower);
respond.multipartFile(self.io, file, etag, &boundary, ranges, stat.size);
return;
},
};
}
respond.file(self.io, file, etag, 0, stat.size - 1, stat.size, false);
}
fn getBlock(self: *Api, respond: anytype, query: []const u8, preconditions: Preconditions) void {
var trace = GetBlockTrace.init(self.allocator);
defer trace.deinit();
const name = queryParam(query, "segment") orelse {
trace.fail(.bad_request, error.MissingSegment);
return respond.err(400, "InvalidRequest", "missing segment");
};
const block_idx = blk: {
const raw = queryParam(query, "blockIndex") orelse {
trace.fail(.bad_request, error.MissingBlockIndex);
return respond.err(400, "InvalidRequest", "missing blockIndex");
};
break :blk std.fmt.parseInt(u32, raw, 10) catch {
trace.fail(.bad_request, error.InvalidBlockIndex);
return respond.err(400, "InvalidRequest", "bad blockIndex");
};
};
const segment_idx = archive_mod.parseSegmentIndex(name) orelse {
trace.fail(.bad_request, error.InvalidSegmentName);
return respond.err(400, "InvalidRequest", "bad segment name");
};
trace.span.setAttribute(.{ .key = "segment.idx", .value = .{ .int = @intCast(segment_idx) } });
trace.span.setAttribute(.{ .key = "block.index", .value = .{ .int = @intCast(block_idx) } });
const manifest_ref = self.archive.manifest.segmentByIndex(segment_idx) orelse {
trace.fail(.not_found, error.SegmentNotFound);
return respond.err(404, "SegmentNotFound", name);
};
var file = self.archive.dir.openFile(self.io, name, .{}) catch |err| {
trace.fail(.error_result, err);
return respond.err(500, "InternalError", "failed to open segment");
};
defer file.close(self.io);
const header = segment.readHeaderFile(self.io, &file) catch |err| {
trace.fail(.error_result, err);
return respond.err(500, "InternalError", "failed to read segment header");
};
if (block_idx >= header.block_count) {
trace.fail(.not_found, error.BlockNotFound);
return respond.err(404, "BlockNotFound", "blockIndex out of range");
}
const entry = segment.readBlockIndexFile(self.io, &file, header, block_idx) catch |err| {
trace.fail(.error_result, err);
return respond.err(500, "InternalError", "failed to read block");
};
const frame = self.allocator.alloc(u8, entry.compressed_size) catch |err| {
trace.fail(.error_result, err);
return respond.err(500, "InternalError", "oom");
};
defer self.allocator.free(frame);
var frame_len_bytes: [8]u8 = undefined;
const frame_len_read = file.readPositionalAll(self.io, &frame_len_bytes, entry.offset) catch |err| {
trace.fail(.error_result, err);
return respond.err(500, "InternalError", "failed to read block");
};
if (frame_len_read != frame_len_bytes.len or std.mem.readInt(u64, &frame_len_bytes, .little) != entry.compressed_size) {
trace.fail(.error_result, error.InvalidBlockFrameLength);
return respond.err(500, "InternalError", "failed to read block");
}
const frame_read = file.readPositionalAll(self.io, frame, entry.offset + 8) catch |err| {
trace.fail(.error_result, err);
return respond.err(500, "InternalError", "failed to read block");
};
if (frame_read != frame.len) {
trace.fail(.error_result, error.ShortBlockFrame);
return respond.err(500, "InternalError", "failed to read block");
}
trace.span.setAttribute(.{ .key = "block.compressed_size", .value = .{ .int = @intCast(frame.len) } });
var checksum_buf: [16]u8 = undefined;
var etag_buf: [32]u8 = undefined;
const etag = std.fmt.bufPrint(&etag_buf, "{s}:{d}", .{ checksumHex(&checksum_buf, header.checksum), block_idx }) catch unreachable;
const modified_s = manifest_ref.mtime.toSeconds();
respond.archiveModified(modified_s);
respond.archiveCacheMaxAge(self.segment_cache_max_age_s);
switch (checkPreconditions(preconditions, etag, modified_s)) {
.proceed => {},
.not_modified => {
trace.ok();
return respond.notModified(etag);
},
.failed => {
trace.fail(.error_result, error.PreconditionFailed);
return respond.preconditionFailed(etag);
},
}
if (preconditions.range) |raw| range: {
if (preconditions.if_range) |candidate| {
if (!ifRangeMatches(candidate, etag, modified_s)) break :range;
}
const ranges = parseRanges(self.allocator, raw, frame.len) catch |err| switch (err) {
error.OutOfMemory => {
trace.fail(.error_result, err);
return respond.err(500, "InternalError", "oom");
},
error.InvalidRange => {
trace.fail(.error_result, err);
return respond.rangeNotSatisfiable(frame.len, false);
},
error.NoOverlap => {
trace.fail(.error_result, err);
return respond.rangeNotSatisfiable(frame.len, true);
},
};
defer self.allocator.free(ranges);
if (sumRangeLengths(ranges) <= frame.len) switch (ranges.len) {
0 => break :range,
1 => {
const r = ranges[0];
trace.ok();
respond.partial(frame[@intCast(r.start)..@intCast(r.start + r.length)], etag, r.start, r.end(), frame.len);
return;
},
else => {
var entropy: [30]u8 = undefined;
self.io.randomSecure(&entropy) catch |err| {
trace.fail(.error_result, err);
return respond.err(500, "InternalError", "failed to generate multipart boundary");
};
const boundary = std.fmt.bytesToHex(entropy, .lower);
trace.ok();
respond.multipartBytes(frame, etag, &boundary, ranges);
return;
},
};
}
trace.ok();
respond.raw(200, frame, etag);
}
};
const GetBlockTrace = struct {
span: observability.Span,
finished: bool = false,
fn init(allocator: Allocator) GetBlockTrace {
return .{ .span = observability.Span.start(allocator, "xrpcapi", "getBlock", observability.root_context, &.{}) };
}
fn resultLabel(result: metrics.GetBlockResult) []const u8 {
return switch (result) {
.ok => "ok",
.not_found => "not_found",
.bad_request => "bad_request",
.error_result => "error",
};
}
fn setResult(self: *GetBlockTrace, result: metrics.GetBlockResult) void {
self.span.setAttribute(.{ .key = "result", .value = .{ .string = resultLabel(result) } });
}
fn ok(self: *GetBlockTrace) void {
if (self.finished) return;
self.setResult(.ok);
self.span.succeed();
self.finished = true;
}
fn fail(self: *GetBlockTrace, result: metrics.GetBlockResult, err: anyerror) void {
if (self.finished) return;
self.setResult(result);
self.span.fail(err);
self.finished = true;
}
fn deinit(self: *GetBlockTrace) void {
if (!self.finished) self.fail(.error_result, error.GetBlockIncomplete);
self.span.deinit();
}
};
pub fn checksumHex(buf: *[16]u8, checksum: u64) []const u8 {
return std.fmt.bufPrint(buf, "{x:0>16}", .{checksum}) catch unreachable;
}
const ByteRange = struct {
start: u64,
length: u64,
fn end(self: ByteRange) u64 {
// Go's ServeContent preserves a zero-length suffix range as
// `bytes=size-(size-1)/size` with an empty body.
return if (self.length == 0) self.start - 1 else self.start + self.length - 1;
}
};
const RangeParseError = error{ InvalidRange, NoOverlap, OutOfMemory };
const TraceCapture = struct {
body: [64 * 1024]u8 = undefined,
len: usize = 0,
};
const TraceCollector = struct {
fn receive(listener: *Io.net.Server, io: Io, capture: *TraceCapture) !void {
var stream = try listener.accept(io);
defer stream.close(io);
var read_buffer: [4096]u8 = undefined;
var write_buffer: [4096]u8 = undefined;
var reader = stream.reader(io, &read_buffer);
var writer = stream.writer(io, &write_buffer);
var server = std.http.Server.init(&reader.interface, &writer.interface);
var request = try server.receiveHead();
var body_buffer: [4096]u8 = undefined;
const body_reader = request.readerExpectNone(&body_buffer);
var body_writer = std.Io.Writer.fixed(&capture.body);
_ = try body_reader.streamRemaining(&body_writer);
capture.len = body_writer.buffered().len;
try request.respond("", .{ .status = .ok, .keep_alive = false });
}
};
const TraceResponder = struct {
code: u16 = 500,
body_len: usize = 0,
fn err(self: *TraceResponder, code: u16, _: []const u8, _: []const u8) void {
self.code = code;
}
fn archiveModified(_: *TraceResponder, _: i64) void {}
fn archiveCacheMaxAge(_: *TraceResponder, _: u64) void {}
fn unauthorized(self: *TraceResponder) void {
self.code = 401;
}
fn notModified(self: *TraceResponder, _: []const u8) void {
self.code = 304;
}
fn preconditionFailed(self: *TraceResponder, _: []const u8) void {
self.code = 412;
}
fn rangeNotSatisfiable(self: *TraceResponder, _: usize, _: bool) void {
self.code = 416;
}
fn partial(self: *TraceResponder, body: []const u8, _: []const u8, _: u64, _: u64, _: usize) void {
self.code = 206;
self.body_len = body.len;
}
fn multipartBytes(self: *TraceResponder, body: []const u8, _: []const u8, _: []const u8, _: []const ByteRange) void {
self.code = 206;
self.body_len = body.len;
}
fn raw(self: *TraceResponder, code: u16, body: []const u8, _: []const u8) void {
self.code = code;
self.body_len = body.len;
}
};
test "getBlock exports canonical success and failure spans to a real offline collector" {
const testing = std.testing;
var threaded: Io.Threaded = .init(testing.allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var listener = (Io.net.IpAddress{ .ip4 = .loopback(0) }).listen(io, .{ .reuse_address = true }) catch unreachable;
defer listener.deinit(io);
var capture: TraceCapture = .{};
var collector = try io.concurrent(TraceCollector.receive, .{ &listener, io, &capture });
defer _ = collector.cancel(io) catch {};
var endpoint_buffer: [128]u8 = undefined;
const endpoint = try std.fmt.bufPrint(
&endpoint_buffer,
"OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:{d}",
.{listener.socket.address.getPort()},
);
var runtime = try observability.Runtime.init(testing.allocator, .{
.io = io,
.environment = &.{ endpoint, "OTEL_BSP_SCHEDULE_DELAY=60000" },
.service_name = "stream-getblock-contract",
.service_version = "offline",
});
defer runtime.deinit();
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var path_buffer: [Io.Dir.max_path_bytes]u8 = undefined;
const path_len = try tmp.dir.realPath(io, &path_buffer);
var archive = try archive_mod.Archive.init(testing.allocator, io, path_buffer[0..path_len]);
defer archive.deinit();
_ = try archive.append(.{
.seq = 0,
.witnessed_at = 1,
.indexed_at = 0,
.kind = .create,
.did = "did:plc:getblocktrace",
.collection = "app.bsky.feed.post",
.rkey = "3l3qo2vuowo2b",
.rev = "3l3qo2vutsw2b",
.payload = "\xa1\x64\x74\x65\x78\x74\x62\x68\x69",
}, 1);
try archive.rotate();
var api: Api = .{ .allocator = testing.allocator, .io = io, .archive = &archive };
var ok_response: TraceResponder = .{};
api.getBlock(&ok_response, "segment=seg_0000000000.jss&blockIndex=0", .{});
try testing.expectEqual(@as(u16, 200), ok_response.code);
try testing.expect(ok_response.body_len > 0);
var bad_response: TraceResponder = .{};
api.getBlock(&bad_response, "blockIndex=0", .{});
try testing.expectEqual(@as(u16, 400), bad_response.code);
try testing.expectEqual(@import("otel-api").common.ProcessResult.success, runtime.shutdown(2_000));
try collector.await(io);
const body = capture.body[0..capture.len];
for ([_][]const u8{
"getBlock",
"jetstream/xrpcapi",
"segment.idx",
"block.index",
"block.compressed_size",
"result",
"bad_request",
"MissingSegment",
}) |needle| try testing.expect(std.mem.indexOf(u8, body, needle) != null);
}
/// Exact shape of Go net/http's parseRange, which pinned upstream calls for
/// both getSegment and getBlock. Non-overlapping members are discarded when
/// another member overlaps; malformed syntax rejects the complete request.
fn parseRanges(allocator: Allocator, raw: []const u8, size: u64) RangeParseError![]ByteRange {
if (!std.mem.startsWith(u8, raw, "bytes=")) return error.InvalidRange;
var ranges: std.ArrayList(ByteRange) = .empty;
errdefer ranges.deinit(allocator);
var no_overlap = false;
var specs = std.mem.splitScalar(u8, raw["bytes=".len..], ',');
while (specs.next()) |spec_raw| {
const spec = std.mem.trim(u8, spec_raw, " \t");
if (spec.len == 0) continue;
const dash = std.mem.indexOfScalar(u8, spec, '-') orelse return error.InvalidRange;
const start_raw = std.mem.trim(u8, spec[0..dash], " \t");
const end_raw = std.mem.trim(u8, spec[dash + 1 ..], " \t");
if (start_raw.len == 0) {
if (end_raw.len == 0 or end_raw[0] == '-') return error.InvalidRange;
const suffix_signed = std.fmt.parseInt(i64, end_raw, 10) catch return error.InvalidRange;
if (suffix_signed < 0) return error.InvalidRange;
const suffix: u64 = @intCast(suffix_signed);
const length = @min(suffix, size);
try ranges.append(allocator, .{ .start = size - length, .length = length });
continue;
}
const start_signed = std.fmt.parseInt(i64, start_raw, 10) catch return error.InvalidRange;
if (start_signed < 0) return error.InvalidRange;
const start: u64 = @intCast(start_signed);
if (start >= size) {
no_overlap = true;
continue;
}
const length = if (end_raw.len == 0)
size - start
else length: {
const requested_end_signed = std.fmt.parseInt(i64, end_raw, 10) catch return error.InvalidRange;
if (requested_end_signed < 0) return error.InvalidRange;
const requested_end: u64 = @intCast(requested_end_signed);
if (requested_end < start) return error.InvalidRange;
break :length @min(requested_end, size - 1) - start + 1;
};
try ranges.append(allocator, .{ .start = start, .length = length });
}
if (no_overlap and ranges.items.len == 0) return error.NoOverlap;
return ranges.toOwnedSlice(allocator);
}
fn sumRangeLengths(ranges: []const ByteRange) u64 {
var total: u64 = 0;
for (ranges) |range| total +|= range.length;
return total;
}
const EtagToken = struct {
value: []const u8,
weak: bool,
rest: []const u8,
};
/// Exact scanner shape used by Go net/http: trim leading MIME whitespace,
/// accept W/ only with that casing, and stop the list at malformed syntax.
fn scanEtag(raw: []const u8) ?EtagToken {
const trimmed = std.mem.trim(u8, raw, " \t\r\n");
const weak = std.mem.startsWith(u8, trimmed, "W/");
const start: usize = if (weak) 2 else 0;
if (trimmed.len < start + 2 or trimmed[start] != '"') return null;
var i = start + 1;
while (i < trimmed.len) : (i += 1) switch (trimmed[i]) {
0x21, 0x23...0x7e, 0x80...0xff => {},
'"' => return .{
.value = trimmed[start + 1 .. i],
.weak = weak,
.rest = trimmed[i + 1 ..],
},
else => return null,
};
return null;
}
fn ifMatchMatches(raw: []const u8, etag: []const u8) bool {
var remaining = raw;
while (true) {
remaining = std.mem.trim(u8, remaining, " \t\r\n");
if (remaining.len == 0) return false;
if (remaining[0] == ',') {
remaining = remaining[1..];
continue;
}
if (remaining[0] == '*') return true;
const token = scanEtag(remaining) orelse return false;
if (!token.weak and std.mem.eql(u8, token.value, etag)) return true;
remaining = token.rest;
}
}
/// If-None-Match uses weak comparison, but otherwise retains Go's scanning
/// behavior: malformed syntax stops evaluation and cannot expose later tags.
fn ifNoneMatchMatches(raw: []const u8, etag: []const u8) bool {
var remaining = raw;
while (true) {
remaining = std.mem.trim(u8, remaining, " \t\r\n");
if (remaining.len == 0) return false;
if (remaining[0] == ',') {
remaining = remaining[1..];
continue;
}
if (remaining[0] == '*') return true;
const token = scanEtag(remaining) orelse return false;
if (std.mem.eql(u8, token.value, etag)) return true;
remaining = token.rest;
}
}
const PreconditionResult = enum { proceed, not_modified, failed };
fn checkPreconditions(headers: Preconditions, etag: []const u8, modified_s: i64) PreconditionResult {
// RFC 7232 section 6, in the same precedence order as net/http.
const if_match = headers.if_match orelse "";
if (if_match.len > 0) {
if (!ifMatchMatches(if_match, etag)) return .failed;
} else if (modified_s != 0) {
if (headers.if_unmodified_since) |raw| {
if (http_time.parse(raw)) |date_s| if (modified_s > date_s) return .failed;
}
}
const if_none_match = headers.if_none_match orelse "";
if (if_none_match.len > 0) {
if (ifNoneMatchMatches(if_none_match, etag)) return .not_modified;
} else if (modified_s != 0) {
if (headers.if_modified_since) |raw| {
if (http_time.parse(raw)) |date_s| if (modified_s <= date_s) return .not_modified;
}
}
return .proceed;
}
fn ifRangeMatches(raw: []const u8, etag: []const u8, modified_s: i64) bool {
if (scanEtag(raw)) |token|
return !token.weak and std.mem.eql(u8, token.value, etag);
if (modified_s == 0) return false;
return if (http_time.parse(raw)) |date_s| date_s == modified_s else false;
}
test "parseRanges matches ServeContent forms" {
const allocator = std.testing.allocator;
const Case = struct { raw: []const u8, want: []const ByteRange };
const cases = [_]Case{
.{ .raw = "bytes=0-99", .want = &.{.{ .start = 0, .length = 100 }} },
.{ .raw = "bytes=500-", .want = &.{.{ .start = 500, .length = 500 }} },
.{ .raw = "bytes=-100", .want = &.{.{ .start = 900, .length = 100 }} },
.{ .raw = "bytes=-0", .want = &.{.{ .start = 1000, .length = 0 }} },
.{ .raw = "bytes=0-5000", .want = &.{.{ .start = 0, .length = 1000 }} },
.{ .raw = "bytes=0-1, 5-9", .want = &.{ .{ .start = 0, .length = 2 }, .{ .start = 5, .length = 5 } } },
.{ .raw = "bytes=0-1, 1000-", .want = &.{.{ .start = 0, .length = 2 }} },
.{ .raw = "bytes=", .want = &.{} },
};
for (cases) |case| {
const got = try parseRanges(allocator, case.raw, 1000);
defer allocator.free(got);
try std.testing.expectEqualSlices(ByteRange, case.want, got);
}
try std.testing.expectError(error.NoOverlap, parseRanges(allocator, "bytes=1000-", 1000));
try std.testing.expectError(error.InvalidRange, parseRanges(allocator, "items=0-1", 1000));
try std.testing.expectError(error.InvalidRange, parseRanges(allocator, "bytes=4-2", 1000));
try std.testing.expectError(error.InvalidRange, parseRanges(allocator, "bytes=9223372036854775808-", 1000));
}
test "strong etag matching" {
try std.testing.expect(ifRangeMatches("\"abc:0\"", "abc:0", 123));
try std.testing.expect(ifRangeMatches("\"abc:0\", \"other\"", "abc:0", 123));
try std.testing.expect(!ifRangeMatches("\"other\", \"abc:0\"", "abc:0", 123));
try std.testing.expect(!ifRangeMatches("*", "abc:0", 123));
try std.testing.expect(!ifRangeMatches("W/\"abc:0\"", "abc:0", 123));
try std.testing.expect(ifRangeMatches("Thu, 01 Jan 1970 00:02:03 GMT", "abc:0", 123));
}
test "If-None-Match accepts weak validators" {
try std.testing.expect(ifNoneMatchMatches("W/\"abc:0\"", "abc:0"));
try std.testing.expect(ifNoneMatchMatches("\"other\", W/\"abc:0\"", "abc:0"));
try std.testing.expect(!ifNoneMatchMatches("W/\"other\"", "abc:0"));
try std.testing.expect(!ifNoneMatchMatches("bad, W/\"abc:0\"", "abc:0"));
}
test "If-Match requires a strong matching validator" {
try std.testing.expect(ifMatchMatches("\"other\", \"abc:0\"", "abc:0"));
try std.testing.expect(ifMatchMatches("*", "abc:0"));
try std.testing.expect(!ifMatchMatches("W/\"abc:0\"", "abc:0"));
try std.testing.expect(!ifMatchMatches("bad, \"abc:0\"", "abc:0"));
}
test "ServeContent precondition precedence" {
try std.testing.expectEqual(PreconditionResult.proceed, checkPreconditions(.{ .if_match = "*", .if_unmodified_since = "Thu, 01 Jan 1970 00:00:00 GMT" }, "abc", 123));
try std.testing.expectEqual(PreconditionResult.failed, checkPreconditions(.{ .if_unmodified_since = "Thu, 01 Jan 1970 00:00:00 GMT" }, "abc", 123));
try std.testing.expectEqual(PreconditionResult.not_modified, checkPreconditions(.{ .if_none_match = "W/\"abc\"" }, "abc", 123));
try std.testing.expectEqual(PreconditionResult.proceed, checkPreconditions(.{ .if_none_match = "\"other\"", .if_modified_since = "Thu, 01 Jan 1970 00:10:00 GMT" }, "abc", 123));
try std.testing.expectEqual(PreconditionResult.proceed, checkPreconditions(.{ .if_modified_since = "Thu, 01 Jan 1970 00:10:00 GMT" }, "abc", 0));
}
fn queryParam(query: []const u8, name: []const u8) ?[]const u8 {
var it = std.mem.splitScalar(u8, query, '&');
while (it.next()) |pair| {
const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue;
if (std.mem.eql(u8, pair[0..eq], name)) return pair[eq + 1 ..];
}
return null;
}
fn authorized(configured: []const u8, header: ?[]const u8) bool {
const raw = header orelse "";
const prefix = "Bearer ";
const valid_scheme = raw.len >= prefix.len and std.ascii.eqlIgnoreCase(raw[0..prefix.len], prefix);
const presented = if (valid_scheme) raw[prefix.len..] else "";
var expected_hash: [32]u8 = undefined;
var presented_hash: [32]u8 = undefined;
std.crypto.hash.sha2.Sha256.hash(configured, &expected_hash, .{});
std.crypto.hash.sha2.Sha256.hash(presented, &presented_hash, .{});
return configured.len > 0 and valid_scheme and
std.crypto.timing_safe.eql([32]u8, expected_hash, presented_hash);
}
fn writeImportStatus(allocator: Allocator, respond: anytype, record: import_jobs.Record) void {
var output: Io.Writer.Allocating = .init(allocator);
defer output.deinit();
var json: std.json.Stringify = .{ .writer = &output.writer };
json.beginObject() catch return respond.err(500, "InternalError", "failed to encode response");
json.objectField("job") catch return;
json.write(record.id) catch return;
json.objectField("state") catch return;
json.write(@tagName(record.state)) catch return;
json.objectField("phase") catch return;
json.write(@tagName(record.phase)) catch return;
if (record.error_message.len > 0) {
json.objectField("error") catch return;
json.write(record.error_message) catch return;
}
if (record.submitted_at_us != 0) {
var time_buffer: [40]u8 = undefined;
json.objectField("submittedAt") catch return;
json.write(formatMillis(&time_buffer, record.submitted_at_us)) catch return;
}
if (record.finished_at_us != 0) {
var time_buffer: [40]u8 = undefined;
json.objectField("finishedAt") catch return;
json.write(formatMillis(&time_buffer, record.finished_at_us)) catch return;
}
inline for (.{
.{ "bucketed", record.bucketed },
.{ "segmentsToApply", record.segments_to_apply },
.{ "segmentsApplied", record.segments_applied },
.{ "rowsTotal", record.rows_total },
.{ "rowsValid", record.rows_valid },
.{ "rowsRejected", record.rows_rejected },
.{ "segmentsExamined", record.segments_examined },
.{ "segmentsPatched", record.segments_patched },
.{ "rowsMutated", record.rows_mutated },
.{ "rowsMatchedAllVersions", record.rows_matched_all_versions },
.{ "rowsMatchedSpecific", record.rows_matched_specific },
.{ "specificCidsUnmatched", record.specific_cids_unmatched },
.{ "rowsCorruptOffset", record.rows_corrupt_offset },
}) |field| {
json.objectField(field[0]) catch return;
json.write(field[1]) catch return;
}
json.endObject() catch return respond.err(500, "InternalError", "failed to encode response");
respond.json(200, output.written());
}
fn formatMillis(buffer: *[40]u8, micros: i64) []const u8 {
var full_buffer: [40]u8 = undefined;
const full = time_format.formatRfc3339(&full_buffer, micros);
@memcpy(buffer[0..23], full[0..23]);
buffer[23] = 'Z';
return buffer[0..24];
}
test "timestamp import bearer auth is fixed-width and exact" {
try std.testing.expect(authorized("secret", "Bearer secret"));
try std.testing.expect(authorized("secret", "bearer secret"));
try std.testing.expect(!authorized("", "Bearer "));
try std.testing.expect(!authorized("secret", null));
try std.testing.expect(!authorized("secret", "Basic secret"));
try std.testing.expect(!authorized("secret", "Bearer secret"));
try std.testing.expect(!authorized("secret", "Bearer SECRET"));
}
test "timestamp import status uses canonical millisecond datetime" {
var buffer: [40]u8 = undefined;
try std.testing.expectEqualStrings("2026-07-13T00:00:01.500Z", formatMillis(
&buffer,
(1783900800 + 1) * std.time.us_per_s + 500_999,
));
}
test "checksumHex is 16 lowercase hex chars" {
var buf: [16]u8 = undefined;
try std.testing.expectEqualStrings("356b4de698e8df94", checksumHex(&buf, 0x356b4de698e8df94));
try std.testing.expectEqualStrings("0000000000000001", checksumHex(&buf, 1));
}
// === planSnapshot (procedure: POST, JSON body) ===
const gloom = @import("../storage/gloom.zig");
const zstd_mod = @import("../storage/zstd.zig");
pub const PlanRequest = struct {
dids: []const []const u8 = &.{},
collections: []const []const u8 = &.{},
/// kind mask, upstream's manifest.KindMask: zero means omitted/match-all,
/// preserving the pre-kind-filter contract (v0.2.0, PR #336)
kinds: u8 = 0,
after_seq: u64 = 0,
before_seq: u64 = std.math.maxInt(u64),
};
pub const kind_commit: u8 = 1;
pub const kind_identity: u8 = 2;
pub const kind_account: u8 = 4;
pub const kind_sync: u8 = 8;
fn kindsAdmit(mask: u8, kind: u8) bool {
return mask == 0 or mask & kind != 0;
}
/// upstream manifest.sentinelKind: which public kind a DID-marker sentinel
/// collection carries (0 = a real record collection)
fn sentinelKindMask(nsid: []const u8) u8 {
if (std.mem.eql(u8, nsid, "$account")) return kind_account;
if (std.mem.eql(u8, nsid, "$identity")) return kind_identity;
if (std.mem.eql(u8, nsid, "$sync")) return kind_sync;
return 0;
}
/// Render the listSegments body. Failures propagate so the caller answers
/// 500; returning without responding would drop the request entirely.
fn renderSegments(
summaries: []const @import("../storage/manifest.zig").Summary,
limit: usize,
after: ?u64,
out: *Io.Writer.Allocating,
) !void {
var s: std.json.Stringify = .{ .writer = &out.writer };
try s.beginObject();
try s.objectField("segments");
try s.beginArray();
var emitted: usize = 0;
var last_idx: u64 = 0;
var remaining = false;
for (summaries) |meta| {
const idx = meta.idx;
if (after != null and idx <= after.?) continue;
if (emitted >= limit) {
remaining = true;
break;
}
var name_buf: [64]u8 = undefined;
const name = archive_mod.formatSegmentName(&name_buf, idx);
try s.beginObject();
try s.objectField("name");
try s.write(name);
try s.objectField("index");
try s.write(idx);
try s.objectField("sizeBytes");
try s.write(meta.size);
try s.objectField("checksum");
var hex_buf: [16]u8 = undefined;
try s.write(checksumHex(&hex_buf, meta.header.checksum));
try s.objectField("eventCount");
try s.write(meta.header.event_count);
try s.objectField("minSeq");
try s.write(meta.header.min_seq);
try s.objectField("maxSeq");
try s.write(meta.header.max_seq);
try s.objectField("minWitnessedAt");
try s.write(meta.header.min_witnessed_at);
try s.objectField("maxWitnessedAt");
try s.write(meta.header.max_witnessed_at);
try s.objectField("blockCount");
try s.write(meta.header.block_count);
try s.endObject();
emitted += 1;
last_idx = idx;
}
try s.endArray();
if (remaining) {
try s.objectField("cursor");
var cur_buf: [24]u8 = undefined;
try s.write(try std.fmt.bufPrint(&cur_buf, "{d}", .{last_idx}));
}
try s.endObject();
}
pub fn planSnapshot(self: *Api, respond: anytype, body: []const u8, key_name: []const u8) void {
var arena = std.heap.ArenaAllocator.init(self.allocator);
defer arena.deinit();
const alloc = arena.allocator();
// Exhaustion is ours, not the caller's: a 400 tells a client its valid
// request is permanently bad and it will never retry the range.
const req = parsePlanRequest(alloc, body, self.plan) catch |err| switch (err) {
error.OutOfMemory => return respond.err(500, "InternalError", "oom"),
// upstream's exact message: the request is well-formed but the
// combination can never match anything, which the caller must learn
error.NeverApplies => return respond.err(400, "InvalidRequest", "collections filter can never apply: kinds excludes commit"),
else => return respond.err(400, "InvalidRequest", "malformed plan request"),
};
self.plan_mutex.lockUncancelable(self.io);
var plan_locked = true;
defer if (plan_locked) self.plan_mutex.unlock(self.io);
const resident = self.archive.manifest.planningSegments(alloc) catch
return respond.err(500, "InternalError", "oom");
defer for (resident) |*item| item.deinit();
var out: Io.Writer.Allocating = .init(alloc);
const summary = renderPlan(self.plan, alloc, req, resident, &out) catch
return respond.err(500, "InternalError", "oom");
// Do not let a slow HTTP reader hold the planner lock while the
// already-materialized JSON is written.
plan_locked = false;
self.plan_mutex.unlock(self.io);
// one structured line per plan: the consumption ledger says how many
// bytes a key moved; this says what they were (credit-system audit
// trail). collections are query metadata in operator-private logs.
var line_buf: [512]u8 = undefined;
log.info("{s}", .{formatPlanLog(&line_buf, key_name, req, summary)});
respond.json(200, out.written());
}
/// what a plan admitted — one structured log line per plan is the audit
/// trail the consumption ledger can't carry (which collections, what
/// range, how much was planned)
pub const PlanSummary = struct {
segments: u64 = 0,
whole_segments: u64 = 0,
blocks: u64 = 0,
planned_through: u64 = 0,
sealed_tip: u64 = 0,
truncated: bool = false,
};
/// render the per-plan audit line: who asked, for what slice, and what
/// the planner admitted. bounded: at most 4 collection NSIDs are named.
pub fn formatPlanLog(buf: []u8, key_name: []const u8, req: PlanRequest, summary: PlanSummary) []const u8 {
var w: Io.Writer = .fixed(buf);
w.print("plan: key={s}", .{key_name}) catch return w.buffered();
w.print(" kinds=", .{}) catch return w.buffered();
if (req.kinds == 0) {
w.print("all", .{}) catch return w.buffered();
} else {
if (req.kinds & kind_commit != 0) w.print("c", .{}) catch return w.buffered();
if (req.kinds & kind_identity != 0) w.print("i", .{}) catch return w.buffered();
if (req.kinds & kind_account != 0) w.print("a", .{}) catch return w.buffered();
if (req.kinds & kind_sync != 0) w.print("s", .{}) catch return w.buffered();
}
w.print(" collections=", .{}) catch return w.buffered();
if (req.collections.len == 0) {
w.print("all", .{}) catch return w.buffered();
} else {
for (req.collections[0..@min(req.collections.len, 4)], 0..) |c, i| {
w.print("{s}{s}", .{ if (i == 0) "" else ",", c }) catch return w.buffered();
}
if (req.collections.len > 4) w.print(",+{d}", .{req.collections.len - 4}) catch return w.buffered();
}
w.print(" dids={d} afterSeq={d}", .{ req.dids.len, req.after_seq }) catch return w.buffered();
if (req.before_seq != std.math.maxInt(u64)) w.print(" beforeSeq={d}", .{req.before_seq}) catch return w.buffered();
w.print(" segments={d} whole={d} blocks={d} plannedThrough={d}{s}", .{
summary.segments, summary.whole_segments, summary.blocks, summary.planned_through,
if (summary.truncated) " truncated" else "",
}) catch return w.buffered();
return w.buffered();
}
/// Render the planSnapshot body. Every failure is propagated so the caller
/// answers 500; returning without responding would leave the request dropped.
fn renderPlan(
plan: PlanConfig,
alloc: Allocator,
req: PlanRequest,
resident: []@import("../storage/manifest.zig").PlanningSegment,
out: *Io.Writer.Allocating,
) !PlanSummary {
var s: std.json.Stringify = .{ .writer = &out.writer };
var segments_json: Io.Writer.Allocating = .init(alloc);
var sj: std.json.Stringify = .{ .writer = &segments_json.writer };
try sj.beginArray();
var sealed_tip: u64 = 0;
var planned_through: u64 = 0;
var entries: u64 = 0;
var segs_examined: u64 = 0;
var segs_matched: u64 = 0;
var blocks_matched: u64 = 0;
var truncated = false;
var whole_count: u64 = 0;
var last_unit_max_seq: u64 = 0;
for (resident) |*sealed| {
const idx = sealed.summary.idx;
var name_buf: [64]u8 = undefined;
const name = archive_mod.formatSegmentName(&name_buf, idx);
const header = sealed.summary.header;
const capped_max = @min(header.max_seq, req.before_seq);
sealed_tip = @max(sealed_tip, capped_max);
segs_examined += 1;
if (sealed.blocks.len == 0 or header.event_count == 0) continue;
if (header.max_seq <= req.after_seq) continue;
if (header.min_seq > req.before_seq) continue;
if (truncated) continue; // still walk for sealed_tip, plan nothing more
const matched = try matchBlocks(alloc, sealed, req);
var match_count: usize = 0;
for (matched) |m| {
if (m) match_count += 1;
}
if (match_count == 0) continue;
const density = @as(f64, @floatFromInt(match_count)) / @as(f64, @floatFromInt(matched.len));
const whole = density >= plan.whole_segment_threshold;
var admitted = matched;
if (whole) {
if (plan.max_entries > 0 and entries >= plan.max_entries and entries > 0) {
truncated = true;
continue;
}
entries += 1;
whole_count += 1;
last_unit_max_seq = header.max_seq;
} else {
admitted = try alloc.alloc(bool, matched.len);
@memset(admitted, false);
var at: usize = 0;
while (at < matched.len) {
if (!matched[at]) {
at += 1;
continue;
}
var last = at;
while (last + 1 < matched.len and matched[last + 1]) last += 1;
if (plan.max_entries > 0 and entries >= plan.max_entries and entries > 0) {
truncated = true;
break;
}
@memset(admitted[at .. last + 1], true);
entries += 1;
blocks_matched += last - at + 1;
last_unit_max_seq = sealed.blocks[last].max_seq;
at = last + 1;
}
if (countRanges(admitted) == 0) continue;
}
try sj.beginObject();
try sj.objectField("name");
try sj.write(name);
try sj.objectField("index");
try sj.write(idx);
try sj.objectField("checksum");
var hex_buf: [16]u8 = undefined;
try sj.write(checksumHex(&hex_buf, header.checksum));
try sj.objectField("minSeq");
try sj.write(header.min_seq);
try sj.objectField("maxSeq");
try sj.write(header.max_seq);
try sj.objectField("mode");
try sj.write(if (whole) "segment" else "blocks");
if (!whole) {
try sj.objectField("blocks");
try writeBlockRanges(&sj, admitted);
}
try sj.endObject();
segs_matched += 1;
if (whole) blocks_matched += match_count;
}
try sj.endArray();
planned_through = if (truncated) last_unit_max_seq else sealed_tip;
try s.beginObject();
try s.objectField("plannedThroughSeq");
try s.write(planned_through);
try s.objectField("sealedTipSeq");
try s.write(sealed_tip);
try s.objectField("segments");
try s.beginWriteRaw();
try s.writer.writeAll(segments_json.written());
s.endWriteRaw();
try s.objectField("stats");
try s.beginObject();
try s.objectField("segmentsExamined");
try s.write(segs_examined);
try s.objectField("segmentsMatched");
try s.write(segs_matched);
try s.objectField("blocksMatched");
try s.write(blocks_matched);
try s.objectField("entries");
try s.write(entries);
try s.endObject();
try s.endObject();
return .{
.segments = segs_matched,
.whole_segments = whole_count,
.blocks = blocks_matched,
.planned_through = planned_through,
.sealed_tip = sealed_tip,
.truncated = truncated,
};
}
/// which blocks of `sealed` may contain matching rows: seq-window pruned,
/// collection-bitmask intersected, per-block DID blooms consulted (a "no"
/// skips for certain — the no-false-negative contract at work)
fn matchBlocks(alloc: Allocator, sealed: *const @import("../storage/manifest.zig").PlanningSegment, req: PlanRequest) ![]bool {
const matched = try alloc.alloc(bool, sealed.blocks.len);
@memset(matched, true);
for (sealed.blocks, 0..) |info, i| {
if (info.event_count == 0 or info.max_seq <= req.after_seq or info.min_seq > req.before_seq) matched[i] = false;
}
// Upstream collectionCandidatesForSegment (v0.2.0, PR #336): the
// kinds/collections axes prune blocks together. A sentinel $-collection
// is admitted only when its kind is (previously: always) — kinds=commit
// now skips marker-only blocks; the marker-safe default (kinds omitted)
// still selects them. Real collections are admitted only while commit
// is; a collections filter that excludes commit is rejected at parse.
// A segment with no collection index at all (sealed before the index
// existed) fails open, as before: kind/collection pruning needs the
// metadata to prune soundly.
if ((req.kinds != 0 or req.collections.len > 0) and sealed.collection_index.entries.len > 0) {
const ci = sealed.collection_index;
const collection_match_all = req.collections.len == 0;
const all_real = collection_match_all and kindsAdmit(req.kinds, kind_commit);
const included = try alloc.alloc(bool, ci.entries.len);
const real = try alloc.alloc(bool, ci.entries.len);
var has_real = false;
var any_included = false;
for (ci.entries, 0..) |entry, id| {
included[id] = false;
const smask = sentinelKindMask(entry.nsid);
real[id] = smask == 0;
if (smask != 0) {
included[id] = kindsAdmit(req.kinds, smask);
} else if (kindsAdmit(req.kinds, kind_commit)) {
has_real = true;
if (!collection_match_all) {
for (req.collections) |c| {
if (std.mem.endsWith(u8, c, ".*")) {
if (std.mem.startsWith(u8, entry.nsid, c[0 .. c.len - 1])) included[id] = true;
} else if (std.mem.eql(u8, entry.nsid, c)) included[id] = true;
}
}
}
if (included[id]) any_included = true;
}
// upstream candidates.empty(): nothing this segment holds can match
const empty = !any_included and (!all_real or !has_real);
for (matched, 0..) |*m, block| {
if (!m.*) continue;
if (empty) {
m.* = false;
continue;
}
if (ci.blockRow(block) == null) continue; // missing bitmask row fails open
m.* = false;
for (included, 0..) |inc, id| {
const admit = inc or (all_real and real[id]);
if (admit and ci.blockHasCollection(block, id)) {
m.* = true;
break;
}
}
}
}
if (req.dids.len > 0) {
var segment_may_match = !sealed.segment_bloom_valid;
if (sealed.segment_bloom_valid) {
for (req.dids) |did| {
if (gloom.containsMarshaled(sealed.segment_bloom, did) catch true) {
segment_may_match = true;
break;
}
}
}
if (!segment_may_match) {
@memset(matched, false);
return matched;
}
for (matched, 0..) |*m, block| {
if (!m.*) continue;
const blob = sealed.blockBloom(block) orelse continue; // missing metadata fails open
var may_match = false;
for (req.dids) |did| {
if (gloom.containsMarshaled(blob, did) catch true) {
may_match = true;
m.* = true;
break;
}
}
m.* = may_match;
}
}
return matched;
}
fn countRanges(matched: []const bool) u64 {
var ranges: u64 = 0;
var in_range = false;
for (matched) |m| {
if (m and !in_range) ranges += 1;
in_range = m;
}
return ranges;
}
/// Write the planSnapshot blockRange lexicon exactly. These field names are
/// wire contract: upstream clients decode `first`/`last`; using different
/// names silently turns every range into block zero in permissive decoders.
fn writeBlockRanges(s: *std.json.Stringify, matched: []const bool) !void {
try s.beginArray();
var i: usize = 0;
while (i < matched.len) {
if (!matched[i]) {
i += 1;
continue;
}
var j = i;
while (j + 1 < matched.len and matched[j + 1]) j += 1;
try s.beginObject();
try s.objectField("first");
try s.write(i);
try s.objectField("last");
try s.write(j);
try s.endObject();
i = j + 1;
}
try s.endArray();
}
fn parsePlanRequest(alloc: Allocator, body: []const u8, config: PlanConfig) !PlanRequest {
var req: PlanRequest = .{};
if (body.len == 0) return req;
const parsed = try std.json.parseFromSliceLeaky(std.json.Value, alloc, body, .{});
if (parsed != .object) return error.Bad;
var has_after = false;
var has_before = false;
if (parsed.object.get("afterSeq")) |v| {
if (v != .integer or v.integer < 0) return error.Bad;
req.after_seq = @intCast(v.integer);
has_after = true;
}
if (parsed.object.get("beforeSeq")) |v| {
if (v != .integer or v.integer < 0) return error.Bad;
req.before_seq = @intCast(v.integer);
has_before = true;
}
req.dids = try parseStringArray(alloc, parsed.object.get("dids"));
req.collections = try parseStringArray(alloc, parsed.object.get("collections"));
req.kinds = try parsePlanKinds(try parseStringArray(alloc, parsed.object.get("kinds")));
if (has_after and has_before and req.before_seq <= req.after_seq) return error.Bad;
try validatePlanDids(alloc, req.dids, config.max_dids);
try validatePlanCollections(alloc, req.collections, config.max_collections);
// upstream plansnapshot.go: a collections filter that can never apply
// (kinds set and excluding commit) is a request error, not an empty plan
if (req.collections.len > 0 and req.kinds != 0 and req.kinds & kind_commit == 0)
return error.NeverApplies;
return req;
}
/// upstream validatePlanKinds: at most 4 values (the enum's size), each one
/// of commit/identity/account/sync; empty means match-all (mask 0)
fn parsePlanKinds(values: []const []const u8) !u8 {
if (values.len > 4) return error.Bad;
var mask: u8 = 0;
for (values) |v| {
if (std.mem.eql(u8, v, "commit")) {
mask |= kind_commit;
} else if (std.mem.eql(u8, v, "identity")) {
mask |= kind_identity;
} else if (std.mem.eql(u8, v, "account")) {
mask |= kind_account;
} else if (std.mem.eql(u8, v, "sync")) {
mask |= kind_sync;
} else return error.Bad;
}
return mask;
}
fn validatePlanDids(alloc: Allocator, dids: []const []const u8, max_dids: usize) !void {
var seen: std.StringHashMapUnmanaged(void) = .empty;
for (dids) |did| {
if (seen.contains(did)) continue;
if (seen.count() == max_dids) return error.Bad;
if (@import("zat").Did.parse(did) == null) return error.Bad;
try seen.put(alloc, did, {});
}
}
fn validatePlanCollections(alloc: Allocator, collections: []const []const u8, max_collections: usize) !void {
var seen: std.StringHashMapUnmanaged(void) = .empty;
for (collections) |collection| {
if (seen.contains(collection)) continue;
if (seen.count() == max_collections) return error.Bad;
if (std.mem.endsWith(u8, collection, ".*")) {
const head = collection[0 .. collection.len - 2];
const probe = try std.fmt.allocPrint(alloc, "{s}.wildcard", .{head});
if (@import("zat").Nsid.parse(probe) == null) return error.Bad;
} else if (@import("zat").Nsid.parse(collection) == null) return error.Bad;
try seen.put(alloc, collection, {});
}
}
fn parseStringArray(alloc: Allocator, v: ?std.json.Value) ![]const []const u8 {
const arr = v orelse return &.{};
if (arr != .array) return error.Bad;
var out = try alloc.alloc([]const u8, arr.array.items.len);
for (arr.array.items, 0..) |item, i| {
if (item != .string) return error.Bad;
out[i] = item.string;
}
return out;
}
test "plan block ranges use lexicon first and last fields" {
var out: Io.Writer.Allocating = .init(std.testing.allocator);
defer out.deinit();
var s: std.json.Stringify = .{ .writer = &out.writer };
try writeBlockRanges(&s, &.{ false, true, true, false, true });
try std.testing.expectEqualStrings(
"[{\"first\":1,\"last\":2},{\"first\":4,\"last\":4}]",
out.written(),
);
}
// Upstream's planner is one-sided: degraded resident metadata must include a
// block (`blockHasAnyCollection` returns true past the slice), never prune it.
// Pruning here is a silent false negative in a collection-filtered backfill.
// `.resident` is untouched because these requests carry no DIDs.
fn planFixture(
blocks: []const segment.BlockIndexEntry,
ci: *const segment.CollectionIndex,
) @import("../storage/manifest.zig").PlanningSegment {
return .{
.resident = undefined,
.summary = .{ .idx = 0, .size = 0, .mtime = undefined, .header = undefined },
.blocks = blocks,
.segment_bloom = &.{},
.segment_bloom_valid = false,
.collection_index = ci,
};
}
fn oneBlock(seq: u64) segment.BlockIndexEntry {
return .{
.offset = 0,
.compressed_size = 1,
.uncompressed_size = 1,
.event_count = 1,
.min_seq = seq,
.max_seq = seq,
.min_witnessed_at = 0,
.max_witnessed_at = 0,
};
}
test "collection filter fails open when a block has no resident bitmask row" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
const blocks = [_]segment.BlockIndexEntry{ oneBlock(1), oneBlock(2) };
var entries = [_]segment.CollectionEntry{.{ .nsid = "app.bsky.feed.post", .count = 1 }};
// one row of bitmasks for two blocks: block 1 has no resident row.
var bitmasks = [_]u8{0};
const ci: segment.CollectionIndex = .{
.entries = &entries,
.bitmasks = &bitmasks,
.bitmask_len = 1,
.buffer = &.{},
};
const sealed = planFixture(&blocks, &ci);
const matched = try matchBlocks(alloc, &sealed, .{ .collections = &.{"app.bsky.feed.post"} });
try std.testing.expect(!matched[0]); // resident row says the collection is absent
try std.testing.expect(matched[1]); // no resident row must not prune
}
test "collection filter fails open when a segment carries no collection index" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
const blocks = [_]segment.BlockIndexEntry{ oneBlock(1), oneBlock(2) };
const ci: segment.CollectionIndex = .{
.entries = &.{},
.bitmasks = &.{},
.bitmask_len = 0,
.buffer = &.{},
};
const sealed = planFixture(&blocks, &ci);
const matched = try matchBlocks(alloc, &sealed, .{ .collections = &.{"app.bsky.feed.post"} });
for (matched) |m| try std.testing.expect(m);
}
test "exact collection reporting does not fail open" {
var entries = [_]segment.CollectionEntry{.{ .nsid = "app.bsky.feed.post", .count = 1 }};
var bitmasks = [_]u8{0};
const ci: segment.CollectionIndex = .{
.entries = &entries,
.bitmasks = &bitmasks,
.bitmask_len = 1,
.buffer = &.{},
};
// inspect-segment reports membership as fact; a missing row is not a hit.
try std.testing.expect(!ci.blockHasCollection(1, 0));
try std.testing.expect(ci.blockRow(1) == null);
}
// Mirrors upstream plan_test.go's kind-mask cases (v0.2.0, PR #336): the
// kinds axis prunes blocks through the same collection index, sentinels are
// admitted per-kind instead of unconditionally, and the marker-safe default
// (kinds omitted) keeps its pre-#336 meaning.
test "plan kinds axis prunes sentinel and real blocks like upstream" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
const blocks = [_]segment.BlockIndexEntry{ oneBlock(1), oneBlock(2), oneBlock(3) };
var entries = [_]segment.CollectionEntry{
.{ .nsid = "$account", .count = 0 },
.{ .nsid = "$sync", .count = 0 },
.{ .nsid = "app.bsky.feed.post", .count = 2 },
};
// block0: $account only; block1: post only; block2: $sync + post
var bitmasks = [_]u8{ 0b001, 0b100, 0b110 };
const ci: segment.CollectionIndex = .{
.entries = &entries,
.bitmasks = &bitmasks,
.bitmask_len = 1,
.buffer = &.{},
};
const sealed = planFixture(&blocks, &ci);
// kinds=commit skips marker-only blocks (the new capability)
const commits = try matchBlocks(alloc, &sealed, .{ .kinds = kind_commit });
try std.testing.expectEqualSlices(bool, &.{ false, true, true }, commits);
// kinds=account selects only the account-marker block
const accounts = try matchBlocks(alloc, &sealed, .{ .kinds = kind_account });
try std.testing.expectEqualSlices(bool, &.{ true, false, false }, accounts);
// kinds omitted + collections: marker-safe default still admits every
// sentinel (pre-#336 behavior preserved bit-for-bit)
const legacy = try matchBlocks(alloc, &sealed, .{ .collections = &.{"app.bsky.feed.post"} });
try std.testing.expectEqualSlices(bool, &.{ true, true, true }, legacy);
// kinds=commit,account + a collections filter that matches nothing:
// only the admitted sentinel's block survives ($sync stays excluded)
const narrow = try matchBlocks(alloc, &sealed, .{
.kinds = kind_commit | kind_account,
.collections = &.{"other.example.thing"},
});
try std.testing.expectEqualSlices(bool, &.{ true, false, false }, narrow);
}
test "plan kinds validation mirrors upstream plansnapshot.go" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
const config: PlanConfig = .{};
// collections + kinds excluding commit can never apply — request error
try std.testing.expectError(error.NeverApplies, parsePlanRequest(alloc,
\\{"collections":["app.bsky.feed.post"],"kinds":["account"]}
, config));
// unknown kind value
try std.testing.expectError(error.Bad, parsePlanRequest(alloc,
\\{"kinds":["bogus"]}
, config));
// more values than the enum holds
try std.testing.expectError(error.Bad, parsePlanRequest(alloc,
\\{"kinds":["commit","commit","commit","commit","commit"]}
, config));
// valid: kinds with commit alongside collections; duplicates fold
const ok = try parsePlanRequest(alloc,
\\{"collections":["app.bsky.feed.post"],"kinds":["commit","commit","sync"]}
, config);
try std.testing.expectEqual(@as(u8, kind_commit | kind_sync), ok.kinds);
}
test "matchBlocks propagates allocation failure instead of planning a false negative" {
const blocks = [_]segment.BlockIndexEntry{oneBlock(1)};
const ci: segment.CollectionIndex = .{
.entries = &.{},
.bitmasks = &.{},
.bitmask_len = 0,
.buffer = &.{},
};
const sealed = planFixture(&blocks, &ci);
var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 0 });
try std.testing.expectError(
error.OutOfMemory,
matchBlocks(failing.allocator(), &sealed, .{ .dids = &.{"did:plc:abc"} }),
);
}
const PlanResponder = struct {
code: u16 = 0,
body: [8192]u8 = undefined,
body_len: usize = 0,
fn err(self: *PlanResponder, code: u16, _: []const u8, _: []const u8) void {
self.code = code;
}
fn json(self: *PlanResponder, code: u16, body: []const u8) void {
self.code = code;
self.body_len = @min(body.len, self.body.len);
@memcpy(self.body[0..self.body_len], body[0..self.body_len]);
}
fn written(self: *const PlanResponder) []const u8 {
return self.body[0..self.body_len];
}
// full-route tests reach the dictionary/archive paths; record the code
fn dictionary(self: *PlanResponder, _: []const u8, _: u32, _: []const u8, not_modified: bool) void {
self.code = if (not_modified) 304 else 200;
}
fn archiveModified(_: *PlanResponder, _: i64) void {}
fn archiveCacheMaxAge(_: *PlanResponder, _: u64) void {}
fn notModified(self: *PlanResponder, _: []const u8) void {
self.code = 304;
}
fn preconditionFailed(self: *PlanResponder, _: []const u8) void {
self.code = 412;
}
fn rangeNotSatisfiable(self: *PlanResponder, _: usize, _: bool) void {
self.code = 416;
}
fn partial(self: *PlanResponder, _: []const u8, _: []const u8, _: u64, _: u64, _: usize) void {
self.code = 206;
}
fn multipartBytes(self: *PlanResponder, _: []const u8, _: []const u8, _: []const u8, _: []const ByteRange) void {
self.code = 206;
}
fn raw(self: *PlanResponder, code: u16, _: []const u8, _: []const u8) void {
self.code = code;
}
fn unauthorized(self: *PlanResponder) void {
self.code = 401;
const body = "{\"error\":\"invalid bearer credential\"}";
self.body_len = body.len;
@memcpy(self.body[0..body.len], body);
}
fn file(self: *PlanResponder, _: Io, _: Io.File, _: []const u8, _: u64, _: u64, _: u64, _: bool) void {
self.code = 200;
}
fn multipartFile(self: *PlanResponder, _: Io, _: Io.File, _: []const u8, _: []const u8, _: []const ByteRange, _: u64) void {
self.code = 206;
}
};
// An allocation failure anywhere inside planning must never surface as a 200
// carrying a smaller plan. A client cannot distinguish that from "no matching
// data" and would skip the missing range forever. Sweeping the fail index
// keeps this honest as the allocation sequence changes.
// Mirrors the hosted Bluesky instances' edge contract (Jetstream v2,
// 2026-08-13): archive endpoints 401 without the configured bearer key;
// the live tail and the dictionary stay open. An EMPTY key leaves the
// archive open — gating a public surface is the operator's deliberate flip,
// the opposite default from the import token's secure-by-default 401.
test "archive api key gates plan/list/segment/block and nothing else" {
const testing = std.testing;
var threaded: Io.Threaded = .init(testing.allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var path_buffer: [Io.Dir.max_path_bytes]u8 = undefined;
const path_len = try tmp.dir.realPath(io, &path_buffer);
var archive = try archive_mod.Archive.init(testing.allocator, io, path_buffer[0..path_len]);
defer archive.deinit();
var api: Api = .{ .allocator = testing.allocator, .io = io, .archive = &archive, .archive_api_key = "sekrit" };
const gated = [_]struct { m: []const u8, p: []const u8 }{
.{ .m = "POST", .p = "/xrpc/network.bsky.jetstream.planSnapshot" },
.{ .m = "GET", .p = "/xrpc/network.bsky.jetstream.listSegments" },
.{ .m = "GET", .p = "/xrpc/network.bsky.jetstream.getSegment" },
.{ .m = "GET", .p = "/xrpc/network.bsky.jetstream.getBlock" },
};
for (gated) |g| {
var no_auth: PlanResponder = .{};
_ = api.handle(&no_auth, g.m, g.p, "", "{}", null, .{});
try testing.expectEqual(@as(u16, 401), no_auth.code);
var bad: PlanResponder = .{};
_ = api.handle(&bad, g.m, g.p, "", "{}", "Bearer wrong", .{});
try testing.expectEqual(@as(u16, 401), bad.code);
// the hosted edge's exact body: bare error field, no XRPC envelope
try testing.expectEqualStrings("{\"error\":\"invalid bearer credential\"}", bad.written());
var good: PlanResponder = .{};
_ = api.handle(&good, g.m, g.p, "", "{}", "Bearer sekrit", .{});
try testing.expect(good.code != 401);
}
// the dictionary stays open, exactly like upstream's hosted edge
var dict: PlanResponder = .{};
_ = api.handle(&dict, "GET", "/xrpc/network.bsky.jetstream.getZstdDictionary", "", "", null, .{});
try testing.expectEqual(@as(u16, 200), dict.code);
// empty key = open archive (today's public contract, unchanged)
var open_api: Api = .{ .allocator = testing.allocator, .io = io, .archive = &archive };
var open: PlanResponder = .{};
_ = open_api.handle(&open, "GET", "/xrpc/network.bsky.jetstream.listSegments", "", "", null, .{});
try testing.expect(open.code != 401);
}
test "key ring: named keys authorize, meter with 429, and revoke on reload" {
const testing = std.testing;
var threaded: Io.Threaded = .init(testing.allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var path_buffer: [Io.Dir.max_path_bytes]u8 = undefined;
const path_len = try tmp.dir.realPath(io, &path_buffer);
var archive = try archive_mod.Archive.init(testing.allocator, io, path_buffer[0..path_len]);
defer archive.deinit();
// a real key file: the ring reloads on mtime, so revocation below is
// exercised the way an operator does it — by editing the file
var key_path_buf: [Io.Dir.max_path_bytes + 32]u8 = undefined;
const key_path = try std.fmt.bufPrint(&key_path_buf, "{s}/keys.conf", .{path_buffer[0..path_len]});
{
var f = try tmp.dir.createFile(io, "keys.conf", .{});
defer f.close(io);
try f.writeStreamingAll(io, "consumer:ring-key:1\n");
}
var ring = api_keys.KeyRing.init(testing.allocator, key_path);
defer ring.deinit();
var api: Api = .{ .allocator = testing.allocator, .io = io, .archive = &archive, .archive_api_key = "fleet", .key_ring = &ring };
// ring key authorizes where the fleet key would too
var ok: PlanResponder = .{};
_ = api.handle(&ok, "GET", "/xrpc/network.bsky.jetstream.listSegments", "", "", "Bearer ring-key", .{});
try testing.expect(ok.code != 401 and ok.code != 429);
// unknown key still 401s
var bad: PlanResponder = .{};
_ = api.handle(&bad, "GET", "/xrpc/network.bsky.jetstream.listSegments", "", "", "Bearer nope", .{});
try testing.expectEqual(@as(u16, 401), bad.code);
// drive the key into deficit: the next request is a 429; the fleet
// key is unmetered and keeps working
ring.charge(io, &ring.entries.items[0], 500_000_000, Api.nowUs(io));
var throttled: PlanResponder = .{};
_ = api.handle(&throttled, "GET", "/xrpc/network.bsky.jetstream.listSegments", "", "", "Bearer ring-key", .{});
try testing.expectEqual(@as(u16, 429), throttled.code);
var fleet: PlanResponder = .{};
_ = api.handle(&fleet, "GET", "/xrpc/network.bsky.jetstream.listSegments", "", "", "Bearer fleet", .{});
try testing.expect(fleet.code != 429 and fleet.code != 401);
// revocation: rewrite the file without the key; the next authorize
// reloads (mtime changed, check throttle bypassed via last_check)
{
var f = try tmp.dir.createFile(io, "keys.conf", .{ .truncate = true });
defer f.close(io);
try f.writeStreamingAll(io, "other:different-key\n");
}
ring.last_check_us = std.math.minInt(i64);
ring.loaded_mtime_us = std.math.minInt(i64);
var revoked: PlanResponder = .{};
_ = api.handle(&revoked, "GET", "/xrpc/network.bsky.jetstream.listSegments", "", "", "Bearer ring-key", .{});
try testing.expectEqual(@as(u16, 401), revoked.code);
}
test "planBackfill never answers 200 with a short plan under allocation failure" {
const testing = std.testing;
var threaded: Io.Threaded = .init(testing.allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var path_buffer: [Io.Dir.max_path_bytes]u8 = undefined;
const path_len = try tmp.dir.realPath(io, &path_buffer);
var archive = try archive_mod.Archive.init(testing.allocator, io, path_buffer[0..path_len]);
defer archive.deinit();
for (0..6) |i| {
_ = try archive.append(.{
.seq = i,
.witnessed_at = @intCast(i + 1),
.indexed_at = 0,
.kind = .create,
.did = "did:plc:planfault",
.collection = "app.bsky.feed.post",
.rkey = "3l3qo2vuowo2b",
.rev = "3l3qo2vutsw2b",
.payload = "\xa1\x64\x74\x65\x78\x74\x62\x68\x69",
}, 1);
if (i == 2) try archive.rotate();
}
try archive.rotate();
const request = "{\"collections\":[\"app.bsky.feed.post\"]}";
var baseline_api: Api = .{ .allocator = testing.allocator, .io = io, .archive = &archive };
var baseline: PlanResponder = .{};
planSnapshot(&baseline_api, &baseline, request, "test");
try testing.expectEqual(@as(u16, 200), baseline.code);
try testing.expect(std.mem.indexOf(u8, baseline.written(), "\"segmentsMatched\":2") != null);
var unanswered: usize = 0;
for (0..256) |fail_index| {
var failing = testing.FailingAllocator.init(testing.allocator, .{ .fail_index = fail_index });
var api: Api = .{ .allocator = failing.allocator(), .io = io, .archive = &archive };
var response: PlanResponder = .{};
planSnapshot(&api, &response, request, "test");
if (response.code == 200) {
try testing.expectEqualStrings(baseline.written(), response.written());
} else if (response.code == 0) {
unanswered += 1;
} else {
try testing.expect(response.code >= 500);
}
}
// Encoding paths that return without responding are a separate defect;
// this asserts the planner does not invent a truthful-looking short plan.
try testing.expect(unanswered == 0);
}
// Same contract as planSnapshot: allocation failure must answer, and must
// never answer 200 with a truncated segment list. A client pages listSegments
// to discover the archive, so a short list silently hides sealed segments.
test "listSegments never answers 200 with a short list under allocation failure" {
const testing = std.testing;
var threaded: Io.Threaded = .init(testing.allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var path_buffer: [Io.Dir.max_path_bytes]u8 = undefined;
const path_len = try tmp.dir.realPath(io, &path_buffer);
var archive = try archive_mod.Archive.init(testing.allocator, io, path_buffer[0..path_len]);
defer archive.deinit();
for (0..6) |i| {
_ = try archive.append(.{
.seq = i,
.witnessed_at = @intCast(i + 1),
.indexed_at = 0,
.kind = .create,
.did = "did:plc:listfault",
.collection = "app.bsky.feed.post",
.rkey = "3l3qo2vuowo2b",
.rev = "3l3qo2vutsw2b",
.payload = "\xa1\x64\x74\x65\x78\x74\x62\x68\x69",
}, 1);
if (i == 2) try archive.rotate();
}
try archive.rotate();
var baseline_api: Api = .{ .allocator = testing.allocator, .io = io, .archive = &archive };
var baseline: PlanResponder = .{};
baseline_api.listSegments(&baseline, "");
try testing.expectEqual(@as(u16, 200), baseline.code);
var unanswered: usize = 0;
for (0..256) |fail_index| {
var failing = testing.FailingAllocator.init(testing.allocator, .{ .fail_index = fail_index });
var api: Api = .{ .allocator = failing.allocator(), .io = io, .archive = &archive };
var response: PlanResponder = .{};
api.listSegments(&response, "");
if (response.code == 200) {
try testing.expectEqualStrings(baseline.written(), response.written());
} else if (response.code == 0) {
unanswered += 1;
} else {
try testing.expect(response.code >= 500);
}
}
try testing.expect(unanswered == 0);
}
test "plan request rejects invalid filters and windows" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const alloc = arena.allocator();
try std.testing.expectError(error.Bad, parsePlanRequest(alloc, "{\"afterSeq\":-1}", .{}));
try std.testing.expectError(error.Bad, parsePlanRequest(alloc, "{\"afterSeq\":10,\"beforeSeq\":10}", .{}));
try std.testing.expectError(error.Bad, parsePlanRequest(alloc, "{\"dids\":[\"not-a-did\"]}", .{}));
try std.testing.expectError(error.Bad, parsePlanRequest(alloc, "{\"collections\":[\"not a collection\"]}", .{}));
_ = try parsePlanRequest(alloc, "{\"dids\":[\"did:plc:abc\"],\"collections\":[\"app.bsky.feed.*\"]}", .{});
try std.testing.expectError(error.Bad, parsePlanRequest(alloc, "{\"dids\":[\"did:plc:a\"]}", .{ .max_dids = 0 }));
try std.testing.expectError(error.Bad, parsePlanRequest(alloc, "{\"collections\":[\"app.bsky.feed.post\"]}", .{ .max_collections = 0 }));
}
test "formatPlanLog: key, kinds letters, capped collections, plan totals" {
var buf: [512]u8 = undefined;
const line = formatPlanLog(&buf, "evelyn", .{
.collections = &.{ "app.bsky.graph.follow", "a.b.c", "d.e.f", "g.h.i", "j.k.l" },
.kinds = kind_commit | kind_sync,
.after_seq = 0,
.dids = &.{},
}, .{ .segments = 6000, .whole_segments = 5800, .blocks = 91000, .planned_through = 123456, .truncated = false });
try std.testing.expectEqualStrings(
"plan: key=evelyn kinds=cs collections=app.bsky.graph.follow,a.b.c,d.e.f,g.h.i,+1 dids=0 afterSeq=0 segments=6000 whole=5800 blocks=91000 plannedThrough=123456",
line,
);
const open_line = formatPlanLog(&buf, "open", .{}, .{ .truncated = true });
try std.testing.expectEqualStrings(
"plan: key=open kinds=all collections=all dids=0 afterSeq=0 segments=0 whole=0 blocks=0 plannedThrough=0 truncated",
open_line,
);
}