const std = @import("std"); const zat = @import("zat"); const hegel = @import("hegel"); const sim = @import("sim_io.zig"); const Rule = enum { query, procedure, auth }; var tally: hegel.Tally(Rule) = .{}; const host = "pds.sim"; const statuses = [_]u16{ 200, 400, 401, 404, 429, 500, 502, 503, 504 }; const max_attempts = 5; const transport_reports_truncation = true; const Hint = union(enum) { none, retry_after: u32, retry_after_date: u32, reset_delta: u32, reset_epoch: u32, }; const Attempt = union(enum) { respond: struct { status: u16, hint: Hint, fault: sim.Fault }, refuse, }; const WireError = enum { @"client sent more attempts than planned", @"refused attempt reached the server", @"wire method differs", @"wire target differs from independent encoding", @"wire body differs", @"procedure lacks JSON content type", @"bearer token differs", @"unauthenticated request carries authorization", }; const Script = struct { arena: std.mem.Allocator, attempts: []Attempt = &.{}, served: usize = 0, refused: usize = 0, now_s: *const i96, expect_method: []const u8 = "", expect_target: []const u8 = "", expect_body: ?[]const u8 = null, expect_auth: ?[]const u8 = null, wire_error: ?WireError = null, fn handle(raw: *anyopaque, request: sim.Request) sim.Response { const self: *Script = @ptrCast(@alignCast(raw)); self.check(request); if (self.served >= self.attempts.len) { self.wire_error = self.wire_error orelse .@"client sent more attempts than planned"; return .{ .status = 500 }; } const planned = self.attempts[self.served]; self.served += 1; const respond = switch (planned) { .respond => |respond| respond, .refuse => { self.wire_error = self.wire_error orelse .@"refused attempt reached the server"; return .{ .status = 500 }; }, }; const body = if (respond.status == 200) "{\"ok\":true}" else std.fmt.allocPrint(self.arena, "{{\"error\":\"Status{d}\",\"message\":\"planned\"}}", .{respond.status}) catch ""; const now = @divFloor(self.now_s.*, std.time.ns_per_s); const headers = switch (respond.hint) { .none => "", .retry_after => |s| std.fmt.allocPrint(self.arena, "retry-after: {d}\r\n", .{s}) catch "", .retry_after_date => |s| httpDate(self.arena, @intCast(now + s)) catch "", .reset_delta => |s| std.fmt.allocPrint(self.arena, "ratelimit-reset: {d}\r\n", .{s}) catch "", .reset_epoch => |s| std.fmt.allocPrint(self.arena, "ratelimit-reset: {d}\r\n", .{now + s}) catch "", }; return .{ .status = respond.status, .headers = headers, .body = body, .fault = respond.fault }; } fn refuse(raw: *anyopaque) bool { const self: *Script = @ptrCast(@alignCast(raw)); if (self.served >= self.attempts.len or self.attempts[self.served] != .refuse) return false; self.served += 1; self.refused += 1; return true; } fn check(self: *Script, request: sim.Request) void { if (self.wire_error != null) return; if (!std.mem.eql(u8, request.method, self.expect_method)) self.wire_error = .@"wire method differs"; if (!std.mem.eql(u8, request.target, self.expect_target)) self.wire_error = .@"wire target differs from independent encoding"; if (self.expect_body) |body| { if (!std.mem.eql(u8, request.body, body)) self.wire_error = .@"wire body differs"; if (!std.mem.eql(u8, request.header("content-type") orelse "", "application/json")) self.wire_error = .@"procedure lacks JSON content type"; } const auth = request.header("authorization"); if (self.expect_auth) |token| { const value = auth orelse ""; if (value.len < 7 or !std.ascii.eqlIgnoreCase(value[0..7], "Bearer ") or !std.mem.eql(u8, value[7..], token)) self.wire_error = .@"bearer token differs"; } else if (auth != null) self.wire_error = .@"unauthenticated request carries authorization"; } }; fn httpDate(a: std.mem.Allocator, unix: u64) ![]const u8 { const days = [_][]const u8{ "Thu", "Fri", "Sat", "Sun", "Mon", "Tue", "Wed" }; const months = [_][]const u8{ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; const epoch: std.time.epoch.EpochSeconds = .{ .secs = unix }; const day = epoch.getEpochDay(); const year_day = day.calculateYearDay(); const month_day = year_day.calculateMonthDay(); const clock = epoch.getDaySeconds(); return std.fmt.allocPrint(a, "retry-after: {s}, {d:0>2} {s} {d} {d:0>2}:{d:0>2}:{d:0>2} GMT\r\n", .{ days[day.day % 7], month_day.day_index + 1, months[month_day.month.numeric() - 1], year_day.year, clock.getHoursIntoDay(), clock.getMinutesIntoHour(), clock.getSecondsIntoMinute(), }); } fn percentEncode(a: std.mem.Allocator, out: *std.ArrayList(u8), value: []const u8) !void { for (value) |c| switch (c) { 'a'...'z', 'A'...'Z', '0'...'9', '-', '_', '.', '~' => try out.append(a, c), else => try out.print(a, "%{X:0>2}", .{c}), }; } fn hintSeconds(hint: Hint) ?u64 { return switch (hint) { .none, .reset_delta => null, .retry_after, .retry_after_date, .reset_epoch => |s| s, }; } fn drawAttempt(case: *hegel.TestCase, keep_alive: bool) !Attempt { if (!keep_alive and try case.int(u8, 0, 9) == 0) return .refuse; const status = statuses[try case.index(statuses.len)]; const hint: Hint = switch (try case.int(u8, 0, 7)) { 0 => .{ .retry_after = try case.int(u32, 0, 90) }, 1 => .{ .retry_after_date = try case.int(u32, 1, 90) }, 2 => .{ .reset_delta = try case.int(u32, 1, 90) }, 3 => .{ .reset_epoch = try case.int(u32, 1, 90) }, else => .none, }; const faults = [_]sim.Fault{ .none, .none, .none, .none, .close_after_response, .reset_before_response, .truncate_body }; return .{ .respond = .{ .status = status, .hint = hint, .fault = faults[try case.index(faults.len)] } }; } const Outcome = union(enum) { ok, status: u16, transport }; /// the documented schedule: base_delay_ms doubled per attempt, doubling at /// most 16 times, capped at max_delay_ms fn backoff(policy: zat.XrpcClient.RetryPolicy, attempt: u8) u64 { var delay = policy.base_delay_ms; for (0..@min(attempt, 16)) |_| delay *= 2; return @min(delay, policy.max_delay_ms); } 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)), try case.int(i64, 1_700_000_000, 1_900_000_000)); var script: Script = .{ .arena = a, .now_s = &io_sim.now_ns }; var network = sim.Network.init(a, &script, Script.handle); network.max_read = try case.int(usize, 1, 512); network.refuse_connect = Script.refuse; try network.addHost(host, .{ 34, 1, 0, 1 }); io_sim.network = &network; const keep_alive = try case.boolean(); var client = zat.XrpcClient.init(io_sim.io(), a, "http://" ++ host); client.transport.keep_alive = keep_alive; sim.withoutGuards(&client.transport); defer client.deinit(); var token: ?[]const u8 = null; var machine = try case.machine(Rule, &.{ 4, 3, 1 }, 12); defer machine.deinit(); tally.case(); while (try machine.next()) |rule| { tally.step(rule); switch (rule) { .auth => { const tokens = [_]?[]const u8{ null, "token", "eyJ.a-b_c.d" }; token = tokens[try case.index(tokens.len)]; if (token) |value| client.setAuth(value) else client.access_token = null; case.note("auth {?s}", .{token}); continue; }, .query, .procedure => {}, } const method: std.http.Method = if (rule == .query) .GET else .POST; const nsid = zat.Nsid.parse("com.example.pbt.call").?; var target: std.ArrayList(u8) = .empty; try target.appendSlice(a, "/xrpc/com.example.pbt.call"); const values = [_][]const u8{ "plain", "a b&c=d", "did:plc:abc", "", "ΓΌ/?#" }; var params: [2]zat.XrpcClient.QueryParam = undefined; const param_count = if (rule == .query) try case.int(usize, 0, 2) else 0; for (params[0..param_count], 0..) |*param, index| { param.* = .{ .name = if (index == 0) "actor" else "cursor", .value = values[try case.index(values.len)] }; try target.append(a, if (index == 0) '?' else '&'); try target.appendSlice(a, param.name); try target.append(a, '='); try percentEncode(a, &target, param.value); } const bodies = [_][]const u8{ "{}", "{\"text\":\"hi\"}", "" }; const body: ?[]const u8 = if (rule == .procedure) bodies[try case.index(bodies.len)] else null; const policy: zat.XrpcClient.RetryPolicy = .{ .max_attempts = try case.int(u8, 1, max_attempts), .base_delay_ms = try case.int(u64, 0, 2_000), .max_delay_ms = try case.int(u64, 0, 60_000), .jitter_percent = 0, .retry_transient_errors = try case.boolean(), }; const attempts = try a.alloc(Attempt, @as(usize, policy.max_attempts) * client.transport.dead_connection_attempts); for (attempts) |*attempt| attempt.* = try drawAttempt(case, keep_alive); script.attempts = attempts; script.served = 0; script.refused = 0; script.expect_method = @tagName(method); script.expect_target = target.items; script.expect_body = body; script.expect_auth = token; case.note("{s} {s} body={?s} policy={any}", .{ @tagName(method), target.items, body, policy }); for (attempts, 0..) |attempt, index| case.note(" attempt {d}: {any}", .{ index, attempt }); var expected_attempts: usize = 0; var expected_ns: i96 = 0; var replays: usize = 0; var policy_attempt: u8 = 0; const replayable = method == .GET; const expected: Outcome = for (attempts) |attempt| { expected_attempts += 1; const last = policy_attempt + 1 >= policy.max_attempts; const retryable_transport, const outcome: Outcome = switch (attempt) { .refuse => .{ true, .transport }, .respond => |respond| switch (respond.fault) { .reset_before_response => blk: { if (replayable and replays + 1 < client.transport.dead_connection_attempts) { replays += 1; case.event("transport replayed request after dead connection"); continue; } break :blk .{ replayable, .transport }; }, // zat does not retry ResponseTruncated; see findings.md .truncate_body => if (transport_reports_truncation) .{ false, .transport } else .{ false, if (respond.status == 200) .ok else .{ .status = respond.status } }, .none, .close_after_response => .{ false, if (respond.status == 200) .ok else .{ .status = respond.status } }, }, }; const delay_ms: u64 = switch (outcome) { .ok => break outcome, .transport => if (!last and policy.retry_transient_errors and retryable_transport) backoff(policy, policy_attempt) else break outcome, .status => |status| blk: { const retryable = switch (status) { 429 => true, 500, 502, 503, 504 => method == .GET, else => false, }; if (last or !retryable) break outcome; const hint = hintSeconds(attempt.respond.hint); break :blk if (hint) |seconds| @min(seconds * std.time.ms_per_s, policy.max_delay_ms) else backoff(policy, policy_attempt); }, }; expected_ns += @as(i96, delay_ms) * std.time.ns_per_ms; policy_attempt += 1; replays = 0; } else unreachable; const before_ns = io_sim.now_ns; const result = if (rule == .query) client.queryParamsChecked(nsid, params[0..param_count], policy) else client.procedureChecked(nsid, body, policy); if (script.wire_error) |origin| switch (origin) { inline else => |tag| return case.fail(@tagName(tag)), }; const truncated = !transport_reports_truncation and attempts[expected_attempts - 1] == .respond and attempts[expected_attempts - 1].respond.fault == .truncate_body; if (truncated) case.event("known: zttp v0.2.0 returns a body cut short of Content-Length"); var actual: Outcome = .transport; if (result) |value| { var owned = value; defer owned.deinit(); switch (owned) { .ok => |response| { actual = .ok; if (!truncated and !std.mem.eql(u8, response.body, "{\"ok\":true}")) return case.fail("success body differs"); }, .err => |xrpc_error| { actual = .{ .status = @backingInt(xrpc_error.status) }; const name = try std.fmt.allocPrint(a, "Status{d}", .{@backingInt(xrpc_error.status)}); if (!truncated and !std.mem.eql(u8, xrpc_error.error_name orelse "", name)) return case.fail("XRPC error name not parsed from body"); }, } } else |err| { case.note("transport error {s}", .{@errorName(err)}); if (err == error.OutOfMemory) return err; } case.note("expected {any} after {d} attempts, {d} ns; actual {any}, {d} ns", .{ expected, expected_attempts, expected_ns, actual, io_sim.now_ns - before_ns }); if (!std.meta.eql(expected, actual)) return case.fail("XRPC outcome differs from retry model"); if (script.served != expected_attempts) return case.fail("server saw a different number of attempts"); if (io_sim.now_ns - before_ns != expected_ns) return case.fail("retry backoff differs from server hints and policy"); switch (expected) { .ok => case.event("call succeeded"), .status => case.event("call returned XRPC error"), .transport => case.event("call failed in transport"), } if (expected_attempts > 1) case.event("call retried"); } tally.finish(network.requests); } pub fn main() !void { defer tally.print(); try hegel.run(.{ .key = "xrpc" }, {}, property); }