//! 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
 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 
 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(
        \\
        \\
        \\stream · the atproto river
stream
); try w.writeAll(if (args.serving) "live" else "filling"); try w.writeAll( \\

Every event, as it happens.

A live, public view of the atproto network—with replay from the archive.

\\
ϟ ° · ˚ · ϟ ° · ˚
Following the networklive reading
); try writeCommas(&w, if (args.seq > 0) @intCast(args.seq) else 0); try w.writeAll( \\

“No one ever steps in the same river twice.”

— Heraclitus
\\

Open the stream

\\ ); try w.writeAll(endpoints.html_routes); try w.writeAll( \\
\\
up ); try writeUptime(&w, args.uptime_s); try w.writeAll(""); try writeCommas(&w, args.events_total); try w.print(" events this run{d} listening
", .{args.subscribers}); try w.print("", .{build_options.git_sha}); try w.writeAll( \\
); 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( \\ \\ \\ \\stream · field report \\
\\
atproto field station · public archive
\\

The river is moving.

{s}
\\
upstream firehose sequence , .{ state_class, state_label }); try writeCommas(&w, if (args.upstream_seq > 0) @intCast(args.upstream_seq) else 0); try w.print( \\
\\
durable cursor , .{}); try writeCommas(&w, args.durable_seq); try w.print("
this process", .{}); try writeCommas(&w, args.process_events); try w.print("
listening{d}
uptime", .{args.subscribers}); try writeUptime(&w, args.uptime_s); try w.print( \\
\\
compatibility receipt · 21 jul 2026

Proved against Jim's Go implementation

\\
20/20live protocol checks passed
\\
803,987of 803,987 sealed rows drained by the official Go V2 client
\\
8/8forced lifecycle crashes recovered
\\
5/5seeded restart-chain worlds recovered
\\
<40 MiBRSS under sixteen throttled archive downloads; previously ~402 MiB
\\
what this machine is actually doing

Runtime configuration

    \\
  • Historical bootstrap{s}
  • \\
  • Delete compaction{s}
  • \\
  • Failed-repo healing{s}
  • \\
  • Commit verification{d} valid · {d} invalid
\\
not pretending

Still open

    \\
  • {s}
\\
touch the system

Public surfaces

\\
build {s} · source
\\Every number above is either live from this process or pinned to the dated audit receipt.
\\
, .{ 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, "POST") != 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, "") != 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, "") != 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)); } }