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

zat.dev/stream

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

0
0
689 lines · 37.6 KB Raw History
//! homepage — the ascii river at GET /
//!
//! the waves are seeded from the current upstream seq, so each observed
//! network position has its own river. curl gets plain text; browsers get
//! the same art in a dark <pre> with slowly drifting waves.

const std = @import("std");
const build_options = @import("build_options");
const endpoints = @import("endpoints.zig");

const wave_width = 58;
const wave_rows = 3;

pub const Args = struct {
    seq: i64,
    events_total: u64,
    subscribers: u32,
    uptime_s: i64,
    serving: bool,
};

pub const StatusArgs = struct {
    upstream_seq: i64,
    durable_seq: u64,
    process_events: u64,
    subscribers: u32,
    uptime_s: i64,
    serving: bool,
    bootstrap_enabled: bool,
    compaction_enabled: bool,
    retry_enabled: bool,
    verify_valid: u64,
    verify_invalid: u64,
    /// Durable lifecycle facts, read from the metadata store rather than from
    /// process-local counters: an operator asking "how long has this been
    /// bootstrapping" needs an answer that survives a restart. Null means the
    /// key is genuinely absent (a fresh data dir), never that a read failed.
    phase: ?[]const u8 = null,
    phase_age_s: ?i64 = null,
    backfill_duration_us: ?i64 = null,
    /// Repository rollup, upstream's BackfillStats. Null while no repository
    /// state exists at all, which is not the same as every counter being zero.
    repos_total: ?u32 = null,
    repos_complete: u32 = 0,
    repos_pending: u32 = 0,
    repos_failed: u32 = 0,
    repos_unavailable: u32 = 0,
    /// Live cursors, upstream's LiveStats.
    next_seq: u64 = 0,
    /// Retention, upstream's CursorLookbackStats. Zero lookback means cursor
    /// replay is disabled, which is reported rather than shown as no retention.
    lookback_s: u64 = 0,
    oldest_retained_seq: ?u64 = null,
    sealed_segments: ?usize = null,
    /// Timestamp import, upstream's ImportInfo. Null when import never ran.
    import_job: ?[]const u8 = null,
};

/// deterministic wave row: same seq → same river, next seq → a new one.
/// `buf` needs 3x wave_width bytes (glyphs are 1-3 bytes each).
fn waveRow(buf: []u8, seq: i64, row: u64) std.Io.Writer.Error![]const u8 {
    var prng = std.Random.DefaultPrng.init(@as(u64, @bitCast(seq)) *% 0x9e3779b97f4a7c15 +% row);
    const rand = prng.random();
    // mostly water, some chop, a little foam
    const glyphs = [_][]const u8{ "~", "~", "~", "~", "\u{2248}", "\u{2248}", "\u{00b7}" };
    var w: std.Io.Writer = .fixed(buf);
    var i: usize = 0;
    while (i < wave_width) : (i += 1) {
        try w.print("{s}", .{glyphs[rand.uintLessThan(usize, glyphs.len)]});
    }
    return w.buffered();
}

fn writeCommas(w: *std.Io.Writer, n: u64) std.Io.Writer.Error!void {
    if (n >= 1000) {
        try writeCommas(w, n / 1000);
        try w.print(",{d:0>3}", .{n % 1000});
    } else {
        try w.print("{d}", .{n});
    }
}

fn writeUptime(w: *std.Io.Writer, s: i64) std.Io.Writer.Error!void {
    const secs: u64 = if (s > 0) @intCast(s) else 0;
    const d = secs / 86_400;
    const h = (secs % 86_400) / 3600;
    const m = (secs % 3600) / 60;
    if (d > 0) {
        try w.print("{d}d {d}h", .{ d, h });
    } else if (h > 0) {
        try w.print("{d}h {d}m", .{ h, m });
    } else {
        try w.print("{d}m", .{m});
    }
}

/// the plain-text page (also the <pre> body of the html page)
pub fn render(buf: []u8, args: Args) std.Io.Writer.Error![]const u8 {
    var w: std.Io.Writer = .fixed(buf);

    try w.print(
        \\
        \\                    ~  s t r e a m  ~
        \\
        \\        the atproto firehose, live and archived.
        \\
        \\
    , .{});

    try w.print("    \u{03df}   \u{00b0}     \u{00b7}    \u{02da}      \u{00b7}     \u{03df}     \u{00b0}    \u{00b7}   \u{02da}\n", .{});
    var row: u64 = 0;
    while (row < wave_rows) : (row += 1) {
        var wbuf: [wave_width * 3]u8 = undefined;
        try w.print("  {s}\n", .{try waveRow(&wbuf, args.seq, row)});
    }

    try w.print(
        \\
        \\      "No one ever steps in the same river twice."
        \\                                       — Heraclitus
        \\
        \\
    , .{});

    if (args.serving) {
        try w.print("      Following the network at sequence ", .{});
        try writeCommas(&w, if (args.seq > 0) @intCast(args.seq) else 0);
        try w.print(".\n\n", .{});
    } else {
        try w.print(
            \\      Backfilling network history.
            \\      Live subscriptions open when the archive catches up.
            \\
        , .{});
    }

    try w.print("\n{s}\n\n", .{endpoints.text_block});

    try w.print("  up ", .{});
    try writeUptime(&w, args.uptime_s);
    try w.print(" \u{00b7} ", .{});
    try writeCommas(&w, args.events_total);
    try w.print(" live events this run \u{00b7} {d} listening\n", .{args.subscribers});
    try w.print("  build {s} \u{00b7} source: tangled.org/zat.dev/stream\n\n", .{build_options.git_sha});

    return w.buffered();
}

