//! Public operator diagnostics backed by durable repo/host metadata. //! //! The upstream page is an operational surface, not a decorative dashboard: //! host sorting and every displayed count come directly from the maintained //! `host/` rows, so request cost is bounded by PDS hosts rather than //! whole-network accounts. const std = @import("std"); const zat = @import("zat"); const repo_export = @import("repo_export.zig"); const repo_store = @import("../ingest/backfill/repo_store.zig"); const Io = std.Io; const Allocator = std.mem.Allocator; const Writer = std.Io.Writer; pub const HostSort = enum { largest, failing }; pub const AccountLookup = struct { query: []const u8 = "", query_kind: []const u8 = "", found: bool = false, error_message: []const u8 = "", did: []const u8 = "", handle: []const u8 = "", pds: []const u8 = "", host: []const u8 = "", active: bool = false, backfill: []const u8 = "", attempts: u32 = 0, last_error: []const u8 = "", backfill_rev: []const u8 = "", latest_rev: []const u8 = "", updated_us: i64 = 0, last_attempt_us: i64 = 0, record_count: i64 = 0, total_bytes: i64 = 0, }; pub fn accountFromQueryAlloc(allocator: Allocator, query: []const u8) !?[]u8 { var is_accounts = false; var account: ?[]u8 = null; var did: ?[]u8 = null; var handle: ?[]u8 = null; errdefer { if (account) |value| allocator.free(value); if (did) |value| allocator.free(value); if (handle) |value| allocator.free(value); } var fields = std.mem.splitScalar(u8, query, '&'); while (fields.next()) |field| { const split = std.mem.indexOfScalar(u8, field, '=') orelse field.len; const key = field[0..split]; const value = if (split < field.len) field[split + 1 ..] else ""; if (std.mem.eql(u8, key, "tab")) is_accounts = std.mem.eql(u8, value, "accounts"); // net/url.Values.Get, used upstream, selects the first occurrence. if (std.mem.eql(u8, key, "account") and account == null) account = try percentDecodeQueryAlloc(allocator, value); if (std.mem.eql(u8, key, "did") and did == null) did = try percentDecodeQueryAlloc(allocator, value); if (std.mem.eql(u8, key, "handle") and handle == null) handle = try percentDecodeQueryAlloc(allocator, value); } if (!is_accounts) { if (account) |value| allocator.free(value); if (did) |value| allocator.free(value); if (handle) |value| allocator.free(value); return null; } if (account) |value| { if (std.mem.trim(u8, value, " \t\r\n").len > 0) { if (did) |old| allocator.free(old); if (handle) |old| allocator.free(old); return value; } allocator.free(value); } if (did) |value| { if (std.mem.trim(u8, value, " \t\r\n").len > 0) { if (handle) |old| allocator.free(old); return value; } allocator.free(value); } return handle orelse try allocator.dupe(u8, ""); } /// Collect one account exactly like upstream's status collector. When an /// identity resolver is configured (the production path), a handle lookup /// MUST resolve authoritatively and an error MUST NOT fall through to the /// local declared-handle index. The index exists only for resolver-less use. pub fn collectAccount( allocator: Allocator, io: Io, store: *repo_store.Store, plc_url: []const u8, raw_account: []const u8, use_identity_resolver: bool, ) !AccountLookup { const account = std.mem.trim(u8, raw_account, " \t\r\n"); if (account.len == 0) return .{}; var result: AccountLookup = .{}; var did: []const u8 = undefined; if (std.ascii.startsWithIgnoreCase(account, "did:")) { result.query_kind = "did"; result.query = account; if (zat.Did.parse(account) == null) { result.error_message = try std.fmt.allocPrint(allocator, "invalid DID: {s}", .{account}); return result; } did = account; } else { const without_at = if (std.mem.startsWith(u8, account, "@")) account[1..] else account; const parsed = zat.Handle.parse(without_at) orelse { result.query_kind = "handle"; result.query = without_at; result.error_message = try std.fmt.allocPrint(allocator, "invalid handle: {s}", .{without_at}); return result; }; const normalized = try asciiLowerAlloc(allocator, parsed.str()); result.query_kind = "handle"; result.query = normalized; if (use_identity_resolver) { var resolver = zat.HandleResolver.init(io, allocator); defer resolver.deinit(); did = resolver.resolve(.{ .raw = normalized }) catch |err| { result.error_message = try std.fmt.allocPrint(allocator, "resolve handle \"{s}\": {s}", .{ normalized, @errorName(err) }); return result; }; } else { did = (try store.lookupDIDByHandle(allocator, normalized)) orelse return result; } } const state = (try store.get(allocator, did)) orelse { result.did = did; return result; }; result = .{ .query = result.query, .query_kind = result.query_kind, .found = true, .did = did, .handle = state.handle, .pds = state.pds, .host = state.host, .active = state.active, .backfill = @tagName(state.status), .attempts = state.attempts, .last_error = state.last_error, .backfill_rev = state.rev, .latest_rev = state.latest_rev, .updated_us = state.updated_us, .last_attempt_us = state.last_attempt_us, .record_count = state.record_count, .total_bytes = state.total_bytes, }; if (use_identity_resolver and (result.handle.len == 0 or result.pds.len == 0)) { var resolver = zat.DidResolver.init(io, allocator); defer resolver.deinit(); resolver.plc_url = plc_url; const parsed_did = zat.Did.parse(did).?; var doc = resolver.resolve(parsed_did) catch null; if (doc) |*resolved| { defer resolved.deinit(); if (result.handle.len == 0) result.handle = if (resolved.handle()) |handle| try allocator.dupe(u8, handle) else ""; if (result.pds.len == 0) result.pds = if (resolved.pdsEndpoint()) |pds| try allocator.dupe(u8, pds) else ""; } } if (result.handle.len == 0 and std.mem.eql(u8, result.query_kind, "handle")) result.handle = result.query; return result; } pub fn renderAccountAlloc( allocator: Allocator, account: AccountLookup, now_us: i64, html: bool, verification: ?repo_export.VerifyReport, verification_error: []const u8, ) ![]u8 { var output: Writer.Allocating = .init(allocator); errdefer output.deinit(); if (html) try renderAccountHtml(&output.writer, account, now_us, verification, verification_error) else try renderAccountText(&output.writer, account, now_us, verification, verification_error); return output.toOwnedSlice(); } pub fn hostSortFromQuery(query: []const u8) ?HostSort { var tab_hosts = false; var sort: HostSort = .largest; var fields = std.mem.splitScalar(u8, query, '&'); while (fields.next()) |field| { const split = std.mem.indexOfScalar(u8, field, '=') orelse field.len; const key = field[0..split]; const value = if (split < field.len) field[split + 1 ..] else ""; if (std.mem.eql(u8, key, "tab")) tab_hosts = std.mem.eql(u8, value, "hosts"); if (std.mem.eql(u8, key, "sort") and std.mem.eql(u8, value, "failing")) sort = .failing; } return if (tab_hosts) sort else null; } pub fn sortHosts(statuses: []repo_store.HostStatus, sort: HostSort) void { std.mem.sort(repo_store.HostStatus, statuses, sort, struct { fn lessThan(mode: HostSort, a: repo_store.HostStatus, b: repo_store.HostStatus) bool { const a_failed = a.count(.failed); const b_failed = b.count(.failed); if (mode == .failing and a_failed != b_failed) return a_failed > b_failed; if (a.total != b.total) return a.total > b.total; if (a_failed != b_failed) return a_failed > b_failed; return std.mem.order(u8, a.host, b.host) == .lt; } }.lessThan); } pub fn renderHostsAlloc(allocator: Allocator, statuses: []repo_store.HostStatus, sort: HostSort, now_us: i64, html: bool) ![]u8 { sortHosts(statuses, sort); var output: Writer.Allocating = .init(allocator); errdefer output.deinit(); if (html) try renderHostsHtml(&output.writer, statuses, sort, now_us) else try renderHostsText(&output.writer, statuses, sort, now_us); return output.toOwnedSlice(); } fn renderAccountText( w: *Writer, account: AccountLookup, now_us: i64, verification: ?repo_export.VerifyReport, verification_error: []const u8, ) !void { try w.writeAll("stream account diagnostics\n\n"); if (account.query.len == 0) return w.writeAll("Supply a DID or handle with ?tab=accounts&account=...\n"); try w.print("query\t{s}\t{s}\n", .{ account.query_kind, account.query }); if (account.error_message.len > 0) return w.print("error\t{s}\n", .{account.error_message}); if (account.did.len > 0) try w.print("did\t{s}\n", .{account.did}); if (!account.found) return w.writeAll("found\tno\n"); try w.writeAll("found\tyes\n"); try w.print("handle\t{s}\npds\t{s}\nhost\t{s}\nactive\t{}\nbackfill\t{s}\nattempts\t{d}\n", .{ account.handle, account.pds, account.host, account.active, account.backfill, account.attempts, }); try w.writeAll("last attempted\t"); try writeAge(w, now_us, account.last_attempt_us); try w.print("\nbackfill rev\t{s}\nlatest rev\t{s}\n", .{ account.backfill_rev, account.latest_rev }); if (account.record_count != 0) try w.print("records\t{d}\n", .{account.record_count}); if (account.total_bytes != 0) try w.print("bytes\t{d}\n", .{account.total_bytes}); if (account.last_error.len > 0) try w.print("last error\t{s}\n", .{account.last_error}); if (verification) |report| { try w.print("\nrepo verification\nresult\t{s}\nauthoritative rev\t{s}\nauthoritative root\t{s}\nlocal rev\t{s}\nlocal root\t{s}\nlocal records\t{d}\n", .{ if (report.match) "Match" else "Match failure", report.authoritative_rev, report.authoritative_root, report.local_latest_rev, report.local_root, report.local_record_count, }); if (report.message.len > 0) try w.print("message\t{s}\n", .{report.message}); } else if (verification_error.len > 0) { try w.print("\nrepo verification\nerror\t{s}\n", .{verification_error}); } } fn renderAccountHtml( w: *Writer, account: AccountLookup, now_us: i64, verification: ?repo_export.VerifyReport, verification_error: []const u8, ) !void { try w.writeAll( \\ \\ \\stream · accounts \\
\\

