// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! What `ci-top` shows, worked out from a status document and the time, and //! nothing about how it is drawn: the rows of each list, what a row's details //! say, and which row is selected. All of it is plain data, so all of it is //! tested without a terminal. const std = @import("std"); const Allocator = std.mem.Allocator; const api = @import("api"); const status = api.status; pub const Section = enum { pending, running, finished, pub fn title(s: Section) []const u8 { return switch (s) { .pending => "Pending", .running => "Running", .finished => "Finished", }; } pub fn headers(s: Section) []const []const u8 { return switch (s) { .pending => &.{ "WAITING", "SOURCE", "TIER", "WORK", "NOTE" }, .running => &.{ "DROPLET", "TIER", "STATE", "AGE", "PHASE", "SOURCE", "WORK" }, .finished => &.{ "DROPLET", "TIER", "RESULT", "ENDED", "TOOK", "SOURCE", "WORK" }, }; } pub fn next(s: Section) Section { return switch (s) { .pending => .running, .running => .finished, .finished => .pending, }; } pub fn previous(s: Section) Section { return switch (s) { .pending => .finished, .running => .pending, .finished => .running, }; } }; /// How a row should look: what it says about how things are going. pub const Tone = enum { normal, good, warn, bad }; /// What a row is about, for its details. pub const Item = union(enum) { pending: status.Pending, droplet: status.Droplet, run: status.Run, }; pub const Row = struct { /// Names the row across refreshes, so the selection can stay on it. key: []const u8, /// One per header. cells: []const []const u8, tone: Tone = .normal, item: Item, }; /// The rows of `section`. Everything returned lives in `arena`. pub fn rows(arena: Allocator, s: status.Status, section: Section, now: i64) Allocator.Error![]const Row { var out: std.ArrayList(Row) = .empty; switch (section) { .pending => for (s.pending) |p| { const note: []const u8 = if (p.backoff) |b| if (b.until > now) try std.fmt.allocPrint(arena, "failed {d}x, retry in {f}", .{ b.failures, duration(b.until - now) }) else try std.fmt.allocPrint(arena, "failed {d}x, retrying", .{b.failures}) else ""; try out.append(arena, .{ .key = try pendingKey(arena, p), .cells = try arena.dupe([]const u8, &.{ try fmt(arena, "{f}", .{duration(now - p.first_seen)}), p.source, p.tier, try describe(arena, p.work), note, }), .tone = if (p.backoff != null) .warn else .normal, .item = .{ .pending = p }, }); }, .running => for (s.running) |d| { const current = currentPhase(d, now); try out.append(arena, .{ .key = try fmt(arena, "d:{d}", .{d.id}), .cells = try arena.dupe([]const u8, &.{ d.name, d.tier, stateName(d), try fmt(arena, "{f}", .{duration(now - d.created_at)}), if (current) |c| try fmt(arena, "{s} {f}", .{ c.name, duration(c.seconds) }) else "", source(d.work), try describe(arena, d.work), }), // Still booting after a quarter of an hour is worth a look; // the daemon gives up at its boot timeout. .tone = if (d.claimed_at == null and now - d.created_at > 900) .warn else .normal, .item = .{ .droplet = d }, }); }, .finished => { for (s.finished) |d| { const outcome = dropletOutcome(d); const ended = endedAt(d); const began = d.work_started_at orelse d.created_at; try out.append(arena, .{ .key = try fmt(arena, "d:{d}", .{d.id}), .cells = try arena.dupe([]const u8, &.{ d.name, d.tier, try outcome.text(arena), try fmt(arena, "{f} ago", .{duration(now - ended)}), try fmt(arena, "{f}", .{duration(ended - began)}), source(d.work), try describe(arena, d.work), }), .tone = outcome.tone(), .item = .{ .droplet = d }, }); } for (s.finished_runs) |r| { const outcome: Outcome = if (r.result) |v| .{ .result = v } else .unreported; const ended = r.finished_at orelse r.created_at; try out.append(arena, .{ .key = try fmt(arena, "r:{d}", .{r.id}), .cells = try arena.dupe([]const u8, &.{ "-", r.tier, try outcome.text(arena), try fmt(arena, "{f} ago", .{duration(now - ended)}), try fmt(arena, "{f}", .{duration(ended - r.created_at)}), "radicle", try describe(arena, .{ .radicle = r }), }), .tone = outcome.tone(), .item = .{ .run = r }, }); } }, } return out.items; } fn fmt(arena: Allocator, comptime format: []const u8, args: anytype) Allocator.Error![]const u8 { return std.fmt.allocPrint(arena, format, args); } fn pendingKey(arena: Allocator, p: status.Pending) Allocator.Error![]const u8 { return switch (p.work) { .forgejo => |f| fmt(arena, "p:{s}/{s}", .{ f.forge, f.handle }), .radicle => |r| fmt(arena, "p:radicle/{d}", .{r.id}), // Pending work is always a job or a run; a warm droplet is not // pending anything. .pool => "p:pool", .unknown => "p:unknown", }; } pub fn source(work: status.Work) []const u8 { return switch (work) { .forgejo => |f| f.forge, .radicle => "radicle", .pool => "pool", .unknown => "?", }; } /// The work in a few words: a Forgejo job by its name, when the forge gave /// one, else by its handle; a Radicle run by what it tests. pub fn describe(arena: Allocator, work: status.Work) Allocator.Error![]const u8 { return switch (work) { .forgejo => |f| if (f.name) |name| if (f.job_id) |id| fmt(arena, "{s} (job {d})", .{ name, id }) else fmt(arena, "{s}", .{name}) else fmt(arena, "job {s}", .{f.handle[0..@min(f.handle.len, 16)]}), .radicle => |r| if (r.commit.len == 0) fmt(arena, "run {d}", .{r.id}) else fmt(arena, "run {d}: {s} {s} at {s}", .{ r.id, r.event, r.ref, r.commit[0..@min(r.commit.len, 8)] }), .pool => "warm, waiting for work", .unknown => "work this ci-top does not know", }; } fn stateName(d: status.Droplet) []const u8 { if (d.state == .claimed and d.work_started_at != null) return "working"; return @tagName(d.state); } const Outcome = union(enum) { result: status.Result, exit: i64, /// Destroyed without saying how its work went: it never booted, went /// silent, or outlived its cap. unreported, fn text(o: Outcome, arena: Allocator) Allocator.Error![]const u8 { return switch (o) { .result => |r| @tagName(r), .exit => |code| if (code == 0) "success" else fmt(arena, "exit {d}", .{code}), .unreported => "no report", }; } fn tone(o: Outcome) Tone { return switch (o) { .result => |r| if (r == .success) .good else .bad, .exit => |code| if (code == 0) .good else .bad, .unreported => .bad, }; } }; fn dropletOutcome(d: status.Droplet) Outcome { // A Radicle run's own result says more than its droplet's exit status. switch (d.work) { .radicle => |r| if (r.result) |v| return .{ .result = v }, .forgejo, .pool, .unknown => {}, } if (d.exit_code) |code| return .{ .exit = code }; return .unreported; } /// When a droplet's work ended: when it said so, or when it was destroyed /// without saying. pub fn endedAt(d: status.Droplet) i64 { return d.done_at orelse d.destroyed_at orelse d.created_at; } /// A span of seconds as a person reads it: `45s`, `3m12s`, `1h04m`, `2d03h`. pub const Duration = struct { seconds: ?i64, pub fn format(d: Duration, w: *std.Io.Writer) std.Io.Writer.Error!void { // A clock that stepped backwards is not a negative span. const signed = d.seconds orelse return w.writeAll("-"); if (signed < 0) return w.writeAll("-"); // Unsigned, or a zero-padded field is printed with a `+`. const s: u64 = @intCast(signed); if (s < 60) return w.print("{d}s", .{s}); if (s < 3600) return w.print("{d}m{d:0>2}s", .{ @divFloor(s, 60), @mod(s, 60) }); if (s < 86400) return w.print("{d}h{d:0>2}m", .{ @divFloor(s, 3600), @divFloor(@mod(s, 3600), 60) }); return w.print("{d}d{d:0>2}h", .{ @divFloor(s, 86400), @divFloor(@mod(s, 86400), 3600) }); } }; pub fn duration(seconds: ?i64) Duration { return .{ .seconds = seconds }; } /// One step of a droplet's life, as the daemon's metrics divide it. pub const Phase = struct { name: []const u8, /// How long it took, or has taken so far; null if it has not begun. seconds: ?i64, /// Under way at `now`. open: bool, }; /// Every step of `d`'s life, as `Metrics.observeDroplet` measures them. A /// step that has begun and not ended runs to `now` -- until the droplet is /// gone, when there is nothing more to wait for. pub fn phases(d: status.Droplet, now: i64) [8]Phase { const spans = [8]struct { []const u8, ?i64, ?i64 }{ .{ "queue", d.queued_at, d.created_at }, .{ "active", d.created_at, d.active_at }, .{ "provision", d.created_at, d.booted_at }, .{ "boot", d.booted_at, d.agent_at }, .{ "claim", d.agent_at, d.claimed_at }, .{ "start", d.claimed_at, d.work_started_at }, .{ "work", d.work_started_at, d.done_at }, .{ "reap", d.done_at, d.destroyed_at }, }; var out: [8]Phase = undefined; for (&out, spans) |*o, span| { const from = span[1] orelse { o.* = .{ .name = span[0], .seconds = null, .open = false }; continue; }; if (span[2]) |to| { o.* = .{ .name = span[0], .seconds = to - from, .open = false }; } else if (d.state == .gone) { o.* = .{ .name = span[0], .seconds = null, .open = false }; } else { o.* = .{ .name = span[0], .seconds = now - from, .open = true }; } } return out; } /// The step a droplet is in now: the latest one under way. pub fn currentPhase(d: status.Droplet, now: i64) ?Phase { const all = phases(d, now); var i = all.len; while (i > 0) { i -= 1; // `active` runs beside `provision`, and says less. if (all[i].open and !std.mem.eql(u8, all[i].name, "active")) return all[i]; } return null; } /// A bar `width` cells wide, `used` of `max` filled. pub fn usageBar(buf: []u8, used: u32, max: u32, width: usize) []const u8 { const full = "█"; const empty = "░"; const n = if (max == 0) width else @min(width, (@as(usize, used) * width + max - 1) / max); var len: usize = 0; for (0..width) |i| { const glyph = if (i < n) full else empty; if (len + glyph.len > buf.len) break; @memcpy(buf[len..][0..glyph.len], glyph); len += glyph.len; } return buf[0..len]; } /// A time as UTC, `2026-09-28 14:03:07`. pub const Utc = struct { seconds: ?i64, pub fn format(u: Utc, w: *std.Io.Writer) std.Io.Writer.Error!void { const s = u.seconds orelse return w.writeAll("-"); if (s < 0) return w.writeAll("-"); const epoch: std.time.epoch.EpochSeconds = .{ .secs = @intCast(s) }; const day = epoch.getEpochDay().calculateYearDay(); const month = day.calculateMonthDay(); const time = epoch.getDaySeconds(); try w.print("{d}-{d:0>2}-{d:0>2} {d:0>2}:{d:0>2}:{d:0>2}", .{ day.year, month.month.numeric(), month.day_index + 1, time.getHoursIntoDay(), time.getMinutesIntoHour(), time.getSecondsIntoMinute(), }); } }; pub fn utc(seconds: ?i64) Utc { return .{ .seconds = seconds }; } /// A labelled line of a row's details. An empty label continues the line /// above. pub const Line = struct { label: []const u8, value: []const u8 }; /// Everything worth saying about `item`. `forges` gives the forge's address /// for a Forgejo job. Everything returned lives in `arena`. pub fn details(arena: Allocator, item: Item, forges: []const status.Forge, now: i64) Allocator.Error![]const Line { var out: std.ArrayList(Line) = .empty; const add = struct { fn f(a: Allocator, list: *std.ArrayList(Line), label: []const u8, comptime format: []const u8, args: anytype) Allocator.Error!void { try list.append(a, .{ .label = label, .value = try std.fmt.allocPrint(a, format, args) }); } }.f; switch (item) { .pending => |p| { try workLines(arena, &out, p.work, forges); try add(arena, &out, "Tier", "{s}", .{p.tier}); try add(arena, &out, "Waiting", "{f}, since {f} UTC", .{ duration(now - p.first_seen), utc(p.first_seen) }); if (p.backoff) |b| { try add(arena, &out, "Backoff", "creating its droplet has failed {d} time(s) in a row", .{b.failures}); try add(arena, &out, "", "next try {f} UTC ({f})", .{ utc(b.until), duration(b.until - now) }); } }, .droplet => |d| { try add(arena, &out, "Droplet", "{s} (row {d})", .{ d.name, d.id }); if (d.do_id) |id| try add(arena, &out, "DigitalOcean", "{d}", .{id}); try add(arena, &out, "Tier", "{s}, {s}", .{ d.tier, d.size orelse "size not yet known" }); try add(arena, &out, "State", "{s}", .{stateName(d)}); if (d.exit_code) |code| try add(arena, &out, "Exit status", "{d}", .{code}); try workLines(arena, &out, d.work, forges); try add(arena, &out, "Created", "{f} UTC, {f} ago", .{ utc(d.created_at), duration(now - d.created_at) }); if (d.heard_at) |t| try add(arena, &out, "Last heard", "{f} ago", .{duration(now - t)}); if (d.destroyed_at) |t| try add(arena, &out, "Destroyed", "{f} UTC", .{utc(t)}); try out.append(arena, .{ .label = "Phases", .value = "" }); for (phases(d, now)) |ph| { if (ph.seconds == null) continue; try add(arena, &out, "", " {s: <10} {f}{s}", .{ ph.name, duration(ph.seconds), if (ph.open) " so far" else "" }); } }, .run => |r| try workLines(arena, &out, .{ .radicle = r }, forges), } return out.items; } fn workLines(arena: Allocator, out: *std.ArrayList(Line), work: status.Work, forges: []const status.Forge) Allocator.Error!void { const add = struct { fn f(a: Allocator, list: *std.ArrayList(Line), label: []const u8, comptime format: []const u8, args: anytype) Allocator.Error!void { try list.append(a, .{ .label = label, .value = try std.fmt.allocPrint(a, format, args) }); } }.f; switch (work) { .pool => try add(arena, out, "Work", "none yet: warm, waiting to be given some", .{}), .unknown => try add(arena, out, "Work", "a kind this ci-top does not know; the daemon is newer", .{}), .forgejo => |f| { const url = for (forges) |forge| { if (std.mem.eql(u8, forge.name, f.forge)) break forge.url; } else null; if (url) |u| try add(arena, out, "Forge", "{s} ({s})", .{ f.forge, u }) else try add(arena, out, "Forge", "{s}", .{f.forge}); if (f.name) |name| try add(arena, out, "Job", "{s}", .{name}); if (f.job_id) |id| try add(arena, out, "Job id", "{d}", .{id}); try add(arena, out, "Handle", "{s}", .{f.handle}); if (f.status) |s| try add(arena, out, "Forge says", "{s}", .{s}); }, .radicle => |r| { try add(arena, out, "Run", "{d}, {s}", .{ r.id, @tagName(r.state) }); if (r.rid.len > 0) { try add(arena, out, "Repository", "{s}", .{r.rid}); try add(arena, out, if (std.mem.eql(u8, r.event, "patch")) "Patch" else "Branch", "{s}", .{r.ref}); try add(arena, out, "Commit", "{s}", .{r.commit}); } if (r.result) |v| try add(arena, out, "Result", "{s}", .{@tagName(v)}); if (r.reason) |why| try add(arena, out, "Why", "{s}", .{why}); try add(arena, out, "Page", "{s}", .{r.url}); }, } } /// Which row of a list is selected, and which is at the top of its window. /// The selection follows its row's key across refreshes, so that a list /// reordering under it does not move it to something else. pub const Selection = struct { index: usize = 0, top: usize = 0, key_buf: [96]u8 = undefined, key_len: usize = 0, pub fn key(s: *const Selection) []const u8 { return s.key_buf[0..s.key_len]; } fn remember(s: *Selection, list: []const Row) void { if (s.index >= list.len) { s.key_len = 0; return; } const k = list[s.index].key; s.key_len = @min(k.len, s.key_buf.len); @memcpy(s.key_buf[0..s.key_len], k[0..s.key_len]); } /// After a refresh: back onto the row it was on, if that is still there, /// else the same place, as near as the list now allows. pub fn follow(s: *Selection, list: []const Row) void { if (s.key_len > 0) for (list, 0..) |row, i| { if (std.mem.eql(u8, row.key, s.key())) { s.index = i; return; } }; s.index = if (list.len == 0) 0 else @min(s.index, list.len - 1); s.remember(list); } pub fn move(s: *Selection, list: []const Row, delta: isize) void { if (list.len == 0) return; const end: isize = @intCast(list.len - 1); s.index = @intCast(std.math.clamp(@as(isize, @intCast(s.index)) + delta, 0, end)); s.remember(list); } pub fn first(s: *Selection, list: []const Row) void { s.index = 0; s.remember(list); } pub fn last(s: *Selection, list: []const Row) void { s.index = list.len -| 1; s.remember(list); } /// Scrolls so that the selected row is among the `visible` shown. pub fn scroll(s: *Selection, visible: usize) void { if (visible == 0) return; if (s.index < s.top) s.top = s.index; if (s.index >= s.top + visible) s.top = s.index + 1 - visible; } }; const testing = std.testing; test "durations read as a person would say them" { const cases = [_]struct { ?i64, []const u8 }{ .{ null, "-" }, .{ -5, "-" }, .{ 0, "0s" }, .{ 45, "45s" }, .{ 60, "1m00s" }, .{ 192, "3m12s" }, .{ 3599, "59m59s" }, .{ 3600, "1h00m" }, .{ 3840, "1h04m" }, .{ 86399, "23h59m" }, .{ 86400 * 2 + 3 * 3600 + 59, "2d03h" }, }; for (cases) |c| { var buf: [16]u8 = undefined; try testing.expectEqualStrings(c[1], try std.fmt.bufPrint(&buf, "{f}", .{duration(c[0])})); } } test "times are UTC" { var buf: [32]u8 = undefined; try testing.expectEqualStrings("2026-09-28 14:03:07", try std.fmt.bufPrint(&buf, "{f}", .{utc(1790604187)})); try testing.expectEqualStrings("-", try std.fmt.bufPrint(&buf, "{f}", .{utc(null)})); } test "a droplet's phases, with the one under way running to now" { var d = status.example.running[0]; d.queued_at = 100; d.created_at = 110; d.active_at = 150; d.booted_at = 140; d.agent_at = 170; d.claimed_at = 171; d.work_started_at = null; const p = phases(d, 200); try testing.expectEqual(@as(?i64, 10), p[0].seconds); try testing.expectEqual(@as(?i64, 30), p[3].seconds); try testing.expect(p[5].open); try testing.expectEqual(@as(?i64, 29), p[5].seconds); try testing.expectEqual(null, p[6].seconds); try testing.expectEqualStrings("start", currentPhase(d, 200).?.name); // Before DigitalOcean calls it active, the droplet is provisioning, not // "active". d.active_at = null; d.booted_at = null; d.agent_at = null; d.claimed_at = null; try testing.expectEqualStrings("provision", currentPhase(d, 200).?.name); // Gone, nothing is under way. d.state = .gone; try testing.expectEqual(null, currentPhase(d, 200)); } test "rows, and a finished Radicle run with no droplet among them" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); var s = status.example; s.finished_runs = &.{.{ .id = 9, .rid = "rad:z3QNJRPpssgFMdfjV8Pgsopix3qE4", .commit = "abcdef0123456789", .event = "patch", .ref = "p1", .tier = "s", .url = "https://ci.example.org/runs/9", .state = .finished, .result = .@"error", .reason = "tier: no such tier", .created_at = 950, .finished_at = 950, }}; const pending = try rows(a, s, .pending, 1000); try testing.expectEqual(@as(usize, 1), pending.len); try testing.expectEqualStrings("p:ocjtech/h2", pending[0].key); try testing.expectEqualStrings("1m40s", pending[0].cells[0]); try testing.expectEqualStrings("test (job 12)", pending[0].cells[3]); try testing.expectEqualStrings("failed 2x, retry in 1m00s", pending[0].cells[4]); try testing.expectEqual(Tone.warn, pending[0].tone); const running = try rows(a, s, .running, 1000); try testing.expectEqualStrings("ci-droplet-7", running[0].cells[0]); try testing.expectEqualStrings("start 2m20s", running[0].cells[4]); try testing.expectEqualStrings("run 3: push main at 0d2b0335", running[0].cells[6]); const finished = try rows(a, s, .finished, 1000); try testing.expectEqual(@as(usize, 2), finished.len); try testing.expectEqualStrings("exit 1", finished[0].cells[2]); try testing.expectEqualStrings("5m00s ago", finished[0].cells[3]); try testing.expectEqual(Tone.bad, finished[0].tone); try testing.expectEqualStrings("r:9", finished[1].key); try testing.expectEqualStrings("error", finished[1].cells[2]); // A cell for every header, in every list. for (std.enums.values(Section)) |section| for (try rows(a, s, section, 1000)) |row| { try testing.expectEqual(section.headers().len, row.cells.len); }; const lines = try details(a, finished[1].item, s.forges, 1000); var saw_reason = false; for (lines) |l| saw_reason = saw_reason or std.mem.eql(u8, l.value, "tier: no such tier"); try testing.expect(saw_reason); const drop = try details(a, running[0].item, s.forges, 1000); try testing.expectEqualStrings("ci-droplet-7 (row 7)", drop[0].value); } test "the selection stays on its row across a refresh" { const item: Item = .{ .run = status.example.running[0].work.radicle }; const before = [_]Row{ .{ .key = "d:1", .cells = &.{}, .item = item }, .{ .key = "d:2", .cells = &.{}, .item = item }, .{ .key = "d:3", .cells = &.{}, .item = item }, }; var sel: Selection = .{}; sel.follow(&before); sel.move(&before, 1); try testing.expectEqualStrings("d:2", sel.key()); // A new row above it: the selection moves down with its row. const after = [_]Row{ .{ .key = "d:4", .cells = &.{}, .item = item }, .{ .key = "d:1", .cells = &.{}, .item = item }, .{ .key = "d:2", .cells = &.{}, .item = item }, }; sel.follow(&after); try testing.expectEqual(@as(usize, 2), sel.index); // Its row gone: the same place, as near as the list allows. const shorter = [_]Row{.{ .key = "d:4", .cells = &.{}, .item = item }}; sel.follow(&shorter); try testing.expectEqual(@as(usize, 0), sel.index); try testing.expectEqualStrings("d:4", sel.key()); sel.follow(&.{}); try testing.expectEqual(@as(usize, 0), sel.index); // Moving never leaves the list, and the window follows. sel.follow(&before); sel.move(&before, 10); try testing.expectEqual(@as(usize, 2), sel.index); sel.scroll(2); try testing.expectEqual(@as(usize, 1), sel.top); sel.move(&before, -10); sel.scroll(2); try testing.expectEqual(@as(usize, 0), sel.top); } test "usage bars" { var buf: [64]u8 = undefined; try testing.expectEqualStrings("██░░░", usageBar(&buf, 2, 5, 5)); try testing.expectEqualStrings("░░░░", usageBar(&buf, 0, 3, 4)); // Rounded up, so one droplet is never an empty bar. try testing.expectEqualStrings("█░░░░░░░░░", usageBar(&buf, 1, 20, 10)); try testing.expectEqualStrings("████", usageBar(&buf, 9, 3, 4)); } test { std.testing.refAllDecls(@This()); }