// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! What the daemon remembers, in SQLite: its droplets, and Radicle runs. //! //! **Droplets.** Every droplet has a row, made before the droplet itself so //! that its name can carry the row's id. The row holds the token the droplet //! authenticates with, the work it is bound to -- a Forgejo job, with the //! ephemeral runner registered for it, or a Radicle run -- and when each step //! of its life happened, which is what the boot measurements are made of. A //! droplet moves through `creating` (the row exists, the droplet may not), //! `booting` (DigitalOcean made it), `claimed` (its agent has asked for its //! work and been given it), `done` (the agent said the work is over) and //! `gone` (destroyed, or found missing). Nothing moves backwards. //! //! **Runs.** A Radicle run exists only here: the broker hands over a commit //! and waits, and the droplet asks this daemon for its job and sends its log //! back. So the run, its source and its log live in the same database, which //! is what lets a restarted daemon pick up where it left off and a waiting //! adapter reconnect. A run moves through `queued` (the adapter has handed it //! over), then `provisioning` (a droplet has been made for it), then //! `running` (the droplet has fetched its job), then `finished`, with a //! result. //! //! A run's own `token_hash` is what droplets made before the `droplets` table //! authenticated with. It is kept so that such a droplet, still running when //! the daemon is upgraded, can finish; nothing new is given one. const std = @import("std"); const Io = std.Io; const Allocator = std.mem.Allocator; const zqlite = @import("zqlite"); const RunStore = @This(); pool: *zqlite.Pool, io: Io, pub const State = enum { queued, provisioning, running, finished }; pub const Result = enum { success, failure, /// The run never got as far as the script: the droplet failed to boot, /// stopped sending heartbeats, or outlived the cap. Reported to the broker /// as a failure, with the reason on the run's page. @"error", }; pub const Run = struct { id: u64, rid: []const u8, commit: []const u8, /// `push` or `patch`. event: []const u8, /// The branch pushed, or the patch's id. ref: []const u8, tier: []const u8, image: ?[]const u8, shell: []const u8, state: State, result: ?Result, reason: ?[]const u8, created_at: i64, started_at: ?i64, heartbeat_at: ?i64, finished_at: ?i64, droplet_id: ?u64, }; pub const NewRun = struct { rid: []const u8, commit: []const u8, event: []const u8, ref: []const u8, tier: []const u8, image: ?[]const u8, shell: []const u8, /// A gzipped tar of the commit, which the droplet unpacks and runs in. source: []const u8, }; /// Bumped with every change to the schema below, and checked against /// `PRAGMA user_version` when the database is opened. const schema_version = 2; /// Version 1: runs, their sources and their logs. const schema_v1 = [_][:0]const u8{ \\create table runs ( \\ id integer primary key autoincrement, \\ rid text not null, \\ commit_oid text not null, \\ event text not null, \\ ref text not null, \\ tier text not null, \\ image text, \\ shell text not null, \\ token_hash text unique, \\ state text not null, \\ result text, \\ reason text, \\ created_at integer not null, \\ started_at integer, \\ heartbeat_at integer, \\ finished_at integer, \\ droplet_id integer \\) , "create index runs_state on runs (state, created_at)", \\create table sources ( \\ run integer primary key references runs (id) on delete cascade, \\ bytes blob not null \\) , \\create table log_chunks ( \\ run integer not null references runs (id) on delete cascade, \\ seq integer not null, \\ bytes blob not null, \\ primary key (run, seq) \\) , }; /// Version 2: droplets, for every source. const schema_v2 = [_][:0]const u8{ \\create table droplets ( \\ id integer primary key autoincrement, \\ do_id integer, \\ tier text not null, \\ size text, \\ image text, \\ state text not null, \\ token_hash text unique, \\ source text not null, \\ forgejo_handle text, \\ forgejo_runner_id integer, \\ forgejo_runner_uuid text, \\ forgejo_runner_token text, \\ run integer, \\ exit_code integer, \\ boot_report text, \\ queued_at integer, \\ created_at integer not null, \\ active_at integer, \\ booted_at integer, \\ agent_at integer, \\ claimed_at integer, \\ work_started_at integer, \\ done_at integer, \\ destroyed_at integer, \\ heard_at integer \\) , "create index droplets_state on droplets (state)", }; pub fn open(gpa: Allocator, io: Io, path: [:0]const u8) !RunStore { const pool = try zqlite.Pool.init(gpa, .{ .size = 4, .path = path, .on_first_connection = &migrate, .on_connection = &configure, }); return .{ .pool = pool, .io = io }; } pub fn deinit(s: *RunStore) void { s.pool.deinit(); s.* = undefined; } fn configure(conn: zqlite.Conn, _: ?*anyopaque) !void { // The scheduler and the HTTP handlers write at once; waiting a little for // the lock beats failing a heartbeat. try conn.busyTimeout(5000); try conn.execNoArgs("pragma foreign_keys = on"); } fn migrate(conn: zqlite.Conn, _: ?*anyopaque) !void { // WAL lets the handlers read while the scheduler writes. try conn.execNoArgs("pragma journal_mode = wal"); const version = if (try conn.row("pragma user_version", .{})) |row| blk: { defer row.deinit(); break :blk row.int(0); } else 0; switch (version) { 0, 1 => { try conn.transaction(); errdefer conn.rollback(); if (version < 1) for (schema_v1) |statement| try conn.execNoArgs(statement); for (schema_v2) |statement| try conn.execNoArgs(statement); try conn.execNoArgs(std.fmt.comptimePrint("pragma user_version = {d}", .{schema_version})); try conn.commit(); }, schema_version => {}, // A database from a newer daemon: running on would mean guessing what // its columns mean. else => return error.UnknownSchemaVersion, } } fn acquire(s: RunStore) !zqlite.Conn { return s.pool.acquire(s.io); } fn release(s: RunStore, conn: zqlite.Conn) void { s.pool.release(s.io, conn); } /// Records a queued run and its source, and returns its id. pub fn create(s: RunStore, run: NewRun, now: i64) !u64 { const conn = try s.acquire(); defer s.release(conn); try conn.transaction(); errdefer conn.rollback(); try conn.exec( "insert into runs (rid, commit_oid, event, ref, tier, image, shell, state, created_at) values (?1, ?2, ?3, ?4, ?5, ?6, ?7, 'queued', ?8)", .{ run.rid, run.commit, run.event, run.ref, run.tier, run.image, run.shell, now }, ); const id = conn.lastInsertedRowId(); try conn.exec("insert into sources (run, bytes) values (?1, ?2)", .{ id, zqlite.blob(run.source) }); try conn.commit(); return @intCast(id); } const columns = "id, rid, commit_oid, event, ref, tier, image, shell, state, result, reason, created_at, started_at, heartbeat_at, finished_at, droplet_id"; fn readRun(arena: Allocator, row: anytype) !Run { return .{ .id = @intCast(row.int(0)), .rid = try arena.dupe(u8, row.text(1)), .commit = try arena.dupe(u8, row.text(2)), .event = try arena.dupe(u8, row.text(3)), .ref = try arena.dupe(u8, row.text(4)), .tier = try arena.dupe(u8, row.text(5)), .image = if (row.nullableText(6)) |t| try arena.dupe(u8, t) else null, .shell = try arena.dupe(u8, row.text(7)), .state = std.meta.stringToEnum(State, row.text(8)) orelse return error.CorruptState, .result = if (row.nullableText(9)) |t| std.meta.stringToEnum(Result, t) orelse return error.CorruptState else null, .reason = if (row.nullableText(10)) |t| try arena.dupe(u8, t) else null, .created_at = row.int(11), .started_at = row.nullableInt(12), .heartbeat_at = row.nullableInt(13), .finished_at = row.nullableInt(14), .droplet_id = if (row.nullableInt(15)) |d| @intCast(d) else null, }; } fn many(s: RunStore, arena: Allocator, comptime where: []const u8, args: anytype) ![]Run { const conn = try s.acquire(); defer s.release(conn); var rows = try conn.rows("select " ++ columns ++ " from runs " ++ where, args); defer rows.deinit(); var out: std.ArrayList(Run) = .empty; while (rows.next()) |row| try out.append(arena, try readRun(arena, row)); if (rows.err) |err| return err; return out.items; } fn one(s: RunStore, arena: Allocator, comptime where: []const u8, args: anytype) !?Run { const conn = try s.acquire(); defer s.release(conn); const row = try conn.row("select " ++ columns ++ " from runs " ++ where, args) orelse return null; defer row.deinit(); return try readRun(arena, row); } pub fn get(s: RunStore, arena: Allocator, id: u64) !?Run { return s.one(arena, "where id = ?1", .{@as(i64, @intCast(id))}); } /// Runs waiting for a droplet, oldest first. pub fn queued(s: RunStore, arena: Allocator) ![]Run { return s.many(arena, "where state = 'queued' order by created_at, id", .{}); } /// Runs that have a droplet, or are about to. pub fn active(s: RunStore, arena: Allocator) ![]Run { return s.many(arena, "where state in ('provisioning', 'running') order by id", .{}); } /// Runs finished at or after `since`, newest first and at most `limit` of /// them. pub fn recentRuns(s: RunStore, arena: Allocator, since: i64, limit: u32) ![]Run { return s.many(arena, "where state = 'finished' and finished_at >= ?1 order by id desc limit ?2", .{ since, @as(i64, limit) }); } /// The run whose droplet presents `token`, if it is still owed a job. pub fn byToken(s: RunStore, arena: Allocator, token: []const u8) !?Run { const hash = hashToken(token); return s.one(arena, "where token_hash = ?1 and state in ('provisioning', 'running')", .{@as([]const u8, &hash)}); } /// Moves a queued run to `provisioning`, with the DigitalOcean id of the /// droplet made for it. Only a queued run moves, so a run the scheduler raced /// with -- cancelled, or already provisioned -- is left as it was and this /// returns false. pub fn provisioned(s: RunStore, id: u64, droplet_id: u64, now: i64) !bool { const conn = try s.acquire(); defer s.release(conn); try conn.exec( "update runs set state = 'provisioning', droplet_id = ?2, started_at = ?3 where id = ?1 and state = 'queued'", .{ @as(i64, @intCast(id)), @as(i64, @intCast(droplet_id)), now }, ); return conn.changes() == 1; } /// The droplet has fetched its job. pub fn started(s: RunStore, id: u64, now: i64) !void { const conn = try s.acquire(); defer s.release(conn); try conn.exec( "update runs set state = 'running', heartbeat_at = ?2 where id = ?1 and state = 'provisioning'", .{ @as(i64, @intCast(id)), now }, ); } /// Appends a chunk of log and counts it as a heartbeat. A chunk sent twice -- /// the droplet retried after a timeout that was not a failure -- is stored /// once, because the pair of run and sequence number is the key. pub fn appendLog(s: RunStore, id: u64, seq: u64, bytes: []const u8, now: i64) !void { const conn = try s.acquire(); defer s.release(conn); try conn.transaction(); errdefer conn.rollback(); if (bytes.len > 0) try conn.exec( "insert or ignore into log_chunks (run, seq, bytes) values (?1, ?2, ?3)", .{ @as(i64, @intCast(id)), @as(i64, @intCast(seq)), zqlite.blob(bytes) }, ); try conn.exec("update runs set heartbeat_at = ?2 where id = ?1", .{ @as(i64, @intCast(id)), now }); try conn.commit(); } /// Ends a run and revokes its token. A run already finished keeps its first /// result: the droplet reporting and the scheduler giving up on it can race, /// and whichever came first is the truth. pub fn finish(s: RunStore, id: u64, result: Result, reason: ?[]const u8, now: i64) !void { const conn = try s.acquire(); defer s.release(conn); try conn.exec( "update runs set state = 'finished', result = ?2, reason = ?3, finished_at = ?4, token_hash = null where id = ?1 and state != 'finished'", .{ @as(i64, @intCast(id)), @tagName(result), reason, now }, ); } pub fn source(s: RunStore, arena: Allocator, id: u64) !?[]const u8 { const conn = try s.acquire(); defer s.release(conn); const row = try conn.row("select bytes from sources where run = ?1", .{@as(i64, @intCast(id))}) orelse return null; defer row.deinit(); return try arena.dupe(u8, row.blob(0)); } /// The whole log so far, in order. pub fn log(s: RunStore, arena: Allocator, id: u64) ![]const u8 { const conn = try s.acquire(); defer s.release(conn); var rows = try conn.rows("select bytes from log_chunks where run = ?1 order by seq", .{@as(i64, @intCast(id))}); defer rows.deinit(); var out: std.ArrayList(u8) = .empty; while (rows.next()) |row| try out.appendSlice(arena, row.blob(0)); if (rows.err) |err| return err; return out.items; } /// Forgets finished runs older than `before`, with their sources and logs, /// and droplets gone since before then. Sources of finished runs go sooner, /// since nothing reads them once the droplet is gone. pub fn prune(s: RunStore, before: i64) !void { const conn = try s.acquire(); defer s.release(conn); try conn.exec("delete from sources where run in (select id from runs where state = 'finished')", .{}); try conn.exec("delete from runs where state = 'finished' and finished_at < ?1", .{before}); try conn.exec("delete from droplets where state = 'gone' and destroyed_at < ?1", .{before}); } // -- droplets ---------------------------------------------------------------- pub const DropletState = enum { creating, booting, claimed, done, gone }; /// What a droplet was made for. pub const Binding = union(enum) { /// A Forgejo job, and the ephemeral runner registered for it. forgejo: struct { /// The forge's configured name. forge: []const u8, handle: []const u8, runner_id: u64, }, /// A Radicle run. radicle: u64, }; pub const Droplet = struct { id: u64, /// DigitalOcean's id, once the droplet exists. do_id: ?u64, tier: []const u8, size: ?[]const u8, image: ?[]const u8, state: DropletState, /// What it is for, or null for a warm droplet not yet given any work. binding: ?Binding, exit_code: ?i64, /// When the work was first seen waiting. queued_at: ?i64, /// When the row was made, just before the droplet was asked for. created_at: i64, /// When a pass first saw DigitalOcean call it active. active_at: ?i64, /// When its kernel started: the agent's first call, less the uptime it /// reported. booted_at: ?i64, /// The agent's first call. agent_at: ?i64, claimed_at: ?i64, /// When the work itself began: a Radicle droplet fetched its job, or the /// forge showed the job running. work_started_at: ?i64, done_at: ?i64, destroyed_at: ?i64, /// The last call from the agent. heard_at: ?i64, }; pub const NewForgejo = struct { forge: []const u8, handle: []const u8, runner: struct { id: u64, uuid: []const u8, token: []const u8 }, }; pub const NewDroplet = struct { tier: []const u8, queued_at: ?i64, token: []const u8, work: union(enum) { forgejo: NewForgejo, radicle: u64, /// A warm droplet, to be given work later. pool, }, }; /// Records a droplet about to be created, and returns the row's id, which /// goes into the droplet's name. pub fn createDroplet(s: RunStore, d: NewDroplet, now: i64) !u64 { const hash = hashToken(d.token); const conn = try s.acquire(); defer s.release(conn); switch (d.work) { .forgejo => |f| try conn.exec( "insert into droplets (tier, state, token_hash, source, forgejo_handle, forgejo_runner_id, forgejo_runner_uuid, forgejo_runner_token, queued_at, created_at) values (?1, 'creating', ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)", .{ d.tier, @as([]const u8, &hash), f.forge, f.handle, @as(i64, @intCast(f.runner.id)), f.runner.uuid, f.runner.token, d.queued_at, now }, ), .radicle => |run| try conn.exec( "insert into droplets (tier, state, token_hash, source, run, queued_at, created_at) values (?1, 'creating', ?2, 'radicle', ?3, ?4, ?5)", .{ d.tier, @as([]const u8, &hash), @as(i64, @intCast(run)), d.queued_at, now }, ), .pool => try conn.exec( "insert into droplets (tier, state, token_hash, source, queued_at, created_at) values (?1, 'creating', ?2, 'pool', ?3, ?4)", .{ d.tier, @as([]const u8, &hash), d.queued_at, now }, ), } return @intCast(conn.lastInsertedRowId()); } /// DigitalOcean made it. pub fn dropletCreated(s: RunStore, id: u64, do_id: u64, size: []const u8, image: []const u8) !void { const conn = try s.acquire(); defer s.release(conn); try conn.exec( "update droplets set state = 'booting', do_id = ?2, size = ?3, image = ?4 where id = ?1 and state = 'creating'", .{ @as(i64, @intCast(id)), @as(i64, @intCast(do_id)), size, image }, ); } const droplet_columns = "id, do_id, tier, size, image, state, source, forgejo_handle, forgejo_runner_id, run, exit_code, queued_at, created_at, active_at, booted_at, agent_at, claimed_at, work_started_at, done_at, destroyed_at, heard_at"; fn readDroplet(arena: Allocator, row: anytype) !Droplet { const from = row.text(6); const binding: ?Binding = if (std.mem.eql(u8, from, "pool")) null else if (std.mem.eql(u8, from, "radicle")) .{ .radicle = @intCast(row.nullableInt(9) orelse return error.CorruptState) } else .{ .forgejo = .{ .forge = try arena.dupe(u8, from), .handle = try arena.dupe(u8, row.nullableText(7) orelse return error.CorruptState), .runner_id = @intCast(row.nullableInt(8) orelse return error.CorruptState), } }; return .{ .id = @intCast(row.int(0)), .do_id = if (row.nullableInt(1)) |v| @intCast(v) else null, .tier = try arena.dupe(u8, row.text(2)), .size = if (row.nullableText(3)) |t| try arena.dupe(u8, t) else null, .image = if (row.nullableText(4)) |t| try arena.dupe(u8, t) else null, .state = std.meta.stringToEnum(DropletState, row.text(5)) orelse return error.CorruptState, .binding = binding, .exit_code = row.nullableInt(10), .queued_at = row.nullableInt(11), .created_at = row.int(12), .active_at = row.nullableInt(13), .booted_at = row.nullableInt(14), .agent_at = row.nullableInt(15), .claimed_at = row.nullableInt(16), .work_started_at = row.nullableInt(17), .done_at = row.nullableInt(18), .destroyed_at = row.nullableInt(19), .heard_at = row.nullableInt(20), }; } fn oneDroplet(s: RunStore, arena: Allocator, comptime where: []const u8, args: anytype) !?Droplet { const conn = try s.acquire(); defer s.release(conn); const row = try conn.row("select " ++ droplet_columns ++ " from droplets " ++ where, args) orelse return null; defer row.deinit(); return try readDroplet(arena, row); } pub fn getDroplet(s: RunStore, arena: Allocator, id: u64) !?Droplet { return s.oneDroplet(arena, "where id = ?1", .{@as(i64, @intCast(id))}); } fn manyDroplets(s: RunStore, arena: Allocator, comptime where: []const u8, args: anytype) ![]Droplet { const conn = try s.acquire(); defer s.release(conn); var rows = try conn.rows("select " ++ droplet_columns ++ " from droplets " ++ where, args); defer rows.deinit(); var out: std.ArrayList(Droplet) = .empty; while (rows.next()) |row| try out.append(arena, try readDroplet(arena, row)); if (rows.err) |err| return err; return out.items; } /// Every droplet not yet gone. pub fn liveDroplets(s: RunStore, arena: Allocator) ![]Droplet { return s.manyDroplets(arena, "where state != 'gone' order by id", .{}); } /// Droplets whose work is over -- done, or gone -- and that ended at or after /// `since`, newest first and at most `limit` of them. One that went without /// ever saying it was done ended when it was destroyed. pub fn recentDroplets(s: RunStore, arena: Allocator, since: i64, limit: u32) ![]Droplet { return s.manyDroplets( arena, "where state in ('done', 'gone') and coalesce(done_at, destroyed_at, created_at) >= ?1 order by id desc limit ?2", .{ since, @as(i64, limit) }, ); } /// The droplet presenting `token`, if it has not been destroyed. A droplet /// that has said it is done keeps its token until then, so that a `done` it /// has to send again is not refused. pub fn dropletByToken(s: RunStore, arena: Allocator, token: []const u8) !?Droplet { const hash = hashToken(token); return s.oneDroplet(arena, "where token_hash = ?1 and state in ('booting', 'claimed', 'done')", .{@as([]const u8, &hash)}); } /// The agent called. The first call is when it came up: it carries the /// kernel's uptime, which dates the boot, and a report of where the boot's /// time went. pub fn heard(s: RunStore, id: u64, now: i64, uptime_seconds: ?i64, boot_report: ?[]const u8) !void { const conn = try s.acquire(); defer s.release(conn); try conn.exec( \\update droplets set \\ heard_at = ?2, \\ agent_at = coalesce(agent_at, ?2), \\ booted_at = coalesce(booted_at, ?2 - ?3), \\ boot_report = coalesce(boot_report, ?4) \\where id = ?1 , .{ @as(i64, @intCast(id)), now, uptime_seconds, boot_report }); } /// The agent has been given its work. Returns false for a droplet that had /// already said it was done, which has nothing more to claim, and for a warm /// one that has not been given any yet. pub fn claimDroplet(s: RunStore, id: u64, now: i64) !bool { const conn = try s.acquire(); defer s.release(conn); try conn.exec( "update droplets set state = 'claimed', claimed_at = coalesce(claimed_at, ?2) where id = ?1 and state in ('booting', 'claimed') and source != 'pool'", .{ @as(i64, @intCast(id)), now }, ); return conn.changes() == 1; } /// Gives a warm droplet a Forgejo job. Returns false if it is not a warm /// droplet waiting for work any more -- gone, or given something else. pub fn assignForgejo(s: RunStore, id: u64, work: NewForgejo, queued_at: i64) !bool { const conn = try s.acquire(); defer s.release(conn); try conn.exec( "update droplets set source = ?2, forgejo_handle = ?3, forgejo_runner_id = ?4, forgejo_runner_uuid = ?5, forgejo_runner_token = ?6, queued_at = ?7 where id = ?1 and source = 'pool' and state = 'booting'", .{ @as(i64, @intCast(id)), work.forge, work.handle, @as(i64, @intCast(work.runner.id)), work.runner.uuid, work.runner.token, queued_at }, ); return conn.changes() == 1; } /// Gives a warm droplet a Radicle run, as `assignForgejo` does a job. pub fn assignRadicle(s: RunStore, id: u64, run: u64, queued_at: i64) !bool { const conn = try s.acquire(); defer s.release(conn); try conn.exec( "update droplets set source = 'radicle', run = ?2, queued_at = ?3 where id = ?1 and source = 'pool' and state = 'booting'", .{ @as(i64, @intCast(id)), @as(i64, @intCast(run)), queued_at }, ); return conn.changes() == 1; } pub const Activity = struct { tier: []const u8, at: i64 }; /// When work last started in each tier: the newest claim by a droplet that /// had work, gone ones included. A tier with none is absent. pub fn lastActivity(s: RunStore, arena: Allocator) ![]Activity { const conn = try s.acquire(); defer s.release(conn); var rows = try conn.rows("select tier, max(claimed_at) from droplets where source != 'pool' and claimed_at is not null group by tier", .{}); defer rows.deinit(); var out: std.ArrayList(Activity) = .empty; while (rows.next()) |row| try out.append(arena, .{ .tier = try arena.dupe(u8, row.text(0)), .at = row.int(1) }); if (rows.err) |err| return err; return out.items; } pub const RunnerCredentials = struct { uuid: []const u8, token: []const u8 }; /// What a Forgejo droplet's agent needs to start its runner. pub fn runnerCredentials(s: RunStore, arena: Allocator, id: u64) !?RunnerCredentials { const conn = try s.acquire(); defer s.release(conn); const row = try conn.row("select forgejo_runner_uuid, forgejo_runner_token from droplets where id = ?1", .{@as(i64, @intCast(id))}) orelse return null; defer row.deinit(); return .{ .uuid = try arena.dupe(u8, row.nullableText(0) orelse return null), .token = try arena.dupe(u8, row.nullableText(1) orelse return null), }; } pub fn markActive(s: RunStore, id: u64, now: i64) !void { const conn = try s.acquire(); defer s.release(conn); try conn.exec("update droplets set active_at = coalesce(active_at, ?2) where id = ?1", .{ @as(i64, @intCast(id)), now }); } pub fn workStarted(s: RunStore, id: u64, now: i64) !void { const conn = try s.acquire(); defer s.release(conn); try conn.exec("update droplets set work_started_at = coalesce(work_started_at, ?2) where id = ?1", .{ @as(i64, @intCast(id)), now }); } /// The agent says its work is over. The first report stands. pub fn dropletDone(s: RunStore, id: u64, exit_code: i64, now: i64) !void { const conn = try s.acquire(); defer s.release(conn); try conn.exec( "update droplets set state = 'done', exit_code = ?2, done_at = ?3, heard_at = ?3 where id = ?1 and state in ('booting', 'claimed')", .{ @as(i64, @intCast(id)), exit_code, now }, ); } /// Destroyed, or found missing: the token stops working and the runner's /// credentials are forgotten. pub fn dropletGone(s: RunStore, id: u64, now: i64) !void { const conn = try s.acquire(); defer s.release(conn); try conn.exec( "update droplets set state = 'gone', destroyed_at = coalesce(destroyed_at, ?2), token_hash = null, forgejo_runner_token = null where id = ?1", .{ @as(i64, @intCast(id)), now }, ); } pub const DropletCount = struct { tier: []const u8, state: DropletState, count: u64 }; /// How many droplets are in each tier and state, for the metrics. pub fn dropletCounts(s: RunStore, arena: Allocator) ![]DropletCount { const conn = try s.acquire(); defer s.release(conn); var rows = try conn.rows("select tier, state, count(*) from droplets where state != 'gone' group by tier, state order by tier, state", .{}); defer rows.deinit(); var out: std.ArrayList(DropletCount) = .empty; while (rows.next()) |row| try out.append(arena, .{ .tier = try arena.dupe(u8, row.text(0)), .state = std.meta.stringToEnum(DropletState, row.text(1)) orelse return error.CorruptState, .count = @intCast(row.int(2)), }); if (rows.err) |err| return err; return out.items; } /// A token as it is stored: its SHA-256, so that a copy of the database is no /// use to anyone wanting to impersonate a droplet. fn hashToken(token: []const u8) [64]u8 { var digest: [32]u8 = undefined; std.crypto.hash.sha2.Sha256.hash(token, &digest, .{}); return std.fmt.bytesToHex(digest, .lower); } /// A fresh token for a droplet: 32 random bytes, as hex. pub fn newToken(io: Io) [64]u8 { var bytes: [32]u8 = undefined; io.random(&bytes); return std.fmt.bytesToHex(bytes, .lower); } const testing = std.testing; fn testStore(tmp: *std.testing.TmpDir, buf: []u8) !RunStore { const path = try std.fmt.bufPrintZ(buf, ".zig-cache/tmp/{s}/runs.db", .{tmp.sub_path}); return open(testing.allocator, testing.io, path); } const example: NewRun = .{ .rid = "rad:z2eDxErDjXEAiYHf7SJYNDnT9Ytaa", .commit = "3f1c9e9453c8de2916e09194c45cf8ae25bf34e5", .event = "push", .ref = "main", .tier = "s", .image = null, .shell = "zig build test\n", .source = "\x1f\x8b not really a tarball", }; test "a run from queued to finished" { var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var buf: [256]u8 = undefined; var store = try testStore(&tmp, &buf); defer store.deinit(); var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); const id = try store.create(example, 100); try testing.expectEqual(@as(usize, 1), (try store.queued(a)).len); try testing.expectEqualStrings(example.source, (try store.source(a, id)).?); try testing.expect(try store.provisioned(id, 555, 110)); // only once try testing.expect(!try store.provisioned(id, 556, 111)); try testing.expectEqual(@as(usize, 0), (try store.queued(a)).len); try testing.expectEqual(@as(?u64, 555), (try store.get(a, id)).?.droplet_id); // a run's own token is only for droplets made before the droplets // table, and a new run has none try testing.expectEqual(null, try store.byToken(a, "0123456789abcdef")); try store.started(id, 120); try store.appendLog(id, 1, "hello ", 130); try store.appendLog(id, 2, "world\n", 140); // a retried chunk is stored once try store.appendLog(id, 2, "world\n", 141); // a heartbeat try store.appendLog(id, 3, "", 150); try testing.expectEqualStrings("hello world\n", try store.log(a, id)); try testing.expectEqual(@as(?i64, 150), (try store.get(a, id)).?.heartbeat_at); try store.finish(id, .success, null, 160); // the first result stands try store.finish(id, .@"error", "heartbeat lost", 170); const done = (try store.get(a, id)).?; try testing.expectEqual(State.finished, done.state); try testing.expectEqual(@as(?Result, .success), done.result); } test "a droplet from creating to gone" { var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var buf: [256]u8 = undefined; var store = try testStore(&tmp, &buf); defer store.deinit(); var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); const token = "0123456789abcdef"; const id = try store.createDroplet(.{ .tier = "s", .queued_at = 90, .token = token, .work = .{ .forgejo = .{ .forge = "ocjtech", .handle = "h1", .runner = .{ .id = 7, .uuid = "uuid-7", .token = "runner-secret" } } }, }, 100); // not usable until DigitalOcean has made it try testing.expectEqual(null, try store.dropletByToken(a, token)); try store.dropletCreated(id, 555, "s-2vcpu-4gb", "12345"); const booting = (try store.dropletByToken(a, token)).?; try testing.expectEqual(DropletState.booting, booting.state); try testing.expectEqualStrings("ocjtech", booting.binding.?.forgejo.forge); try testing.expectEqualStrings("h1", booting.binding.?.forgejo.handle); try testing.expectEqual(@as(u64, 7), booting.binding.?.forgejo.runner_id); try testing.expectEqual(null, try store.dropletByToken(a, "wrong")); // the first call dates the boot; later ones only count as heard try store.heard(id, 150, 30, "report"); try store.heard(id, 160, 40, "another"); try testing.expect(try store.claimDroplet(id, 160)); // claiming again changes nothing try testing.expect(try store.claimDroplet(id, 170)); const creds = (try store.runnerCredentials(a, id)).?; try testing.expectEqualStrings("runner-secret", creds.token); try store.markActive(id, 140); try store.workStarted(id, 180); try store.dropletDone(id, 0, 300); // a second report does not replace the first try store.dropletDone(id, 1, 310); // and a droplet that is done has nothing to claim try testing.expect(!try store.claimDroplet(id, 320)); const done = (try store.getDroplet(a, id)).?; try testing.expectEqual(DropletState.done, done.state); try testing.expectEqual(@as(?i64, 0), done.exit_code); try testing.expectEqual(@as(?i64, 150), done.agent_at); try testing.expectEqual(@as(?i64, 120), done.booted_at); try testing.expectEqual(@as(?i64, 160), done.claimed_at); try testing.expectEqual(@as(?i64, 140), done.active_at); try testing.expectEqual(@as(?i64, 180), done.work_started_at); try testing.expectEqual(@as(?i64, 300), done.done_at); try testing.expectEqual(@as(?i64, 300), done.heard_at); // done still authenticates, so a repeated report is not refused try testing.expect(try store.dropletByToken(a, token) != null); const counts = try store.dropletCounts(a); try testing.expectEqual(@as(usize, 1), counts.len); try testing.expectEqual(DropletState.done, counts[0].state); try store.dropletGone(id, 320); try testing.expectEqual(null, try store.dropletByToken(a, token)); try testing.expectEqual(null, try store.runnerCredentials(a, id)); try testing.expectEqual(@as(usize, 0), (try store.liveDroplets(a)).len); const run = try store.create(example, 100); const rad = try store.createDroplet(.{ .tier = "l", .queued_at = 100, .token = "other", .work = .{ .radicle = run } }, 101); try testing.expectEqual(Binding{ .radicle = run }, (try store.getDroplet(a, rad)).?.binding); try testing.expectEqual(@as(usize, 1), (try store.liveDroplets(a)).len); try store.prune(1000); try testing.expectEqual(null, try store.getDroplet(a, id)); try testing.expect(try store.getDroplet(a, rad) != null); } test "recent history, newest first" { var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var buf: [256]u8 = undefined; var store = try testStore(&tmp, &buf); defer store.deinit(); var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); // Four droplets: one ended long ago, two recently -- one by saying it was // done, one by being destroyed without -- and one still at work. var ids: [4]u64 = undefined; for (&ids, 0..) |*id, i| { var token_buf: [8]u8 = undefined; id.* = try store.createDroplet(.{ .tier = "s", .queued_at = null, .token = try std.fmt.bufPrint(&token_buf, "t{d}", .{i}), .work = .{ .radicle = i + 1 }, }, @intCast(100 * i)); try store.dropletCreated(id.*, 500 + i, "s-2vcpu-4gb", "snap"); } try store.dropletDone(ids[0], 0, 50); try store.dropletGone(ids[0], 60); try store.dropletGone(ids[1], 250); try store.dropletDone(ids[2], 1, 300); const recent = try store.recentDroplets(a, 200, 10); try testing.expectEqual(@as(usize, 2), recent.len); try testing.expectEqual(ids[2], recent[0].id); try testing.expectEqual(ids[1], recent[1].id); try testing.expectEqual(@as(usize, 1), (try store.recentDroplets(a, 0, 1)).len); try testing.expectEqual(@as(usize, 3), (try store.recentDroplets(a, 0, 10)).len); const old = try store.create(example, 10); try store.finish(old, .success, null, 20); const new = try store.create(example, 30); try store.finish(new, .failure, "no", 40); _ = try store.create(example, 50); const runs = try store.recentRuns(a, 15, 10); try testing.expectEqual(@as(usize, 2), runs.len); try testing.expectEqual(new, runs[0].id); try testing.expectEqual(@as(usize, 1), (try store.recentRuns(a, 30, 10)).len); } test "a version 1 database is brought up to date" { var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var buf: [256]u8 = undefined; const path = try std.fmt.bufPrintZ(&buf, ".zig-cache/tmp/{s}/runs.db", .{tmp.sub_path}); { const conn = try zqlite.open(path, zqlite.OpenFlags.Create | zqlite.OpenFlags.ReadWrite); defer conn.close(); for (schema_v1) |statement| try conn.execNoArgs(statement); try conn.exec("insert into runs (rid, commit_oid, event, ref, tier, shell, state, created_at) values ('r', 'c', 'push', 'main', 's', 'x', 'queued', 1)", .{}); try conn.execNoArgs("pragma user_version = 1"); } var store = try open(testing.allocator, testing.io, path); defer store.deinit(); var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); try testing.expectEqual(@as(usize, 1), (try store.queued(arena.allocator())).len); _ = try store.createDroplet(.{ .tier = "s", .queued_at = null, .token = "t", .work = .{ .radicle = 1 } }, 2); } test "pruning" { var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var buf: [256]u8 = undefined; var store = try testStore(&tmp, &buf); defer store.deinit(); var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); const old = try store.create(example, 100); try store.finish(old, .failure, null, 200); const recent = try store.create(example, 300); try store.finish(recent, .success, null, 400); const waiting = try store.create(example, 500); try store.prune(300); try testing.expectEqual(null, try store.get(a, old)); try testing.expect(try store.get(a, recent) != null); try testing.expectEqual(null, try store.source(a, recent)); try testing.expect(try store.source(a, waiting) != null); } test "the schema version is checked" { var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var buf: [256]u8 = undefined; { var store = try testStore(&tmp, &buf); defer store.deinit(); const conn = try store.acquire(); defer store.release(conn); try conn.execNoArgs("pragma user_version = 99"); } try testing.expectError(error.UnknownSchemaVersion, testStore(&tmp, &buf)); } test { std.testing.refAllDecls(@This()); } test "a warm droplet is given work once" { var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var buf: [256]u8 = undefined; var store = try testStore(&tmp, &buf); defer store.deinit(); var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); const id = try store.createDroplet(.{ .tier = "s", .queued_at = null, .token = "warm", .work = .pool }, 100); try store.dropletCreated(id, 555, "s-2vcpu-4gb", "snap"); const idle = (try store.getDroplet(a, id)).?; try testing.expectEqual(null, idle.binding); // nothing to claim yet try testing.expect(!try store.claimDroplet(id, 110)); const work: NewForgejo = .{ .forge = "ocjtech", .handle = "h1", .runner = .{ .id = 7, .uuid = "u", .token = "t" } }; try testing.expect(try store.assignForgejo(id, work, 105)); // not twice, and not to a Radicle run either try testing.expect(!try store.assignForgejo(id, work, 106)); try testing.expect(!try store.assignRadicle(id, 3, 106)); const given = (try store.getDroplet(a, id)).?; try testing.expectEqualStrings("h1", given.binding.?.forgejo.handle); try testing.expectEqual(@as(?i64, 105), given.queued_at); try testing.expect(try store.claimDroplet(id, 120)); // Activity counts droplets that had work, not warm ones waiting. const other = try store.createDroplet(.{ .tier = "l", .queued_at = null, .token = "warm2", .work = .pool }, 130); try store.dropletCreated(other, 556, "s-4vcpu-8gb", "snap"); const activity = try store.lastActivity(a); try testing.expectEqual(@as(usize, 1), activity.len); try testing.expectEqualStrings("s", activity[0].tier); try testing.expectEqual(@as(i64, 120), activity[0].at); }