Account diagnostics

\\

Inspect durable backfill state for one repository. Handle queries resolve through the network identity directory before the local status row is loaded.

\\
"); if (account.query.len == 0) return w.writeAll("

Enter a DID or handle.

"); if (account.error_message.len > 0) { try w.writeAll("

"); try writeHtmlEscaped(w, account.error_message); return w.writeAll("

"); } if (!account.found) { try w.writeAll("
No local repository status was found"); if (account.did.len > 0) { try w.writeAll(" for "); try writeHtmlEscaped(w, account.did); try w.writeAll(""); } return w.writeAll(".
"); } try w.writeAll("
DID
"); try writeHtmlEscaped(w, account.did); try w.writeAll("
Declared handle
"); try writeHtmlCodeOrUnknown(w, account.handle); try w.writeAll("
PDS endpoint
"); try writeHtmlCodeOrUnknown(w, account.pds); try w.writeAll("
Active
"); try w.writeAll(if (account.active) "true" else "false"); try w.writeAll("
Backfill
"); try writeHtmlEscaped(w, account.backfill); try w.print("
Retries
{d}
Last attempted
", .{account.attempts}); try writeAge(w, now_us, account.last_attempt_us); try w.writeAll("
Backfill rev
"); try writeHtmlCodeOrUnknown(w, account.backfill_rev); try w.writeAll("
Latest rev
"); try writeHtmlCodeOrUnknown(w, account.latest_rev); try w.writeAll("
"); if (account.record_count != 0) try w.print("
Records
{d}
", .{account.record_count}); if (account.total_bytes != 0) try w.print("
Bytes
{d}
", .{account.total_bytes}); if (account.last_error.len > 0) { try w.writeAll("
Last error
"); try writeHtmlEscaped(w, account.last_error); try w.writeAll("
"); } try w.writeAll("
"); if (verification) |report| { try w.writeAll("

