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
//! admin endpoint handlers for relay management.
//!
//! all handlers require Bearer token auth against RELAY_ADMIN_PASSWORD.
//! includes host blocking/unblocking, account bans, and backfill control.
//!
//! DB-accessing handlers use DbRequest + DbRequestQueue to route queries
//! through pool_io workers.
const std = @import("std");
const Io = std.Io;
const h = @import("http.zig");
const router = @import("router.zig");
const websocket = @import("websocket");
const event_log_mod = @import("../event_log.zig");
const backfill_mod = @import("../collection_index/backfill.zig");
const cleaner_mod = @import("../collection_index/cleaner.zig");
const resync_mod = @import("../collection_index/resync.zig");
const util = @import("../util/util.zig");
const log = std.log.scoped(.relay);
/// default idle window for /admin/hosts/reconnect. Long enough that an
/// ordinarily quiet PDS is not mistaken for a deaf one, short enough to be
/// useful during an incident. Overridable per call.
const default_reconnect_min_idle_s: i64 = 60;
const getenv = util.getenv;
const formatTimestamp = util.formatTimestamp;
const HttpContext = router.HttpContext;
const DbRequest = event_log_mod.DbRequest;
const DiskPersist = event_log_mod.DiskPersist;
/// check admin auth via headers, send error response if not authorized. returns true if authorized.
pub fn checkAdmin(conn: *h.Conn, headers: ?*const websocket.Handshake.KeyValue) bool {
const admin_pw = getenv("RELAY_ADMIN_PASSWORD") orelse {
h.respondJson(conn, .forbidden, "{\"error\":\"admin endpoint not configured\"}");
return false;
};
const kv = headers orelse {
h.respondJson(conn, .unauthorized, "{\"error\":\"missing authorization header\"}");
return false;
};
// handshake parser lowercases all header names
const auth_value = kv.get("authorization") orelse {
h.respondJson(conn, .unauthorized, "{\"error\":\"missing authorization header\"}");
return false;
};
const bearer_prefix = "Bearer ";
if (!std.mem.startsWith(u8, auth_value, bearer_prefix)) {
h.respondJson(conn, .unauthorized, "{\"error\":\"invalid authorization scheme\"}");
return false;
}
const token = auth_value[bearer_prefix.len..];
if (!std.mem.eql(u8, token, admin_pw)) {
h.respondJson(conn, .unauthorized, "{\"error\":\"invalid token\"}");
return false;
}
return true;
}
pub fn handleBan(conn: *h.Conn, body: []const u8, headers: *const websocket.Handshake.KeyValue, ctx: *HttpContext) void {
if (!checkAdmin(conn, headers)) return;
const parsed = std.json.parseFromSlice(struct { did: []const u8 }, ctx.persist.allocator, body, .{ .ignore_unknown_fields = true }) catch {
h.respondJson(conn, .bad_request, "{\"error\":\"invalid JSON, expected {\\\"did\\\":\\\"...\\\"}\"}");
return;
};
defer parsed.deinit();
const did = parsed.value.did;
// resolve DID → UID via DbRequestQueue
const UidReq = struct {
base: DbRequest = .{ .callback = &execute },
did_buf: [256]u8 = undefined,
did_len: usize = 0,
uid: u64 = 0,
fn execute(b: *DbRequest, dp: *DiskPersist) void {
const self: *@This() = @fieldParentPtr("base", b);
const d = self.did_buf[0..self.did_len];
// check database
if (dp.db.rowUnsafe("SELECT uid FROM account WHERE did = $1", .{d}) catch null) |row| {
var r = row;
defer r.deinit() catch {};
self.uid = @intCast(r.get(i64, 0));
return;
}
// create new account row
_ = dp.db.exec("INSERT INTO account (did) VALUES ($1) ON CONFLICT (did) DO NOTHING", .{d}) catch {
b.err = error.DatabaseError;
return;
};
var row = dp.db.rowUnsafe("SELECT uid FROM account WHERE did = $1", .{d}) catch {
b.err = error.DatabaseError;
return;
} orelse {
b.err = error.AccountCreationFailed;
return;
};
defer row.deinit() catch {};
self.uid = @intCast(row.get(i64, 0));
}
};
var uid_req: UidReq = .{};
const copy_len = @min(did.len, uid_req.did_buf.len);
@memcpy(uid_req.did_buf[0..copy_len], did[0..copy_len]);
uid_req.did_len = copy_len;
ctx.db_queue.push(&uid_req.base);
uid_req.base.wait(ctx.io, ctx.shutdown);
if (uid_req.base.err != null) {
h.respondJson(conn, .internal_server_error, "{\"error\":\"failed to resolve DID\"}");
return;
}
// remove from collection index so banned accounts don't appear in listReposByCollection
ctx.collection_index.removeAll(did) catch |err| {
log.debug("collection removeAll after ban failed: {s}", .{@errorName(err)});
};
// build CBOR #account frame and route takedown + persist + broadcast
// through host_ops queue (pool_io thread) — fire and forget.
const host_ops_mod = @import("../host_ops.zig");
var td: host_ops_mod.HostOp.Payload.Takedown = .{ .uid = uid_req.uid };
if (buildAccountFrame(ctx.persist.allocator, did)) |frame_bytes| {
defer ctx.persist.allocator.free(frame_bytes);
if (frame_bytes.len <= td.frame_buf.len) {
@memcpy(td.frame_buf[0..frame_bytes.len], frame_bytes);
td.frame_len = @intCast(frame_bytes.len);
}
}
ctx.host_ops.push(.{
.host_id = 0, // not host-specific
.kind = .takedown_user,
.payload = .{ .takedown = td },
});
log.info("admin: banned {s} (uid={d}), takedown enqueued", .{ did, uid_req.uid });
h.respondJson(conn, .ok, "{\"success\":true}");
}
pub fn handleAdminListHosts(conn: *h.Conn, headers: *const websocket.Handshake.KeyValue, ctx: *HttpContext) void {
if (!checkAdmin(conn, headers)) return;
// list all hosts via DbRequestQueue
const ListAllHostsReq = struct {
base: DbRequest = .{ .callback = &execute },
alloc: std.mem.Allocator,
result: ?[]event_log_mod.DiskPersist.Host = null,
fn execute(b: *DbRequest, dp: *DiskPersist) void {
const self: *@This() = @fieldParentPtr("base", b);
self.result = dp.listAllHosts(self.alloc) catch |e| {
b.err = e;
return;
};
}
};
var list_req: ListAllHostsReq = .{ .alloc = ctx.persist.allocator };
ctx.db_queue.push(&list_req.base);
list_req.base.wait(ctx.io, ctx.shutdown);
if (list_req.base.err != null or list_req.result == null) {
h.respondJson(conn, .internal_server_error, "{\"error\":\"DatabaseError\",\"message\":\"query failed\"}");
return;
}
const hosts = list_req.result.?;
defer {
for (hosts) |host| {
ctx.persist.allocator.free(host.hostname);
ctx.persist.allocator.free(host.status);
}
ctx.persist.allocator.free(hosts);
}
var aw: Io.Writer.Allocating = .init(ctx.persist.allocator);
defer aw.deinit();
const w = &aw.writer;
w.writeAll("{\"hosts\":[") catch return;
for (hosts, 0..) |host, i| {
if (i > 0) w.writeByte(',') catch return;
if (host.account_limit) |limit| {
w.print("{{\"id\":{d},\"hostname\":\"{s}\",\"status\":\"{s}\",\"last_seq\":{d},\"failed_attempts\":{d},\"account_limit\":{d}}}", .{
host.id,
host.hostname,
host.status,
host.last_seq,
host.failed_attempts,
limit,
}) catch return;
} else {
w.print("{{\"id\":{d},\"hostname\":\"{s}\",\"status\":\"{s}\",\"last_seq\":{d},\"failed_attempts\":{d},\"account_limit\":null}}", .{
host.id,
host.hostname,
host.status,
host.last_seq,
host.failed_attempts,
}) catch return;
}
}
w.print("],\"active_workers\":{d}}}", .{ctx.slurper.workerCount()}) catch return;
h.respondJson(conn, .ok, aw.written());
}
pub fn handleAdminBlockHost(conn: *h.Conn, body: []const u8, headers: *const websocket.Handshake.KeyValue, ctx: *HttpContext) void {
if (!checkAdmin(conn, headers)) return;
const parsed = std.json.parseFromSlice(struct { hostname: []const u8 }, ctx.persist.allocator, body, .{ .ignore_unknown_fields = true }) catch {
h.respondJson(conn, .bad_request, "{\"error\":\"BadRequest\",\"message\":\"invalid JSON\"}");
return;
};
defer parsed.deinit();
const BlockHostReq = struct {
base: DbRequest = .{ .callback = &execute },
hostname_buf: [256]u8 = undefined,
hostname_len: usize = 0,
host_id: u64 = 0,
fn execute(b: *DbRequest, dp: *DiskPersist) void {
const self: *@This() = @fieldParentPtr("base", b);
const hn = self.hostname_buf[0..self.hostname_len];
const info = dp.getOrCreateHost(hn) catch |e| {
b.err = e;
return;
};
self.host_id = info.id;
dp.updateHostStatus(info.id, "blocked") catch |e| {
b.err = e;
return;
};
}
};
var req: BlockHostReq = .{};
const copy_len = @min(parsed.value.hostname.len, req.hostname_buf.len);
@memcpy(req.hostname_buf[0..copy_len], parsed.value.hostname[0..copy_len]);
req.hostname_len = copy_len;
ctx.db_queue.push(&req.base);
req.base.wait(ctx.io, ctx.shutdown);
if (req.base.err != null) {
h.respondJson(conn, .internal_server_error, "{\"error\":\"DatabaseError\",\"message\":\"operation failed\"}");
return;
}
log.info("admin: blocked host {s} (id={d})", .{ parsed.value.hostname, req.host_id });
h.respondJson(conn, .ok, "{\"success\":true}");
}
pub fn handleAdminUnblockHost(conn: *h.Conn, body: []const u8, headers: *const websocket.Handshake.KeyValue, ctx: *HttpContext) void {
if (!checkAdmin(conn, headers)) return;
const parsed = std.json.parseFromSlice(struct { hostname: []const u8 }, ctx.persist.allocator, body, .{ .ignore_unknown_fields = true }) catch {
h.respondJson(conn, .bad_request, "{\"error\":\"BadRequest\",\"message\":\"invalid JSON\"}");
return;
};
defer parsed.deinit();
const UnblockHostReq = struct {
base: DbRequest = .{ .callback = &execute },
hostname_buf: [256]u8 = undefined,
hostname_len: usize = 0,
host_id: u64 = 0,
fn execute(b: *DbRequest, dp: *DiskPersist) void {
const self: *@This() = @fieldParentPtr("base", b);
const hn = self.hostname_buf[0..self.hostname_len];
const info = dp.getOrCreateHost(hn) catch |e| {
b.err = e;
return;
};
self.host_id = info.id;
dp.updateHostStatus(info.id, "active") catch |e| {
b.err = e;
return;
};
dp.resetHostFailures(info.id) catch {};
}
};
var req: UnblockHostReq = .{};
const copy_len = @min(parsed.value.hostname.len, req.hostname_buf.len);
@memcpy(req.hostname_buf[0..copy_len], parsed.value.hostname[0..copy_len]);
req.hostname_len = copy_len;
ctx.db_queue.push(&req.base);
req.base.wait(ctx.io, ctx.shutdown);
if (req.base.err != null) {
h.respondJson(conn, .internal_server_error, "{\"error\":\"DatabaseError\",\"message\":\"operation failed\"}");
return;
}
log.info("admin: unblocked host {s} (id={d})", .{ parsed.value.hostname, req.host_id });
h.respondJson(conn, .ok, "{\"success\":true}");
}
/// force a host's worker to drop and re-establish its connection.
///
/// In-band recovery for a worker that is alive but deaf. Unlike
/// block+unblock this never changes the host's status, so a host cannot be
/// left stranded as blocked if the operator's second call does not land.
///
/// POST /admin/hosts/reconnect?min_idle_seconds=60&dry_run=true
/// body: {"hostname": "..."}
///
/// `min_idle_seconds` guards against tearing down a healthy worker: a deaf
/// host and a merely quiet host are indistinguishable from seq sampling, so
/// reconnecting on silence alone manufactures the connection churn it is
/// trying to recover from. It is a query parameter, not a constant, so the
/// window can be widened mid-incident without a redeploy.
pub fn handleAdminReconnectHost(conn: *h.Conn, query: []const u8, body: []const u8, headers: *const websocket.Handshake.KeyValue, ctx: *HttpContext) void {
if (!checkAdmin(conn, headers)) return;
const min_idle_s = blk: {
const raw = h.queryParam(query, "min_idle_seconds") orelse break :blk default_reconnect_min_idle_s;
break :blk std.fmt.parseInt(i64, raw, 10) catch {
h.respondJson(conn, .bad_request, "{\"error\":\"BadRequest\",\"message\":\"min_idle_seconds must be an integer\"}");
return;
};
};
if (min_idle_s < 0) {
h.respondJson(conn, .bad_request, "{\"error\":\"BadRequest\",\"message\":\"min_idle_seconds must not be negative\"}");
return;
}
const dry_run = if (h.queryParam(query, "dry_run")) |v| std.mem.eql(u8, v, "true") else false;
const parsed = std.json.parseFromSlice(struct { hostname: []const u8 }, ctx.persist.allocator, body, .{ .ignore_unknown_fields = true }) catch {
h.respondJson(conn, .bad_request, "{\"error\":\"BadRequest\",\"message\":\"invalid JSON\"}");
return;
};
defer parsed.deinit();
// resolve the host WITHOUT creating it: reconnecting a host we have never
// seen is a caller error, not a reason to add one.
const LookupReq = struct {
base: DbRequest = .{ .callback = &execute },
hostname_buf: [256]u8 = undefined,
hostname_len: usize = 0,
host_id: u64 = 0,
found: bool = false,
fn execute(b: *DbRequest, dp: *DiskPersist) void {
const self: *@This() = @fieldParentPtr("base", b);
const hn = self.hostname_buf[0..self.hostname_len];
const maybe_id = dp.getHostIdForHostname(hn) catch |e| {
b.err = e;
return;
};
if (maybe_id) |id| {
self.host_id = id;
self.found = true;
}
}
};
var req: LookupReq = .{};
const copy_len = @min(parsed.value.hostname.len, req.hostname_buf.len);
@memcpy(req.hostname_buf[0..copy_len], parsed.value.hostname[0..copy_len]);
req.hostname_len = copy_len;
ctx.db_queue.push(&req.base);
req.base.wait(ctx.io, ctx.shutdown);
if (req.base.err != null) {
h.respondJson(conn, .internal_server_error, "{\"error\":\"DatabaseError\",\"message\":\"operation failed\"}");
return;
}
if (!req.found) {
h.respondJson(conn, .not_found, "{\"error\":\"NotFound\",\"message\":\"unknown host\"}");
return;
}
const min_idle_ms = min_idle_s * std.time.ms_per_s;
var buf: [256]u8 = undefined;
if (dry_run) {
// report the decision, and for a skip the idle time behind it -- the
// skips are what tell an operator whether their silent-set is real.
const outcome = ctx.slurper.inspectReconnect(req.host_id, min_idle_ms);
const payload = switch (outcome) {
.reconnected => std.fmt.bufPrint(&buf, "{{\"dry_run\":true,\"would\":\"reconnect\"}}", .{}),
.skipped_recent_frame => |idle_ms| std.fmt.bufPrint(&buf, "{{\"dry_run\":true,\"would\":\"skip\",\"reason\":\"recent_frame\",\"idle_seconds\":{d},\"min_idle_seconds\":{d}}}", .{ @divFloor(idle_ms, std.time.ms_per_s), min_idle_s }),
.no_worker => std.fmt.bufPrint(&buf, "{{\"dry_run\":true,\"would\":\"skip\",\"reason\":\"no_worker\"}}", .{}),
.respawn_failed => std.fmt.bufPrint(&buf, "{{\"dry_run\":true,\"would\":\"reconnect\"}}", .{}),
} catch {
h.respondJson(conn, .internal_server_error, "{\"error\":\"Internal\"}");
return;
};
h.respondJson(conn, .ok, payload);
return;
}
switch (ctx.slurper.forceReconnect(req.host_id, min_idle_ms)) {
.reconnected => {
log.info("admin: forced reconnect for host {s} (id={d})", .{ parsed.value.hostname, req.host_id });
h.respondJson(conn, .ok, "{\"success\":true,\"reconnected\":true}");
},
.skipped_recent_frame => |idle_ms| {
const payload = std.fmt.bufPrint(&buf, "{{\"success\":true,\"reconnected\":false,\"reason\":\"recent_frame\",\"idle_seconds\":{d},\"min_idle_seconds\":{d}}}", .{ @divFloor(idle_ms, std.time.ms_per_s), min_idle_s }) catch "{\"success\":true,\"reconnected\":false,\"reason\":\"recent_frame\"}";
h.respondJson(conn, .ok, payload);
},
.no_worker => h.respondJson(conn, .not_found, "{\"error\":\"NoWorker\",\"message\":\"host has no active worker\"}"),
.respawn_failed => h.respondJson(conn, .internal_server_error, "{\"error\":\"RespawnFailed\",\"message\":\"worker torn down but respawn could not be queued\"}"),
}
}
/// set or clear the account_limit override for a host.
pub fn handleAdminChangeLimits(conn: *h.Conn, body: []const u8, headers: *const websocket.Handshake.KeyValue, ctx: *HttpContext) void {
if (!checkAdmin(conn, headers)) return;
const parsed = std.json.parseFromSlice(
struct { host: []const u8, account_limit: ?u64 },
ctx.persist.allocator,
body,
.{ .ignore_unknown_fields = true },
) catch {
h.respondJson(conn, .bad_request, "{\"error\":\"invalid JSON, expected {\\\"host\\\":\\\"...\\\",\\\"account_limit\\\":...}\"}");
return;
};
defer parsed.deinit();
const ChangeLimitsReq = struct {
base: DbRequest = .{ .callback = &execute },
hostname_buf: [256]u8 = undefined,
hostname_len: usize = 0,
new_limit: ?u64,
host_id: ?u64 = null,
effective: u64 = 0,
fn execute(b: *DbRequest, dp: *DiskPersist) void {
const self: *@This() = @fieldParentPtr("base", b);
const hn = self.hostname_buf[0..self.hostname_len];
self.host_id = dp.getHostIdForHostname(hn) catch |e| {
b.err = e;
return;
};
const hid = self.host_id orelse return;
dp.setHostAccountLimit(hid, self.new_limit) catch |e| {
b.err = e;
return;
};
self.effective = if (self.new_limit) |l| l else dp.getHostAccountCount(hid);
}
};
var req: ChangeLimitsReq = .{ .new_limit = parsed.value.account_limit };
const copy_len = @min(parsed.value.host.len, req.hostname_buf.len);
@memcpy(req.hostname_buf[0..copy_len], parsed.value.host[0..copy_len]);
req.hostname_len = copy_len;
ctx.db_queue.push(&req.base);
req.base.wait(ctx.io, ctx.shutdown);
if (req.base.err != null) {
h.respondJson(conn, .internal_server_error, "{\"error\":\"database error\"}");
return;
}
const host_id = req.host_id orelse {
h.respondJson(conn, .not_found, "{\"error\":\"host not found\"}");
return;
};
// update running subscriber's rate limits immediately
ctx.slurper.updateHostLimits(host_id, req.effective);
if (parsed.value.account_limit) |limit| {
log.info("admin: set account_limit for {s} (id={d}): {d}", .{ parsed.value.host, host_id, limit });
} else {
log.info("admin: cleared account_limit for {s} (id={d}), reverted to COUNT(*)", .{ parsed.value.host, host_id });
}
h.respondJson(conn, .ok, "{\"success\":true}");
}
pub fn handleAdminBackfillTrigger(conn: *h.Conn, query: []const u8, headers: *const websocket.Handshake.KeyValue, backfiller: *backfill_mod.Backfiller) void {
if (!checkAdmin(conn, headers)) return;
const source = h.queryParam(query, "source") orelse "bsky.network";
backfiller.start(source) catch |err| {
switch (err) {
error.AlreadyRunning => {
h.respondJson(conn, .conflict, "{\"error\":\"backfill already in progress\"}");
},
else => {
h.respondJson(conn, .internal_server_error, "{\"error\":\"failed to start backfill\"}");
},
}
return;
};
var buf: [256]u8 = undefined;
const resp_body = std.fmt.bufPrint(&buf, "{{\"status\":\"started\",\"source\":\"{s}\"}}", .{source}) catch {
h.respondJson(conn, .ok, "{\"status\":\"started\"}");
return;
};
h.respondJson(conn, .ok, resp_body);
}
pub fn handleAdminBackfillStatus(conn: *h.Conn, headers: *const websocket.Handshake.KeyValue, backfiller: *backfill_mod.Backfiller) void {
if (!checkAdmin(conn, headers)) return;
const body = backfiller.getStatus(backfiller.allocator) catch {
h.respondJson(conn, .internal_server_error, "{\"error\":\"failed to query backfill status\"}");
return;
};
defer backfiller.allocator.free(body);
h.respondJson(conn, .ok, body);
}
pub fn handleCleanupTrigger(conn: *h.Conn, query: []const u8, headers: *const websocket.Handshake.KeyValue, cleaner: *cleaner_mod.Cleaner) void {
if (!checkAdmin(conn, headers)) return;
const scope: cleaner_mod.Scope = if (h.queryParam(query, "scope")) |name| blk: {
if (std.mem.eql(u8, name, "inactive-accounts")) break :blk .inactive_accounts;
if (std.mem.eql(u8, name, "invalid-collections")) break :blk .invalid_collections;
h.respondJson(conn, .bad_request, "{\"error\":\"scope must be inactive-accounts or invalid-collections\"}");
return;
} else .inactive_accounts;
cleaner.start(scope) catch |err| {
switch (err) {
error.AlreadyRunning => {
h.respondJson(conn, .conflict, "{\"error\":\"cleanup already in progress\"}");
},
else => {
h.respondJson(conn, .internal_server_error, "{\"error\":\"failed to start cleanup\"}");
},
}
return;
};
h.respondJson(conn, .ok, "{\"status\":\"started\"}");
}
pub fn handleCleanupStatus(conn: *h.Conn, headers: *const websocket.Handshake.KeyValue, cleaner: *cleaner_mod.Cleaner) void {
if (!checkAdmin(conn, headers)) return;
const status = cleaner.getStatus();
var buf: [256]u8 = undefined;
const body = std.fmt.bufPrint(&buf, "{{\"running\":{},\"scanned\":{d},\"removed\":{d}}}", .{
status.running,
status.scanned,
status.removed,
}) catch {
h.respondJson(conn, .internal_server_error, "{\"error\":\"format failed\"}");
return;
};
h.respondJson(conn, .ok, body);
}
pub fn handleResyncStatus(conn: *h.Conn, headers: *const websocket.Handshake.KeyValue, resyncer: *resync_mod.Resyncer) void {
if (!checkAdmin(conn, headers)) return;
var buf: [256]u8 = undefined;
const body = std.fmt.bufPrint(&buf, "{{\"processed\":{d},\"failed\":{d},\"dropped\":{d},\"queue_depth\":{d}}}", .{
resyncer.processed.load(.monotonic),
resyncer.failed.load(.monotonic),
resyncer.dropped.load(.monotonic),
resyncer.queueDepth(),
}) catch {
h.respondJson(conn, .internal_server_error, "{\"error\":\"format failed\"}");
return;
};
h.respondJson(conn, .ok, body);
}
pub fn handleResyncTrigger(conn: *h.Conn, body: []const u8, headers: *const websocket.Handshake.KeyValue, resyncer: *resync_mod.Resyncer) void {
if (!checkAdmin(conn, headers)) return;
const parsed = std.json.parseFromSlice(
struct { did: []const u8, hostname: []const u8 },
std.heap.c_allocator,
body,
.{ .ignore_unknown_fields = true },
) catch {
h.respondJson(conn, .bad_request, "{\"error\":\"invalid JSON, expected {\\\"did\\\":\\\"...\\\",\\\"hostname\\\":\\\"...\\\"}\"}");
return;
};
defer parsed.deinit();
resyncer.enqueue(parsed.value.did, parsed.value.hostname);
h.respondJson(conn, .ok, "{\"status\":\"enqueued\"}");
}
// --- protocol helpers (used only by handleBan) ---
/// build a CBOR #account frame for a takedown event.
fn buildAccountFrame(allocator: std.mem.Allocator, did: []const u8) ?[]const u8 {
const zat = @import("zat");
const cbor = zat.cbor;
const header: cbor.Value = .{ .map = &.{
.{ .key = "op", .value = .{ .unsigned = 1 } },
.{ .key = "t", .value = .{ .text = "#account" } },
} };
var time_buf: [24]u8 = undefined;
const time_str = formatTimestamp(&time_buf);
const payload: cbor.Value = .{ .map = &.{
.{ .key = "seq", .value = .{ .unsigned = 0 } },
.{ .key = "did", .value = .{ .text = did } },
.{ .key = "time", .value = .{ .text = time_str } },
.{ .key = "active", .value = .{ .boolean = false } },
.{ .key = "status", .value = .{ .text = "takendown" } },
} };
const header_bytes = cbor.encodeAlloc(allocator, header) catch return null;
const payload_bytes = cbor.encodeAlloc(allocator, payload) catch {
allocator.free(header_bytes);
return null;
};
var frame = allocator.alloc(u8, header_bytes.len + payload_bytes.len) catch {
allocator.free(header_bytes);
allocator.free(payload_bytes);
return null;
};
@memcpy(frame[0..header_bytes.len], header_bytes);
@memcpy(frame[header_bytes.len..], payload_bytes);
allocator.free(header_bytes);
allocator.free(payload_bytes);
return frame;
}
/// GET /admin/ingest-stall — the liveness stall detector's knobs and verdict.
pub fn handleIngestStallStatus(conn: *h.Conn, headers: *const websocket.Handshake.KeyValue, ctx: *HttpContext) void {
if (!checkAdmin(conn, headers)) return;
var buf: [512]u8 = undefined;
h.respondJson(conn, .ok, ctx.ingest_liveness.formatJson(&buf, util.milliTimestamp(ctx.io)));
}
/// POST /admin/ingest-stall
/// body: any subset of {"enabled":bool,"threshold_fps":N,"window_sec":N,"startup_grace_sec":N}
///
/// takes effect immediately and is NOT persisted: a restart returns to the
/// RELAY_INGEST_STALL_* env defaults. `{"enabled":false}` is the kill switch
/// for capture-before-restart forensics on a wedged pod.
pub fn handleIngestStallUpdate(conn: *h.Conn, body: []const u8, headers: *const websocket.Handshake.KeyValue, ctx: *HttpContext) void {
if (!checkAdmin(conn, headers)) return;
const Update = struct {
enabled: ?bool = null,
threshold_fps: ?u64 = null,
window_sec: ?u64 = null,
startup_grace_sec: ?u64 = null,
};
const parsed = std.json.parseFromSlice(Update, ctx.persist.allocator, body, .{ .ignore_unknown_fields = true }) catch {
h.respondJson(conn, .bad_request, "{\"error\":\"BadRequest\",\"message\":\"expected JSON with any of enabled, threshold_fps, window_sec, startup_grace_sec\"}");
return;
};
defer parsed.deinit();
const u = parsed.value;
if (u.enabled == null and u.threshold_fps == null and u.window_sec == null and u.startup_grace_sec == null) {
h.respondJson(conn, .bad_request, "{\"error\":\"BadRequest\",\"message\":\"no fields to update\"}");
return;
}
if (u.window_sec) |w| if (w == 0) {
h.respondJson(conn, .bad_request, "{\"error\":\"BadRequest\",\"message\":\"window_sec must be positive\"}");
return;
};
const il = ctx.ingest_liveness;
if (u.enabled) |v| {
il.enabled.store(v, .release);
log.warn("admin: ingest stall liveness {s} (not persisted; env default returns on restart)", .{if (v) "enabled" else "DISABLED"});
}
if (u.threshold_fps) |v| {
il.threshold_fps.store(v, .release);
log.warn("admin: ingest stall threshold set to {d} fps (not persisted)", .{v});
}
if (u.window_sec) |v| {
il.window_sec.store(v, .release);
log.warn("admin: ingest stall window set to {d}s (not persisted)", .{v});
}
if (u.startup_grace_sec) |v| {
il.startup_grace_sec.store(v, .release);
log.warn("admin: ingest stall startup grace set to {d}s (not persisted)", .{v});
}
var buf: [512]u8 = undefined;
h.respondJson(conn, .ok, il.formatJson(&buf, util.milliTimestamp(ctx.io)));
}
/// GET /admin/ws-ping — the websocket keepalive pinger's knobs.
pub fn handleWsPingStatus(conn: *h.Conn, headers: *const websocket.Handshake.KeyValue, ctx: *HttpContext) void {
if (!checkAdmin(conn, headers)) return;
var buf: [256]u8 = undefined;
h.respondJson(conn, .ok, ctx.ws_ping.formatJson(&buf));
}
/// POST /admin/ws-ping
/// body: any subset of {"enabled":bool,"interval_sec":N,"max_failures":N}
///
/// takes effect on each pinger's next tick and is NOT persisted: a restart
/// returns to the RELAY_WS_PING_* env defaults. `{"enabled":false}` is the
/// kill switch — connections revert to no-keepalive behavior.
pub fn handleWsPingUpdate(conn: *h.Conn, body: []const u8, headers: *const websocket.Handshake.KeyValue, ctx: *HttpContext) void {
if (!checkAdmin(conn, headers)) return;
const Update = struct {
enabled: ?bool = null,
interval_sec: ?u64 = null,
max_failures: ?u64 = null,
};
const parsed = std.json.parseFromSlice(Update, ctx.persist.allocator, body, .{ .ignore_unknown_fields = true }) catch {
h.respondJson(conn, .bad_request, "{\"error\":\"BadRequest\",\"message\":\"expected JSON with any of enabled, interval_sec, max_failures\"}");
return;
};
defer parsed.deinit();
const u = parsed.value;
if (u.enabled == null and u.interval_sec == null and u.max_failures == null) {
h.respondJson(conn, .bad_request, "{\"error\":\"BadRequest\",\"message\":\"no fields to update\"}");
return;
}
if (u.interval_sec) |v| if (v == 0) {
h.respondJson(conn, .bad_request, "{\"error\":\"BadRequest\",\"message\":\"interval_sec must be positive\"}");
return;
};
if (u.max_failures) |v| if (v == 0) {
h.respondJson(conn, .bad_request, "{\"error\":\"BadRequest\",\"message\":\"max_failures must be positive\"}");
return;
};
const wp = ctx.ws_ping;
if (u.enabled) |v| {
wp.enabled.store(v, .release);
log.warn("admin: ws keepalive pinger {s} (not persisted; env default returns on restart)", .{if (v) "enabled" else "DISABLED"});
}
if (u.interval_sec) |v| {
wp.interval_sec.store(v, .release);
log.warn("admin: ws keepalive interval set to {d}s (not persisted)", .{v});
}
if (u.max_failures) |v| {
wp.max_failures.store(v, .release);
log.warn("admin: ws keepalive max_failures set to {d} (not persisted)", .{v});
}
var buf: [256]u8 = undefined;
h.respondJson(conn, .ok, wp.formatJson(&buf));
}