// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! What `GET /status` answers with: every piece of work the daemon knows of, //! and the droplet each one has, in one document. //! //! The daemon writes it and `ci-top` reads it, and both take it from here, in //! the module neither needs SQLite for, so that the two cannot drift apart. //! Every time is seconds since the epoch. const std = @import("std"); const Allocator = std.mem.Allocator; /// Bumped when a field changes meaning or goes away. A reader seeing a /// version it does not know says so rather than showing what it misreads. /// Bumped when the document gains something a reader would want to know /// about: 2 added warm droplets, as `pool` work. A reader older than the /// daemon still reads the document, and shows what it does not know as /// unknown rather than refusing all of it; see `unknown` below. pub const version = 2; pub const Status = struct { version: u32 = version, /// When the daemon answered. generated_at: i64, /// When the scheduler last finished a pass: how fresh `pending`, the /// forges' polls and the backoffs are. Null before the first. snapshot_at: ?i64 = null, public_url: []const u8, dry_run: bool = false, tiers: []const Tier = &.{}, forges: []const Forge = &.{}, /// Work waiting for a droplet, oldest first. pending: []const Pending = &.{}, /// Droplets being created, booting, or at work. running: []const Droplet = &.{}, /// Droplets that are done or gone, most recently ended first. finished: []const Droplet = &.{}, /// Radicle runs that ended without a droplet in `finished`: refused for /// a `droplet.yaml` that could not run, or whose droplet has been pruned. finished_runs: []const Run = &.{}, /// Waiting work the last pass had no room for in its tier. deferred: ?u32 = null, /// Droplets the last pass would not touch, because they are not ours. refused: ?u32 = null, }; pub const Tier = struct { name: []const u8, size: []const u8, max: u32, /// Droplets of this tier the database has not seen go. live: u32 = 0, /// What the last pass counted standing, before provisioning: DigitalOcean's /// view, where `live` is the database's. standing: ?u32 = null, }; pub const Forge = struct { name: []const u8, url: []const u8, last_poll: ?i64 = null, last_ok: ?i64 = null, /// Why the last poll failed, if it did. last_error: ?[]const u8 = null, next_poll: ?i64 = null, }; /// What a droplet is for. pub const Work = union(enum) { forgejo: ForgejoJob, radicle: Run, /// A warm droplet, booted and waiting to be given work. pool, /// A kind of work a newer daemon has that this build does not. Never /// written; only read. unknown, /// One key, naming the kind of work, whose value is the work. A kind /// this build does not know is `unknown` rather than an error, so that /// a reader older than the daemon still reads the rest. pub fn jsonParse(allocator: Allocator, source: anytype, options: std.json.ParseOptions) !Work { const value = try std.json.innerParse(std.json.Value, allocator, source, options); return jsonParseFromValue(allocator, value, options); } pub fn jsonParseFromValue(allocator: Allocator, value: std.json.Value, options: std.json.ParseOptions) !Work { const object = switch (value) { .object => |o| o, else => return error.UnexpectedToken, }; if (object.count() != 1) return error.UnexpectedToken; var it = object.iterator(); const entry = it.next().?; inline for (std.meta.fields(Work)) |field| { if (comptime std.mem.eql(u8, field.name, "unknown")) continue; if (std.mem.eql(u8, entry.key_ptr.*, field.name)) { if (field.type == void) return @unionInit(Work, field.name, {}); return @unionInit(Work, field.name, try std.json.innerParseFromValue(field.type, allocator, entry.value_ptr.*, options)); } } return .unknown; } }; pub const ForgejoJob = struct { /// The forge's configured name. forge: []const u8, /// Opaque, and unique to one attempt of one job. handle: []const u8, /// Forgejo's id for the job, while it is in the forge's listing. job_id: ?u64 = null, /// The job's name in its workflow, when the forge says. name: ?[]const u8 = null, /// `waiting` or `running`, while the forge lists it. status: ?[]const u8 = null, }; pub const Run = struct { id: u64, rid: []const u8, commit: []const u8, /// `push` or `patch`. event: []const u8, ref: []const u8, tier: []const u8, /// The run's page. url: []const u8, state: RunState, result: ?Result = null, reason: ?[]const u8 = null, created_at: i64, started_at: ?i64 = null, finished_at: ?i64 = null, }; pub const Pending = struct { /// A forge's name, or `radicle`. source: []const u8, tier: []const u8, /// When the daemon first saw it waiting. first_seen: i64, work: Work, /// Set when creating its droplet has failed, and it waits before the /// next try. backoff: ?Backoff = null, }; pub const Backoff = struct { /// `/` or `radicle/`. key: []const u8, /// How many tries in a row have failed. failures: u32, /// Not tried again before this. until: i64, }; pub const Droplet = struct { /// The daemon's row id, which is in the droplet's name. id: u64, /// `ci-droplet-`, as DigitalOcean lists it. name: []const u8, /// DigitalOcean's id, once it exists. do_id: ?u64 = null, tier: []const u8, size: ?[]const u8 = null, state: DropletState, work: Work, /// What the agent reported when the work ended. exit_code: ?i64 = null, queued_at: ?i64 = null, created_at: i64, active_at: ?i64 = null, booted_at: ?i64 = null, agent_at: ?i64 = null, claimed_at: ?i64 = null, work_started_at: ?i64 = null, done_at: ?i64 = null, destroyed_at: ?i64 = null, heard_at: ?i64 = null, }; // Each has an `unknown`, which a value this build does not know is read as: // see `Lenient`. Never written; only read. pub const DropletState = enum { creating, booting, claimed, done, gone, unknown, pub const jsonParse = Lenient(@This()).jsonParse; pub const jsonParseFromValue = Lenient(@This()).jsonParseFromValue; }; pub const RunState = enum { queued, provisioning, running, finished, unknown, pub const jsonParse = Lenient(@This()).jsonParse; pub const jsonParseFromValue = Lenient(@This()).jsonParseFromValue; }; pub const Result = enum { success, failure, @"error", unknown, pub const jsonParse = Lenient(@This()).jsonParse; pub const jsonParseFromValue = Lenient(@This()).jsonParseFromValue; }; /// An enum read by name, with a name this build does not know read as /// `.unknown` rather than an error. fn Lenient(comptime E: type) type { return struct { pub fn jsonParse(allocator: Allocator, source: anytype, options: std.json.ParseOptions) !E { const name = try std.json.innerParse([]const u8, allocator, source, options); return std.meta.stringToEnum(E, name) orelse .unknown; } pub fn jsonParseFromValue(_: Allocator, value: std.json.Value, _: std.json.ParseOptions) !E { return switch (value) { .string => |name| std.meta.stringToEnum(E, name) orelse .unknown, else => error.UnexpectedToken, }; } }; } /// A deep copy of `value`, every slice and string in `arena`. pub fn clone(comptime T: type, arena: Allocator, value: T) Allocator.Error!T { switch (@typeInfo(T)) { .pointer => |p| { if (p.size != .slice) @compileError("clone: only slices are copied, not " ++ @typeName(T)); if (p.child == u8) return arena.dupe(u8, value); const out = try arena.alloc(p.child, value.len); for (out, value) |*o, v| o.* = try clone(p.child, arena, v); return out; }, .optional => |o| return if (value) |v| try clone(o.child, arena, v) else null, .@"struct" => |s| { var out: T = undefined; inline for (s.fields) |f| @field(out, f.name) = try clone(f.type, arena, @field(value, f.name)); return out; }, .@"union" => |u| { if (u.tag_type == null) @compileError("clone: untagged union " ++ @typeName(T)); switch (value) { inline else => |v, tag| return @unionInit(T, @tagName(tag), try clone(@TypeOf(v), arena, v)), } }, .array => |a| { var out: T = undefined; for (&out, value) |*o, v| o.* = try clone(a.child, arena, v); return out; }, else => return value, } } /// The document as JSON. pub fn write(status: Status, w: *std.Io.Writer) std.Io.Writer.Error!void { return std.json.Stringify.value(status, .{ .emit_null_optional_fields = false }, w); } /// Reads a document, ignoring fields this build does not know: a daemon /// newer than the reader may have added some. pub fn parse(arena: Allocator, text: []const u8) !Status { return std.json.parseFromSliceLeaky(Status, arena, text, .{ .ignore_unknown_fields = true, .allocate = .alloc_always, }); } const testing = std.testing; pub const example: Status = .{ .generated_at = 1000, .snapshot_at = 998, .public_url = "https://ci.example.org", .tiers = &.{.{ .name = "s", .size = "s-2vcpu-4gb", .max = 2, .live = 1, .standing = 1 }}, .forges = &.{.{ .name = "ocjtech", .url = "https://git.jcollie.dev", .last_poll = 990, .last_ok = 990, .next_poll = 1005 }}, .pending = &.{.{ .source = "ocjtech", .tier = "s", .first_seen = 900, .work = .{ .forgejo = .{ .forge = "ocjtech", .handle = "h2", .job_id = 12, .name = "test", .status = "waiting" } }, .backoff = .{ .key = "ocjtech/h2", .failures = 2, .until = 1060 }, }}, .running = &.{.{ .id = 7, .name = "ci-droplet-7", .do_id = 555, .tier = "s", .size = "s-2vcpu-4gb", .state = .claimed, .work = .{ .radicle = .{ .id = 3, .rid = "rad:z3QNJRPpssgFMdfjV8Pgsopix3qE4", .commit = "0d2b0335d245f58375385a9ebb076a72d9398a48", .event = "push", .ref = "main", .tier = "s", .url = "https://ci.example.org/runs/3", .state = .running, .created_at = 800, } }, .queued_at = 800, .created_at = 810, .claimed_at = 860, }}, .finished = &.{.{ .id = 6, .name = "ci-droplet-6", .tier = "s", .state = .gone, .work = .{ .forgejo = .{ .forge = "ocjtech", .handle = "h1" } }, .exit_code = 1, .created_at = 500, .done_at = 700, .destroyed_at = 705, }}, }; test "a status survives the trip through JSON" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); var out: std.Io.Writer.Allocating = .init(a); try write(example, &out.writer); // Nothing that is not there is written as null. try testing.expect(std.mem.indexOf(u8, out.written(), "null") == null); const back = try parse(a, out.written()); try testing.expectEqual(@as(u32, version), back.version); try testing.expectEqual(@as(u32, 2), back.pending[0].backoff.?.failures); try testing.expectEqualStrings("test", back.pending[0].work.forgejo.name.?); try testing.expectEqual(@as(u64, 3), back.running[0].work.radicle.id); try testing.expectEqual(DropletState.gone, back.finished[0].state); try testing.expectEqual(@as(?i64, 1), back.finished[0].exit_code); try testing.expectEqual(null, back.finished[0].work.forgejo.job_id); // A newer daemon's fields are passed over. const newer = try std.mem.replaceOwned(u8, a, out.written(), "\"dry_run\"", "\"later\":[1,2],\"dry_run\""); _ = try parse(a, newer); } test "a clone shares nothing with what it was copied from" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); var handle = "h2".*; var pending = example.pending[0]; pending.work.forgejo.handle = &handle; const copy = try clone(Pending, a, pending); handle[1] = '9'; try testing.expectEqualStrings("h2", copy.work.forgejo.handle); try testing.expectEqualStrings("ocjtech/h2", copy.backoff.?.key); const whole = try clone(Status, a, example); try testing.expect(whole.running.ptr != example.running.ptr); try testing.expectEqualStrings(example.running[0].work.radicle.rid, whole.running[0].work.radicle.rid); } test { std.testing.refAllDecls(@This()); } test "a newer daemon's document is still read" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const text = \\{"version":99,"generated_at":1,"public_url":"https://ci.example.org","tiers":[],"forges":[],"pending":[], \\ "running":[ \\ {"id":1,"name":"ci-droplet-1","tier":"s","state":"hibernating","created_at":1,"work":{"teleport":{"x":1}}}, \\ {"id":2,"name":"ci-droplet-2","tier":"s","state":"booting","created_at":1,"work":{"pool":{}}}, \\ {"id":3,"name":"ci-droplet-3","tier":"s","state":"claimed","created_at":1,"work":{"forgejo":{"forge":"ocjtech","handle":"h","shiny":true}}} \\ ], \\ "finished":[],"finished_runs":[]} ; const got = try parse(arena.allocator(), text); try testing.expectEqual(@as(u32, 99), got.version); try testing.expectEqual(DropletState.unknown, got.running[0].state); try testing.expectEqual(Work.unknown, got.running[0].work); try testing.expectEqual(Work.pool, got.running[1].work); try testing.expectEqualStrings("h", got.running[2].work.forgejo.handle); }