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
//! loopback e2e: two in-process fake v2 instances drive the REAL unified
//! client — websocket.zig live tail, HttpTransport archive sweep — through
//! the failure modes that motivated multi-host failover (docs/failover.md):
//! a primary that dies mid-live, and a primary that goes connected-but-
//! silent (the 2026-08-16 bsky.network front wedge). the fixtures serve
//! the actual wire: listSegments/planSnapshot JSON, raw-block zstd frames
//! over getBlock, and subscribeEvents lexicon frames over a hand-rolled
//! websocket upgrade.
const std = @import("std");
const zat = @import("zat");
const archive = @import("archive_backfill.zig");
const client_mod = @import("client.zig");
const livedecode = @import("livedecode.zig");
const Io = std.Io;
const Allocator = std.mem.Allocator;
const testing = std.testing;
/// witnessed base: 2026-07-13T00:00:00Z (the livedecode fixture's day)
const epoch_s: i64 = 1783900800;
fn witnessedUs(offset_s: i64) i64 {
return (epoch_s + offset_s) * std.time.us_per_s;
}
const Row = struct {
seq: u64,
/// seconds past epoch_s (0..59: rendered into one RFC3339 minute)
t: i64,
did: []const u8 = "did:plc:loopback",
collection: []const u8 = "app.bsky.feed.post",
};
const Instance = struct {
io: Io,
allocator: Allocator,
listener: Io.net.Server,
port: u16,
sealed: []const Row,
live: []const Row,
/// close the websocket after emitting `live` (a server that dies mid-tail)
live_then_close: bool = false,
/// accept the websocket, emit nothing, hold it open (the silent wedge)
silent_ws: bool = false,
/// after this many websocket sessions, close every new connection
/// immediately (the host is down)
max_ws_sessions: u32 = std.math.maxInt(u32),
ws_sessions: u32 = 0,
wire_cursors: [32]?u64 = @splat(null),
archive_calls: usize = 0,
reject_archive: bool = false,
reject_ws_count: u32 = 0,
first_session_rows: ?usize = null,
retention_floor_us: ?u64 = null,
cursor_too_old: bool = false,
page_size: usize = 0,
page_rows: ?[]const Row = null,
plan_calls: usize = 0,
last_before_seq: ?u64 = null,
first_tip: ?u64 = null,
stalled_plan: bool = false,
archive_fault: enum { none, fetch, decode, segment } = .none,
compression: enum { none, valid, rotate, same, invalid, hang } = .none,
/// set once a .hang dictionary response has sent its head and is
/// withholding the body
dict_hung: std.atomic.Value(bool) = .init(false),
bad_compressed_first: bool = false,
include_cursor_boundary: bool = false,
dict_calls: usize = 0,
compressed_sessions: usize = 0,
reject_plan: bool = false,
retry_block_calls: ?usize = null,
live_authorized: bool = false,
archive_authorized: bool = false,
archive_missing_auth: bool = false,
fn init(io: Io, allocator: Allocator, sealed: []const Row, live: []const Row) !Instance {
var listener = try (Io.net.IpAddress{ .ip4 = .loopback(0) }).listen(io, .{ .reuse_address = true });
errdefer listener.deinit(io);
return .{
.io = io,
.allocator = allocator,
.listener = listener,
.port = listener.socket.address.getPort(),
.sealed = sealed,
.live = live,
};
}
fn deinit(self: *Instance) void {
self.listener.deinit(self.io);
}
fn hostUrl(self: *const Instance, buf: []u8) []const u8 {
return std.fmt.bufPrint(buf, "http://127.0.0.1:{d}", .{self.port}) catch unreachable;
}
/// sequential accept loop: every handler terminates promptly — the
/// client under test closes its previous socket before reconnecting,
/// so a held websocket never blocks the next accept for long. exits
/// via the /quit poison pill so no thread is ever inside accept when
/// the listener closes (Io.Threaded panics on that race in Debug).
fn serve(self: *Instance) !void {
while (true) {
var stream = self.listener.accept(self.io) catch return;
const stop_requested = self.handleConn(&stream) catch false;
stream.close(self.io);
if (stop_requested) return;
}
}
/// unblock and stop the serve loop from the test thread
fn quit(self: *Instance) void {
var transport = zat.HttpTransport.init(self.io, self.allocator);
defer transport.deinit();
// A shutdown request must not retry after the server has exited.
transport.dead_connection_attempts = 1;
var url_buf: [64]u8 = undefined;
const url = std.fmt.bufPrint(&url_buf, "http://127.0.0.1:{d}/quit", .{self.port}) catch unreachable;
var response = transport.fetch(.{ .url = url, .deadline_ns = std.time.ns_per_s }) catch return;
response.deinit(self.allocator);
}
fn handleConn(self: *Instance, stream: *Io.net.Stream) !bool {
var rbuf: [8192]u8 = undefined;
var wbuf: [16384]u8 = undefined;
var reader = stream.reader(self.io, &rbuf);
var writer = stream.writer(self.io, &wbuf);
const r = &reader.interface;
const w = &writer.interface;
var head: [4096]u8 = undefined;
var n: usize = 0;
while (std.mem.indexOf(u8, head[0..n], "\r\n\r\n") == null) {
if (n == head.len) return error.HeadTooLarge;
head[n] = try r.takeByte();
n += 1;
}
const request = head[0..n];
const line_end = std.mem.indexOf(u8, request, "\r\n") orelse return error.BadRequest;
var line = std.mem.tokenizeScalar(u8, request[0..line_end], ' ');
const method = line.next() orelse return error.BadRequest;
const target = line.next() orelse return error.BadRequest;
var arena_state = std.heap.ArenaAllocator.init(self.allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
if (std.mem.startsWith(u8, target, "/quit")) {
try respondBytes(w, "text/plain", "");
return true;
}
if (std.mem.indexOf(u8, target, "subscribeEvents") != null) {
self.live_authorized = headerValue(request, "Authorization") != null;
try self.handleWebsocket(request, target, r, w);
return false;
}
if (std.mem.indexOf(u8, target, "getZstdDictionary") != null) {
self.dict_calls += 1;
if (self.compression == .none) {
try w.writeAll("HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
try w.flush();
} else if (self.compression == .invalid) {
try respondBytes(w, "application/octet-stream", "invalid dictionary");
} else if (self.compression == .hang) {
try w.writeAll("HTTP/1.1 200 OK\r\nContent-Type: application/octet-stream\r\nContent-Length: 64\r\nConnection: close\r\n\r\n");
try w.flush();
self.dict_hung.store(true, .release);
var discard: [64]u8 = undefined;
while (true) {
const read = r.readSliceShort(&discard) catch break;
if (read == 0) break;
}
} else {
var dict = @embedFile("testdata/live.dict").*;
if (self.compression == .rotate and self.dict_calls > 1) {
const old = std.mem.readInt(u32, dict[4..8], .little);
std.mem.writeInt(u32, dict[4..8], old + 1, .little);
}
try respondBytes(w, "application/octet-stream", &dict);
}
return false;
}
self.archive_calls += 1;
if (self.reject_archive) {
try w.writeAll("HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
try w.flush();
return false;
}
const authorized = if (headerValue(request, "Authorization")) |value| std.mem.eql(u8, value, "Bearer test-archive-key") else false;
self.archive_authorized = self.archive_authorized or authorized;
self.archive_missing_auth = self.archive_missing_auth or !authorized;
if (std.mem.indexOf(u8, target, "listSegments") != null) {
try respondJson(w, try self.segmentListJson(arena));
return false;
}
if (std.mem.eql(u8, method, "POST") and std.mem.indexOf(u8, target, "planSnapshot") != null) {
const body = try arena.alloc(u8, contentLength(request) orelse 0);
try r.readSliceAll(body);
self.plan_calls += 1;
if (self.reject_plan) {
try w.writeAll("HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
try w.flush();
return false;
}
if (self.page_size > 0) {
const parsed = try std.json.parseFromSlice(std.json.Value, arena, body, .{});
const fields = parsed.value.object;
const after: u64 = if (fields.get("afterSeq")) |v| @intCast(v.integer) else 0;
self.last_before_seq = if (fields.get("beforeSeq")) |v| @intCast(v.integer) else null;
var start: usize = 0;
while (start < self.sealed.len and self.sealed[start].seq <= after) : (start += 1) {}
var end = @min(start + self.page_size, self.sealed.len);
if (self.last_before_seq) |before| {
while (end > start and self.sealed[end - 1].seq > before) : (end -= 1) {}
}
self.page_rows = self.sealed[start..end];
}
try respondJson(w, try self.planJson(arena));
return false;
}
if (std.mem.indexOf(u8, target, "getSegment") != null and self.archive_fault == .segment) {
try respondBytes(w, "application/octet-stream", "invalid segment header");
return false;
}
if (std.mem.indexOf(u8, target, "getBlock") != null) {
if (self.retry_block_calls) |count| {
self.retry_block_calls = count + 1;
try w.writeAll("HTTP/1.1 503 Service Unavailable\r\nRetry-After: 0\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
try w.flush();
return false;
}
if (self.archive_fault != .none) {
const second = std.mem.indexOf(u8, target, "segment=second") != null;
const block: u64 = if (std.mem.indexOf(u8, target, "blockIndex=1") != null) 1 else if (std.mem.indexOf(u8, target, "blockIndex=2") != null) 2 else 0;
if (!second and block == 1) {
if (self.archive_fault == .fetch) {
try w.writeAll("HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
try w.flush();
} else try respondBytes(w, "application/octet-stream", "invalid zstd frame");
return false;
}
var fixture = self.*;
fixture.sealed = &.{.{ .seq = if (second) 100 else block + 1, .t = if (second) 10 else @intCast(block + 1) }};
fixture.page_rows = null;
try respondBytes(w, "application/octet-stream", try fixture.blockZstd(arena));
return false;
}
try respondBytes(w, "application/octet-stream", try self.blockZstd(arena));
return false;
}
try w.writeAll("HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
try w.flush();
return false;
}
fn segmentListJson(self: *const Instance, arena: Allocator) ![]const u8 {
if (self.sealed.len == 0) return "{\"segments\": []}";
return std.fmt.allocPrint(arena,
\\{{"segments": [{{"name": "seg_0000000001", "minSeq": {d}, "maxSeq": {d}, "minWitnessedAt": {d}, "maxWitnessedAt": {d}}}]}}
, .{
self.sealed[0].seq,
self.sealed[self.sealed.len - 1].seq,
witnessedUs(self.sealed[0].t),
witnessedUs(self.sealed[self.sealed.len - 1].t),
});
}
fn planJson(self: *const Instance, arena: Allocator) ![]const u8 {
if (self.archive_fault == .segment) return
\\{"plannedThroughSeq":100,"sealedTipSeq":100,"segments":[
\\{"name":"first","index":0,"mode":"segment"},
\\{"name":"second","index":1,"mode":"blocks","blocks":[{"first":0,"last":0}]}]}
;
if (self.archive_fault != .none) return
\\{"plannedThroughSeq":100,"sealedTipSeq":100,"segments":[
\\{"name":"first","index":0,"mode":"blocks","blocks":[{"first":0,"last":2}]},
\\{"name":"second","index":1,"mode":"blocks","blocks":[{"first":0,"last":0}]}]}
;
if (self.sealed.len == 0)
return "{\"plannedThroughSeq\": 0, \"sealedTipSeq\": 0, \"segments\": []}";
const tip = self.last_before_seq orelse (if (self.plan_calls == 1) self.first_tip else null) orelse self.sealed[self.sealed.len - 1].seq;
if (self.stalled_plan) return std.fmt.allocPrint(arena, "{{\"plannedThroughSeq\":0,\"sealedTipSeq\":{d},\"segments\":[]}}", .{tip});
const rows = self.page_rows orelse self.sealed;
if (rows.len == 0) return std.fmt.allocPrint(arena, "{{\"plannedThroughSeq\":{d},\"sealedTipSeq\":{d},\"segments\":[]}}", .{ tip, tip });
return std.fmt.allocPrint(arena,
\\{{"plannedThroughSeq": {d}, "sealedTipSeq": {d}, "segments": [
\\ {{"name": "seg_0000000001", "index": 0, "checksum": "0", "minSeq": {d}, "maxSeq": {d},
\\ "mode": "blocks", "blocks": [{{"first": 0, "last": 0}}]}}]}}
, .{ rows[rows.len - 1].seq, tip, rows[0].seq, rows[rows.len - 1].seq });
}
/// the sealed rows as one columnar jss block wrapped in a raw-block
/// zstd frame (no compressor needed: magic, single-segment FHD with
/// 4-byte FCS, one raw block)
fn blockZstd(self: *const Instance, arena: Allocator) ![]u8 {
const source_rows = self.page_rows orelse self.sealed;
const rows = try arena.alloc(BlockRow, source_rows.len);
for (source_rows, rows) |row, *out| out.* = .{
.seq = row.seq,
.witnessed_at = witnessedUs(row.t),
.kind = 1, // create
.collection = row.collection,
.did = row.did,
.rkey = "rkey1",
.rev = "rev1",
.payload = &archive.test_record_cbor,
};
const block = try archive.buildTestBlock(arena, rows);
var out: std.Io.Writer.Allocating = .init(arena);
const w = &out.writer;
try w.writeAll(&.{ 0x28, 0xb5, 0x2f, 0xfd, 0xa0 }); // magic + FHD
try w.writeInt(u32, @intCast(block.len), .little); // frame content size
try w.writeInt(u24, @intCast(
(block.len << 3) | 0b001,
), .little); // last raw block
try w.writeAll(block);
return out.written();
}
const BlockRow = @typeInfo(@typeInfo(@TypeOf(archive.buildTestBlock)).@"fn".param_types[1].?).pointer.child;
fn handleWebsocket(self: *Instance, request: []const u8, target: []const u8, r: *Io.Reader, w: *Io.Writer) !void {
if (self.ws_sessions < self.wire_cursors.len) self.wire_cursors[self.ws_sessions] = queryCursor(target);
self.ws_sessions += 1;
if (self.ws_sessions <= self.reject_ws_count) return;
if (self.cursor_too_old) {
const body = "{\"error\":\"CursorTooOld\"}";
try w.print("HTTP/1.1 400 Bad Request\r\nContent-Type: application/json\r\nContent-Length: {d}\r\nConnection: close\r\n\r\n{s}", .{ body.len, body });
try w.flush();
return;
}
if (self.ws_sessions > self.max_ws_sessions) return; // down: slam the door
const compressed = std.mem.indexOf(u8, target, "zstdDictionary=") != null;
if (compressed) self.compressed_sessions += 1;
if (compressed and self.ws_sessions == 1 and (self.compression == .rotate or self.compression == .same)) {
const body = "{\"error\":\"UnknownZstdDictionary\"}";
try w.print("HTTP/1.1 400 Bad Request\r\nContent-Type: application/json\r\nContent-Length: {d}\r\nConnection: close\r\n\r\n{s}", .{ body.len, body });
try w.flush();
return;
}
const key = headerValue(request, "Sec-WebSocket-Key") orelse return error.NoKey;
var sha = std.crypto.hash.Sha1.init(.{});
sha.update(key);
sha.update("258EAFA5-E914-47DA-95CA-C5AB0DC85B11");
var digest: [20]u8 = undefined;
sha.final(&digest);
var accept_buf: [28]u8 = undefined;
const accept = std.base64.standard.Encoder.encode(&accept_buf, &digest);
try w.print("HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: {s}\r\nSec-WebSocket-Protocol: xrpc.v1.json\r\n\r\n", .{accept});
try w.flush();
const cursor = queryCursor(target);
const clamped = if (cursor) |c| if (self.retention_floor_us) |floor| c >= 1_000_000_000_000_000 and c < floor else false else false;
if (clamped) try writeTextFrame(w,
\\{"$type":"message","payload":{"$type":"network.bsky.jetstream.subscribeEvents#info","name":"OutdatedCursor","message":"resumed at retention floor"}}
);
if (compressed and self.bad_compressed_first) try writeFrame(w, "invalid zstd", 0x82);
if (!self.silent_ws) {
const rows = if (self.ws_sessions == 1 and self.first_session_rows != null) self.live[0..self.first_session_rows.?] else self.live;
for (rows) |row| {
if (self.retention_floor_us) |floor| if (witnessedUs(row.t) < floor) continue;
if (!self.include_cursor_boundary) {
if (cursor) |c| {
if (c >= 1_000_000_000_000_000) {
if (witnessedUs(row.t) < c) continue;
} else if (row.seq < c) continue;
}
}
var frame_buf: [512]u8 = undefined;
const frame = try std.fmt.bufPrint(&frame_buf,
\\{{"$type":"message","payload":{{"$type":"network.bsky.jetstream.subscribeEvents#commit","collection":"{s}","did":"{s}","operation":"create","record":{{"$type":"app.bsky.feed.post","text":"hi"}},"rev":"rev1","rkey":"rkey1","seq":{d},"time":"2026-07-13T00:00:{d:0>2}.000000Z"}}}}
, .{ row.collection, row.did, row.seq, @as(u64, @intCast(row.t)) });
if (compressed) {
var buffer: [600]u8 = undefined;
var output: Io.Writer = .fixed(&buffer);
try output.writeAll(&.{ 0x28, 0xb5, 0x2f, 0xfd, 0xa3 });
const id = std.mem.readInt(u32, @embedFile("testdata/live.dict")[4..8], .little) + @as(u32, if (self.compression == .rotate and self.dict_calls > 1) 1 else 0);
try output.writeInt(u32, id, .little);
try output.writeInt(u32, @intCast(frame.len), .little);
try output.writeInt(u24, @intCast((frame.len << 3) | 1), .little);
try output.writeAll(frame);
try writeFrame(w, output.buffered(), 0x82);
} else try writeTextFrame(w, frame);
}
if (self.live_then_close or (self.ws_sessions == 1 and self.first_session_rows != null)) return;
}
// hold the tail open; the client closing its socket (stop, stall,
// rotation, reconnect) ends this read
var discard: [256]u8 = undefined;
while (true) {
const read = r.readSliceShort(&discard) catch return;
if (read == 0) return;
}
}
};
fn writeTextFrame(w: *Io.Writer, payload: []const u8) !void {
return writeFrame(w, payload, 0x81);
}
fn writeFrame(w: *Io.Writer, payload: []const u8, opcode: u8) !void {
if (payload.len < 126) {
try w.writeAll(&.{ opcode, @as(u8, @intCast(payload.len)) });
} else {
try w.writeAll(&.{ opcode, 126 });
try w.writeInt(u16, @intCast(payload.len), .big);
}
try w.writeAll(payload);
try w.flush();
}
fn headerValue(request: []const u8, name: []const u8) ?[]const u8 {
var lines = std.mem.tokenizeSequence(u8, request, "\r\n");
while (lines.next()) |l| {
if (l.len > name.len + 2 and std.ascii.startsWithIgnoreCase(l, name) and l[name.len] == ':')
return std.mem.trim(u8, l[name.len + 1 ..], " ");
}
return null;
}
fn contentLength(request: []const u8) ?usize {
const v = headerValue(request, "Content-Length") orelse return null;
return std.fmt.parseInt(usize, v, 10) catch null;
}
fn queryCursor(target: []const u8) ?u64 {
const idx = std.mem.indexOf(u8, target, "cursor=") orelse return null;
var end = idx + "cursor=".len;
while (end < target.len and std.ascii.isDigit(target[end])) end += 1;
return std.fmt.parseInt(u64, target[idx + "cursor=".len .. end], 10) catch null;
}
fn respondJson(w: *Io.Writer, body: []const u8) !void {
try respondBytes(w, "application/json", body);
}
fn respondBytes(w: *Io.Writer, content_type: []const u8, body: []const u8) !void {
try w.print("HTTP/1.1 200 OK\r\nContent-Type: {s}\r\nContent-Length: {d}\r\nConnection: close\r\n\r\n", .{ content_type, body.len });
try w.writeAll(body);
try w.flush();
}
const Collected = struct { seq: u64, t: i64 };
fn CollectingHandler(comptime stop_after: usize) type {
return struct {
events: [32]Collected = undefined,
len: usize = 0,
/// commit rows missing canonical record bytes (both halves must
/// populate record_cbor for create/update — upstream RecordCBOR)
missing_record_cbor: usize = 0,
pub fn onEvent(self: *@This(), event: livedecode.Event) bool {
if (self.len == self.events.len) return false;
if (event.payload == .commit and event.payload.commit.operation != .delete and event.payload.commit.record_cbor.len == 0)
self.missing_record_cbor += 1;
self.events[self.len] = .{
.seq = event.seq,
.t = @divFloor(event.time_us, std.time.us_per_s) - epoch_s,
};
self.len += 1;
return self.len < stop_after;
}
fn slice(self: *const @This()) []const Collected {
return self.events[0..self.len];
}
};
}
fn subscribeWithin(io: Io, options: client_mod.Options, handler: anytype) !void {
const Runner = struct {
fn run(task_io: Io, task_options: client_mod.Options, task_handler: @TypeOf(handler), done: *std.atomic.Value(bool)) !void {
defer done.store(true, .release);
try client_mod.subscribe(task_io, testing.allocator, task_options, task_handler);
}
};
var done: std.atomic.Value(bool) = .init(false);
var future = try io.concurrent(Runner.run, .{ io, options, handler, &done });
defer _ = future.cancel(io) catch {};
const start = Io.Timestamp.now(io, .awake).toMicroseconds();
while (!done.load(.acquire)) {
if (Io.Timestamp.now(io, .awake).toMicroseconds() - start >= 10 * std.time.us_per_s)
return error.TestTimeout;
try io.sleep(Io.Duration.fromMilliseconds(10), .awake);
}
try future.await(io);
}
test "e2e timestamp failover needs no archive and reconnects with fallback sequences" {
try timestampFailover(false);
}
test "e2e timestamp failover preserves resume through a refused connection" {
try timestampFailover(true);
}
fn timestampFailover(reject_first: bool) !void {
var threaded: Io.Threaded = .init(testing.allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var primary = try Instance.init(io, testing.allocator, &.{}, &.{ .{ .seq = 1001, .t = 20 }, .{ .seq = 1002, .t = 21 } });
primary.live_then_close = true;
primary.max_ws_sessions = 1;
primary.reject_archive = true;
var fallback = try Instance.init(io, testing.allocator, &.{}, &.{ .{ .seq = 1, .t = 10 }, .{ .seq = 2, .t = 11 }, .{ .seq = 3, .t = 20 }, .{ .seq = 4, .t = 22 } });
fallback.reject_archive = true;
fallback.reject_ws_count = if (reject_first) 1 else 0;
fallback.first_session_rows = if (reject_first) null else 3;
var primary_future = try io.concurrent(Instance.serve, .{&primary});
defer primary.deinit();
defer _ = primary_future.cancel(io) catch {};
defer primary.quit();
var fallback_future = try io.concurrent(Instance.serve, .{&fallback});
defer fallback.deinit();
defer _ = fallback_future.cancel(io) catch {};
defer fallback.quit();
const Handler = struct {
collected: CollectingHandler(5) = .{},
failures: usize = 0,
pub fn onEvent(self: *@This(), event: livedecode.Event) bool {
return self.collected.onEvent(event);
}
pub fn onError(self: *@This(), _: anyerror) bool {
self.failures += 1;
return self.failures < 16;
}
};
var handler = Handler{};
var primary_url: [64]u8 = undefined;
var fallback_url: [64]u8 = undefined;
try subscribeWithin(io, .{
.hosts = &.{ primary.hostUrl(&primary_url), fallback.hostUrl(&fallback_url) },
.zstd_compression = false,
.failover_after_errors = 2,
.failover_stall_ns = 300 * std.time.ns_per_ms,
.backoff_min_ns = std.time.ns_per_ms,
.backoff_max_ns = 4 * std.time.ns_per_ms,
}, &handler);
const expected = [_]Collected{ .{ .seq = 1001, .t = 20 }, .{ .seq = 1002, .t = 21 }, .{ .seq = 2, .t = 11 }, .{ .seq = 3, .t = 20 }, .{ .seq = 4, .t = 22 } };
try testing.expectEqualSlices(Collected, &expected, handler.collected.slice());
try testing.expectEqual(@as(usize, 0), primary.archive_calls + fallback.archive_calls);
try testing.expectEqual(@as(?u64, @intCast(witnessedUs(11))), fallback.wire_cursors[0]);
try testing.expectEqual(@as(?u64, if (reject_first) @intCast(witnessedUs(11)) else 3), fallback.wire_cursors[1]);
}
test "e2e initial timestamp survives a dead primary without widening the replay window" {
try initialCursorFailover(@intCast(witnessedUs(11)), false);
}
test "e2e initial sequence cannot transfer from a dead primary" {
try initialCursorFailover(42, true);
}
fn initialCursorFailover(cursor: u64, expect_unhealthy: bool) !void {
var threaded: Io.Threaded = .init(testing.allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var primary = try Instance.init(io, testing.allocator, &.{}, &.{});
primary.max_ws_sessions = 0;
var fallback = try Instance.init(io, testing.allocator, &.{}, &.{ .{ .seq = 1, .t = 10 }, .{ .seq = 2, .t = 11 } });
var primary_future = try io.concurrent(Instance.serve, .{&primary});
defer primary.deinit();
defer _ = primary_future.cancel(io) catch {};
defer primary.quit();
var fallback_future = try io.concurrent(Instance.serve, .{&fallback});
defer fallback.deinit();
defer _ = fallback_future.cancel(io) catch {};
defer fallback.quit();
var primary_url: [64]u8 = undefined;
var fallback_url: [64]u8 = undefined;
var handler = CollectingHandler(1){};
const result = subscribeWithin(io, .{
.hosts = &.{ primary.hostUrl(&primary_url), fallback.hostUrl(&fallback_url) },
.live_cursor = cursor,
.failover_after_errors = 1,
.zstd_compression = false,
.backoff_min_ns = std.time.ns_per_ms,
}, &handler);
if (expect_unhealthy) {
try testing.expectError(error.HostUnhealthy, result);
try testing.expectEqual(@as(usize, 0), handler.len);
try testing.expectEqual(@as(u32, 0), fallback.ws_sessions);
} else {
try result;
try testing.expectEqualSlices(Collected, &.{.{ .seq = 2, .t = 11 }}, handler.slice());
try testing.expectEqual(@as(?u64, cursor), fallback.wire_cursors[0]);
}
try testing.expectEqual(@as(usize, 0), primary.archive_calls + fallback.archive_calls);
}
test "e2e expired timestamp reports the retention gap before delivering retained events" {
var threaded: Io.Threaded = .init(testing.allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var host = try Instance.init(io, testing.allocator, &.{}, &.{ .{ .seq = 1, .t = 10 }, .{ .seq = 2, .t = 20 } });
host.retention_floor_us = @intCast(witnessedUs(20));
var future = try io.concurrent(Instance.serve, .{&host});
defer host.deinit();
defer _ = future.cancel(io) catch {};
defer host.quit();
const Handler = struct {
collected: CollectingHandler(1) = .{},
outdated: usize = 0,
warned_before_event: bool = false,
pub fn onEvent(self: *@This(), event: livedecode.Event) bool {
self.warned_before_event = self.outdated == 1;
return self.collected.onEvent(event);
}
pub fn onInfo(self: *@This(), info: livedecode.Info) void {
if (std.mem.eql(u8, info.name, "OutdatedCursor")) self.outdated += 1;
}
};
var handler = Handler{};
var url: [64]u8 = undefined;
try subscribeWithin(io, .{
.hosts = &.{host.hostUrl(&url)},
.live_cursor = @intCast(witnessedUs(10)),
.zstd_compression = false,
}, &handler);
try testing.expect(handler.warned_before_event);
try testing.expectEqualSlices(Collected, &.{.{ .seq = 2, .t = 20 }}, handler.collected.slice());
try testing.expectEqual(@as(usize, 0), host.archive_calls);
}
test "e2e expired live sequence returns CursorTooOld without skipping to tip" {
var threaded: Io.Threaded = .init(testing.allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var host = try Instance.init(io, testing.allocator, &.{}, &.{});
host.cursor_too_old = true;
var future = try io.concurrent(Instance.serve, .{&host});
defer host.deinit();
defer _ = future.cancel(io) catch {};
defer host.quit();
var url: [64]u8 = undefined;
var handler = CollectingHandler(1){};
try testing.expectError(error.CursorTooOld, subscribeWithin(io, .{
.hosts = &.{host.hostUrl(&url)},
.live_cursor = 42,
.zstd_compression = false,
}, &handler));
try testing.expectEqual(@as(u32, 1), host.ws_sessions);
try testing.expectEqual(@as(usize, 0), host.archive_calls);
try testing.expectEqual(@as(usize, 0), handler.slice().len);
}
test "e2e failover: archive replay completes before live timestamp failover" {
var threaded: Io.Threaded = .init(testing.allocator, .{});
defer threaded.deinit();
const io = threaded.io();
// primary: sealed seqs 1-2 (t=1,2), live 3-4 (t=3,4), then the host dies
var primary = try Instance.init(io, testing.allocator, &.{ .{ .seq = 1, .t = 1 }, .{ .seq = 2, .t = 2 } }, &.{ .{ .seq = 3, .t = 3 }, .{ .seq = 4, .t = 4 } });
primary.live_then_close = true;
primary.max_ws_sessions = 1;
// fallback: a DIFFERENT seq space. floor = last_time(4s) - rewind(1s)
// = 3s: seq 1001 (t=2) is trimmed, 1002 (t=3, boundary duplicate)
// and 1003 (t=5) deliver, then live 1004 (t=6)
var fallback = try Instance.init(io, testing.allocator, &.{}, &.{ .{ .seq = 1001, .t = 2 }, .{ .seq = 1002, .t = 3 }, .{ .seq = 1003, .t = 5 }, .{ .seq = 1004, .t = 6 } });
fallback.reject_archive = true;
// LIFO: request shutdown, join the serve task, then close the listener.
var primary_future = try io.concurrent(Instance.serve, .{&primary});
defer primary.deinit();
defer _ = primary_future.cancel(io) catch {};
defer primary.quit();
var fallback_future = try io.concurrent(Instance.serve, .{&fallback});
defer fallback.deinit();
defer _ = fallback_future.cancel(io) catch {};
defer fallback.quit();
var primary_url: [64]u8 = undefined;
var fallback_url: [64]u8 = undefined;
var handler = CollectingHandler(7){};
try subscribeWithin(io, .{
.hosts = &.{ primary.hostUrl(&primary_url), fallback.hostUrl(&fallback_url) },
.after_seq = 0,
.failover_after_errors = 2,
.failover_rewind_us = 1 * std.time.us_per_s,
.backoff_min_ns = 1 * std.time.ns_per_ms,
.backoff_max_ns = 4 * std.time.ns_per_ms,
}, &handler);
const expected = [_]Collected{
.{ .seq = 1, .t = 1 }, .{ .seq = 2, .t = 2 }, .{ .seq = 3, .t = 3 },
.{ .seq = 4, .t = 4 }, .{ .seq = 1002, .t = 3 }, .{ .seq = 1003, .t = 5 },
.{ .seq = 1004, .t = 6 },
};
try testing.expectEqualSlices(Collected, &expected, handler.slice());
try testing.expectEqual(@as(usize, 0), handler.missing_record_cbor);
try testing.expect(primary.plan_calls > 0);
try testing.expectEqual(@as(usize, 0), fallback.archive_calls);
}
test "e2e stall: connected-but-silent primary rotates; fresh tip on the fallback" {
var threaded: Io.Threaded = .init(testing.allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var primary = try Instance.init(io, testing.allocator, &.{}, &.{});
primary.silent_ws = true;
primary.max_ws_sessions = 1; // one silent session, then down
var fallback = try Instance.init(io, testing.allocator, &.{}, &.{ .{ .seq = 501, .t = 10 }, .{ .seq = 502, .t = 11 } });
var primary_future = try io.concurrent(Instance.serve, .{&primary});
defer primary.deinit();
defer _ = primary_future.cancel(io) catch {};
defer primary.quit();
var fallback_future = try io.concurrent(Instance.serve, .{&fallback});
defer fallback.deinit();
defer _ = fallback_future.cancel(io) catch {};
defer fallback.quit();
var primary_url: [64]u8 = undefined;
var fallback_url: [64]u8 = undefined;
var handler = CollectingHandler(2){};
try client_mod.subscribe(io, testing.allocator, .{
.hosts = &.{ primary.hostUrl(&primary_url), fallback.hostUrl(&fallback_url) },
.failover_after_errors = 1,
.failover_stall_ns = 300 * std.time.ns_per_ms,
.backoff_min_ns = 1 * std.time.ns_per_ms,
.backoff_max_ns = 4 * std.time.ns_per_ms,
}, &handler);
const expected = [_]Collected{ .{ .seq = 501, .t = 10 }, .{ .seq = 502, .t = 11 } };
try testing.expectEqualSlices(Collected, &expected, handler.slice());
try testing.expectEqual(@as(usize, 0), handler.missing_record_cbor);
}
test "e2e live-phase clean stop: onEvent=false ends subscribe instead of reconnect-looping" {
var threaded: Io.Threaded = .init(testing.allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var host = try Instance.init(io, testing.allocator, &.{}, &.{ .{ .seq = 1, .t = 1 }, .{ .seq = 2, .t = 2 } });
var future = try io.concurrent(Instance.serve, .{&host});
defer host.deinit();
defer _ = future.cancel(io) catch {};
defer host.quit();
var url: [64]u8 = undefined;
var handler = CollectingHandler(1){};
try client_mod.subscribe(io, testing.allocator, .{
.hosts = &.{host.hostUrl(&url)},
.backoff_min_ns = 1 * std.time.ns_per_ms,
.backoff_max_ns = 4 * std.time.ns_per_ms,
}, &handler);
try testing.expectEqual(@as(usize, 1), handler.len);
try testing.expectEqual(@as(u64, 1), handler.slice()[0].seq);
}
// Upstream engine_test.go: TestEngineMultiPageBackfillCutover and
// TestEnginePinnedBeforeSeqAcrossPages (289b032 and 58c4d7f).
test "conformance: snapshot consumes every plan page and pins the sealed tip" {
var threaded: Io.Threaded = .init(testing.allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var host = try Instance.init(io, testing.allocator, &.{
.{ .seq = 1, .t = 1 }, .{ .seq = 2, .t = 2 }, .{ .seq = 3, .t = 3 }, .{ .seq = 4, .t = 4 },
}, &.{});
host.page_size = 1;
host.first_tip = 3;
var future = try io.concurrent(Instance.serve, .{&host});
defer host.deinit();
defer _ = future.cancel(io) catch {};
defer host.quit();
var url: [64]u8 = undefined;
var handler = CollectingHandler(32){};
try client_mod.subscribe(io, testing.allocator, .{
.hosts = &.{host.hostUrl(&url)},
.after_seq = 0,
.snapshot_only = true,
.concurrency = 1,
}, &handler);
try testing.expectEqualSlices(Collected, &.{
.{ .seq = 1, .t = 1 }, .{ .seq = 2, .t = 2 }, .{ .seq = 3, .t = 3 },
}, handler.slice());
try testing.expectEqual(@as(usize, 3), host.plan_calls);
try testing.expectEqual(@as(?u64, 3), host.last_before_seq);
}
// Upstream TestEngineLiveOnlyAppliesCollectionFilter and
// TestMatcherDIDFilterAllKinds: the server deliberately ignores filters.
test "conformance: live delivery reapplies collection and DID filters" {
var threaded: Io.Threaded = .init(testing.allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var host = try Instance.init(io, testing.allocator, &.{}, &.{
.{ .seq = 1, .t = 1, .collection = "app.bsky.feed.like" },
.{ .seq = 2, .t = 2, .did = "did:plc:other" },
.{ .seq = 3, .t = 3 },
});
var future = try io.concurrent(Instance.serve, .{&host});
defer host.deinit();
defer _ = future.cancel(io) catch {};
defer host.quit();
const Handler = struct {
collected: CollectingHandler(32) = .{},
pub fn onEvent(self: *@This(), event: livedecode.Event) bool {
_ = self.collected.onEvent(event);
return event.seq < 3;
}
};
var handler = Handler{};
var url: [64]u8 = undefined;
try client_mod.subscribe(io, testing.allocator, .{
.hosts = &.{host.hostUrl(&url)},
.collections = &.{"app.bsky.feed.post"},
.dids = &.{"did:plc:loopback"},
}, &handler);
try testing.expectEqualSlices(Collected, &.{.{ .seq = 3, .t = 3 }}, handler.collected.slice());
}
// Upstream sweepSealedArchive rejects a non-advancing continuation.
test "conformance: a stalled plan fails instead of looping" {
var threaded: Io.Threaded = .init(testing.allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var host = try Instance.init(io, testing.allocator, &.{.{ .seq = 3, .t = 3 }}, &.{});
host.stalled_plan = true;
var future = try io.concurrent(Instance.serve, .{&host});
defer host.deinit();
defer _ = future.cancel(io) catch {};
defer host.quit();
var url: [64]u8 = undefined;
var handler = CollectingHandler(32){};
try testing.expectError(error.PlanStalled, client_mod.subscribe(io, testing.allocator, .{
.hosts = &.{host.hostUrl(&url)},
.after_seq = 0,
.snapshot_only = true,
}, &handler));
try testing.expectEqual(@as(usize, 1), host.plan_calls);
}
test "archive block budget applies across plan pages" {
var threaded: Io.Threaded = .init(testing.allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var host = try Instance.init(io, testing.allocator, &.{
.{ .seq = 1, .t = 1 }, .{ .seq = 2, .t = 2 }, .{ .seq = 3, .t = 3 },
}, &.{});
host.page_size = 1;
var future = try io.concurrent(Instance.serve, .{&host});
defer host.deinit();
defer _ = future.cancel(io) catch {};
defer host.quit();
const Handler = struct {
count: usize = 0,
pub fn onRow(self: *@This(), _: livedecode.Event) bool {
self.count += 1;
return true;
}
};
var handler = Handler{};
var url: [64]u8 = undefined;
const result = try archive.run(io, testing.allocator, .{
.host = host.hostUrl(&url),
.after_seq = 0,
.max_blocks = 2,
.concurrency = 1,
}, &handler);
try testing.expect(result.truncated);
try testing.expectEqual(@as(u64, 2), result.blocks_decoded);
try testing.expectEqual(@as(usize, 2), handler.count);
try testing.expectEqual(@as(usize, 2), host.plan_calls);
try testing.expectEqual(@as(u64, 3), result.sealed_tip_seq);
}
// Upstream TestDownloadBlocksErrorStopsEntryNotPlan: good prefix, error,
// then the next entry; a decode error instead leaves later blocks readable.
test "archive errors are ordered and the caller chooses whether to continue" {
for ([_]bool{ true, false }) |accept_error| {
for ([_]usize{ 1, 4 }) |concurrency| {
for ([_]bool{ false, true }) |decode_failure| {
var threaded: Io.Threaded = .init(testing.allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var host = try Instance.init(io, testing.allocator, &.{}, &.{});
host.archive_fault = if (decode_failure) .decode else .fetch;
var future = try io.concurrent(Instance.serve, .{&host});
defer host.deinit();
defer _ = future.cancel(io) catch {};
defer host.quit();
const Handler = struct {
items: [8]u64 = undefined,
len: usize = 0,
accept: bool,
err: ?anyerror = null,
pub fn onEvent(self: *@This(), event: livedecode.Event) bool {
self.items[self.len] = event.seq;
self.len += 1;
return true;
}
pub fn onError(self: *@This(), err: anyerror) bool {
self.err = err;
self.items[self.len] = 0;
self.len += 1;
return self.accept;
}
};
var handler = Handler{ .accept = accept_error };
var url: [64]u8 = undefined;
// If an archive failure incorrectly rotates, port 1 cannot
// supply the next entry and the expected sequence is lost.
try client_mod.subscribe(io, testing.allocator, .{
.hosts = &.{ host.hostUrl(&url), "http://127.0.0.1:1" },
.after_seq = 0,
.snapshot_only = true,
.concurrency = concurrency,
}, &handler);
try testing.expectEqual(@as(?anyerror, if (decode_failure) error.BlockDecompressFailed else error.FetchFailed), handler.err);
const expected: []const u64 = if (!accept_error) &.{ 1, 0 } else if (decode_failure) &.{ 1, 0, 3, 100 } else &.{ 1, 0, 100 };
try testing.expectEqualSlices(u64, expected, handler.items[0..handler.len]);
}
}
}
}
test "archive plan failures stay terminal even when the caller accepts errors" {
var threaded: Io.Threaded = .init(testing.allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var host = try Instance.init(io, testing.allocator, &.{}, &.{});
host.reject_plan = true;
var future = try io.concurrent(Instance.serve, .{&host});
defer host.deinit();
defer _ = future.cancel(io) catch {};
defer host.quit();
const Handler = struct {
errors: usize = 0,
pub fn onEvent(_: *@This(), _: livedecode.Event) bool {
return true;
}
pub fn onError(self: *@This(), _: anyerror) bool {
self.errors += 1;
return true;
}
};
var handler = Handler{};
var url: [64]u8 = undefined;
try testing.expectError(error.PlanFailed, client_mod.subscribe(io, testing.allocator, .{
.hosts = &.{host.hostUrl(&url)},
.after_seq = 0,
.snapshot_only = true,
}, &handler));
try testing.expectEqual(@as(usize, 0), handler.errors);
}
test "a whole segment error can be accepted or declined before the next entry" {
for ([_]bool{ true, false }) |accept| {
var threaded: Io.Threaded = .init(testing.allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var host = try Instance.init(io, testing.allocator, &.{}, &.{});
host.archive_fault = .segment;
var future = try io.concurrent(Instance.serve, .{&host});
defer host.deinit();
defer _ = future.cancel(io) catch {};
defer host.quit();
const Handler = struct {
accept: bool,
errors: usize = 0,
last: u64 = 0,
pub fn onRow(self: *@This(), event: livedecode.Event) bool {
self.last = event.seq;
return true;
}
pub fn onError(self: *@This(), err: anyerror) bool {
if (err != error.MalformedSegment) @panic("unexpected error");
self.errors += 1;
return self.accept;
}
};
var handler = Handler{ .accept = accept };
var url: [64]u8 = undefined;
const result = try archive.run(io, testing.allocator, .{ .host = host.hostUrl(&url) }, &handler);
try testing.expectEqual(@as(usize, 1), handler.errors);
try testing.expectEqual(@as(u64, if (accept) 100 else 0), handler.last);
try testing.expectEqual(!accept, result.stopped);
}
}
test "archive key authenticates archive requests but not live handshakes" {
var threaded: Io.Threaded = .init(testing.allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var host = try Instance.init(io, testing.allocator, &.{.{ .seq = 1, .t = 1 }}, &.{.{ .seq = 2, .t = 2 }});
var future = try io.concurrent(Instance.serve, .{&host});
defer host.deinit();
defer _ = future.cancel(io) catch {};
defer host.quit();
var url: [64]u8 = undefined;
var handler = CollectingHandler(2){};
try client_mod.subscribe(io, testing.allocator, .{
.hosts = &.{host.hostUrl(&url)},
.after_seq = 0,
.api_key = "test-archive-key",
.concurrency = 1,
}, &handler);
try testing.expectEqual(@as(usize, 2), handler.len);
try testing.expect(host.archive_authorized);
try testing.expect(!host.archive_missing_auth);
try testing.expect(!host.live_authorized);
}
test "archive block retries stop after three HTTP attempts" {
var threaded: Io.Threaded = .init(testing.allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var host = try Instance.init(io, testing.allocator, &.{.{ .seq = 1, .t = 1 }}, &.{});
host.retry_block_calls = 0;
var future = try io.concurrent(Instance.serve, .{&host});
defer host.deinit();
defer _ = future.cancel(io) catch {};
defer host.quit();
var url: [64]u8 = undefined;
var handler = CollectingHandler(2){};
try testing.expectError(error.FetchRetriesExhausted, client_mod.subscribe(io, testing.allocator, .{
.hosts = &.{host.hostUrl(&url)},
.after_seq = 0,
.snapshot_only = true,
.concurrency = 1,
}, &handler));
try testing.expectEqual(@as(?usize, 3), host.retry_block_calls);
try testing.expectEqual(@as(usize, 0), handler.len);
}
test "default compression negotiates and recovers dictionary rotation" {
inline for (.{ .valid, .rotate, .same, .invalid, .none }) |mode| {
var threaded: Io.Threaded = .init(testing.allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var host = try Instance.init(io, testing.allocator, &.{}, &.{.{ .seq = 1, .t = 1 }});
host.compression = mode;
var future = try io.concurrent(Instance.serve, .{&host});
defer host.deinit();
defer _ = future.cancel(io) catch {};
defer host.quit();
var url: [64]u8 = undefined;
var handler = CollectingHandler(1){};
try client_mod.subscribe(io, testing.allocator, .{ .hosts = &.{host.hostUrl(&url)} }, &handler);
try testing.expectEqual(@as(usize, 1), handler.len);
try testing.expectEqual(@as(usize, if (mode == .rotate or mode == .same) 2 else 1), host.dict_calls);
try testing.expectEqual(@as(usize, if (mode == .rotate) 2 else if (mode == .valid or mode == .same) 1 else 0), host.compressed_sessions);
}
}
test "explicitly disabled compression makes no dictionary request" {
var threaded: Io.Threaded = .init(testing.allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var host = try Instance.init(io, testing.allocator, &.{}, &.{.{ .seq = 1, .t = 1 }});
host.compression = .valid;
var future = try io.concurrent(Instance.serve, .{&host});
defer host.deinit();
defer _ = future.cancel(io) catch {};
defer host.quit();
var url: [64]u8 = undefined;
var handler = CollectingHandler(1){};
try client_mod.subscribe(io, testing.allocator, .{ .hosts = &.{host.hostUrl(&url)}, .zstd_compression = false }, &handler);
try testing.expectEqual(@as(usize, 1), handler.len);
try testing.expectEqual(@as(usize, 0), host.dict_calls);
try testing.expectEqual(@as(usize, 0), host.compressed_sessions);
}
test "malformed compressed live frame follows caller continue or stop policy" {
inline for (.{ true, false }) |accept| {
var threaded: Io.Threaded = .init(testing.allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var host = try Instance.init(io, testing.allocator, &.{}, &.{.{ .seq = 1, .t = 1 }});
host.compression = .valid;
host.bad_compressed_first = true;
var future = try io.concurrent(Instance.serve, .{&host});
defer host.deinit();
defer _ = future.cancel(io) catch {};
defer host.quit();
const Handler = struct {
errors: usize = 0,
events: usize = 0,
pub fn onError(self: *@This(), err: anyerror) bool {
testing.expectEqual(error.DecompressFailed, err) catch @panic("unexpected live error");
self.errors += 1;
return accept;
}
pub fn onEvent(self: *@This(), _: livedecode.Event) bool {
self.events += 1;
return false;
}
};
var handler = Handler{};
var url: [64]u8 = undefined;
try client_mod.subscribe(io, testing.allocator, .{ .hosts = &.{host.hostUrl(&url)} }, &handler);
try testing.expectEqual(@as(usize, 1), handler.errors);
try testing.expectEqual(@as(usize, if (accept) 1 else 0), handler.events);
try testing.expectEqual(@as(u32, 1), host.ws_sessions);
}
}
test "live resume suppresses boundary sent by server" {
var threaded: Io.Threaded = .init(testing.allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var host = try Instance.init(io, testing.allocator, &.{}, &.{ .{ .seq = 1, .t = 1 }, .{ .seq = 2, .t = 2 } });
host.include_cursor_boundary = true;
var future = try io.concurrent(Instance.serve, .{&host});
defer host.deinit();
defer _ = future.cancel(io) catch {};
defer host.quit();
var url: [64]u8 = undefined;
var handler = CollectingHandler(1){};
try client_mod.subscribe(io, testing.allocator, .{ .hosts = &.{host.hostUrl(&url)}, .live_cursor = 1, .zstd_compression = false }, &handler);
try testing.expectEqual(@as(u64, 2), handler.events[0].seq);
}
test "dictionary rejection reports recovery and honors caller stop" {
inline for (.{ true, false }) |accept| {
var threaded: Io.Threaded = .init(testing.allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var host = try Instance.init(io, testing.allocator, &.{}, &.{.{ .seq = 1, .t = 1 }});
host.compression = .rotate;
var future = try io.concurrent(Instance.serve, .{&host});
defer host.deinit();
defer _ = future.cancel(io) catch {};
defer host.quit();
const Handler = struct {
errors: usize = 0,
events: usize = 0,
pub fn onError(self: *@This(), _: anyerror) bool {
self.errors += 1;
return accept;
}
pub fn onEvent(self: *@This(), _: livedecode.Event) bool {
self.events += 1;
return false;
}
};
var handler = Handler{};
var url: [64]u8 = undefined;
try client_mod.subscribe(io, testing.allocator, .{ .hosts = &.{host.hostUrl(&url)} }, &handler);
try testing.expectEqual(@as(usize, 1), handler.errors);
try testing.expectEqual(@as(usize, if (accept) 1 else 0), handler.events);
try testing.expectEqual(@as(u32, if (accept) 2 else 1), host.ws_sessions);
try testing.expectEqual(@as(usize, 2), host.dict_calls);
}
}
test "cancel during the dictionary fetch ends subscribe with error.Canceled" {
var threaded: Io.Threaded = .init(testing.allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var host = try Instance.init(io, testing.allocator, &.{}, &.{.{ .seq = 1, .t = 1 }});
host.compression = .hang;
var future = try io.concurrent(Instance.serve, .{&host});
defer host.deinit();
defer _ = future.cancel(io) catch {};
defer host.quit();
const Runner = struct {
fn run(task_io: Io, options: client_mod.Options, handler: *CollectingHandler(1)) !void {
try client_mod.subscribe(task_io, testing.allocator, options, handler);
}
};
var url: [64]u8 = undefined;
var handler = CollectingHandler(1){};
var subscription = try io.concurrent(Runner.run, .{ io, client_mod.Options{ .hosts = &.{host.hostUrl(&url)} }, &handler });
errdefer _ = subscription.cancel(io) catch {};
const start = Io.Timestamp.now(io, .awake).toMicroseconds();
while (!host.dict_hung.load(.acquire)) {
if (Io.Timestamp.now(io, .awake).toMicroseconds() - start >= 10 * std.time.us_per_s)
return error.TestTimeout;
try io.sleep(Io.Duration.fromMilliseconds(1), .awake);
}
// zttp only surfaces a cancel that lands in the body phase; give the
// client time to consume the response head the server just flushed
try io.sleep(Io.Duration.fromMilliseconds(100), .awake);
try testing.expectError(error.Canceled, subscription.cancel(io));
try testing.expectEqual(@as(usize, 0), handler.len);
try testing.expectEqual(@as(u32, 0), host.ws_sessions);
}
test "stall timeout without concurrency tails inline instead of reconnect-looping" {
var threaded: Io.Threaded = .init(testing.allocator, .{});
defer threaded.deinit();
const io = threaded.io();
var host = try Instance.init(io, testing.allocator, &.{}, &.{ .{ .seq = 1, .t = 1 }, .{ .seq = 2, .t = 2 } });
var future = try io.concurrent(Instance.serve, .{&host});
defer host.deinit();
defer _ = future.cancel(io) catch {};
defer host.quit();
var client_threaded: Io.Threaded = .init(testing.allocator, .{ .concurrent_limit = .nothing });
defer client_threaded.deinit();
const Handler = struct {
collected: CollectingHandler(2) = .{},
failures: usize = 0,
pub fn onEvent(self: *@This(), event: livedecode.Event) bool {
return self.collected.onEvent(event);
}
pub fn onError(self: *@This(), _: anyerror) bool {
self.failures += 1;
return false;
}
};
var handler = Handler{};
var url: [64]u8 = undefined;
try client_mod.subscribe(client_threaded.io(), testing.allocator, .{
.hosts = &.{host.hostUrl(&url)},
.zstd_compression = false,
.failover_stall_ns = 300 * std.time.ns_per_ms,
.backoff_min_ns = 1 * std.time.ns_per_ms,
.backoff_max_ns = 4 * std.time.ns_per_ms,
}, &handler);
try testing.expectEqual(@as(usize, 0), handler.failures);
try testing.expectEqual(@as(usize, 2), handler.collected.len);
try testing.expectEqual(@as(u32, 1), host.ws_sessions);
}