Repo verification

Result
Match" else "match-fail\">Match failure"); try w.writeAll("
authoritative rev
"); try writeHtmlCodeOrUnknown(w, report.authoritative_rev); try w.writeAll("
authoritative root
"); try writeHtmlCodeOrUnknown(w, report.authoritative_root); try w.writeAll("
local rev
"); try writeHtmlCodeOrUnknown(w, report.local_latest_rev); try w.writeAll("
local root
"); try writeHtmlCodeOrUnknown(w, report.local_root); try w.print("
local records
{d}
", .{report.local_record_count}); if (report.message.len > 0) { try w.writeAll("
Message
"); try writeHtmlEscaped(w, report.message); try w.writeAll("
"); } try w.writeAll("
"); } else if (verification_error.len > 0) { try w.writeAll("

Repo verification

"); try writeHtmlEscaped(w, verification_error); try w.writeAll("
"); } try w.writeAll(""); } fn renderHostsText(w: *Writer, statuses: []const repo_store.HostStatus, sort: HostSort, now_us: i64) !void { try w.print("stream host diagnostics\nsort: {s}\n\n", .{@tagName(sort)}); if (statuses.len == 0) { try w.writeAll("No host aggregates have been recorded yet.\n"); return; } try w.writeAll("host\trepos\tactive\tcomplete\tfailed\tunavailable\tlast attempt\tlatest error\n"); for (statuses) |status| { try w.print("{s}\t{d}\t{d}\t{d}\t{d}\t{d}\t", .{ status.host, status.total, status.active, status.count(.complete), status.count(.failed), status.count(.unavailable), }); try writeAge(w, now_us, status.last_attempt_us); try w.writeByte('\t'); if (hasErrors(status)) { try w.writeAll(className(status.latest_error_class)); if (status.latest_error.len > 0) try w.print(" {s}", .{status.latest_error}); } try w.writeByte('\n'); for (status.recent_errors) |sample| { try w.print(" {s}\t", .{sample.did}); try writeAge(w, now_us, sample.attempted_us); try w.print("\t{s} {s}\n", .{ className(sample.class), sample.message }); } } } fn renderHostsHtml(w: *Writer, statuses: []const repo_store.HostStatus, sort: HostSort, now_us: i64) !void { try w.writeAll( \\ \\ \\stream · hosts \\
\\

Host diagnostics

\\

Durable PDS aggregates from repository backfill and healing. Counts update atomically with each account row; historical errors remain visible after recovery.

); try w.writeAll(if (sort == .largest) "Largest hosts"); try w.writeAll(if (sort == .failing) "Failing hosts
"); if (statuses.len == 0) { try w.writeAll("

No host aggregates have been recorded yet.

"); return; } try w.writeAll("
"); for (statuses) |status| { try w.writeAll(""); if (status.recent_errors.len > 0) { try w.writeAll(""); } } try w.writeAll( "
HostReposActiveCompleteFailedUnavailableLast attemptLatest error
"); try writeHtmlEscaped(w, status.host); try w.print("{d}{d}{d}{d}{d}", .{ status.total, status.active, status.count(.complete), status.count(.failed), status.count(.unavailable), }); try writeAge(w, now_us, status.last_attempt_us); try w.writeAll(""); if (hasErrors(status)) { try w.writeAll(""); try writeHtmlEscaped(w, className(status.latest_error_class)); try w.writeAll(" "); try writeHtmlEscaped(w, status.latest_error); } try w.writeAll("
    "); for (status.recent_errors) |sample| { try w.writeAll("
  • "); try writeHtmlEscaped(w, sample.did); try w.writeAll(""); try writeAge(w, now_us, sample.attempted_us); try w.writeAll(""); try writeHtmlEscaped(w, className(sample.class)); try w.writeAll(""); try writeHtmlEscaped(w, sample.message); try w.writeAll("
  • "); } try w.writeAll("
", ); } fn className(class: repo_store.ErrorClass) []const u8 { return if (class == .transport) "unknown" else @tagName(class); } fn hasErrors(status: repo_store.HostStatus) bool { for (status.error_counts) |count| if (count > 0) return true; return status.recent_errors.len > 0; } fn writeAge(w: *Writer, now_us: i64, then_us: i64) !void { if (then_us <= 0) return w.writeAll("never"); const seconds: u64 = @intCast(@max(@divTrunc(now_us -| then_us, std.time.us_per_s), 0)); if (seconds < 60) return w.print("{d}s ago", .{seconds}); if (seconds < 3600) return w.print("{d}m ago", .{seconds / 60}); if (seconds < 86_400) return w.print("{d}h ago", .{seconds / 3600}); return w.print("{d}d ago", .{seconds / 86_400}); } fn writeHtmlEscaped(w: *Writer, raw: []const u8) !void { for (raw) |byte| switch (byte) { '&' => try w.writeAll("&"), '<' => try w.writeAll("<"), '>' => try w.writeAll(">"), '"' => try w.writeAll("""), '\'' => try w.writeAll("'"), else => try w.writeByte(byte), }; } fn writeHtmlCodeOrUnknown(w: *Writer, raw: []const u8) !void { if (raw.len == 0) return w.writeAll("unknown"); try w.writeAll(""); try writeHtmlEscaped(w, raw); try w.writeAll(""); } fn asciiLowerAlloc(allocator: Allocator, raw: []const u8) ![]u8 { const out = try allocator.alloc(u8, raw.len); for (raw, out) |byte, *dst| dst.* = std.ascii.toLower(byte); return out; } fn percentDecodeQueryAlloc(allocator: Allocator, raw: []const u8) ![]u8 { var out: std.ArrayList(u8) = .empty; errdefer out.deinit(allocator); var i: usize = 0; while (i < raw.len) { if (raw[i] == '+') { try out.append(allocator, ' '); i += 1; } else if (raw[i] == '%') { if (i + 2 >= raw.len) return error.InvalidQueryEncoding; const byte = std.fmt.parseInt(u8, raw[i + 1 .. i + 3], 16) catch return error.InvalidQueryEncoding; try out.append(allocator, byte); i += 3; } else { try out.append(allocator, raw[i]); i += 1; } } return out.toOwnedSlice(allocator); } test "host query and upstream sort modes are exact" { const testing = std.testing; try testing.expectEqual(HostSort.largest, hostSortFromQuery("tab=hosts").?); try testing.expectEqual(HostSort.failing, hostSortFromQuery("sort=failing&tab=hosts").?); try testing.expect(hostSortFromQuery("tab=accounts&sort=failing") == null); var rows = [_]repo_store.HostStatus{ .{ .host = "small-failing", .total = 2, .by_status = .{ 0, 0, 1, 1, 0 } }, .{ .host = "large", .total = 10, .by_status = .{ 0, 0, 10, 0, 0 } }, .{ .host = "most-failing", .total = 3, .by_status = .{ 0, 0, 0, 3, 0 } }, }; sortHosts(&rows, .largest); try testing.expectEqualStrings("large", rows[0].host); sortHosts(&rows, .failing); try testing.expectEqualStrings("most-failing", rows[0].host); try testing.expectEqualStrings("small-failing", rows[1].host); } test "host rendering is unbounded, escaped, and preserves diagnostic history" { const testing = std.testing; var recent = [_]repo_store.HostErrorSample{ .{ .did = "did:plc:a&b", .attempted_us = 9 * std.time.us_per_s, .class = .http_5xx, .message = "" }, }; var rows = [_]repo_store.HostStatus{ .{ .host = "pds.example", .total = 1, .active = 1, .by_status = .{ 0, 0, 0, 1, 0 }, .last_attempt_us = 9 * std.time.us_per_s, .latest_error = "", .latest_error_class = .http_5xx, .recent_errors = &recent, }, }; const html = try renderHostsAlloc(testing.allocator, &rows, .failing, 10 * std.time.us_per_s, true); defer testing.allocator.free(html); try testing.expect(std.mem.indexOf(u8, html, "Failing hosts") != null); try testing.expect(std.mem.indexOf(u8, html, "<script>alert(1)</script>") != null); try testing.expect(std.mem.indexOf(u8, html, "") == null); try testing.expect(std.mem.indexOf(u8, html, "host-filter") != null); try testing.expect(std.mem.indexOf(u8, html, "id=\"hosts-table\"") != null); try testing.expect(std.mem.indexOf(u8, html, "host-errors-row") != null); try testing.expect(std.mem.indexOf(u8, html, "tab=accounts") != null); try testing.expect(std.mem.indexOf(u8, html, "1s ago") != null); } test "account query decoding and normalization select only the accounts tab" { const testing = std.testing; try testing.expect(try accountFromQueryAlloc(testing.allocator, "tab=hosts&account=ignored") == null); const account = (try accountFromQueryAlloc(testing.allocator, "account=%40Alice.Example&tab=accounts")).?; defer testing.allocator.free(account); try testing.expectEqualStrings("@Alice.Example", account); const legacy_did = (try accountFromQueryAlloc(testing.allocator, "tab=accounts&did=did%3Aplc%3Alegacy&handle=ignored.example")).?; defer testing.allocator.free(legacy_did); try testing.expectEqualStrings("did:plc:legacy", legacy_did); const explicit_wins = (try accountFromQueryAlloc(testing.allocator, "tab=accounts&account=chosen.example&did=did%3Aplc%3Aignored")).?; defer testing.allocator.free(explicit_wins); try testing.expectEqualStrings("chosen.example", explicit_wins); } test "resolver-less account lookup uses the durable handle index and renders exact state" { const testing = std.testing; var threaded: Io.Threaded = .init(testing.allocator, .{}); defer threaded.deinit(); const io = threaded.io(); var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); var path_buf: [Io.Dir.max_path_bytes]u8 = undefined; const path_len = try tmp.dir.realPath(io, &path_buf); const meta_store = @import("../storage/meta_store.zig"); var meta = try meta_store.Store.open(testing.allocator, path_buf[0..path_len]); defer meta.deinit(); var store = try repo_store.Store.init(testing.allocator, io, &meta); defer store.deinit(); const did = "did:plc:accountfixture"; try store.put(did, .{ .status = .complete, .active = true, .rev = "3lbackfill", .latest_rev = "3llatest", .handle = "alice.example", .pds = "https://pds.example", .host = "pds.example", .attempts = 2, .last_attempt_us = 9 * std.time.us_per_s, .record_count = 7, .total_bytes = 99, }); var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const account = try collectAccount(arena.allocator(), io, &store, "http://unused", " @ALICE.EXAMPLE ", false); try testing.expect(account.found); try testing.expectEqualStrings("handle", account.query_kind); try testing.expectEqualStrings("alice.example", account.query); try testing.expectEqualStrings(did, account.did); try testing.expectEqualStrings("3lbackfill", account.backfill_rev); try testing.expectEqualStrings("3llatest", account.latest_rev); const verification: repo_export.VerifyReport = .{ .did = did, .match = true, .authoritative_rev = "3llatest", .authoritative_root = "bafyroot", .local_latest_rev = "3llatest", .local_root = "bafyroot", .local_record_count = 7, }; const html = try renderAccountAlloc(testing.allocator, account, 10 * std.time.us_per_s, true, verification, ""); defer testing.allocator.free(html); try testing.expect(std.mem.indexOf(u8, html, "Account diagnostics") != null); try testing.expect(std.mem.indexOf(u8, html, "alice.example") != null); try testing.expect(std.mem.indexOf(u8, html, "3llatest") != null); try testing.expect(std.mem.indexOf(u8, html, "7") != null); try testing.expect(std.mem.indexOf(u8, html, "1s ago") != null); try testing.expect(std.mem.indexOf(u8, html, "Repo verification") != null); try testing.expect(std.mem.indexOf(u8, html, "match-ok\">Match") != null); try testing.expect(std.mem.indexOf(u8, html, "bafyroot") != null); } test "account lookup validates DID and reports a resolved DID missing locally" { const testing = std.testing; var threaded: Io.Threaded = .init(testing.allocator, .{}); defer threaded.deinit(); const io = threaded.io(); var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); var path_buf: [Io.Dir.max_path_bytes]u8 = undefined; const path_len = try tmp.dir.realPath(io, &path_buf); const meta_store = @import("../storage/meta_store.zig"); var meta = try meta_store.Store.open(testing.allocator, path_buf[0..path_len]); defer meta.deinit(); var store = try repo_store.Store.init(testing.allocator, io, &meta); defer store.deinit(); var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const invalid = try collectAccount(arena.allocator(), io, &store, "http://unused", "DID:plc:wrongcase", false); try testing.expect(std.mem.startsWith(u8, invalid.error_message, "invalid DID:")); const missing = try collectAccount(arena.allocator(), io, &store, "http://unused", "did:plc:missing", false); try testing.expect(!missing.found); try testing.expectEqualStrings("did:plc:missing", missing.did); } // === segments and collections === // // Upstream's status surface exposes a segments view and a collections view. // Both render from metadata the manifest already holds resident, so a request // costs a walk over sealed segments rather than any disk read — the same // bounded-cost rule the host view follows. pub const SegmentRow = struct { index: u64, size_bytes: u64, event_count: u32, unique_did_count: u32, block_count: u32, min_seq: u64, max_seq: u64, min_witnessed_at: i64, max_witnessed_at: i64, }; pub const CollectionRow = struct { nsid: []const u8, event_count: u64, segment_count: u32, }; pub fn segmentTabFromQuery(query: []const u8) ?[]const u8 { var it = std.mem.splitScalar(u8, query, '&'); while (it.next()) |pair| { const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; if (!std.mem.eql(u8, pair[0..eq], "tab")) continue; const value = pair[eq + 1 ..]; if (std.mem.eql(u8, value, "segments") or std.mem.eql(u8, value, "collections")) return value; } return null; } pub fn renderSegmentsAlloc(allocator: Allocator, rows: []const SegmentRow, html: bool) ![]u8 { var output: Writer.Allocating = .init(allocator); errdefer output.deinit(); if (html) try renderSegmentsHtml(&output.writer, rows) else try renderSegmentsText(&output.writer, rows); return output.toOwnedSlice(); } pub fn renderCollectionsAlloc(allocator: Allocator, rows: []const CollectionRow, html: bool) ![]u8 { var output: Writer.Allocating = .init(allocator); errdefer output.deinit(); if (html) try renderCollectionsHtml(&output.writer, rows) else try renderCollectionsText(&output.writer, rows); return output.toOwnedSlice(); } /// Descending event count, then nsid, so the busiest collections lead and the /// order is stable for an operator refreshing the page. pub fn sortCollections(rows: []CollectionRow) void { std.mem.sort(CollectionRow, rows, {}, struct { fn lessThan(_: void, a: CollectionRow, b: CollectionRow) bool { if (a.event_count != b.event_count) return a.event_count > b.event_count; return std.mem.order(u8, a.nsid, b.nsid) == .lt; } }.lessThan); } fn renderSegmentsText(w: *Writer, rows: []const SegmentRow) !void { try w.writeAll("stream sealed segments\n\n"); if (rows.len == 0) { try w.writeAll("No sealed segments yet.\n"); return; } try w.writeAll("index\tevents\tunique dids\tblocks\tmin seq\tmax seq\tbytes\n"); var events: u64 = 0; var bytes: u64 = 0; for (rows) |row| { try w.print("{d}\t{d}\t{d}\t{d}\t{d}\t{d}\t{d}\n", .{ row.index, row.event_count, row.unique_did_count, row.block_count, row.min_seq, row.max_seq, row.size_bytes, }); events += row.event_count; bytes += row.size_bytes; } try w.print("\n{d} sealed segments, {d} events, {d} bytes\n", .{ rows.len, events, bytes }); } fn renderCollectionsText(w: *Writer, rows: []const CollectionRow) !void { try w.writeAll("stream archived collections\n\n"); if (rows.len == 0) { try w.writeAll("No collections have been archived yet.\n"); return; } try w.writeAll("collection\tevents\tsegments\n"); for (rows) |row| { try w.print("{s}\t{d}\t{d}\n", .{ row.nsid, row.event_count, row.segment_count }); } try w.print("\n{d} collections\n", .{rows.len}); } const page_head = \\ \\ \\ ; /// The hosts and accounts pages already ship this stylesheet; segments and /// collections reuse it verbatim so the operator surface stays one design. const page_style = \\
; fn writeNav(w: *Writer, active: []const u8) !void { try w.writeAll(""); } fn renderSegmentsHtml(w: *Writer, rows: []const SegmentRow) !void { try w.writeAll(page_head); try w.writeAll("stream — segments" ++ page_style); try w.writeAll("

Sealed segments

"); try writeNav(w, "segments"); try w.writeAll("
"); if (rows.len == 0) { try w.writeAll("
No sealed segments yet.
"); return; } var events: u64 = 0; var bytes: u64 = 0; for (rows) |row| { events += row.event_count; bytes += row.size_bytes; } try w.print( "

{d} sealed segments, {d} events, {d} bytes on disk.

", .{ rows.len, events, bytes }, ); try w.writeAll("
" ++ "" ++ ""); for (rows) |row| { try w.print( "" ++ "" ++ "", .{ row.index, row.event_count, row.unique_did_count, row.block_count, row.min_seq, row.max_seq, row.size_bytes }, ); } try w.writeAll("
IndexEventsUnique DIDsBlocksMin seqMax seqBytes
{d}{d}{d}{d}{d}{d}{d}
"); } fn renderCollectionsHtml(w: *Writer, rows: []const CollectionRow) !void { try w.writeAll(page_head); try w.writeAll("stream — collections" ++ page_style); try w.writeAll("

Archived collections

"); try writeNav(w, "collections"); try w.writeAll("
"); if (rows.len == 0) { try w.writeAll("
No collections have been archived yet.
"); return; } try w.print("

{d} collections across the sealed archive.

", .{rows.len}); try w.writeAll(""); try w.writeAll("
" ++ ""); for (rows) |row| { try w.writeAll("", .{ row.event_count, row.segment_count }); } try w.writeAll("
CollectionEventsSegments
"); try writeHtmlEscaped(w, row.nsid); try w.print("{d}{d}
"); }