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
const std = @import("std");
const zat = @import("zat");
const hegel = @import("hegel");
const sim = @import("sim_io.zig");
pub const std_options: std.Options = .{ .log_level = .warn };
const Rule = enum { subscribe };
var tally: hegel.Tally(Rule) = .{};
const Plan = union(enum) {
refuse,
reject,
stream: struct { events: usize, garbage_at: ?usize, close_frame: bool },
};
const hosts = [_][]const u8{ "ws://relay1.sim", "ws://relay2.sim:7777" };
const host_names = [_][]const u8{ "relay1.sim", "relay2.sim" };
const host_headers = [_][]const u8{ "relay1.sim", "relay2.sim:7777" };
const WireError = enum {
@"handshake target differs from cursor model",
@"handshake Host header differs",
@"handshake went to the wrong host",
};
const World = struct {
a: std.mem.Allocator,
sim_io: *sim.SimIo,
plan: []const Plan,
host_count: usize,
log_base: i64,
log_len: i64,
attempts: usize = 0,
attempt_started: std.ArrayList(i96) = .empty,
targets: []const []const u8 = &.{},
commit_cid: zat.Cid = undefined,
wire_error: ?WireError = null,
stop: bool = false,
fn refuse(raw: *anyopaque) bool {
const self: *World = @ptrCast(@alignCast(raw));
const index = self.attempts;
self.attempts += 1;
self.attempt_started.append(self.a, self.sim_io.now_ns) catch {};
if (index >= self.plan.len) {
self.stop = true;
return true;
}
return self.plan[index] == .refuse;
}
fn handle(raw: *anyopaque, request: sim.Request) sim.Response {
const self: *World = @ptrCast(@alignCast(raw));
const index = self.attempts - 1;
const host = index % self.host_count;
if (self.wire_error == null) {
if (!std.mem.eql(u8, request.host, host_names[host])) self.wire_error = .@"handshake went to the wrong host";
if (!std.mem.eql(u8, request.target, self.targets[index])) self.wire_error = .@"handshake target differs from cursor model";
if (!std.mem.eql(u8, request.header("host") orelse "", host_headers[host])) self.wire_error = .@"handshake Host header differs";
}
const stream = switch (self.plan[index]) {
.stream => |stream| stream,
else => return .{ .status = 503, .body = "busy" },
};
const accept = sim.websocketAccept(request.header("sec-websocket-key") orelse "");
var out: std.ArrayList(u8) = .empty;
out.print(self.a, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: {s}\r\n\r\n", .{accept}) catch return .{ .status = 500 };
var seq = self.resumeFrom(request.target);
for (0..stream.events + 1) |position| {
if (stream.garbage_at == position) sim.websocketFrame(&out, self.a, 2, "\xa1\x61tgarbage") catch {};
if (position == stream.events or seq >= self.log_base + self.log_len) break;
const frame = zat.firehose.encodeCommitEvent(self.a, .{
.seq = seq,
.repo_did = "did:plc:abcdefghijklmnopqrstuvwx",
.commit_cid = self.commit_cid,
.rev = "2222222222222",
.blocks = "blocks",
.ops = &.{},
.time = "2026-11-04T00:00:00Z",
}) catch return .{ .status = 500 };
sim.websocketFrame(&out, self.a, 2, frame) catch {};
seq += 1;
}
if (stream.close_frame) sim.websocketFrame(&out, self.a, 8, "\x03\xe8") catch {};
return .{ .raw = out.items };
}
fn resumeFrom(self: *World, target: []const u8) i64 {
const marker = "?cursor=";
const at = std.mem.indexOf(u8, target, marker) orelse return self.log_base;
const cursor = std.fmt.parseInt(i64, target[at + marker.len ..], 10) catch return self.log_base;
return @max(self.log_base, cursor + 1);
}
};
const Handler = struct {
world: *World,
delivered: std.ArrayList(i64) = .empty,
connects: usize = 0,
errors: std.ArrayList([]const u8) = .empty,
pub fn onEvent(self: *Handler, event: zat.FirehoseEvent) void {
self.delivered.append(self.world.a, event.seq().?) catch {};
}
pub fn onConnect(self: *Handler, _: []const u8) void {
self.connects += 1;
}
pub fn onError(self: *Handler, err: anyerror) void {
self.errors.append(self.world.a, @errorName(err)) catch {};
}
pub fn shouldStop(self: *Handler) bool {
return self.world.stop;
}
};
fn property(_: void, case: *hegel.TestCase) !void {
var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
defer arena.deinit();
const a = arena.allocator();
var io_sim = sim.SimIo.init(try case.int(u32, 0, std.math.maxInt(u32)), 1_800_000_000);
tally.case();
tally.step(.subscribe);
const outage = try case.boolean();
const plan = try a.alloc(Plan, try case.int(usize, 1, 16));
for (plan) |*entry| entry.* = switch (if (outage and try case.int(u8, 0, 9) != 0) 0 else try case.int(u8, 0, 5)) {
0 => .refuse,
1 => .reject,
else => blk: {
const events = try case.int(usize, 0, 4);
break :blk .{ .stream = .{
.events = events,
.garbage_at = if (try case.int(u8, 0, 3) == 0) try case.int(usize, 0, events) else null,
.close_frame = try case.boolean(),
} };
},
};
var world: World = .{
.a = a,
.sim_io = &io_sim,
.plan = plan,
.host_count = try case.int(usize, 1, hosts.len),
.log_base = try case.int(i64, 1, 1_000_000),
.log_len = try case.int(i64, 0, 30),
};
const initial_cursor: ?i64 = if (try case.boolean()) world.log_base + try case.int(i64, -2, 5) else null;
var network = sim.Network.init(a, &world, World.handle);
network.max_read = try case.int(usize, 1, 256);
network.refuse_connect = World.refuse;
try network.addHost("relay1.sim", .{ 34, 3, 0, 1 });
try network.addHost("relay2.sim", .{ 34, 3, 0, 2 });
io_sim.network = &network;
case.note("hosts={d} log={d}+{d} cursor={?d} plan={any}", .{ world.host_count, world.log_base, world.log_len, initial_cursor, plan });
var expected_delivered: std.ArrayList(i64) = .empty;
var expected_sleeps: std.ArrayList(u64) = .empty;
var expected_targets: std.ArrayList([]const u8) = .empty;
{
var last: ?i64 = initial_cursor;
var backoff: u64 = 1;
var prev_host: usize = 0;
var connected = false;
for (0..plan.len) |index| {
const host = index % world.host_count;
if (index > 0 and host != prev_host) backoff = 1;
if (connected) backoff = 1;
try expected_targets.append(a, if (last) |cursor|
try std.fmt.allocPrint(a, "/xrpc/com.atproto.sync.subscribeRepos?cursor={d}", .{cursor})
else
"/xrpc/com.atproto.sync.subscribeRepos");
connected = plan[index] == .stream;
if (plan[index] == .stream) {
var seq = if (last) |cursor| @max(world.log_base, cursor + 1) else world.log_base;
for (0..plan[index].stream.events) |_| {
if (seq >= world.log_base + world.log_len) break;
try expected_delivered.append(a, seq);
last = seq;
seq += 1;
}
}
try expected_sleeps.append(a, backoff);
prev_host = host;
backoff = @min(backoff * 2, 60);
}
}
var client = zat.FirehoseClient.init(io_sim.io(), a, .{ .hosts = hosts[0..world.host_count], .cursor = initial_cursor });
defer client.deinit();
var handler: Handler = .{ .world = &world };
world.targets = expected_targets.items;
world.commit_cid = try zat.Cid.forDagCbor(a, "commit");
try client.subscribe(&handler);
if (world.wire_error) |origin| switch (origin) {
inline else => |tag| return case.fail(@tagName(tag)),
};
case.note("delivered {any}, expected {any}; errors {any}", .{ handler.delivered.items, expected_delivered.items, handler.errors.items });
if (!std.mem.eql(i64, handler.delivered.items, expected_delivered.items)) return case.fail("delivered events differ from cursor model");
if (world.attempts != plan.len + 1) return case.fail("subscription made a different number of attempts");
var sleeps: std.ArrayList(u64) = .empty;
for (world.attempt_started.items[1..], world.attempt_started.items[0 .. world.attempt_started.items.len - 1]) |later, earlier| {
try sleeps.append(a, @intCast(@divExact(later - earlier, std.time.ns_per_s)));
}
case.note("sleeps {any}, expected {any}", .{ sleeps.items, expected_sleeps.items });
if (!std.mem.eql(u64, sleeps.items, expected_sleeps.items)) return case.fail("reconnect backoff differs from model");
var streams: usize = 0;
for (plan) |entry| streams += @intFromBool(entry == .stream);
if (handler.connects != streams) return case.fail("onConnect count differs from accepted handshakes");
if (network.upgrade_crlf_splits_avoided > 0) case.event("known: websocket v0.2.0 drops a header split mid-CRLF");
if (expected_delivered.items.len > 0) case.event("events delivered");
if (streams > 1 and expected_delivered.items.len > 0) case.event("resumed from cursor after reconnect");
for (expected_sleeps.items) |sleep| if (sleep >= 8) case.event("backoff grew past 8s");
for (expected_sleeps.items) |sleep| if (sleep == 60) case.event("backoff reached its 60s cap");
for (plan) |entry| if (entry == .stream and entry.stream.garbage_at != null) case.event("undecodable frame skipped");
tally.finish(expected_delivered.items.len);
}
pub fn main() !void {
defer tally.print();
try hegel.run(.{ .key = "firehose" }, {}, property);
}