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
const std = @import("std");
const zat = @import("zat");
const broadcaster = @import("internal/broadcaster.zig");
const validator = @import("internal/validator.zig");
const event_log = @import("internal/event_log.zig");
const index = @import("internal/collection_index/index.zig");
const frame_worker = @import("internal/frame_worker.zig");
const subscriber = @import("internal/subscriber.zig");
const util = @import("internal/util/util.zig");
const Entry = struct { frame: []const u8, did: []const u8, rev: []const u8 };
const SubmissionTime = struct { scheduled_ns: i96, began_ns: i96, accepted_ns: i96 };
fn readClockMetadata(allocator: std.mem.Allocator, io: std.Io, path: []const u8) ![]const u8 {
const file = try std.Io.Dir.cwd().openFile(io, path, .{});
defer file.close(io);
var buffer: [256]u8 = undefined;
var reader = file.readerStreaming(io, &buffer);
return reader.interface.allocRemaining(allocator, .limited(4096));
}
pub fn run(
allocator: std.mem.Allocator,
io: std.Io,
pool_io: std.Io,
bc: *broadcaster.Broadcaster,
val: *validator.Validator,
dp: *event_log.DiskPersist,
ci: *index.CollectionIndex,
pool: *frame_worker.FramePool,
shutdown: *std.atomic.Value(bool),
) !void {
const path = util.getenv("RELAY_REPLAY_CORPUS") orelse return error.MissingReplayCorpus;
const start_file = util.getenv("RELAY_REPLAY_START") orelse return error.MissingReplayStart;
const trace_path = util.getenv("RELAY_REPLAY_TRACE_PATH");
const trace_enabled = trace_path != null and trace_path.?.len != 0;
if (trace_enabled and @import("builtin").os.tag != .linux) return error.TraceRequiresLinux;
const rate = util.parseEnvInt(u64, "RELAY_REPLAY_RATE", 500);
const limit = util.parseEnvInt(usize, "RELAY_REPLAY_LIMIT", 64);
if (rate == 0 or rate > 5000 or limit == 0 or limit > 10000) return error.InvalidReplayBounds;
var arena = std.heap.ArenaAllocator.init(allocator);
defer arena.deinit();
const a = arena.allocator();
const complete_file = try std.fmt.allocPrint(a, "{s}.complete", .{start_file});
if (std.Io.Dir.cwd().access(io, complete_file, .{})) |_| {
std.log.info("REPLAY_REOPEN", .{});
return;
} else |err| if (err != error.FileNotFound) return err;
const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, a, .limited(64 << 20));
const corpus = try @import("relay_corpus").parse(a, bytes);
const total = corpus.len;
var entries: std.ArrayList(Entry) = .empty;
for (corpus[0..@min(limit, total)]) |entry| {
const raw = entry.frame;
const header = try zat.cbor.decode(a, raw);
if (header.value.getInt("op") != 1 or !std.mem.eql(u8, header.value.getString("t") orelse "", "#commit")) return error.InvalidCorpusFrame;
const body = try zat.cbor.decodeAll(a, raw[header.consumed..]);
const did = body.getString("repo") orelse return error.MissingCorpusDid;
try val.cache.put(did, .{
.key_type = if (entry.curve_type == 0) .p256 else .secp256k1,
.raw = entry.pubkey[0..33].*,
.len = 33,
.resolve_time = util.timestamp(pool_io),
});
const result = val.validateCommit(body);
if (!result.valid or result.skipped) return error.CorpusValidationFailed;
try entries.append(a, .{ .frame = raw, .did = did, .rev = body.getString("rev") orelse return error.MissingCorpusRevision });
}
const times: []SubmissionTime = if (trace_enabled) try a.alloc(SubmissionTime, entries.items.len) else &.{};
const boot_id = if (trace_enabled) try readClockMetadata(a, io, "/proc/sys/kernel/random/boot_id") else "";
const time_offsets = if (trace_enabled) try readClockMetadata(a, io, "/proc/self/timens_offsets") else "";
const ready_file = try std.fmt.allocPrint(a, "{s}.ready", .{start_file});
try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = ready_file, .data = "ready" });
std.log.info("REPLAY_READY frames={d} rate={d}", .{ entries.items.len, rate });
const deadline = std.Io.Clock.awake.now(io).addDuration(.fromSeconds(30));
while (true) {
if (std.Io.Dir.cwd().access(io, start_file, .{})) |_| break else |err| {
if (err != error.FileNotFound) return err;
}
if (std.Io.Clock.awake.now(io).compare(.gte, deadline)) return error.ReplayStartTimeout;
try io.sleep(.fromMilliseconds(10), .awake);
}
var sub = subscriber.Subscriber.init(allocator, io, bc, val, dp, shutdown, .{ .hostname = "offline.host.bsky.network" });
sub.pool = pool;
sub.pool_io = pool_io;
sub.collection_index = ci;
defer sub.progress.drain(&sub.last_upstream_seq, true) catch {};
const validated_before = bc.stats.validated.load(.acquire);
const skipped_before = bc.stats.skipped.load(.acquire);
const failed_before = bc.stats.failed.load(.acquire);
const started = std.Io.Clock.awake.now(io);
var max_schedule_ns: i96 = 0;
var max_submit_ns: i96 = 0;
for (entries.items, 0..) |entry, i| {
const due = started.addDuration(.fromNanoseconds(@intCast(i * std.time.ns_per_s / rate)));
const now = std.Io.Clock.awake.now(io);
if (now.compare(.lt, due)) try io.sleep(now.durationTo(due), .awake);
const began = std.Io.Clock.awake.now(io);
max_schedule_ns = @max(max_schedule_ns, due.durationTo(began).toNanoseconds());
try sub.acceptFrame(entry.frame);
const accepted = std.Io.Clock.awake.now(io);
max_submit_ns = @max(max_submit_ns, began.durationTo(accepted).toNanoseconds());
if (trace_enabled) times[i] = .{ .scheduled_ns = due.nanoseconds, .began_ns = began.nanoseconds, .accepted_ns = accepted.nanoseconds };
}
const submitted = std.Io.Clock.awake.now(io);
try sub.progress.drain(&sub.last_upstream_seq, true);
try dp.flush();
const finished = std.Io.Clock.awake.now(io);
const valid = bc.stats.validated.load(.acquire) - validated_before;
const skipped = bc.stats.skipped.load(.acquire) - skipped_before;
const failed = bc.stats.failed.load(.acquire) - failed_before;
std.log.info("REPLAY_DONE frames={d} validated={d} skipped={d} failed={d} submit_ns={d} drain_ns={d} schedule_max_ns={d} submit_max_ns={d}", .{
entries.items.len, valid, skipped, failed,
started.durationTo(submitted).toNanoseconds(), submitted.durationTo(finished).toNanoseconds(), max_schedule_ns, max_submit_ns,
});
if (valid != entries.items.len or skipped != 0 or failed != 0) return error.ReplayVerificationFailed;
const profiles = .{ &bc.stats.replay_frame, &bc.stats.replay_validate, &bc.stats.replay_index, &bc.stats.replay_post_index };
inline for (profiles, .{ "frame", "validate", "index", "post_index" }) |profile, name| {
if (profile.count.load(.acquire) != valid) return error.IncompleteReplayProfile;
std.log.info("REPLAY_PROFILE stage={s} count={d} total_ns={d} max_ns={d}", .{
name, profile.count.load(.acquire), profile.total_ns.load(.acquire), profile.max_ns.load(.acquire),
});
}
if (trace_enabled) {
const Row = struct { did: []const u8, rev: []const u8, scheduled_ns: []const u8, began_ns: []const u8, accepted_ns: []const u8 };
const rows = try a.alloc(Row, entries.items.len);
for (entries.items, times, rows) |entry, time, *row| row.* = .{
.did = entry.did,
.rev = entry.rev,
.scheduled_ns = try std.fmt.allocPrint(a, "{d}", .{time.scheduled_ns}),
.began_ns = try std.fmt.allocPrint(a, "{d}", .{time.began_ns}),
.accepted_ns = try std.fmt.allocPrint(a, "{d}", .{time.accepted_ns}),
};
const trace = try std.json.Stringify.valueAlloc(a, .{
.clock = .{ .clock = "CLOCK_MONOTONIC", .platform = "linux", .boot_id = std.mem.trim(u8, boot_id, " \t\r\n"), .time_offsets = std.mem.trim(u8, time_offsets, " \t\r\n") },
.frames = rows,
}, .{});
try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = trace_path.?, .data = trace });
}
try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = complete_file, .data = "complete" });
}