// Browser rendering lives below as a structured live instrument. The text
// representation above remains intentionally useful to curl and terminals.

/// The river is a live instrument: every displayed runtime value and the wave
/// pattern refresh from the public status report without a page reload.
pub fn renderHtml(buf: []u8, args: Args) std.Io.Writer.Error![]const u8 {
    var w: std.Io.Writer = .fixed(buf);
    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="#07131b">
        \\<title>stream · the atproto river</title><style>
        \\:root{--night:#07131b;--deep:#0a1f2a;--ink:#d8e7ed;--dim:#829aa5;--line:#1d3b49;--water:#43a9d1;--foam:#c2efff;--gold:#d1a955}
        \\*{box-sizing:border-box}body{margin:0;background:var(--night);color:var(--ink);font:15px/1.55 "Avenir Next",Avenir,"Segoe UI",sans-serif}main{width:min(780px,100%);margin:auto;padding:40px 22px 52px}
        \\.top{display:flex;justify-content:space-between;align-items:center;padding-bottom:14px;border-bottom:1px solid var(--line)}.wordmark{font:600 13px/1 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.48em}.state{display:flex;align-items:center;gap:8px;color:var(--dim);font:12px ui-monospace,SFMono-Regular,Menlo,monospace}.dot{width:7px;height:7px;border-radius:50%;background:var(--water);box-shadow:0 0 0 4px #43a9d119;animation:pulse 2.4s ease-out infinite}
        \\.hero{padding:47px 0 25px}h1{max-width:660px;margin:0;font:500 clamp(39px,8vw,69px)/.98 "Avenir Next Condensed","Arial Narrow",sans-serif;letter-spacing:-.045em}.lede{max-width:520px;margin:19px 0 0;color:#a9bdc6;font-size:17px}
        \\.river{position:relative;overflow:hidden;margin:31px -22px 0;padding:29px 22px 24px;border-block:1px solid var(--line);background:linear-gradient(180deg,#091923,var(--deep) 62%,#081923)}.weather{margin:0 0 6px 2ch;color:#83aebe;letter-spacing:1.35em;white-space:nowrap}.waves{margin:0;color:var(--water);font:14px/1.42 ui-monospace,SFMono-Regular,Menlo,monospace;white-space:pre}.wave{display:block;width:max-content;min-width:100%;animation:drift 8s ease-in-out infinite alternate}.wave:nth-child(2){color:#3489ad;animation-duration:11s;animation-direction:alternate-reverse}.wave:nth-child(3){color:#286d8d;animation-duration:17s}
        \\.reading{display:flex;justify-content:space-between;gap:20px;align-items:baseline;margin-top:23px;padding-top:15px;border-top:1px solid #2a5060}.reading-label{color:var(--dim);font-size:13px}.fresh{display:block;margin-top:4px;color:#5f7e8c;font:11px ui-monospace,SFMono-Regular,Menlo,monospace}.seq{color:var(--foam);font:500 clamp(19px,5vw,27px)/1 ui-monospace,SFMono-Regular,Menlo,monospace;font-variant-numeric:tabular-nums}
        \\blockquote{margin:27px 0 42px;padding-left:17px;border-left:1px solid var(--gold);color:#8299a3}blockquote p{margin:0 0 3px;color:#b3c4ca}blockquote cite{font-style:normal;font-size:13px}h2{margin:0 0 13px;color:var(--dim);font:600 11px/1.2 ui-monospace,SFMono-Regular,Menlo,monospace;letter-spacing:.14em;text-transform:uppercase}
        \\.routes{border-top:1px solid var(--line)}.route{display:grid;grid-template-columns:54px minmax(190px,1fr) 1.4fr;gap:12px;padding:11px 0;border-bottom:1px solid var(--line);align-items:baseline}.method,.path,.desc{text-align:left}.method{color:var(--gold);font:12px ui-monospace,SFMono-Regular,Menlo,monospace}.path{color:var(--foam);font:13px ui-monospace,SFMono-Regular,Menlo,monospace;overflow-wrap:anywhere}.desc{color:var(--dim);font-size:13px}.ops{display:flex;gap:18px;margin-top:14px}.ops a,footer a{color:#79bed9;text-decoration:none}.ops a:hover,footer a:hover{text-decoration:underline}
        \\.telemetry{display:flex;flex-wrap:wrap;gap:8px 17px;margin-top:39px;padding-top:15px;border-top:1px solid var(--line);color:#91a7b1;font:12px/1.6 ui-monospace,SFMono-Regular,Menlo,monospace;font-variant-numeric:tabular-nums}.telemetry span+span:before{content:"·";margin-right:17px;color:#385664}footer{display:flex;justify-content:space-between;margin-top:12px;color:#58727e;font:11px ui-monospace,SFMono-Regular,Menlo,monospace}a:focus-visible{outline:2px solid var(--water);outline-offset:4px}
        \\@keyframes drift{to{transform:translateX(-1.4ch)}}@keyframes pulse{70%{box-shadow:0 0 0 9px transparent}}@media(max-width:590px){main{padding:24px 17px 38px}.hero{padding-top:36px}.river{margin-inline:-17px;padding-inline:17px}.route{grid-template-columns:45px 1fr}.desc{grid-column:2}.reading{display:block}.seq{display:block;margin-top:6px}.telemetry{display:grid;gap:3px}.telemetry span+span:before{content:none}footer{display:block}.weather{letter-spacing:.9em}}@media(prefers-reduced-motion:reduce){.wave,.dot{animation:none}}
        \\</style></head><body><main><header class="top"><div class="wordmark">stream</div><div class="state"><i class="dot"></i><span id="state-label">
    );
    try w.writeAll(if (args.serving) "live" else "filling");
    try w.writeAll(
        \\</span></div></header><section class="hero"><h1>Every event, as it happens.</h1><p class="lede">A live, public view of the atproto network—with replay from the archive.</p></section>
        \\<section class="river" aria-label="Live network current"><div class="weather">ϟ ° · ˚ · ϟ ° · ˚</div><pre class="waves" aria-hidden="true">
    );
    var row: u64 = 0;
    while (row < wave_rows) : (row += 1) {
        var wave_buf: [wave_width * 3]u8 = undefined;
        try w.print("<span class=\"wave\" id=\"wave{d}\">{s}</span>", .{ row, try waveRow(&wave_buf, args.seq, row) });
    }
    try w.writeAll(
        \\</pre><div class="reading"><div><span class="reading-label">Following the network</span><span class="fresh" id="freshness">live reading</span></div><strong class="seq" id="live-seq">
    );
    try writeCommas(&w, if (args.seq > 0) @intCast(args.seq) else 0);
    try w.writeAll(
        \\</strong></div></section><blockquote><p>“No one ever steps in the same river twice.”</p><cite>— Heraclitus</cite></blockquote>
        \\<section><h2>Open the stream</h2><div class="routes">
        \\
    );
    try w.writeAll(endpoints.html_routes);
    try w.writeAll(
        \\</div>
        \\<nav class="ops" aria-label="Operations"><a href="/status">status</a></nav></section><div class="telemetry"><span>up <b id="uptime">
    );
    try writeUptime(&w, args.uptime_s);
    try w.writeAll("</b></span><span><b id=\"events\">");
    try writeCommas(&w, args.events_total);
    try w.print("</b> events this run</span><span><b id=\"listeners\">{d}</b> listening</span></div>", .{args.subscribers});
    try w.print("<footer><span>build {s}</span><a href=\"https://tangled.org/zat.dev/stream\">source</a></footer>", .{build_options.git_sha});
    try w.writeAll(
        \\<script>
        \\const $=id=>document.getElementById(id),fmt=n=>Number(n).toLocaleString('en-US');let last=Date.now();
        \\function waves(seed){let x=BigInt(seed)||1n,g=['~','~','~','~','≈','≈','·'];for(let r=0;r<3;r++){let out='';for(let i=0;i<58;i++){x^=x<<13n;x^=x>>7n;x^=x<<17n;out+=g[Number((x+BigInt(r))%7n)]}$('wave'+r).textContent=out}}
        \\async function sample(){try{const text=await fetch('/status',{cache:'no-store',headers:{Accept:'text/plain'}}).then(r=>{if(!r.ok)throw Error(r.status);return r.text()});const get=n=>{const m=text.match(new RegExp('^'+n+'\\s+(.+)$','m'));return m&&m[1].trim()},num=n=>{const v=get(n);return v&&v.replaceAll(',','')},seq=num('upstream seq'),events=num('events this run'),listeners=num('listeners'),up=get('uptime');if(seq){$('live-seq').textContent=fmt(seq);waves(seq)}if(events)$('events').textContent=fmt(events);if(listeners)$('listeners').textContent=fmt(listeners);if(up)$('uptime').textContent=up;last=Date.now();$('freshness').textContent='updated just now'}catch(e){$('freshness').textContent='live reading paused'}}
        \\setInterval(()=>{const age=Math.floor((Date.now()-last)/1000);if(age>3)$('freshness').textContent=`updated ${age}s ago`},1000);sample();setInterval(sample,2000);
        \\</script></main></body></html>
    );
    return w.buffered();
}

/// Plain-text field report for terminals and non-browser HTTP clients.
/// One-line provenance statement derived from live state, not a baked date:
/// with bootstrap configured, steady_state means the whole-network bootstrap
/// completed and repair continues; any other phase means it is still running.
fn provenanceLine(args: StatusArgs) []const u8 {
    if (!args.bootstrap_enabled)
        return "this public archive began live; it is not a historical bootstrap";
    if (args.phase) |phase| {
        if (std.mem.eql(u8, phase, "steady_state"))
            return "whole-network historical bootstrap complete; failed and changed repositories heal continuously";
    }
    return "historical bootstrap is in progress; completion is not yet proven";
}

/// Sentence-case variant for the HTML field card.
fn provenanceLineHtml(args: StatusArgs) []const u8 {
    if (!args.bootstrap_enabled)
        return "This public archive began live; it is not a whole-network historical bootstrap.";
    if (args.phase) |phase| {
        if (std.mem.eql(u8, phase, "steady_state"))
            return "Whole-network historical bootstrap complete; failed and changed repositories heal continuously.";
    }
    return "Historical bootstrap is in progress; whole-network completion is not yet proven.";
}

pub fn renderStatus(buf: []u8, args: StatusArgs) std.Io.Writer.Error![]const u8 {
    var w: std.Io.Writer = .fixed(buf);
    try w.print("stream field report\n\nstate            {s}\nupstream seq     ", .{if (args.serving) "live" else "filling"});
    try writeCommas(&w, if (args.upstream_seq > 0) @intCast(args.upstream_seq) else 0);
    try w.print("\ndurable cursor   ", .{});
    try writeCommas(&w, args.durable_seq);
    try w.print("\nevents this run  ", .{});
    try writeCommas(&w, args.process_events);
    try w.print("\nlisteners        {d}\nuptime           ", .{args.subscribers});
    try writeUptime(&w, args.uptime_s);
    if (args.phase) |phase| {
        try w.print("\nphase            {s}", .{phase});
        if (args.phase_age_s) |age| {
            try w.print(" for ", .{});
            try writeUptime(&w, age);
        }
    }
    if (args.backfill_duration_us) |dur| {
        try w.print("\nbackfill took    ", .{});
        try writeUptime(&w, @divTrunc(dur, std.time.us_per_s));
    }
    if (args.repos_total) |total| {
        try w.print("\n\nrepositories\n  total          ", .{});
        try writeCommas(&w, total);
        try w.print("\n  complete       ", .{});
        try writeCommas(&w, args.repos_complete);
        if (total > 0) try w.print(" ({d}%)", .{@divTrunc(@as(u64, args.repos_complete) * 100, total)});
        try w.print("\n  pending        ", .{});
        try writeCommas(&w, args.repos_pending);
        try w.print("\n  failed         ", .{});
        try writeCommas(&w, args.repos_failed);
        try w.print("\n  unavailable    ", .{});
        try writeCommas(&w, args.repos_unavailable);
    }
    try w.print("\n\narchive\n  next seq        ", .{});
    try writeCommas(&w, args.next_seq);
    if (args.sealed_segments) |segs| {
        try w.print("\n  sealed segs     ", .{});
        try writeCommas(&w, segs);
    }
    if (args.lookback_s == 0) {
        try w.print("\n  cursor replay   disabled", .{});
    } else {
        try w.print("\n  cursor lookback ", .{});
        try writeUptime(&w, @intCast(args.lookback_s));
        if (args.oldest_retained_seq) |oldest| {
            try w.print("\n  oldest retained ", .{});
            try writeCommas(&w, oldest);
        }
    }
    if (args.import_job) |job| try w.print("\n\ntimestamp import\n  job             {s}", .{job});
    // Separate the durable sections above from the run-scoped lines below.
    try w.print("\n", .{});
    try w.print(
        "\nverified         {d} valid / {d} invalid\n\n" ++
            "configuration\n" ++
            "  historical bootstrap  {s}\n" ++
            "  delete compaction      {s}\n" ++
            "  failed-repo healing    {s}\n\n" ++
            "admission\n" ++
            "  this image digest is bound to receipts/{s}.json in the\n" ++
            "  source repo: full suite run (unit, contract, lifecycle,\n" ++
            "  power-loss, and differential oracles) on the exact source\n\n" ++
            "provenance\n" ++
            "  {s}\n\n" ++
            "build {s} · https://tangled.org/zat.dev/stream\n",
        .{
            args.verify_valid,
            args.verify_invalid,
            if (args.bootstrap_enabled) "enabled" else "off",
            if (args.compaction_enabled) "enabled" else "off",
            if (args.retry_enabled) "enabled" else "off",
            build_options.git_sha,
            provenanceLine(args),
            build_options.git_sha,
        },
    );
    return w.buffered();
}

/// A phone-first hydrology field card: live facts, proof, then honest gaps.
/// No JavaScript, remote fonts, or external assets are needed to read it.
pub fn renderStatusHtml(buf: []u8, args: StatusArgs) std.Io.Writer.Error![]const u8 {
    var w: std.Io.Writer = .fixed(buf);
    const state_class: []const u8 = if (args.serving) "live" else "fill";
    const state_label: []const u8 = if (args.serving) "flowing" else "filling";
    try w.print(
        \\<!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 · field report</title>
        \\<style>
        \\:root {{ --ink:#dcecf0; --dim:#8ba4ad; --deep:#081820;
        \\  --panel:#0d242d; --line:#244550; --water:#58b8d6;
        \\  --foam:#bdefff; --silt:#d6ad63; --coral:#ef8178; }}
        \\* {{ box-sizing:border-box }}
        \\body {{ margin:0; color:var(--ink); background:var(--deep);
        \\  font:15px/1.5 "Avenir Next",Avenir,"Segoe UI",sans-serif; }}
        \\main {{ width:min(760px,100%); margin:auto; padding:24px 18px 64px; }}
        \\.mast {{ position:relative; overflow:hidden; border:1px solid var(--line);
        \\  padding:22px 20px 24px; background:linear-gradient(145deg,#0d2933,#0a1d25); }}
        \\.mast:after {{ content:""; position:absolute; left:-5%; right:-5%; bottom:0;
        \\  height:3px; background:var(--water); box-shadow:0 -8px 28px #58b8d666;
        \\  animation:tide 7s ease-in-out infinite alternate; }}
        \\@keyframes tide {{ to {{ transform:translateX(4%) scaleX(.94) }} }}
        \\.eyebrow,.label {{ color:var(--dim); font:600 11px/1.2 ui-monospace,SFMono-Regular,monospace;
        \\  letter-spacing:.13em; text-transform:uppercase; }}
        \\h1 {{ margin:12px 0 2px; font:500 clamp(30px,9vw,54px)/.98
        \\  "Avenir Next Condensed","Arial Narrow",sans-serif; letter-spacing:-.035em; }}
        \\.state {{ display:inline-flex; gap:8px; align-items:center; color:var(--foam);
        \\  margin-top:13px; font-weight:600; }}
        \\.dot {{ width:8px; height:8px; border-radius:50%; background:var(--water);
        \\  box-shadow:0 0 0 5px #58b8d61e; }} .fill .dot {{ background:var(--silt) }}
        \\.gauge {{ margin-top:26px; padding-top:13px; border-top:1px solid var(--line); }}
        \\.reading {{ display:block; margin-top:5px; color:var(--foam);
        \\  font:500 clamp(25px,8vw,43px)/1 ui-monospace,SFMono-Regular,monospace;
        \\  letter-spacing:-.055em; font-variant-numeric:tabular-nums; }}
        \\.grid {{ display:grid; grid-template-columns:repeat(2,1fr); border:1px solid var(--line);
        \\  border-top:0; }} .cell {{ min-width:0; padding:16px 14px; border-top:1px solid var(--line); }}
        \\.cell:nth-child(odd) {{ border-right:1px solid var(--line); }}
        \\.value {{ display:block; margin-top:4px; color:var(--foam);
        \\  font:500 20px/1.2 ui-monospace,SFMono-Regular,monospace; font-variant-numeric:tabular-nums; }}
        \\section {{ margin-top:34px; }} h2 {{ margin:7px 0 14px; font-size:22px; letter-spacing:-.02em; }}
        \\.receipt {{ display:grid; gap:1px; background:var(--line); border:1px solid var(--line); }}
        \\.proof {{ background:var(--panel); padding:15px; display:grid;
        \\  grid-template-columns:72px 1fr; gap:14px; align-items:baseline; }}
        \\.proof b {{ color:var(--foam); font:600 19px/1 ui-monospace,SFMono-Regular,monospace; }}
        \\.proof span {{ color:#bdd0d6; }}
        \\.switches,.gaps {{ list-style:none; padding:0; margin:0; border-top:1px solid var(--line); }}
        \\.switches li,.gaps li {{ display:flex; justify-content:space-between; gap:18px;
        \\  padding:12px 2px; border-bottom:1px solid var(--line); }}
        \\.off {{ color:var(--silt); font-family:ui-monospace,SFMono-Regular,monospace; }}
        \\.on {{ color:var(--water); font-family:ui-monospace,SFMono-Regular,monospace; }}
        \\.gaps li {{ display:block; padding-left:18px; position:relative; color:#bdd0d6; }}
        \\.gaps li:before {{ content:""; width:6px; height:6px; border:1px solid var(--coral);
        \\  position:absolute; left:1px; top:20px; transform:rotate(45deg); }}
        \\.routes {{ display:flex; flex-wrap:wrap; gap:8px; }} a {{ color:var(--foam); }}
        \\.routes a {{ border:1px solid var(--line); padding:7px 9px; text-decoration:none;
        \\  font:12px ui-monospace,SFMono-Regular,monospace; }}
        \\footer {{ margin-top:38px; padding-top:15px; border-top:1px solid var(--line);
        \\  color:var(--dim); font:12px/1.7 ui-monospace,SFMono-Regular,monospace; }}
        \\@media(min-width:620px) {{ main {{ padding-top:44px }} .grid {{ grid-template-columns:repeat(4,1fr) }}
        \\  .cell:nth-child(n) {{ border-right:1px solid var(--line) }} .cell:last-child {{ border-right:0 }} }}
        \\@media(prefers-reduced-motion:reduce) {{ .mast:after {{ animation:none }} }}
        \\</style></head><body><main>
        \\<header class="mast"><div class="eyebrow">atproto field station · public archive</div>
        \\<h1>The river is moving.</h1><div class="state {s}"><i class="dot"></i>{s}</div>
        \\<div class="gauge"><span class="label">upstream firehose sequence</span><span class="reading">
    , .{ state_class, state_label });
    try writeCommas(&w, if (args.upstream_seq > 0) @intCast(args.upstream_seq) else 0);
    try w.print(
        \\</span></div></header><div class="grid">
        \\<div class="cell"><span class="label">durable cursor</span><span class="value">
    , .{});
    try writeCommas(&w, args.durable_seq);
    try w.print("</span></div><div class=\"cell\"><span class=\"label\">this process</span><span class=\"value\">", .{});
    try writeCommas(&w, args.process_events);
    try w.print("</span></div><div class=\"cell\"><span class=\"label\">listening</span><span class=\"value\">{d}</span></div><div class=\"cell\"><span class=\"label\">uptime</span><span class=\"value\">", .{args.subscribers});
    try writeUptime(&w, args.uptime_s);
    try w.print(
        \\</span></div></div>
        \\<section><span class="eyebrow">compatibility receipt · 21 jul 2026</span><h2>Proved against Jim's Go implementation</h2>
        \\<div class="receipt"><div class="proof"><b>20/20</b><span>live protocol checks passed</span></div>
        \\<div class="proof"><b>803,987</b><span>of 803,987 sealed rows drained by the official Go V2 client</span></div>
        \\<div class="proof"><b>8/8</b><span>forced lifecycle crashes recovered</span></div>
        \\<div class="proof"><b>5/5</b><span>seeded restart-chain worlds recovered</span></div>
        \\<div class="proof"><b>&lt;40 MiB</b><span>RSS under sixteen throttled archive downloads; previously ~402 MiB</span></div></div></section>
        \\<section><span class="eyebrow">what this machine is actually doing</span><h2>Runtime configuration</h2><ul class="switches">
        \\<li><span>Historical bootstrap</span><b class="{s}">{s}</b></li>
        \\<li><span>Delete compaction</span><b class="{s}">{s}</b></li>
        \\<li><span>Failed-repo healing</span><b class="{s}">{s}</b></li>
        \\<li><span>Commit verification</span><b class="on">{d} valid · {d} invalid</b></li></ul></section>
        \\<section><span class="eyebrow">not pretending</span><h2>Still open</h2><ul class="gaps">
        \\<li>{s}</li></ul></section>
        \\<section><span class="eyebrow">touch the system</span><h2>Public surfaces</h2><div class="routes">
        \\<a href="/">river</a>
        \\<a href="/xrpc/network.bsky.jetstream.listSegments">sealed archive</a></div></section>
        \\<footer>build {s} · <a href="https://tangled.org/zat.dev/stream">source</a><br>
        \\Every number above is either live from this process or pinned to the dated audit receipt.</footer>
        \\</main></body></html>
    , .{
        if (args.bootstrap_enabled) "on" else "off",
        if (args.bootstrap_enabled) "enabled" else "off",
        if (args.compaction_enabled) "on" else "off",
        if (args.compaction_enabled) "enabled" else "off",
        if (args.retry_enabled) "on" else "off",
        if (args.retry_enabled) "enabled" else "off",
        args.verify_valid,
        args.verify_invalid,
        provenanceLineHtml(args),
        build_options.git_sha,
    });
    return w.buffered();
}

// === tests ===

const testing = std.testing;

test "waves are deterministic per seq and differ across seqs" {
    var a: [wave_width * 3]u8 = undefined;
    var b: [wave_width * 3]u8 = undefined;
    const r1 = try waveRow(&a, 42, 0);
    const r2 = try waveRow(&b, 42, 0);
    try testing.expectEqualStrings(r1, r2);
    var c: [wave_width * 3]u8 = undefined;
    const r3 = try waveRow(&c, 43, 0);
    try testing.expect(!std.mem.eql(u8, r1, r3));
}

test "render carries live numbers and the quote" {
    var buf: [8192]u8 = undefined;
    const out = try render(&buf, .{
        .seq = 29_401_223,
        .events_total = 182_401_554,
        .subscribers = 12,
        .uptime_s = 4 * 86_400 + 12 * 3600,
        .serving = true,
    });
    try testing.expect(std.mem.indexOf(u8, out, "s t r e a m") != null);
    try testing.expect(std.mem.indexOf(u8, out, "Heraclitus") != null);
    try testing.expect(std.mem.indexOf(u8, out, "— Heraclitus\n\n") != null);
    try testing.expect(std.mem.indexOf(u8, out, "29,401,223") != null);
    try testing.expect(std.mem.indexOf(u8, out, "182,401,554 live events this run") != null);
    try testing.expect(std.mem.indexOf(u8, out, "12 listening") != null);
    try testing.expect(std.mem.indexOf(u8, out, "up 4d 12h") != null);
    try testing.expect(std.mem.indexOf(u8, out, "subscribeEvents") != null);
}

test "bootstrap variant explains subscription readiness" {
    var buf: [8192]u8 = undefined;
    const out = try render(&buf, .{ .seq = 0, .events_total = 0, .subscribers = 0, .uptime_s = 30, .serving = false });
    try testing.expect(std.mem.indexOf(u8, out, "Backfilling network history") != null);
    try testing.expect(std.mem.indexOf(u8, out, "archive catches up") != null);
    try testing.expect(std.mem.indexOf(u8, out, "refresh:") == null);
}

test "html is structured, live-updating, and implementation-language neutral" {
    var buf: [16384]u8 = undefined;
    const out = try renderHtml(&buf, .{ .seq = 7, .events_total = 1, .subscribers = 0, .uptime_s = 60, .serving = true });
    try testing.expect(std.mem.indexOf(u8, out, "id=\"live-seq\"") != null);
    try testing.expect(std.mem.indexOf(u8, out, "id=\"events\"") != null);
    try testing.expect(std.mem.indexOf(u8, out, "id=\"listeners\"") != null);
    try testing.expect(std.mem.indexOf(u8, out, "fetch('/status'") != null);
    try testing.expect(std.mem.indexOf(u8, out, "fetch('/metrics'") == null);
    try testing.expect(std.mem.indexOf(u8, out, "<span class=\"method\">POST</span>") != null);
    try testing.expect(std.mem.indexOf(u8, out, "@keyframes drift") != null);
    try testing.expect(std.mem.indexOf(u8, out, "zig") == null);
    try testing.expect(std.mem.indexOf(u8, out, "</html>") != null);
}

test "status report is honest and phone-ready" {
    const args: StatusArgs = .{
        .upstream_seq = 823_000_001,
        .durable_seq = 803_987,
        .process_events = 22_890,
        .subscribers = 3,
        .uptime_s = 3660,
        .serving = true,
        .bootstrap_enabled = false,
        .compaction_enabled = false,
        .retry_enabled = false,
        .verify_valid = 22_800,
        .verify_invalid = 2,
    };
    var text_buf: [8192]u8 = undefined;
    const text = try renderStatus(&text_buf, args);
    try testing.expect(std.mem.indexOf(u8, text, "823,000,001") != null);
    try testing.expect(std.mem.indexOf(u8, text, "historical bootstrap  off") != null);
    try testing.expect(std.mem.indexOf(u8, text, "provenance") != null);
    try testing.expect(std.mem.indexOf(u8, text, "this public archive began live") != null);
    try testing.expect(std.mem.indexOf(u8, text, "receipts/") != null);

    var html_buf: [32 * 1024]u8 = undefined;
    const html = try renderStatusHtml(&html_buf, args);
    try testing.expect(std.mem.indexOf(u8, html, "width=device-width") != null);
    try testing.expect(std.mem.indexOf(u8, html, "The river is moving") != null);
    try testing.expect(std.mem.indexOf(u8, html, "not pretending") != null);
    try testing.expect(std.mem.indexOf(u8, html, "This public archive began live") != null);
    try testing.expect(std.mem.indexOf(u8, html, "</html>") != null);

    var bootstrap_args = args;
    bootstrap_args.bootstrap_enabled = true;
    bootstrap_args.serving = false;
    const bootstrap_text = try renderStatus(&text_buf, bootstrap_args);
    try testing.expect(std.mem.indexOf(u8, bootstrap_text, "historical bootstrap is in progress") != null);
    try testing.expect(std.mem.indexOf(u8, bootstrap_text, "this public archive began live") == null);

    const bootstrap_html = try renderStatusHtml(&html_buf, bootstrap_args);
    try testing.expect(std.mem.indexOf(u8, bootstrap_html, "Historical bootstrap is in progress") != null);
    try testing.expect(std.mem.indexOf(u8, bootstrap_html, "This public archive began live") == null);

    // steady_state with bootstrap configured: completion is provable from
    // live state, so the page must claim it (this replaced two baked lines
    // that kept a July date and "not yet proven" alive into August)
    var steady_args = bootstrap_args;
    steady_args.phase = "steady_state";
    const steady_text = try renderStatus(&text_buf, steady_args);
    try testing.expect(std.mem.indexOf(u8, steady_text, "bootstrap complete") != null);
    try testing.expect(std.mem.indexOf(u8, steady_text, "not yet proven") == null);
    const steady_html = try renderStatusHtml(&html_buf, steady_args);
    try testing.expect(std.mem.indexOf(u8, steady_html, "bootstrap complete") != null);
}

// An operator asking "how long has this been bootstrapping" needs an answer
// that survives a restart, which is why these come from the durable phase
// store rather than process-local counters. Absent must render as absent: a
// fresh data dir has no phase, and showing "0m" there would claim the run just
// started when nothing has run at all.
test "status summary reports durable lifecycle timing, and omits it when absent" {
    var buf: [8192]u8 = undefined;
    const base: StatusArgs = .{
        .upstream_seq = 10,
        .durable_seq = 10,
        .process_events = 10,
        .subscribers = 0,
        .uptime_s = 60,
        .serving = true,
        .bootstrap_enabled = false,
        .compaction_enabled = false,
        .retry_enabled = false,
        .verify_valid = 0,
        .verify_invalid = 0,
    };

    var with = base;
    with.phase = "bootstrap";
    with.phase_age_s = 3 * 3600 + 25 * 60;
    with.backfill_duration_us = 90 * 60 * std.time.us_per_s;
    const shown = try renderStatus(&buf, with);
    try testing.expect(std.mem.indexOf(u8, shown, "phase            bootstrap for 3h 25m") != null);
    try testing.expect(std.mem.indexOf(u8, shown, "backfill took    1h 30m") != null);

    // A fresh data dir has no phase key; the lines disappear rather than
    // rendering a zero that reads like a just-started run.
    var without_buf: [8192]u8 = undefined;
    const hidden = try renderStatus(&without_buf, base);
    try testing.expect(std.mem.indexOf(u8, hidden, "phase ") == null);
    try testing.expect(std.mem.indexOf(u8, hidden, "backfill took") == null);

    // The admission block names the receipt for THIS build rather than
    // baking a dated suite tally that rots as new receipts land.
    try testing.expect(std.mem.indexOf(u8, shown, "receipts/") != null);
    try testing.expect(std.mem.indexOf(u8, shown, build_options.git_sha) != null);
}

// The river at GET / is an aesthetic choice and diverges from upstream on
// purpose. The field report at /status is the surface that corresponds to
// upstream's /status, so it owes the same information set: repository rollup
// (BackfillStats), live cursors (LiveStats), retention (CursorLookbackStats)
// and import state (ImportInfo). This pins the set so it cannot quietly shrink
// back to the handful of process-local counters it started as.
test "field report carries upstream's status information set" {
    var buf: [8192]u8 = undefined;
    const out = try renderStatus(&buf, .{
        .upstream_seq = 500,
        .durable_seq = 480,
        .process_events = 12,
        .subscribers = 1,
        .uptime_s = 120,
        .serving = true,
        .bootstrap_enabled = true,
        .compaction_enabled = true,
        .retry_enabled = true,
        .verify_valid = 9,
        .verify_invalid = 1,
        .phase = "steady_state",
        .phase_age_s = 600,
        .backfill_duration_us = 45 * 60 * std.time.us_per_s,
        .repos_total = 200,
        .repos_complete = 150,
        .repos_pending = 30,
        .repos_failed = 15,
        .repos_unavailable = 5,
        .next_seq = 4_242,
        .lookback_s = 36 * 3600,
        .oldest_retained_seq = 77,
        .sealed_segments = 12,
        .import_job = "job-7 (running, apply)",
    });
    try testing.expect(std.mem.indexOf(u8, out, "total          200") != null);
    try testing.expect(std.mem.indexOf(u8, out, "complete       150 (75%)") != null);
    try testing.expect(std.mem.indexOf(u8, out, "pending        30") != null);
    try testing.expect(std.mem.indexOf(u8, out, "failed         15") != null);
    try testing.expect(std.mem.indexOf(u8, out, "unavailable    5") != null);
    try testing.expect(std.mem.indexOf(u8, out, "next seq        4,242") != null);
    try testing.expect(std.mem.indexOf(u8, out, "sealed segs     12") != null);
    try testing.expect(std.mem.indexOf(u8, out, "cursor lookback 1d 12h") != null);
    try testing.expect(std.mem.indexOf(u8, out, "oldest retained 77") != null);
    try testing.expect(std.mem.indexOf(u8, out, "job-7 (running, apply)") != null);
}

test "disabled cursor replay is reported, not shown as no retention" {
    var buf: [8192]u8 = undefined;
    const out = try renderStatus(&buf, .{
        .upstream_seq = 1,
        .durable_seq = 1,
        .process_events = 0,
        .subscribers = 0,
        .uptime_s = 1,
        .serving = true,
        .bootstrap_enabled = false,
        .compaction_enabled = false,
        .retry_enabled = false,
        .verify_valid = 0,
        .verify_invalid = 0,
        .lookback_s = 0,
        .sealed_segments = 3,
    });
    try testing.expect(std.mem.indexOf(u8, out, "cursor replay   disabled") != null);
    try testing.expect(std.mem.indexOf(u8, out, "oldest retained") == null);
    // No repository state at all is not "0 of 0 complete".
    try testing.expect(std.mem.indexOf(u8, out, "repositories") == null);
}

test "page renderers reject short buffers and accept exact fits" {
    const args: Args = .{ .seq = 1234567, .events_total = 7654321, .subscribers = 42, .uptime_s = 90061, .serving = true };
    const status: StatusArgs = .{
        .upstream_seq = 1234567,
        .durable_seq = 1234566,
        .process_events = 7654321,
        .subscribers = 42,
        .uptime_s = 90061,
        .serving = true,
        .bootstrap_enabled = true,
        .compaction_enabled = true,
        .retry_enabled = true,
        .verify_valid = 100,
        .verify_invalid = 1,
        .phase = "steady_state",
        .phase_age_s = 60,
        .backfill_duration_us = 90000000,
        .repos_total = 100,
        .repos_complete = 90,
        .repos_pending = 5,
        .repos_failed = 4,
        .repos_unavailable = 1,
        .next_seq = 1234568,
        .lookback_s = 3600,
        .oldest_retained_seq = 100,
        .sealed_segments = 2,
        .import_job = "completed",
    };
    inline for (.{ render, renderHtml, renderStatus, renderStatusHtml }, 0..) |renderer, i| {
        var expected_buf: [32 * 1024]u8 = undefined;
        var actual_buf: [32 * 1024]u8 = undefined;
        const input = if (i < 2) args else status;
        const expected = try renderer(&expected_buf, input);
        for ([_]usize{ 0, 1, expected.len - 1 }) |len|
            try testing.expectError(error.WriteFailed, renderer(actual_buf[0..len], input));
        try testing.expectEqualStrings(expected, try renderer(actual_buf[0..expected.len], input));
    }
}