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
//! frame processing worker — heavy frame handling offloaded from reader threads
//!
//! the reader thread (subscriber) does lightweight header decode, cursor tracking,
//! and rate limiting, then submits raw frame bytes here for heavy processing:
//! CBOR decode, DID resolution, signature validation, DB persist, broadcast.
//!
//! double decode (reader + worker both parse CBOR header) is intentional —
//! CBOR decode is ~1-2μs, far cheaper than serializing decoded values across threads.
const std = @import("std");
const Io = std.Io;
const zat = @import("zat");
const broadcaster = @import("broadcaster.zig");
const validator_mod = @import("validator.zig");
const event_log_mod = @import("event_log.zig");
const collection_index_mod = @import("collection_index/index.zig");
const resync_mod = @import("collection_index/resync.zig");
const status_checker_mod = @import("status_checker.zig");
const thread_pool = @import("util/thread_pool.zig");
const util = @import("util/util.zig");
const ingest_ack = @import("ingest_ack.zig");
const replay_profile = @import("build_options").offline_replay or @import("build_options").profile_stages;
const Allocator = std.mem.Allocator;
const log = std.log.scoped(.relay);
const microTimestamp = util.microTimestamp;
pub const FrameWork = struct {
data: []u8, // raw frame bytes (heap-duped by reader, freed by worker)
host_id: u64,
hostname: []const u8, // owned (heap-duped at submit, freed by worker)
allocator: Allocator,
io: Io,
// shared references (all thread-safe, all outlive the work item)
bc: *broadcaster.Broadcaster,
validator: *validator_mod.Validator,
persist: ?*event_log_mod.DiskPersist,
collection_index: ?*collection_index_mod.CollectionIndex,
resyncer: ?*resync_mod.Resyncer,
status_checker: ?*status_checker_mod.StatusChecker = null,
receipt: ?*ingest_ack.Receipt = null,
};
pub fn processFrame(work: *FrameWork) void {
var success = false;
defer if (work.receipt) |receipt| receipt.complete(success);
_ = work.bc.stats.pool_queued_bytes.fetchSub(work.data.len, .monotonic);
defer work.allocator.free(work.data);
defer work.allocator.free(work.hostname);
processFrameInner(work) catch |err| {
log.warn("frame processing failed for host {s}: {s}", .{ work.hostname, @errorName(err) });
return;
};
success = true;
}
fn processFrameInner(work: *FrameWork) !void {
const entered = if (comptime replay_profile) Io.Clock.awake.now(work.io) else undefined;
defer if (comptime replay_profile) work.bc.stats.replay_frame.observe(entered.durationTo(Io.Clock.awake.now(work.io)).toNanoseconds());
var arena = std.heap.ArenaAllocator.init(work.allocator);
defer arena.deinit();
const alloc = arena.allocator();
const data = work.data;
// re-decode header (cheap — ~1-2μs)
const header_result = zat.cbor.decode(alloc, data) catch |err| {
if (err == error.OutOfMemory) return err;
log.debug("worker: frame header decode failed: {s} (len={d})", .{ @errorName(err), data.len });
_ = work.bc.stats.decode_errors.fetchAdd(1, .monotonic);
return;
};
const header = header_result.value;
const payload_data = data[header_result.consumed..];
const op = header.getInt("op") orelse return;
if (op != 1) return; // only process message frames (error frames handled by reader)
const frame_type = header.getString("t") orelse return;
const payload = zat.cbor.decodeAll(alloc, payload_data) catch |err| {
if (err == error.OutOfMemory) return err;
log.debug("worker: frame payload decode failed: {s} (type={s})", .{ @errorName(err), frame_type });
_ = work.bc.stats.decode_errors.fetchAdd(1, .monotonic);
return;
};
// route by frame type — unknown types already filtered by reader
const is_commit = std.mem.eql(u8, frame_type, "#commit");
const is_sync = std.mem.eql(u8, frame_type, "#sync");
const is_account = std.mem.eql(u8, frame_type, "#account");
const is_identity = std.mem.eql(u8, frame_type, "#identity");
if (!is_commit and !is_sync and !is_account and !is_identity) return;
// extract DID: "repo" for commits, "did" for identity/account
const did: ?[]const u8 = if (is_commit)
payload.getString("repo")
else
payload.getString("did");
// on #identity event, evict cached signing key so next commit re-resolves
if (is_identity) {
if (did) |d| work.validator.evictKey(d);
}
// resolve DID → numeric UID for event header (host-aware)
const uid: u64 = if (work.persist) |dp| blk: {
if (did) |d| {
const result = try dp.uidForDidFromHost(d, work.host_id);
// host authority enforcement: verify DID doc confirms this host.
// #identity events are exempt — any PDS can emit them (same as indigo).
// covers both first-seen DIDs (is_new) and host migrations (host_changed).
if ((result.is_new or result.host_changed) and !is_identity) {
if (result.is_new) _ = work.bc.stats.host_authority_is_new.fetchAdd(1, .monotonic);
if (result.host_changed) _ = work.bc.stats.host_authority_host_changed.fetchAdd(1, .monotonic);
_ = work.bc.stats.host_authority_checks.fetchAdd(1, .monotonic);
const ha_t0 = microTimestamp(work.io);
defer {
const elapsed: u64 = @intCast(@max(0, microTimestamp(work.io) - ha_t0));
_ = work.bc.stats.host_authority_time_us.fetchAdd(elapsed, .monotonic);
}
switch (work.validator.resolveHostAuthority(d, work.host_id, work.hostname, .{
.skip_reject_cache = is_account,
})) {
.migrate => {
// DID doc confirms the host — update and continue
try dp.setAccountHostId(result.uid, work.host_id);
if (result.host_changed) {
log.info("host {s}: account migrated uid={d} did={s}", .{
work.hostname, result.uid, d,
});
}
},
.reject => {
// DID doc does not confirm — drop the event. Network-confirmed
// first occurrences are sampled by Validator; cache hits stay quiet.
log.debug("host {s}: dropping event, host authority failed uid={d} did={s}", .{
work.hostname, result.uid, d,
});
_ = work.bc.stats.failed.fetchAdd(1, .monotonic);
_ = work.bc.stats.failed_host_authority.fetchAdd(1, .monotonic);
return;
},
.accept => {},
}
}
break :blk result.uid;
} else break :blk @as(u64, 0);
} else 0;
// process #account events: update upstream status
if (is_account) {
if (work.persist) |dp| {
if (uid > 0) {
const is_active = payload.getBool("active") orelse false;
const status_str = payload.getString("status");
const new_status: []const u8 = if (is_active)
"active"
else
(status_str orelse "inactive");
dp.updateAccountUpstreamStatus(uid, new_status) catch |err| {
log.debug("upstream status update failed: {s}", .{@errorName(err)});
};
// on any non-active status, remove all collection index entries
// (covers deleted, takendown, suspended, deactivated, and future unknown statuses)
if (!is_active) {
if (work.collection_index) |ci| {
if (did) |d| {
ci.removeAll(d) catch |err| {
log.debug("collection removeAll failed: {s}", .{@errorName(err)});
};
}
}
}
}
}
}
// for commits and syncs: check account is active, validate, extract state
var commit_data_cid: ?[]const u8 = null;
var commit_cid: ?[]const u8 = null;
var commit_rev: ?[]const u8 = null;
if (is_commit or is_sync) {
// drop events for inactive accounts.
if (work.persist) |dp| {
if (uid > 0) {
const activity = try dp.accountActivity(uid);
if (!activity.active()) {
// a repo event from the account's own confirmed host while
// upstream_status is non-active is self-contradicting — the
// PDS wouldn't emit it for an account inactive on it. usual
// cause: a migration's #account activation was lost. queue a
// getRepoStatus re-check (never for local takedowns).
if (activity.local_ok and !activity.upstream_ok) {
if (work.status_checker) |sc| {
if (did) |d| sc.enqueue(uid, d, work.hostname);
}
}
_ = work.bc.stats.skipped.fetchAdd(1, .monotonic);
return;
}
}
}
// rev checks: stale, future, chain continuity
if (is_commit and uid > 0) {
if (payload.getString("rev")) |incoming_rev| {
// future-rev rejection: drop commits with timestamps too far ahead
if (zat.Tid.parse(incoming_rev)) |tid| {
const rev_us: i64 = @intCast(tid.timestamp());
const now_us = microTimestamp(work.io);
const skew_us: i64 = work.validator.config.rev_clock_skew * 1_000_000;
if (rev_us > now_us + skew_us) {
log.info("host {s}: dropping future rev uid={d} rev={s}", .{
work.hostname, uid, incoming_rev,
});
_ = work.bc.stats.failed.fetchAdd(1, .monotonic);
_ = work.bc.stats.failed_future_rev.fetchAdd(1, .monotonic);
return;
}
}
if (work.persist) |dp| {
if (try dp.getAccountState(uid, alloc)) |prev| {
// stale rev check
if (std.mem.order(u8, incoming_rev, prev.rev) != .gt) {
log.debug("host {s}: dropping stale commit uid={d} rev={s} <= {s}", .{
work.hostname, uid, incoming_rev, prev.rev,
});
_ = work.bc.stats.skipped.fetchAdd(1, .monotonic);
return;
}
// chain continuity: since should match stored rev
if (payload.getString("since")) |since| {
if (!std.mem.eql(u8, since, prev.rev)) {
log.info("host {s}: chain break uid={d} since={s} stored_rev={s}", .{
work.hostname, uid, since, prev.rev,
});
_ = work.bc.stats.chain_breaks_since.fetchAdd(1, .monotonic);
}
}
// With prior repo state, prevData is required for an
// inductive Sync 1.1 proof. Missing/null cannot be
// repaired by MST inversion, so drop the commit.
if (!work.validator.validatePrevDataPresence(payload)) {
log.info("host {s}: dropping commit with missing prevData uid={d}", .{
work.hostname, uid,
});
return;
}
// chain continuity: prevData CID should match stored data_cid.
// only meaningful with verify_commit_diff — that's the only path
// that stores a real MST root in data_cid.
if (work.validator.config.verify_commit_diff) {
if (payload.get("prevData")) |pd| {
if (pd == .cid) {
const prev_data_encoded = try zat.multibase.encode(alloc, .base32lower, pd.cid.raw);
if (prev_data_encoded.len > 0 and prev.data_cid.len > 0 and
!std.mem.eql(u8, prev_data_encoded, prev.data_cid))
{
log.info("host {s}: chain break uid={d} prevData mismatch", .{
work.hostname, uid,
});
_ = work.bc.stats.chain_breaks_prev_data.fetchAdd(1, .monotonic);
}
}
}
}
}
}
}
}
if (is_commit) {
const result = result: {
const began = if (comptime replay_profile) Io.Clock.awake.now(work.io) else undefined;
defer if (comptime replay_profile) work.bc.stats.replay_validate.observe(began.durationTo(Io.Clock.awake.now(work.io)).toNanoseconds());
break :result work.validator.validateCommitObserved(payload, .{ .frame = data, .host = work.hostname });
};
if (!result.valid) return;
commit_data_cid = result.data_cid;
commit_cid = result.commit_cid;
commit_rev = result.commit_rev;
// track collections from commit ops (phase 1 live indexing)
if (work.collection_index) |ci| {
if (did) |d| {
if (payload.get("ops")) |ops| {
const began = if (comptime replay_profile) Io.Clock.awake.now(work.io) else undefined;
defer if (comptime replay_profile) work.bc.stats.replay_index.observe(began.durationTo(Io.Clock.awake.now(work.io)).toNanoseconds());
try ci.trackCommitOps(d, ops);
}
}
}
} else {
// #sync: signature verification only, no ops/MST
const result = work.validator.validateSync(payload);
if (!result.valid) return;
commit_data_cid = result.data_cid;
commit_cid = result.commit_cid;
commit_rev = result.commit_rev;
// enqueue collection index resync — #sync means repo discontinuity
if (work.resyncer) |r| {
if (did) |d| r.enqueue(d, work.hostname);
}
}
}
const post_index = if (comptime replay_profile) Io.Clock.awake.now(work.io) else undefined;
defer if (comptime replay_profile) work.bc.stats.replay_post_index.observe(post_index.durationTo(Io.Clock.awake.now(work.io)).toNanoseconds());
// determine event kind for persistence
const kind: event_log_mod.EvtKind = if (is_commit)
.commit
else if (is_sync)
.sync
else if (is_account)
.account
else
.identity;
// persist + resequence + enqueue under ordering lock to guarantee
// broadcast_queue insertion order matches seq assignment order.
if (work.persist) |dp| {
work.bc.lockPersistOrder(work.io);
const relay_seq = dp.persist(kind, uid, data) catch |err| {
work.bc.unlockPersistOrder();
log.warn("persist failed: {s}", .{@errorName(err)});
return err;
};
work.bc.stats.relay_seq.store(relay_seq, .release);
const broadcast_data = broadcaster.resequenceFrame(alloc, data, relay_seq) orelse {
work.bc.unlockPersistOrder();
return error.FrameResequenceFailed;
};
const owned = work.allocator.dupe(u8, broadcast_data) catch |err| {
work.bc.unlockPersistOrder();
return err;
};
work.bc.broadcast_queue.push(relay_seq, owned, &work.bc.stats, work.io);
work.bc.unlockPersistOrder();
try dp.flush();
// update per-DID state outside the ordering lock (Postgres round-trip)
if ((is_commit or is_sync) and uid > 0) {
if (commit_rev) |rev| {
const cid_str: []const u8 = if (commit_data_cid) |cid_raw|
try zat.multibase.encode(alloc, .base32lower, cid_raw)
else
"";
const head_str = if (commit_cid) |cid_raw| try zat.multibase.encode(alloc, .base32lower, cid_raw) else "";
if (dp.updateAccountState(uid, rev, cid_str, head_str)) |updated| {
if (!updated) {
log.debug("host {s}: stale state update lost race uid={d} rev={s}", .{
work.hostname, uid, rev,
});
}
} else |err| {
log.debug("account state update failed: {s}", .{@errorName(err)});
return err;
}
}
}
} else {
const upstream_seq = payload.getUint("seq") orelse 0;
const owned = try work.allocator.dupe(u8, data);
work.bc.broadcast_queue.push(upstream_seq, owned, &work.bc.stats, work.io);
}
}
pub const FramePool = thread_pool.ThreadPool(FrameWork, processFrame);