Something went wrong. Try again.
Ephemeral DigitalOcean droplets for Forgejo Actions and Radicle CI, from one daemon
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! What the scheduler knows that the database does not, kept where `GET//! /status` can read it: the jobs each forge listed at its last poll, how//! each poll went, which work is backing off, and what the last pass counted.//!//! The scheduler publishes a fresh copy after every pass and the handlers//! read a copy of their own, so neither ever holds the lock for longer than a//! swap or a copy, and neither sees the other's memory.//!//! `report` is the other half: it puts that together with the database's//! rows into the document `api.status` describes. It does no I/O, so what a//! status says for a given state can be tested without a daemon.
const std = @import("std");const Io = std.Io;const Allocator = std.mem.Allocator;
const api = @import("api");const status = api.status;const Config = @import("Config.zig");const RunStore = @import("RunStore.zig");const tags = @import("tags.zig");
const StatusBoard = @This();
mutex: Io.Mutex = .init,/// Owns `current`.arena: ?std.heap.ArenaAllocator = null,current: ?Published = null,
pub const Published = struct { /// When the pass that published it finished. at: i64, forges: []const status.Forge, /// Every job each forge listed at its last good poll, waiting or running. jobs: []const ListedJob, backoff: []const status.Backoff, /// What the last pass that got as far as planning counted, by tier in /// the configuration's order. standing: ?[]const u32 = null, deferred: ?u32 = null, refused: ?u32 = null,};
pub const ListedJob = struct { forge: []const u8, handle: []const u8, id: u64, name: ?[]const u8 = null, /// `waiting` or `running`. status: []const u8, tier: []const u8, /// When the daemon first saw it waiting; for a running job, when it was /// listed. first_seen: i64,};
pub fn deinit(b: *StatusBoard) void { if (b.arena) |*a| a.deinit(); b.* = undefined;}
/// Replaces what is published with a copy of `p`. The copy is made before/// the lock is taken and the old one freed after it is let go.pub fn publish(b: *StatusBoard, io: Io, gpa: Allocator, p: Published) Allocator.Error!void { var fresh: std.heap.ArenaAllocator = .init(gpa); errdefer fresh.deinit(); const copy = try status.clone(Published, fresh.allocator(), p);
b.mutex.lockUncancelable(io); const old = b.arena; b.arena = fresh; b.current = copy; b.mutex.unlock(io);
if (old) |o| { var a = o; a.deinit(); }}
/// A copy of what is published, in `arena`, or null before the first pass.pub fn read(b: *StatusBoard, io: Io, arena: Allocator) (Allocator.Error || Io.Cancelable)!?Published { try b.mutex.lock(io); defer b.mutex.unlock(io); const p = b.current orelse return null; return try status.clone(Published, arena, p);}
/// Everything `report` puts together.pub const Input = struct { now: i64, config: Config, published: ?Published, /// Every droplet not yet gone. live: []const RunStore.Droplet, /// Droplets done or gone lately, as `RunStore.recentDroplets` lists them. recent: []const RunStore.Droplet, /// Radicle runs waiting for a droplet. queued: []const RunStore.Run, /// Radicle runs finished lately. recent_runs: []const RunStore.Run, /// Every other run a droplet above is bound to, so that a droplet can be /// shown with its run's commit and ref. A run missing here has been /// pruned, and is shown by its id alone. runs: []const RunStore.Run,};
/// The status document for `in`. Everything returned lives in `arena`, and/// may point into `in`.pub fn report(arena: Allocator, in: Input) Allocator.Error!status.Status { const published = in.published; const jobs: []const ListedJob = if (published) |p| p.jobs else &.{}; const backoff: []const status.Backoff = if (published) |p| p.backoff else &.{};
const lookup: Lookup = .{ .arena = arena, .public_url = in.config.public_url, .jobs = jobs, .run_lists = &.{ in.queued, in.recent_runs, in.runs }, };
// -- droplets -- var running: std.ArrayList(status.Droplet) = .empty; var finished: std.ArrayList(status.Droplet) = .empty; for (in.live) |row| switch (row.state) { .creating, .booting, .claimed => try running.append(arena, try lookup.droplet(row)), // Shown with the recent ones, which include it. .done, .gone => {}, }; for (in.recent) |row| try finished.append(arena, try lookup.droplet(row)); std.sort.pdq(status.Droplet, finished.items, {}, endedLater);
// -- what waits -- var pending: std.ArrayList(status.Pending) = .empty; for (jobs) |job| { if (!std.mem.eql(u8, job.status, "waiting")) continue; // A job stays waiting until its droplet's runner takes it, and by // then it is that droplet's: shown there, not here. if (bound(in.live, job.forge, job.handle)) continue; const key = try std.mem.concat(arena, u8, &.{ job.forge, "/", job.handle }); try pending.append(arena, .{ .source = job.forge, .tier = job.tier, .first_seen = job.first_seen, .work = .{ .forgejo = lookup.forgejoJob(job.forge, job.handle) }, .backoff = findBackoff(backoff, key), }); } for (in.queued) |run| { const key = try std.fmt.allocPrint(arena, "radicle/{d}", .{run.id}); try pending.append(arena, .{ .source = "radicle", .tier = run.tier, .first_seen = run.created_at, .work = .{ .radicle = try lookup.toRun(run) }, .backoff = findBackoff(backoff, key), }); } std.sort.pdq(status.Pending, pending.items, {}, waitedLonger);
// -- runs with no droplet to show them by -- var finished_runs: std.ArrayList(status.Run) = .empty; for (in.recent_runs) |run| { if (shown(finished.items, run.id) or shown(running.items, run.id)) continue; try finished_runs.append(arena, try lookup.toRun(run)); }
// -- tiers and forges -- const tiers = try arena.alloc(status.Tier, in.config.tiers.len); for (tiers, in.config.tiers, 0..) |*t, tier, i| { var live: u32 = 0; for (in.live) |row| { if (std.mem.eql(u8, row.tier, tier.name)) live += 1; } const counted: []const u32 = if (published) |p| p.standing orelse &.{} else &.{}; t.* = .{ .name = tier.name, .size = tier.size, .max = tier.max, .live = live, .standing = if (i < counted.len) counted[i] else null, }; } const forges: []const status.Forge = if (published) |p| p.forges else blk: { const out = try arena.alloc(status.Forge, in.config.forges.len); for (out, in.config.forges) |*o, f| o.* = .{ .name = f.name, .url = f.url }; break :blk out; };
return .{ .generated_at = in.now, .snapshot_at = if (published) |p| p.at else null, .public_url = in.config.public_url, .dry_run = in.config.dry_run, .tiers = tiers, .forges = forges, .pending = pending.items, .running = running.items, .finished = finished.items, .finished_runs = finished_runs.items, .deferred = if (published) |p| p.deferred else null, .refused = if (published) |p| p.refused else null, };}
const Lookup = struct { arena: Allocator, public_url: []const u8, jobs: []const ListedJob, run_lists: []const []const RunStore.Run,
fn droplet(l: Lookup, row: RunStore.Droplet) Allocator.Error!status.Droplet { var name_buf: [32]u8 = undefined; const name = tags.dropletName(&name_buf, row.id) catch unreachable; return .{ .id = row.id, .name = try l.arena.dupe(u8, name), .do_id = row.do_id, .tier = row.tier, .size = row.size, .state = mapEnum(status.DropletState, row.state), .work = if (row.binding) |b| switch (b) { .forgejo => |f| .{ .forgejo = l.forgejoJob(f.forge, f.handle) }, .radicle => |id| .{ .radicle = try l.run(id) }, } else .pool, .exit_code = row.exit_code, .queued_at = row.queued_at, .created_at = row.created_at, .active_at = row.active_at, .booted_at = row.booted_at, .agent_at = row.agent_at, .claimed_at = row.claimed_at, .work_started_at = row.work_started_at, .done_at = row.done_at, .destroyed_at = row.destroyed_at, .heard_at = row.heard_at, }; }
/// The job as the forge last listed it, or its handle alone once the /// forge has stopped listing it. fn forgejoJob(l: Lookup, forge: []const u8, handle: []const u8) status.ForgejoJob { for (l.jobs) |job| { if (std.mem.eql(u8, job.forge, forge) and std.mem.eql(u8, job.handle, handle)) return .{ .forge = forge, .handle = handle, .job_id = job.id, .name = job.name, .status = job.status, }; } return .{ .forge = forge, .handle = handle }; }
fn run(l: Lookup, id: u64) Allocator.Error!status.Run { for (l.run_lists) |list| for (list) |r| { if (r.id == id) return l.toRun(r); }; return .{ .id = id, .rid = "", .commit = "", .event = "", .ref = "", .tier = "", .url = try l.url(id), .state = .finished, .created_at = 0, }; }
fn toRun(l: Lookup, r: RunStore.Run) Allocator.Error!status.Run { return .{ .id = r.id, .rid = r.rid, .commit = r.commit, .event = r.event, .ref = r.ref, .tier = r.tier, .url = try l.url(r.id), .state = mapEnum(status.RunState, r.state), .result = if (r.result) |v| mapEnum(status.Result, v) else null, .reason = r.reason, .created_at = r.created_at, .started_at = r.started_at, .finished_at = r.finished_at, }; }
fn url(l: Lookup, id: u64) Allocator.Error![]const u8 { return std.fmt.allocPrint(l.arena, "{s}/runs/{d}", .{ l.public_url, id }); }};
/// The same enum on the wire: the names are checked to match below.fn mapEnum(comptime To: type, from: anytype) To { return switch (from) { inline else => |tag| @field(To, @tagName(tag)), };}
fn bound(live: []const RunStore.Droplet, forge: []const u8, handle: []const u8) bool { for (live) |row| if (row.binding) |b| switch (b) { .forgejo => |f| if (std.mem.eql(u8, f.forge, forge) and std.mem.eql(u8, f.handle, handle)) return true, .radicle => {}, }; return false;}
fn shown(droplets: []const status.Droplet, run: u64) bool { for (droplets) |d| switch (d.work) { .radicle => |r| if (r.id == run) return true, .forgejo, .pool, .unknown => {}, }; return false;}
fn findBackoff(backoff: []const status.Backoff, key: []const u8) ?status.Backoff { for (backoff) |b| if (std.mem.eql(u8, b.key, key)) return b; return null;}
/// When a droplet's work ended: when it said so, or when it was destroyed/// without saying.fn endedAt(d: status.Droplet) i64 { return d.done_at orelse d.destroyed_at orelse d.created_at;}
fn endedLater(_: void, a: status.Droplet, b: status.Droplet) bool { const ea = endedAt(a); const eb = endedAt(b); return if (ea != eb) ea > eb else a.id > b.id;}
fn waitedLonger(_: void, a: status.Pending, b: status.Pending) bool { return a.first_seen < b.first_seen;}
comptime { // What the wire says must be what the database means, plus the `unknown` // a reader falls back to for a value newer than it. for (.{ .{ RunStore.DropletState, status.DropletState }, .{ RunStore.State, status.RunState }, .{ RunStore.Result, status.Result }, }) |pair| { const a = @typeInfo(pair[0]).@"enum".fields; const b = @typeInfo(pair[1]).@"enum".fields; if (a.len + 1 != b.len or !std.mem.eql(u8, b[a.len].name, "unknown")) @compileError("enum mismatch: " ++ @typeName(pair[0])); for (a, b[0..a.len]) |x, y| if (!std.mem.eql(u8, x.name, y.name)) @compileError("enum mismatch: " ++ @typeName(pair[0])); }}
const testing = std.testing;
test "publishing replaces what a reader sees, and not what it already has" { var board: StatusBoard = .{}; defer board.deinit(); const io = testing.io; var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const a = arena.allocator();
try testing.expectEqual(null, try board.read(io, a));
var name = "ocjtech".*; try board.publish(io, testing.allocator, .{ .at = 10, .forges = &.{.{ .name = &name, .url = "https://git.jcollie.dev", .last_error = "Timeout" }}, .jobs = &.{}, .backoff = &.{.{ .key = "ocjtech/h", .failures = 1, .until = 70 }}, .standing = &.{ 1, 2 }, }); // The board has its own copy. name[0] = 'X'; const first = (try board.read(io, a)).?; try testing.expectEqualStrings("ocjtech", first.forges[0].name); try testing.expectEqual(@as(u32, 2), first.standing.?[1]);
try board.publish(io, testing.allocator, .{ .at = 20, .forges = &.{}, .jobs = &.{}, .backoff = &.{} }); // What was read before is the reader's, and outlives the old copy. try testing.expectEqualStrings("Timeout", first.forges[0].last_error.?); const second = (try board.read(io, a)).?; try testing.expectEqual(@as(i64, 20), second.at); try testing.expectEqual(null, second.standing);}
const test_config: Config = .{ .region = "nyc3", .base_image = "ubuntu-26-04-x64", .snapshot_prefix = "forgejo-runner", .runner_image = "runner-image", .runner_binary_url = "https://example.com/runner", .runner_binary_sha256 = "0" ** 64, .public_url = "https://ci.example.org", .agent = "/nonexistent", .tiers = &.{ .{ .name = "s", .size = "s-2vcpu-4gb", .max = 2 }, .{ .name = "l", .size = "s-4vcpu-8gb", .max = 1 } }, .forges = &.{.{ .name = "ocjtech", .url = "https://git.jcollie.dev", .credential = "a" }},};
fn testDroplet(id: u64, state: RunStore.DropletState, binding: RunStore.Binding) RunStore.Droplet { return .{ .id = id, .do_id = 500 + id, .tier = "s", .size = "s-2vcpu-4gb", .image = null, .state = state, .binding = binding, .exit_code = null, .queued_at = 10, .created_at = 20, .active_at = null, .booted_at = null, .agent_at = null, .claimed_at = null, .work_started_at = null, .done_at = null, .destroyed_at = null, .heard_at = null, };}
fn testRun(id: u64, state: RunStore.State, created_at: i64) RunStore.Run { return .{ .id = id, .rid = "rad:z3QNJRPpssgFMdfjV8Pgsopix3qE4", .commit = "0d2b0335d245f58375385a9ebb076a72d9398a48", .event = "push", .ref = "main", .tier = "l", .image = null, .shell = "", .state = state, .result = if (state == .finished) .success else null, .reason = null, .created_at = created_at, .started_at = null, .heartbeat_at = null, .finished_at = if (state == .finished) created_at + 5 else null, .droplet_id = null, };}
test "a report sorts work into waiting, at work, and over" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const a = arena.allocator();
const fj = RunStore.Binding{ .forgejo = .{ .forge = "ocjtech", .handle = "booting", .runner_id = 7 } }; var done = testDroplet(3, .done, .{ .forgejo = .{ .forge = "ocjtech", .handle = "over", .runner_id = 8 } }); done.done_at = 90; done.exit_code = 2; var gone = testDroplet(2, .gone, .{ .radicle = 40 }); gone.destroyed_at = 95; const live = [_]RunStore.Droplet{ testDroplet(4, .booting, fj), done };
const s = try report(a, .{ .now = 100, .config = test_config, .published = .{ .at = 99, .forges = &.{.{ .name = "ocjtech", .url = "https://git.jcollie.dev", .last_poll = 98 }}, .jobs = &.{ .{ .forge = "ocjtech", .handle = "waits", .id = 11, .name = "build", .status = "waiting", .tier = "s", .first_seen = 50 }, // Waiting, but its droplet is booting: that droplet's. .{ .forge = "ocjtech", .handle = "booting", .id = 12, .name = "test", .status = "waiting", .tier = "s", .first_seen = 5 }, }, .backoff = &.{.{ .key = "radicle/41", .failures = 3, .until = 400 }}, .standing = &.{ 2, 0 }, .deferred = 1, }, .live = &live, .recent = &.{ gone, done }, .queued = &.{testRun(41, .queued, 30)}, .recent_runs = &.{ testRun(40, .finished, 1), testRun(39, .finished, 2) }, .runs = &.{}, });
// Oldest first, whatever the source. try testing.expectEqual(@as(usize, 2), s.pending.len); try testing.expectEqual(@as(u64, 41), s.pending[0].work.radicle.id); try testing.expectEqual(@as(u32, 3), s.pending[0].backoff.?.failures); try testing.expectEqualStrings("https://ci.example.org/runs/41", s.pending[0].work.radicle.url); try testing.expectEqualStrings("waits", s.pending[1].work.forgejo.handle); try testing.expectEqualStrings("build", s.pending[1].work.forgejo.name.?); try testing.expectEqual(null, s.pending[1].backoff);
try testing.expectEqual(@as(usize, 1), s.running.len); try testing.expectEqualStrings("ci-droplet-4", s.running[0].name); try testing.expectEqualStrings("test", s.running[0].work.forgejo.name.?); try testing.expectEqualStrings("waiting", s.running[0].work.forgejo.status.?);
// Most recently ended first; the forge no longer lists the done one's job. try testing.expectEqual(@as(usize, 2), s.finished.len); try testing.expectEqual(@as(u64, 2), s.finished[0].id); try testing.expectEqualStrings("main", s.finished[0].work.radicle.ref); try testing.expectEqual(status.DropletState.gone, s.finished[0].state); try testing.expectEqual(@as(?i64, 2), s.finished[1].exit_code); try testing.expectEqual(null, s.finished[1].work.forgejo.job_id);
// Run 40 is shown by its droplet; 39 has none. try testing.expectEqual(@as(usize, 1), s.finished_runs.len); try testing.expectEqual(@as(u64, 39), s.finished_runs[0].id);
try testing.expectEqual(@as(u32, 2), s.tiers[0].live); try testing.expectEqual(@as(?u32, 2), s.tiers[0].standing); try testing.expectEqual(@as(u32, 0), s.tiers[1].live); try testing.expectEqual(@as(?i64, 99), s.snapshot_at); try testing.expectEqual(@as(?u32, 1), s.deferred);}
test "a report before the first pass has the database's view alone" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const s = try report(arena.allocator(), .{ .now = 100, .config = test_config, .published = null, .live = &.{}, .recent = &.{}, .queued = &.{}, .recent_runs = &.{}, .runs = &.{}, }); try testing.expectEqual(null, s.snapshot_at); try testing.expectEqual(@as(usize, 1), s.forges.len); try testing.expectEqual(null, s.forges[0].last_poll); try testing.expectEqual(null, s.tiers[0].standing);}
test { std.testing.refAllDecls(@This());}