~ knotless Search/
↑↓ move↵ open⇧↵ all results

zat.dev/stream

jetstream v2 in zig · mirror of https://tangled.org/zat.dev/stream

0
0
855 lines · 44.2 KB Raw History
//! 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/<bucket>` 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(
        \\<!doctype html><html lang="en"><head><meta charset="utf-8">
        \\<meta name="viewport" content="width=device-width,initial-scale=1">
        \\<meta name="theme-color" content="#081820"><title>stream · accounts</title>
        \\<style>
        \\:root{--ink:#dcecf0;--dim:#8ba4ad;--deep:#081820;--panel:#0d242d;--line:#244550;--water:#58b8d6;--foam:#bdefff;--bad:#ef8178;--good:#83d3aa}
        \\*{box-sizing:border-box}body{margin:0;color:var(--ink);background:var(--deep);font:14px/1.5 "Avenir Next",Avenir,"Segoe UI",sans-serif}main{width:min(900px,100%);margin:auto;padding:28px 16px 64px}a{color:var(--foam)}
        \\header{display:flex;gap:18px;align-items:end;justify-content:space-between;border-bottom:1px solid var(--line);padding-bottom:18px}h1{margin:0;font-size:clamp(30px,7vw,52px);font-weight:500;letter-spacing:-.04em}nav{display:flex;gap:12px;flex-wrap:wrap}nav a{padding:7px 9px;border:1px solid var(--line);text-decoration:none;font:12px ui-monospace,SFMono-Regular,monospace}.active{background:var(--water);color:var(--deep)!important;border-color:var(--water)!important}
        \\.lede{color:var(--dim);max-width:70ch;margin:14px 0 24px}form{display:flex;gap:8px;margin:20px 0 26px}input{flex:1;min-width:0;padding:11px 12px;color:var(--ink);background:var(--panel);border:1px solid var(--line);font:14px ui-monospace,SFMono-Regular,monospace}input:focus{outline:1px solid var(--water);border-color:var(--water)}button{padding:10px 15px;color:var(--deep);background:var(--water);border:0;font-weight:650;cursor:pointer}
        \\.panel{border:1px solid var(--line);background:var(--panel);padding:18px}.verification{margin-top:18px}.verification h2{margin:0 0 10px;font-size:17px;font-weight:600}.error{color:var(--bad);overflow-wrap:anywhere}.empty{color:var(--dim)}dl{display:grid;grid-template-columns:150px minmax(0,1fr);gap:0;margin:0}dt,dd{margin:0;padding:8px 0;border-bottom:1px solid var(--line)}dt{color:var(--dim)}dd{overflow-wrap:anywhere}code{color:var(--foam);font:13px ui-monospace,SFMono-Regular,monospace}.match-ok{color:var(--good)}.match-fail{color:var(--bad)}
        \\@media(max-width:620px){header{display:block}nav{margin-top:14px}form{align-items:stretch;flex-direction:column}dl{grid-template-columns:1fr}dt{border-bottom:0;padding-bottom:0}dd{padding-top:2px}}</style></head><body><main>
        \\<header><div><h1>Account diagnostics</h1></div><nav aria-label="status views"><a href="/status">Summary</a><a href="/status?tab=hosts">Hosts</a><a class="active" href="/status?tab=accounts">Accounts</a></nav></header>
        \\<p class="lede">Inspect durable backfill state for one repository. Handle queries resolve through the network identity directory before the local status row is loaded.</p>
        \\<form method="get" action="/status"><input type="hidden" name="tab" value="accounts"><input name="account" aria-label="DID or handle" placeholder="did:plc:… or alice.example" value="
    );
    try writeHtmlEscaped(w, account.query);
    try w.writeAll("\"><button type=\"submit\">Inspect account</button></form>");
    if (account.query.len == 0) return w.writeAll("<p class=\"panel empty\">Enter a DID or handle.</p></main></body></html>");
    if (account.error_message.len > 0) {
        try w.writeAll("<p class=\"panel error\">");
        try writeHtmlEscaped(w, account.error_message);
        return w.writeAll("</p></main></body></html>");
    }
    if (!account.found) {
        try w.writeAll("<div class=\"panel empty\">No local repository status was found");
        if (account.did.len > 0) {
            try w.writeAll(" for <code>");
            try writeHtmlEscaped(w, account.did);
            try w.writeAll("</code>");
        }
        return w.writeAll(".</div></main></body></html>");
    }
    try w.writeAll("<div class=\"panel\"><dl><dt>DID</dt><dd><code>");
    try writeHtmlEscaped(w, account.did);
    try w.writeAll("</code></dd><dt>Declared handle</dt><dd>");
    try writeHtmlCodeOrUnknown(w, account.handle);
    try w.writeAll("</dd><dt>PDS endpoint</dt><dd>");
    try writeHtmlCodeOrUnknown(w, account.pds);
    try w.writeAll("</dd><dt>Active</dt><dd>");
    try w.writeAll(if (account.active) "true" else "false");
    try w.writeAll("</dd><dt>Backfill</dt><dd><code>");
    try writeHtmlEscaped(w, account.backfill);
    try w.print("</code></dd><dt>Retries</dt><dd>{d}</dd><dt>Last attempted</dt><dd>", .{account.attempts});
    try writeAge(w, now_us, account.last_attempt_us);
    try w.writeAll("</dd><dt>Backfill rev</dt><dd>");
    try writeHtmlCodeOrUnknown(w, account.backfill_rev);
    try w.writeAll("</dd><dt>Latest rev</dt><dd>");
    try writeHtmlCodeOrUnknown(w, account.latest_rev);
    try w.writeAll("</dd>");
    if (account.record_count != 0) try w.print("<dt>Records</dt><dd>{d}</dd>", .{account.record_count});
    if (account.total_bytes != 0) try w.print("<dt>Bytes</dt><dd>{d}</dd>", .{account.total_bytes});
    if (account.last_error.len > 0) {
        try w.writeAll("<dt>Last error</dt><dd class=\"error\">");
        try writeHtmlEscaped(w, account.last_error);
        try w.writeAll("</dd>");
    }
    try w.writeAll("</dl></div>");
    if (verification) |report| {
        try w.writeAll("<section class=\"panel verification\"><h2>Repo verification</h2><dl><dt>Result</dt><dd class=\"");
        try w.writeAll(if (report.match) "match-ok\">Match" else "match-fail\">Match failure");
        try w.writeAll("</dd><dt>authoritative rev</dt><dd>");
        try writeHtmlCodeOrUnknown(w, report.authoritative_rev);
        try w.writeAll("</dd><dt>authoritative root</dt><dd>");
        try writeHtmlCodeOrUnknown(w, report.authoritative_root);
        try w.writeAll("</dd><dt>local rev</dt><dd>");
        try writeHtmlCodeOrUnknown(w, report.local_latest_rev);
        try w.writeAll("</dd><dt>local root</dt><dd>");
        try writeHtmlCodeOrUnknown(w, report.local_root);
        try w.print("</dd><dt>local records</dt><dd>{d}</dd>", .{report.local_record_count});
        if (report.message.len > 0) {
            try w.writeAll("<dt>Message</dt><dd class=\"error\">");
            try writeHtmlEscaped(w, report.message);
            try w.writeAll("</dd>");
        }
        try w.writeAll("</dl></section>");
    } else if (verification_error.len > 0) {
        try w.writeAll("<section class=\"panel verification\"><h2>Repo verification</h2><div class=\"error\">");
        try writeHtmlEscaped(w, verification_error);
        try w.writeAll("</div></section>");
    }
    try w.writeAll("</main></body></html>");
}

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(
        \\<!doctype html><html lang="en"><head><meta charset="utf-8">
        \\<meta name="viewport" content="width=device-width,initial-scale=1">
        \\<meta name="theme-color" content="#081820"><title>stream · hosts</title>
        \\<style>
        \\:root{--ink:#dcecf0;--dim:#8ba4ad;--deep:#081820;--panel:#0d242d;--line:#244550;--water:#58b8d6;--foam:#bdefff;--bad:#ef8178}
        \\*{box-sizing:border-box}body{margin:0;color:var(--ink);background:var(--deep);font:14px/1.45 "Avenir Next",Avenir,"Segoe UI",sans-serif}
        \\main{width:min(1180px,100%);margin:auto;padding:28px 16px 64px}a{color:var(--foam)}header{display:flex;gap:18px;align-items:end;justify-content:space-between;border-bottom:1px solid var(--line);padding-bottom:18px}
        \\h1{margin:0;font-size:clamp(30px,7vw,52px);font-weight:500;letter-spacing:-.04em}nav{display:flex;gap:12px}nav a,.toggle a{padding:7px 9px;border:1px solid var(--line);text-decoration:none;font:12px ui-monospace,SFMono-Regular,monospace}.active{background:var(--water);color:var(--deep)!important;border-color:var(--water)!important}
        \\.lede{color:var(--dim);max-width:70ch;margin:14px 0 24px}.toggle{display:flex;gap:8px;margin:22px 0 14px}.filter{width:min(440px,100%);margin:0 0 14px;padding:9px 11px;color:var(--ink);background:var(--panel);border:1px solid var(--line);border-radius:0;font:13px ui-monospace,SFMono-Regular,monospace}.filter:focus{outline:1px solid var(--water);border-color:var(--water)}.table-wrap{overflow:auto;border:1px solid var(--line)}table{border-collapse:collapse;width:100%;min-width:880px}th,td{text-align:left;padding:10px 11px;border-bottom:1px solid var(--line);vertical-align:top}th{color:var(--dim);font-size:11px;letter-spacing:.08em;text-transform:uppercase;background:#0a1d25;position:sticky;top:0}.num{text-align:right;font-variant-numeric:tabular-nums}code{color:var(--foam);font:12px ui-monospace,SFMono-Regular,monospace}.error{max-width:390px;overflow-wrap:anywhere}.samples td{padding:0 11px 13px;background:var(--panel)}.samples ul{list-style:none;margin:0;padding:8px 0 0}.samples li{display:grid;grid-template-columns:minmax(180px,1fr) 110px 90px minmax(220px,2fr);gap:10px;padding:7px 0;border-top:1px solid var(--line)}.bad{color:var(--bad)}.empty{border:1px solid var(--line);background:var(--panel);padding:18px;color:var(--dim)}
        \\@media(max-width:620px){header{display:block}nav{margin-top:14px}.samples li{grid-template-columns:1fr}.toggle{flex-wrap:wrap}}</style></head><body><main>
        \\<header><div><h1>Host diagnostics</h1></div><nav aria-label="status views"><a href="/status">Summary</a><a class="active" href="/status?tab=hosts">Hosts</a><a href="/status?tab=accounts">Accounts</a></nav></header>
        \\<p class="lede">Durable PDS aggregates from repository backfill and healing. Counts update atomically with each account row; historical errors remain visible after recovery.</p><div class="toggle" aria-label="host sort">
    );
    try w.writeAll(if (sort == .largest) "<a class=\"active\"" else "<a");
    try w.writeAll(" href=\"/status?tab=hosts&amp;sort=largest\">Largest hosts</a>");
    try w.writeAll(if (sort == .failing) "<a class=\"active\"" else "<a");
    try w.writeAll(" href=\"/status?tab=hosts&amp;sort=failing\">Failing hosts</a></div><input id=\"host-filter\" class=\"filter\" placeholder=\"filter host, class, DID, or error\" aria-label=\"filter hosts\">");
    if (statuses.len == 0) {
        try w.writeAll("<p class=\"empty\">No host aggregates have been recorded yet.</p></main></body></html>");
        return;
    }
    try w.writeAll("<div class=\"table-wrap\"><table id=\"hosts-table\"><thead><tr><th>Host</th><th class=\"num\">Repos</th><th class=\"num\">Active</th><th class=\"num\">Complete</th><th class=\"num\">Failed</th><th class=\"num\">Unavailable</th><th>Last attempt</th><th>Latest error</th></tr></thead><tbody>");
    for (statuses) |status| {
        try w.writeAll("<tr class=\"host-row\"><td><code>");
        try writeHtmlEscaped(w, status.host);
        try w.print("</code></td><td class=\"num\">{d}</td><td class=\"num\">{d}</td><td class=\"num\">{d}</td><td class=\"num\">{d}</td><td class=\"num\">{d}</td><td>", .{
            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("</td><td class=\"error\">");
        if (hasErrors(status)) {
            try w.writeAll("<code>");
            try writeHtmlEscaped(w, className(status.latest_error_class));
            try w.writeAll("</code> ");
            try writeHtmlEscaped(w, status.latest_error);
        }
        try w.writeAll("</td></tr>");
        if (status.recent_errors.len > 0) {
            try w.writeAll("<tr class=\"samples host-errors-row\"><td colspan=\"8\"><ul>");
            for (status.recent_errors) |sample| {
                try w.writeAll("<li><span><code>");
                try writeHtmlEscaped(w, sample.did);
                try w.writeAll("</code></span><span>");
                try writeAge(w, now_us, sample.attempted_us);
                try w.writeAll("</span><code class=\"bad\">");
                try writeHtmlEscaped(w, className(sample.class));
                try w.writeAll("</code><span class=\"error\">");
                try writeHtmlEscaped(w, sample.message);
                try w.writeAll("</span></li>");
            }
            try w.writeAll("</ul></td></tr>");
        }
    }
    try w.writeAll(
        "</tbody></table></div><script>document.addEventListener(\"input\",function(event){" ++
            "if(event.target.id!==\"host-filter\")return;var q=event.target.value.toLowerCase();" ++
            "document.querySelectorAll(\"#hosts-table tbody tr.host-row\").forEach(function(row){" ++
            "var detail=row.nextElementSibling;var text=row.textContent;" ++
            "if(detail&&detail.classList.contains(\"host-errors-row\"))text+=\" \"+detail.textContent;" ++
            "var hidden=text.toLowerCase().indexOf(q)===-1;row.hidden=hidden;" ++
            "if(detail&&detail.classList.contains(\"host-errors-row\"))detail.hidden=hidden;});});" ++
            "</script></main></body></html>",
    );
}

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("&amp;"),
        '<' => try w.writeAll("&lt;"),
        '>' => try w.writeAll("&gt;"),
        '"' => try w.writeAll("&quot;"),
        '\'' => try w.writeAll("&#39;"),
        else => try w.writeByte(byte),
    };
}

fn writeHtmlCodeOrUnknown(w: *Writer, raw: []const u8) !void {
    if (raw.len == 0) return w.writeAll("unknown");
    try w.writeAll("<code>");
    try writeHtmlEscaped(w, raw);
    try w.writeAll("</code>");
}

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 = "<script>alert(1)</script>" },
    };
    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 = "<script>alert(1)</script>",
            .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, "&lt;script&gt;alert(1)&lt;/script&gt;") != null);
    try testing.expect(std.mem.indexOf(u8, html, "<script>alert(1)</script>") == 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</dd>") != 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 =
    \\<!doctype html><html lang="en"><head><meta charset="utf-8">
    \\<meta name="viewport" content="width=device-width,initial-scale=1">
    \\<meta name="theme-color" content="#081820">
;

/// 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 =
    \\<style>
    \\:root{--ink:#dcecf0;--dim:#8ba4ad;--deep:#081820;--panel:#0d242d;--line:#244550;--water:#58b8d6;--foam:#bdefff;--bad:#ef8178}
    \\*{box-sizing:border-box}body{margin:0;color:var(--ink);background:var(--deep);font:14px/1.45 "Avenir Next",Avenir,"Segoe UI",sans-serif}
    \\main{width:min(1180px,100%);margin:auto;padding:28px 16px 64px}a{color:var(--foam)}header{display:flex;gap:18px;align-items:end;justify-content:space-between;border-bottom:1px solid var(--line);padding-bottom:18px}
    \\h1{margin:0;font-size:clamp(30px,7vw,52px);font-weight:500;letter-spacing:-.04em}nav{display:flex;gap:12px}nav a,.toggle a{padding:7px 9px;border:1px solid var(--line);text-decoration:none;font:12px ui-monospace,SFMono-Regular,monospace}.active{background:var(--water);color:var(--deep)!important;border-color:var(--water)!important}
    \\.lede{color:var(--dim);max-width:70ch;margin:14px 0 24px}.toggle{display:flex;gap:8px;margin:22px 0 14px}.filter{width:min(440px,100%);margin:0 0 14px;padding:9px 11px;color:var(--ink);background:var(--panel);border:1px solid var(--line);border-radius:0;font:13px ui-monospace,SFMono-Regular,monospace}.filter:focus{outline:1px solid var(--water);border-color:var(--water)}.table-wrap{overflow:auto;border:1px solid var(--line)}table{border-collapse:collapse;width:100%;min-width:880px}th,td{text-align:left;padding:10px 11px;border-bottom:1px solid var(--line);vertical-align:top}th{color:var(--dim);font-size:11px;letter-spacing:.08em;text-transform:uppercase;background:#0a1d25;position:sticky;top:0}.num{text-align:right;font-variant-numeric:tabular-nums}code{color:var(--foam);font:12px ui-monospace,SFMono-Regular,monospace}.error{max-width:390px;overflow-wrap:anywhere}.samples td{padding:0 11px 13px;background:var(--panel)}.samples ul{list-style:none;margin:0;padding:8px 0 0}.samples li{display:grid;grid-template-columns:minmax(180px,1fr) 110px 90px minmax(220px,2fr);gap:10px;padding:7px 0;border-top:1px solid var(--line)}.bad{color:var(--bad)}.empty{border:1px solid var(--line);background:var(--panel);padding:18px;color:var(--dim)}
    \\@media(max-width:620px){header{display:block}nav{margin-top:14px}.samples li{grid-template-columns:1fr}.toggle{flex-wrap:wrap}}</style></head><body><main>
;

fn writeNav(w: *Writer, active: []const u8) !void {
    try w.writeAll("<nav aria-label=\"status views\">");
    const tabs = [_]struct { href: []const u8, label: []const u8, key: []const u8 }{
        .{ .href = "/status", .label = "Summary", .key = "summary" },
        .{ .href = "/status?tab=hosts", .label = "Hosts", .key = "hosts" },
        .{ .href = "/status?tab=accounts", .label = "Accounts", .key = "accounts" },
        .{ .href = "/status?tab=segments", .label = "Segments", .key = "segments" },
        .{ .href = "/status?tab=collections", .label = "Collections", .key = "collections" },
    };
    for (tabs) |tab| {
        if (std.mem.eql(u8, tab.key, active))
            try w.print("<a class=\"active\" href=\"{s}\">{s}</a>", .{ tab.href, tab.label })
        else
            try w.print("<a href=\"{s}\">{s}</a>", .{ tab.href, tab.label });
    }
    try w.writeAll("</nav>");
}

fn renderSegmentsHtml(w: *Writer, rows: []const SegmentRow) !void {
    try w.writeAll(page_head);
    try w.writeAll("<title>stream — segments</title>" ++ page_style);
    try w.writeAll("<header><div><h1>Sealed segments</h1></div>");
    try writeNav(w, "segments");
    try w.writeAll("</header>");
    if (rows.len == 0) {
        try w.writeAll("<div class=\"empty\">No sealed segments yet.</div></body></html>");
        return;
    }
    var events: u64 = 0;
    var bytes: u64 = 0;
    for (rows) |row| {
        events += row.event_count;
        bytes += row.size_bytes;
    }
    try w.print(
        "<p class=\"lede\">{d} sealed segments, {d} events, {d} bytes on disk.</p>",
        .{ rows.len, events, bytes },
    );
    try w.writeAll("<div class=\"table-wrap\"><table><thead><tr><th class=\"num\">Index</th>" ++
        "<th class=\"num\">Events</th><th class=\"num\">Unique DIDs</th><th class=\"num\">Blocks</th>" ++
        "<th class=\"num\">Min seq</th><th class=\"num\">Max seq</th><th class=\"num\">Bytes</th></tr></thead><tbody>");
    for (rows) |row| {
        try w.print(
            "<tr><td class=\"num\">{d}</td><td class=\"num\">{d}</td><td class=\"num\">{d}</td>" ++
                "<td class=\"num\">{d}</td><td class=\"num\">{d}</td><td class=\"num\">{d}</td>" ++
                "<td class=\"num\">{d}</td></tr>",
            .{ row.index, row.event_count, row.unique_did_count, row.block_count, row.min_seq, row.max_seq, row.size_bytes },
        );
    }
    try w.writeAll("</tbody></table></div></body></html>");
}

fn renderCollectionsHtml(w: *Writer, rows: []const CollectionRow) !void {
    try w.writeAll(page_head);
    try w.writeAll("<title>stream — collections</title>" ++ page_style);
    try w.writeAll("<header><div><h1>Archived collections</h1></div>");
    try writeNav(w, "collections");
    try w.writeAll("</header>");
    if (rows.len == 0) {
        try w.writeAll("<div class=\"empty\">No collections have been archived yet.</div></body></html>");
        return;
    }
    try w.print("<p class=\"lede\">{d} collections across the sealed archive.</p>", .{rows.len});
    try w.writeAll("<input id=\"collection-filter\" class=\"filter\" placeholder=\"filter collection\" aria-label=\"filter collections\">");
    try w.writeAll("<div class=\"table-wrap\"><table id=\"collections-table\"><thead><tr><th>Collection</th>" ++
        "<th class=\"num\">Events</th><th class=\"num\">Segments</th></tr></thead><tbody>");
    for (rows) |row| {
        try w.writeAll("<tr class=\"collection-row\"><td><code>");
        try writeHtmlEscaped(w, row.nsid);
        try w.print("</code></td><td class=\"num\">{d}</td><td class=\"num\">{d}</td></tr>", .{ row.event_count, row.segment_count });
    }
    try w.writeAll("</tbody></table></div><script>document.addEventListener(\"input\",function(event){" ++
        "if(event.target.id!==\"collection-filter\")return;" ++
        "var needle=event.target.value.toLowerCase();" ++
        "document.querySelectorAll(\"#collections-table tbody tr.collection-row\").forEach(function(row){" ++
        "row.style.display=row.textContent.toLowerCase().indexOf(needle)===-1?\"none\":\"\";});});</script></body></html>");
}