Something went wrong. Try again.
Ephemeral DigitalOcean droplets for Forgejo Actions and Radicle CI, from one daemon
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! The daemon's HTTP side: one handler for the broker's adapter, on a Unix//! socket; one for the droplets and for people, behind a reverse proxy on the//! internet; and one for Prometheus, on an address of its own.//!//! **The adapter's API** takes a run and hands back its result://!//! * `POST /runs` -- a commit, its `.radicle/droplet.yaml`, and a gzipped//! tar of its tree. Answers with the run's id and its page.//! * `GET /runs/<id>/wait` -- the result, once there is one, or the state so//! far after a minute of waiting, so that no request stays open for the//! length of a run.//!//! **The droplets' API** is how a droplet gets its work, and it is only ever//! the droplet that asks: this daemon never connects to one, so a droplet//! runs no sshd and admits nothing inbound. Every request carries the token//! the droplet was given at creation, which names that droplet and nothing//! else, and which stops working once it is destroyed.//!//! * `GET /droplet/v1/agent` -- the `ci-agent` binary.//! * `POST /droplet/v1/claim` -- the droplet's work: a Forgejo job, with the//! runner registered for it, or a Radicle run. The first call also dates//! the boot and says where its time went.//! * `POST /droplet/v1/done` -- the work is over, with its exit status; the//! droplet is destroyed on the scheduler's next pass.//!//! and, for a Radicle run://!//! * `GET /droplet/v1/job` -- what to run, and in what image.//! * `GET /droplet/v1/source` -- the tree to run it in.//! * `POST /droplet/v1/log?seq=<n>` -- the next piece of output; an empty//! one is a heartbeat.//! * `POST /droplet/v1/result` -- the script's exit status.//!//! **The pages** are public: `/runs/<id>` and `/runs/<id>/log.txt`, which//! the broker records as each run's `info_url`, and the broker's own report//! pages under `/reports/`.//!//! **`GET /status`** is for people watching the fleet -- `ci-top` -- and//! answers with `api.status.Status`: every piece of work waiting, the droplet//! each running one has, and what finished lately. It is served only when a//! status token is configured, and only to a request presenting it; that//! token is not a droplet's, and a droplet's is not it.//!//! **`/metrics`** is Prometheus's, on the metrics listener only: see//! `Metrics`.//!//! **`POST /forgejo/<forge>/webhook`** takes a forge's webhook, signed with//! its secret. An event that creates workflow runs -- a push, a tag, a pull//! request -- prompts the scheduler to poll that forge in the next few//! seconds rather than at its next interval. Nothing is provisioned from the//! payload: the forge's own API stays the only word on what is waiting, so a//! forged or replayed delivery costs a few API calls and no more.
const std = @import("std");const Io = std.Io;const Allocator = std.mem.Allocator;const datetime = @import("datetime");const http = @import("http");const Request = http.server.Request;const Response = http.server.Response;
const Config = @import("Config.zig");const DropletSpec = @import("DropletSpec.zig");const Metrics = @import("Metrics.zig");const RunStore = @import("RunStore.zig");const StatusBoard = @import("StatusBoard.zig");const broker = @import("broker.zig");const api = @import("api");
const log = std.log.scoped(.service);
const Service = @This();
io: Io,config: Config,store: *RunStore,metrics: ?*Metrics = null,tier_names: []const []const u8,/// What the scheduler last published, for `/status`.board: ?*StatusBoard = null,/// The SHA-256 of the token `/status` asks for, or null to serve no/// `/status` at all.status_token_sha256: ?[32]u8 = null,/// Set to wake the scheduler before its tick: a droplet is done, a run was/// submitted, a webhook came in. Null outside the daemon.wake: ?*Io.Event = null,/// Per forge, in `config.forges` order: when it was last prompted to poll/// soon, in seconds since the epoch. The scheduler reads these.prompts: []std.atomic.Value(i64) = &.{},/// Per forge: the secret its webhooks are signed with, or null for none.webhook_secrets: []const ?[]const u8 = &.{},
/// The largest source tarball the adapter may hand over.pub const max_source_len = 256 * 1024 * 1024;/// The largest piece of log a droplet may send at once.pub const max_log_chunk_len = 1024 * 1024;/// How long `/wait` holds a request before answering with the state so far.const wait_seconds = 60;/// The largest boot report kept. The agent sends a few kilobytes.pub const max_boot_report_len = 64 * 1024;/// How long `/droplet/v1/claim` holds a warm droplet's request before/// answering that there is no work yet. Well inside any proxy's timeout, and/// often enough to serve as the droplet's heartbeat.pub const claim_wait_seconds = 25;/// The largest webhook payload read. A push of many commits is a few hundred/// kilobytes.pub const max_webhook_len = 1024 * 1024;
fn signal(s: *Service) void { if (s.wake) |w| w.set(s.io);}
/// Asks the scheduler to poll forge `index` soon.fn prompt(s: *Service, index: usize) void { if (index >= s.prompts.len) return; _ = s.prompts[index].fetchMax(s.now(), .release); s.signal();}
fn now(s: *const Service) i64 { return @intCast(@divFloor(datetime.Instant.now(s.io).timestamp, std.time.ns_per_s));}
// -- the adapter's API -------------------------------------------------------
/// What the adapter sends. `source` is base64, since JSON has no bytes.pub const Submission = struct { rid: []const u8, commit: []const u8, event: broker.Event, ref: []const u8, /// The text of `.radicle/droplet.yaml` at the commit, parsed here so that /// the adapter needs to know nothing about it. spec: []const u8, source: []const u8,};
pub const Submitted = struct { id: u64, info_url: []const u8,};
pub const Waited = struct { state: RunStore.State, result: ?RunStore.Result = null,};
pub fn adapter(s: *Service, req: *Request, res: *Response) anyerror!void { const path = req.target.path; if (std.mem.eql(u8, path, "/runs")) { if (!std.mem.eql(u8, req.method.name, "POST")) return res.sendStatus(.method_not_allowed); return s.submit(req, res); } if (std.mem.startsWith(u8, path, "/runs/") and std.mem.endsWith(u8, path, "/wait")) { const id = std.fmt.parseInt(u64, path["/runs/".len .. path.len - "/wait".len], 10) catch return res.sendStatus(.not_found); return s.wait(req, res, id); } return res.sendStatus(.not_found);}
fn submit(s: *Service, req: *Request, res: *Response) !void { const arena = req.arena; const body = req.body.readAlloc(arena, max_source_len * 4 / 3 + 64 * 1024) catch return res.sendStatus(.payload_too_large); const sub = std.json.parseFromSliceLeaky(Submission, arena, body, .{ .allocate = .alloc_always }) catch return res.sendStatus(.bad_request); if (!broker.validRid(sub.rid) or !broker.validOid(sub.commit)) return res.sendStatus(.bad_request);
const decoder = std.base64.standard.Decoder; const source = try arena.alloc(u8, decoder.calcSizeForSlice(sub.source) catch return res.sendStatus(.bad_request)); decoder.decode(source, sub.source) catch return res.sendStatus(.bad_request);
var diagnostic: []const u8 = ""; const spec: ?DropletSpec = DropletSpec.parse(arena, sub.spec, s.tier_names, &diagnostic) catch |err| switch (err) { error.OutOfMemory => return err, error.InvalidSpec => null, };
const t = s.now(); const id = try s.store.create(.{ .rid = sub.rid, .commit = sub.commit, .event = @tagName(sub.event), .ref = sub.ref, .tier = if (spec) |sp| sp.tier else "", .image = if (spec) |sp| sp.image else null, .shell = if (spec) |sp| sp.shell else "", .source = if (spec != null) source else "", }, t); // A spec that cannot be run is still a run: the broker is told it failed, // and the page says why, which is more use than an adapter that exits. if (spec == null) try s.store.finish(id, .@"error", diagnostic, t) else s.signal(); log.info("run {d}: {s} {s} at {s}{s}", .{ id, sub.rid, @tagName(sub.event), sub.commit, if (spec == null) " refused" else "" });
try res.setHeader("content-type", "application/json"); res.status = .created; var out: Io.Writer.Allocating = .init(arena); try std.json.Stringify.value(Submitted{ .id = id, .info_url = try s.runUrl(arena, id) }, .{}, &out.writer); try res.send(out.written());}
fn wait(s: *Service, req: *Request, res: *Response, id: u64) !void { const arena = req.arena; var waited: u32 = 0; const run = while (true) : (waited += 2) { const run = try s.store.get(arena, id) orelse return res.sendStatus(.not_found); if (run.state == .finished or waited >= wait_seconds) break run; try Io.sleep(s.io, .fromSeconds(2), .awake); }; try res.setHeader("content-type", "application/json"); var out: Io.Writer.Allocating = .init(arena); try std.json.Stringify.value(Waited{ .state = run.state, .result = run.result }, .{}, &out.writer); try res.send(out.written());}
fn runUrl(s: *const Service, arena: Allocator, id: u64) ![]const u8 { return std.fmt.allocPrint(arena, "{s}/runs/{d}", .{ s.config.public_url, id });}
// -- the droplets' API and the pages -----------------------------------------
const Job = api.droplet.Job;const Outcome = api.droplet.Outcome;
pub fn public(s: *Service, req: *Request, res: *Response) anyerror!void { const path = req.target.path; const method = req.method.name;
// Nothing here is for search engines: a run's page and log are for // whoever the broker or a patch sent there, and they are pruned after // the retention period, so an index of them is an index of dead links. // The header covers every response, logs and reports included, which a // `<meta>` tag in the HTML could not; robots.txt asks crawlers not to // fetch at all, for those that ask first. try res.setHeader("x-robots-tag", "noindex, nofollow"); if (std.mem.eql(u8, path, "/robots.txt")) { try res.setHeader("content-type", "text/plain; charset=utf-8"); return res.send(robots_txt); }
if (std.mem.startsWith(u8, path, "/forgejo/") and std.mem.endsWith(u8, path, "/webhook")) { if (!std.mem.eql(u8, method, "POST")) return res.sendStatus(.method_not_allowed); return s.webhook(req, res, path["/forgejo/".len .. path.len - "/webhook".len]); }
if (std.mem.eql(u8, path, "/status")) return s.statusReport(req, res);
if (std.mem.startsWith(u8, path, "/droplet/v1/")) { const what = path["/droplet/v1/".len..]; const token = bearer(req) orelse return res.sendStatus(.unauthorized); // The agent binary is not secret, but it is served only to a droplet // of ours, so that this is not a free download host. const caller = try s.authenticate(req.arena, token) orelse return res.sendStatus(.unauthorized);
if (std.mem.eql(u8, what, "agent") and std.mem.eql(u8, method, "GET")) return s.sendFile(req, res, s.config.agent, "application/octet-stream"); if (std.mem.eql(u8, what, "claim") and std.mem.eql(u8, method, "POST")) { const d = caller.droplet orelse return res.sendStatus(.not_found); return s.claim(req, res, d); } if (std.mem.eql(u8, what, "done") and std.mem.eql(u8, method, "POST")) { const d = caller.droplet orelse return res.sendStatus(.not_found); return s.done(req, res, d); }
// The rest is a Radicle run's, and only while it is running. const run = caller.run orelse return res.sendStatus(.not_found); if (caller.droplet) |d| try s.store.heard(d.id, s.now(), null, null); if (std.mem.eql(u8, what, "job") and std.mem.eql(u8, method, "GET")) { if (caller.droplet) |d| try s.store.workStarted(d.id, s.now()); return s.job(req, res, run); } if (std.mem.eql(u8, what, "source") and std.mem.eql(u8, method, "GET")) { const bytes = try s.store.source(req.arena, run.id) orelse return res.sendStatus(.gone); try res.setHeader("content-type", "application/gzip"); return res.send(bytes); } if (std.mem.eql(u8, what, "log") and std.mem.eql(u8, method, "POST")) return s.logChunk(req, res, run); if (std.mem.eql(u8, what, "result") and std.mem.eql(u8, method, "POST")) return s.result(req, res, run); return res.sendStatus(.not_found); }
if (!std.mem.eql(u8, method, "GET") and !std.mem.eql(u8, method, "HEAD")) return res.sendStatus(.method_not_allowed);
if (std.mem.startsWith(u8, path, "/runs/")) { const rest = path["/runs/".len..]; if (std.mem.endsWith(u8, rest, "/log.txt")) { const id = std.fmt.parseInt(u64, rest[0 .. rest.len - "/log.txt".len], 10) catch return res.sendStatus(.not_found); _ = try s.store.get(req.arena, id) orelse return res.sendStatus(.not_found); try res.setHeader("content-type", "text/plain; charset=utf-8"); return res.send(try s.store.log(req.arena, id)); } const id = std.fmt.parseInt(u64, rest, 10) catch return res.sendStatus(.not_found); const run = try s.store.get(req.arena, id) orelse return res.sendStatus(.not_found); return s.page(req, res, run); }
if (if (s.config.radicle) |r| r.report_dir else null) |dir| { if (std.mem.eql(u8, path, "/reports")) return res.redirect(.moved_permanently, "/reports/"); if (std.mem.startsWith(u8, path, "/reports/")) { // Decoded and normalised once, by the one function that knows how // to refuse a `..` that would leave the directory. var buf: [1024]u8 = undefined; const resolved = req.target.resolvePath(&buf) catch return res.sendStatus(.not_found); var rel = resolved["/reports".len..]; while (rel.len > 0 and rel[0] == '/') rel = rel[1..]; if (rel.len == 0) rel = "index.html"; const full = try std.fs.path.join(req.arena, &.{ dir, rel }); return s.sendFile(req, res, full, contentType(rel)); } }
return res.sendStatus(.not_found);}
pub const robots_txt = \\User-agent: * \\Disallow: / \\;
/// Who is calling, by the token they present.const Caller = struct { /// The droplet, unless it is one from before the droplet database. droplet: ?RunStore.Droplet = null, /// The Radicle run it may act for, while that run is under way. run: ?RunStore.Run = null,};
fn authenticate(s: *Service, arena: Allocator, token: []const u8) !?Caller { if (try s.store.dropletByToken(arena, token)) |d| { var caller: Caller = .{ .droplet = d }; if (d.binding) |b| switch (b) { .radicle => |id| if (try s.store.get(arena, id)) |run| { if (run.state == .provisioning or run.state == .running) caller.run = run; }, .forgejo => {}, }; return caller; } // A droplet made before the droplet database presents its run's token. if (try s.store.byToken(arena, token)) |run| return .{ .run = run }; return null;}
/// The droplet's work. A droplet made for a job or a run has it at once. A/// warm one waits here, `claim_wait_seconds` at a time, until the scheduler/// gives it some, and every call counts as its heartbeat meanwhile.fn claim(s: *Service, req: *Request, res: *Response, d: RunStore.Droplet) !void { const arena = req.arena; const body = req.body.readAlloc(arena, max_boot_report_len + 4096) catch return res.sendStatus(.payload_too_large); const said = std.json.parseFromSliceLeaky(api.droplet.Claim, arena, body, .{ .ignore_unknown_fields = true, .allocate = .alloc_always }) catch return res.sendStatus(.bad_request); const t = s.now(); const report = if (said.boot_report) |r| r[0..@min(r.len, max_boot_report_len)] else null; const uptime = if (said.uptime_seconds) |u| if (u >= 0 and u < 365 * 86400) u else null else null; try s.store.heard(d.id, t, uptime, report); if (d.agent_at == null) { // The droplet came up: how long DigitalOcean took, and how long the // guest, as far as the kernel's uptime can say. if (uptime) |u| { log.info("droplet {d}: agent up {d}s after it was asked for, {d}s after its kernel started", .{ d.id, t - d.created_at, u }); } else { log.info("droplet {d}: agent up {d}s after it was asked for", .{ d.id, t - d.created_at }); } }
var row = d; var waited: u32 = 0; const binding = while (true) : (waited += 1) { if (row.binding) |b| break b; if (row.state != .booting) return res.sendStatus(.gone); if (waited >= claim_wait_seconds) return res.sendStatus(.no_content); try Io.sleep(s.io, .fromSeconds(1), .awake); row = try s.store.getDroplet(arena, d.id) orelse return res.sendStatus(.gone); }; if (!try s.store.claimDroplet(d.id, s.now())) return res.sendStatus(.gone);
const assignment: api.droplet.Assignment = switch (binding) { .radicle => |id| .{ .radicle = id }, .forgejo => |f| blk: { const forge = for (s.config.forges) |fc| { if (std.mem.eql(u8, fc.name, f.forge)) break fc; } else return res.sendStatus(.gone); const creds = try s.store.runnerCredentials(arena, d.id) orelse return res.sendStatus(.gone); break :blk .{ .forgejo = .{ .url = forge.url, .runner_uuid = creds.uuid, .runner_token = creds.token, .handle = f.handle, .label = try std.mem.concat(arena, u8, &.{ forge.label_prefix, d.tier }), .image = s.config.runner_image, .nix_config = s.config.job_nix_config, } }; }, }; if (d.binding == null) log.info("droplet {d}: warm, given its work after waiting", .{d.id});
try res.setHeader("content-type", "application/json"); var out: Io.Writer.Allocating = .init(arena); try std.json.Stringify.value(assignment, .{}, &out.writer); try res.send(out.written());}
fn done(s: *Service, req: *Request, res: *Response, d: RunStore.Droplet) !void { const body = req.body.readAlloc(req.arena, 1024) catch return res.sendStatus(.payload_too_large); const outcome = std.json.parseFromSliceLeaky(Outcome, req.arena, body, .{}) catch return res.sendStatus(.bad_request); const t = s.now(); try s.store.dropletDone(d.id, outcome.exit_code, t); // A Radicle droplet reports its run's result before it says it is done. // One that did not -- the agent failed before the script ran, or could // not reach the result endpoint -- has its run failed here, with what // there is to say, rather than left for the scheduler to find without a // droplet. if (d.binding) |b| switch (b) { .radicle => |id| try s.store.finish(id, .@"error", try std.fmt.allocPrint(req.arena, "the droplet finished without a result (exit status {d})", .{outcome.exit_code}), t), // A job that ends is usually followed by the next one of its // workflow, waiting on it with `needs:`. .forgejo => |f| if (s.forgeIndex(f.forge)) |i| s.prompt(i), }; log.info("droplet {d}: done, exit status {d}", .{ d.id, outcome.exit_code }); // Destroyed now, rather than at the next tick, and its slot freed. s.signal(); return res.sendStatus(.no_content);}
fn forgeIndex(s: *const Service, name: []const u8) ?usize { for (s.config.forges, 0..) |f, i| if (std.mem.eql(u8, f.name, name)) return i; return null;}
/// The events that make workflow runs, by `X-Forgejo-Event-Type`. Schedules/// make them too, but with no webhook.const run_events = [_][]const u8{ "push", "create", "release", "pull_request", "pull_request_sync", "workflow_dispatch" };
fn webhook(s: *Service, req: *Request, res: *Response, name: []const u8) !void { const index = s.forgeIndex(name) orelse return res.sendStatus(.not_found); const secret = (if (index < s.webhook_secrets.len) s.webhook_secrets[index] else null) orelse return res.sendStatus(.not_found); const signature = req.header("x-forgejo-signature") orelse return res.sendStatus(.unauthorized); const body = req.body.readAlloc(req.arena, max_webhook_len) catch return res.sendStatus(.payload_too_large); if (!validSignature(secret, body, signature)) { log.warn("{s}: a webhook with a bad signature was refused", .{name}); return res.sendStatus(.unauthorized); } const event = req.header("x-forgejo-event-type") orelse ""; for (run_events) |e| if (std.mem.eql(u8, event, e)) { log.debug("{s}: {s} webhook; polling soon", .{ name, event }); s.prompt(index); break; }; return res.sendStatus(.no_content);}
/// Whether `signature` is the lowercase hex HMAC-SHA256 of `body` under/// `secret`, which is what Forgejo sends as `X-Forgejo-Signature`. Compared/// in constant time, so that how long a refusal takes says nothing about how/// much of a guess was right.pub fn validSignature(secret: []const u8, body: []const u8, signature: []const u8) bool { const Hmac = std.crypto.auth.hmac.sha2.HmacSha256; var mac: [Hmac.mac_length]u8 = undefined; Hmac.create(&mac, body, secret); const expected = std.fmt.bytesToHex(mac, .lower); if (signature.len != expected.len) return false; return std.crypto.timing_safe.eql([expected.len]u8, expected, signature[0..expected.len].*);}
/// How far back `/status` looks for finished work unless asked otherwise.pub const default_status_hours = 24;/// How many finished droplets, and runs, `/status` lists unless asked/// otherwise, and the most it will.pub const default_status_limit = 50;pub const max_status_limit = 500;
/// `GET /status`: see the top of this file. `since_hours` and `limit` bound/// what finished lately.fn statusReport(s: *Service, req: *Request, res: *Response) !void { // Not configured is not there at all, rather than there and refusing. const want = s.status_token_sha256 orelse return res.sendStatus(.not_found); if (!std.mem.eql(u8, req.method.name, "GET")) return res.sendStatus(.method_not_allowed); // Its own token, checked here and nowhere else: never `authenticate`, so // a droplet's token is no use for this, nor this token for a droplet's // endpoints. const token = bearer(req) orelse return unauthorized(res); var got: [32]u8 = undefined; std.crypto.hash.sha2.Sha256.hash(token, &got, .{}); // Digests, so their length is fixed and says nothing; compared in // constant time, so the time taken says nothing either. if (!std.crypto.timing_safe.eql([32]u8, got, want)) return unauthorized(res);
var hours: i64 = default_status_hours; var limit: u32 = default_status_limit; var it = req.target.queryIterator(); while (it.next()) |pair| { const value = pair.value orelse continue; if (std.mem.eql(u8, pair.name, "since_hours")) hours = std.fmt.parseInt(i64, value, 10) catch return res.sendStatus(.bad_request); if (std.mem.eql(u8, pair.name, "limit")) limit = std.fmt.parseInt(u32, value, 10) catch return res.sendStatus(.bad_request); } // Nothing older than the retention period is left to find. hours = std.math.clamp(hours, 0, s.config.retention_days * 24); limit = @min(limit, max_status_limit);
const arena = req.arena; const t = s.now(); const since = t - hours * 3600; const live = try s.store.liveDroplets(arena); const recent = try s.store.recentDroplets(arena, since, limit); const recent_runs = try s.store.recentRuns(arena, since, limit); const queued = try s.store.queued(arena); // The runs droplets are bound to that neither list above has: the ones // under way, and the ones finished before `since`. var runs: std.ArrayList(RunStore.Run) = .empty; try runs.appendSlice(arena, try s.store.active(arena)); for ([_][]const RunStore.Droplet{ live, recent }) |rows| for (rows) |row| if (row.binding) |b| switch (b) { .radicle => |id| { if (hasRun(runs.items, id) or hasRun(recent_runs, id)) continue; if (try s.store.get(arena, id)) |r| try runs.append(arena, r); }, .forgejo => {}, };
const published = if (s.board) |b| try b.read(s.io, arena) else null; const report = try StatusBoard.report(arena, .{ .now = t, .config = s.config, .published = published, .live = live, .recent = recent, .queued = queued, .recent_runs = recent_runs, .runs = runs.items, });
try res.setHeader("content-type", "application/json"); // It is somebody's view of the fleet right now, and nothing a proxy // should keep. try res.setHeader("cache-control", "no-store"); var out: Io.Writer.Allocating = .init(arena); try api.status.write(report, &out.writer); try res.send(out.written());}
fn hasRun(runs: []const RunStore.Run, id: u64) bool { for (runs) |r| if (r.id == id) return true; return false;}
fn unauthorized(res: *Response) !void { try res.setHeader("www-authenticate", "Bearer"); return res.sendStatus(.unauthorized);}
/// Prometheus's, on the metrics listener.pub fn metricsHandler(s: *Service, req: *Request, res: *Response) anyerror!void { if (!std.mem.eql(u8, req.target.path, "/metrics")) return res.sendStatus(.not_found); const m = s.metrics orelse return res.sendStatus(.not_found); var out: Io.Writer.Allocating = .init(req.arena); try m.write(&out.writer, try s.store.dropletCounts(req.arena)); try res.setHeader("content-type", "text/plain; version=0.0.4; charset=utf-8"); try res.send(out.written());}
fn bearer(req: *const Request) ?[]const u8 { const value = req.header("authorization") orelse return null; if (value.len <= "Bearer ".len or !std.ascii.eqlIgnoreCase(value[0.."Bearer ".len], "Bearer ")) return null; return value["Bearer ".len..];}
fn job(s: *Service, req: *Request, res: *Response, run: RunStore.Run) !void { try s.store.started(run.id, s.now()); try res.setHeader("content-type", "application/json"); var out: Io.Writer.Allocating = .init(req.arena); try std.json.Stringify.value(Job{ .id = run.id, .rid = run.rid, .commit = run.commit, .image = run.image orelse s.config.runner_image, .shell = run.shell, .nix_config = s.config.job_nix_config, }, .{}, &out.writer); try res.send(out.written());}
fn logChunk(s: *Service, req: *Request, res: *Response, run: RunStore.Run) !void { var seq: ?u64 = null; var it = req.target.queryIterator(); while (it.next()) |pair| { if (std.mem.eql(u8, pair.name, "seq")) seq = std.fmt.parseInt(u64, pair.value orelse "", 10) catch null; } const n = seq orelse return res.sendStatus(.bad_request); const bytes = req.body.readAlloc(req.arena, max_log_chunk_len) catch return res.sendStatus(.payload_too_large); try s.store.appendLog(run.id, n, bytes, s.now()); return res.sendStatus(.no_content);}
fn result(s: *Service, req: *Request, res: *Response, run: RunStore.Run) !void { const body = req.body.readAlloc(req.arena, 1024) catch return res.sendStatus(.payload_too_large); const outcome = std.json.parseFromSliceLeaky(Outcome, req.arena, body, .{}) catch return res.sendStatus(.bad_request); const verdict: RunStore.Result = if (outcome.exit_code == 0) .success else .failure; const reason = if (outcome.exit_code == 0) null else try std.fmt.allocPrint(req.arena, "the script exited with status {d}", .{outcome.exit_code}); try s.store.finish(run.id, verdict, reason, s.now()); log.info("run {d}: {s}", .{ run.id, @tagName(verdict) }); return res.sendStatus(.no_content);}
fn sendFile(s: *Service, req: *Request, res: *Response, path: []const u8, content_type: []const u8) !void { const bytes = Io.Dir.cwd().readFileAlloc(s.io, path, req.arena, .limited(max_source_len)) catch |err| switch (err) { error.FileNotFound, error.IsDir, error.NotDir => return res.sendStatus(.not_found), else => return err, }; try res.setHeader("content-type", content_type); return res.send(bytes);}
fn contentType(name: []const u8) []const u8 { const types = [_]struct { []const u8, []const u8 }{ .{ ".html", "text/html; charset=utf-8" }, .{ ".css", "text/css" }, .{ ".json", "application/json" }, .{ ".rss", "application/rss+xml" }, .{ ".txt", "text/plain; charset=utf-8" }, .{ ".log", "text/plain; charset=utf-8" }, }; for (types) |t| if (std.mem.endsWith(u8, name, t[0])) return t[1]; return "application/octet-stream";}
/// A run's page: what it tested, how it went, and its log so far. It reloads/// itself until the run is over.fn page(s: *Service, req: *Request, res: *Response, run: RunStore.Run) !void { const arena = req.arena; const output = try s.store.log(arena, run.id); var w: Io.Writer.Allocating = .init(arena); const status = if (run.result) |r| @tagName(r) else @tagName(run.state); try w.writer.print( \\<!DOCTYPE html> \\<html lang="en"><head><meta charset="utf-8"> \\<meta name="viewport" content="width=device-width, initial-scale=1"> \\<meta name="robots" content="noindex, nofollow"> \\{s}<title>Run {d}: {s}</title> \\<style> \\:root {{ color-scheme: light dark; font-family: system-ui, sans-serif; }} \\body {{ margin: 0 auto; max-width: 72rem; padding: 1rem; }} \\dl {{ display: grid; grid-template-columns: max-content 1fr; gap: .25rem 1rem; }} \\dt {{ font-weight: 600; }} dd {{ margin: 0; overflow-wrap: anywhere; }} \\pre {{ padding: 1rem; overflow-x: auto; border: 1px solid #8884; border-radius: .25rem; }} \\.success {{ color: #1a7f37; }} .failure, .error {{ color: #cf222e; }} \\</style></head><body> \\<h1>Run {d} <span class="{s}">{s}</span></h1> \\<dl> \\<dt>Repository</dt><dd><code>{f}</code></dd> \\<dt>{s}</dt><dd><code>{f}</code></dd> \\<dt>Commit</dt><dd><code>{f}</code></dd> \\<dt>Tier</dt><dd>{f}</dd> \\ , .{ if (run.state == .finished) "" else "<meta http-equiv=\"refresh\" content=\"10\">\n", run.id, status, run.id, status, status, html(run.rid), if (std.mem.eql(u8, run.event, "patch")) "Patch" else "Branch", html(run.ref), html(run.commit), html(run.tier), }); if (run.reason) |reason| try w.writer.print("<dt>Why</dt><dd>{f}</dd>\n", .{html(reason)}); try w.writer.print( \\</dl> \\<p><a href="/runs/{d}/log.txt">Plain text</a></p> \\<pre>{f}</pre> \\</body></html> \\ , .{ run.id, html(output) }); try res.setHeader("content-type", "text/html; charset=utf-8"); try res.send(w.written());}
const Html = struct { text: []const u8, pub fn format(h: Html, w: *Io.Writer) Io.Writer.Error!void { for (h.text) |c| switch (c) { '<' => try w.writeAll("<"), '>' => try w.writeAll(">"), '&' => try w.writeAll("&"), '"' => try w.writeAll("""), '\'' => try w.writeAll("'"), else => try w.writeByte(c), }; }};
fn html(text: []const u8) Html { return .{ .text = text };}
test "html escaping" { var out: Io.Writer.Allocating = .init(std.testing.allocator); defer out.deinit(); try out.writer.print("{f}", .{html("<script>alert('x' & \"y\")</script>")}); try std.testing.expectEqualStrings("<script>alert('x' & "y")</script>", out.written());}
test { std.testing.refAllDecls(@This());}
// -- the adapter's API, end to end -------------------------------------------
const unix = @import("unix.zig");
/// One request over the socket, as the adapter makes it.fn adapterCall(io: Io, path: []const u8, method: http.protocol.Method, target: []const u8, content: ?[]const u8) !struct { status: u16, body: []u8 } { const gpa = std.testing.allocator; var conn: http.http1.client.Connection = try .init(io, gpa, try unix.connect(io, gpa, path, .{}), .{}); defer conn.deinit(); const response = try conn.send(.{ .method = method, .target = target, .host = "localhost", .body = if (content) |c| .{ .exact = c.len } else .none, .content = content, }); return .{ .status = response.status, .body = try conn.readAll(response, 64 * 1024) };}
test "the adapter's API, over a real socket and a real database" { const testing = std.testing; const gpa = testing.allocator; var threaded: Io.Threaded = .init(gpa, .{}); defer threaded.deinit(); const io = threaded.io();
var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); var db_buf: [128]u8 = undefined; const db_path = try std.fmt.bufPrintZ(&db_buf, ".zig-cache/tmp/{s}/runs.db", .{tmp.sub_path}); var sock_buf: [128]u8 = undefined; const sock_path = try std.fmt.bufPrint(&sock_buf, ".zig-cache/tmp/{s}/a.sock", .{tmp.sub_path});
var store = try RunStore.open(gpa, io, db_path); defer store.deinit(); var service: Service = .{ .io = io, .config = test_config, .store = &store, .tier_names = &.{ "s", "l" }, };
var listener = try unix.Listener.listen(io, sock_path); defer listener.deinit(io); var server: http.server.Server = .init(io, gpa, listener.listener(), .init(&service, adapter), .{}); const serve = struct { fn f(s: *http.server.Server) Io.Cancelable!void { s.serve() catch |err| switch (err) { error.Canceled => return error.Canceled, else => std.debug.panic("serve: {s}", .{@errorName(err)}), }; } }.f; var group: Io.Group = .init; defer group.cancel(io); try group.concurrent(io, serve, .{&server});
var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); const a = arena.allocator();
const submitRun = struct { fn f(al: Allocator, iof: Io, path: []const u8, spec: []const u8) !Submitted { const encoded = try al.alloc(u8, std.base64.standard.Encoder.calcSize(4)); _ = std.base64.standard.Encoder.encode(encoded, "tar!"); var body: Io.Writer.Allocating = .init(al); try std.json.Stringify.value(Submission{ .rid = "rad:z3QNJRPpssgFMdfjV8Pgsopix3qE4", .commit = "0d2b0335d245f58375385a9ebb076a72d9398a48", .event = .push, .ref = "main", .spec = spec, .source = encoded, }, .{}, &body.writer); const r = try adapterCall(iof, path, .post, "/runs", body.written()); defer std.testing.allocator.free(r.body); try std.testing.expectEqual(@as(u16, 201), r.status); return std.json.parseFromSliceLeaky(Submitted, al, try al.dupe(u8, r.body), .{ .allocate = .alloc_always }); } }.f;
// A good run is queued, with its source, and its page is the info URL. const good = try submitRun(a, io, sock_path, "tier: l\nshell: |\n make check\n"); try testing.expectEqualStrings(try std.fmt.allocPrint(a, "https://ci.example.org/runs/{d}", .{good.id}), good.info_url); const queued = (try store.get(a, good.id)).?; try testing.expectEqual(RunStore.State.queued, queued.state); try testing.expectEqualStrings("l", queued.tier); try testing.expectEqualStrings("make check\n", queued.shell); try testing.expectEqualStrings("tar!", (try store.source(a, good.id)).?);
// A droplet.yaml that cannot run is still a run: finished at once, with // the reason, so the broker is told and the page says why. const bad = try submitRun(a, io, sock_path, "tier: xl\nshell: make\n"); const refused = (try store.get(a, bad.id)).?; try testing.expectEqual(RunStore.State.finished, refused.state); try testing.expectEqual(@as(?RunStore.Result, .@"error"), refused.result); try testing.expect(std.mem.indexOf(u8, refused.reason.?, "tier") != null); { const r = try adapterCall(io, sock_path, .get, try std.fmt.allocPrint(a, "/runs/{d}/wait", .{bad.id}), null); defer gpa.free(r.body); const waited = try std.json.parseFromSliceLeaky(Waited, a, try a.dupe(u8, r.body), .{ .allocate = .alloc_always }); try testing.expectEqual(@as(?RunStore.Result, .@"error"), waited.result); }
// `/wait` answers as soon as the run ends: finish it while the adapter is // waiting, and the answer is the result rather than the state so far. const finisher = struct { fn f(s: *RunStore, iof: Io, id: u64) Io.Cancelable!void { try Io.sleep(iof, .fromSeconds(1), .awake); s.finish(id, .success, null, 1) catch unreachable; } }.f; try group.concurrent(io, finisher, .{ &store, io, good.id }); { const r = try adapterCall(io, sock_path, .get, try std.fmt.allocPrint(a, "/runs/{d}/wait", .{good.id}), null); defer gpa.free(r.body); const waited = try std.json.parseFromSliceLeaky(Waited, a, try a.dupe(u8, r.body), .{ .allocate = .alloc_always }); try testing.expectEqual(RunStore.State.finished, waited.state); try testing.expectEqual(@as(?RunStore.Result, .success), waited.result); }
// A malformed submission is refused outright, and nothing is recorded. { const r = try adapterCall(io, sock_path, .post, "/runs", "{\"rid\":\"rad:z3uB/../../etc\"}"); defer gpa.free(r.body); try testing.expectEqual(@as(u16, 400), r.status); } try testing.expectEqual(null, try store.get(a, bad.id + 1));}
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, .job_nix_config = "max-jobs = auto\n", .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" }},};
/// One request to the droplets' API, as the agent makes it.fn dropletCall(io: Io, path: []const u8, method: http.protocol.Method, target: []const u8, token: []const u8, content: ?[]const u8) !struct { status: u16, body: []u8 } { const gpa = std.testing.allocator; var conn: http.http1.client.Connection = try .init(io, gpa, try unix.connect(io, gpa, path, .{}), .{}); defer conn.deinit(); var auth_buf: [128]u8 = undefined; var fields = [_]http.protocol.Headers.Field{.{ .name = "authorization", .value = try std.fmt.bufPrint(&auth_buf, "Bearer {s}", .{token}) }}; const response = try conn.send(.{ .method = method, .target = target, .host = "localhost", .headers = .initBorrowed(&fields), .body = if (content) |c| .{ .exact = c.len } else .none, .content = content, }); return .{ .status = response.status, .body = try conn.readAll(response, 64 * 1024) };}
test "the droplets' API, over a real socket and a real database" { const testing = std.testing; const gpa = testing.allocator; var threaded: Io.Threaded = .init(gpa, .{}); defer threaded.deinit(); const io = threaded.io();
var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); var db_buf: [128]u8 = undefined; const db_path = try std.fmt.bufPrintZ(&db_buf, ".zig-cache/tmp/{s}/runs.db", .{tmp.sub_path}); var sock_buf: [128]u8 = undefined; const sock_path = try std.fmt.bufPrint(&sock_buf, ".zig-cache/tmp/{s}/p.sock", .{tmp.sub_path});
var store = try RunStore.open(gpa, io, db_path); defer store.deinit(); var service: Service = .{ .io = io, .config = test_config, .store = &store, .tier_names = &.{ "s", "l" } };
var listener = try unix.Listener.listen(io, sock_path); defer listener.deinit(io); var server: http.server.Server = .init(io, gpa, listener.listener(), .init(&service, public), .{}); const serve = struct { fn f(sv: *http.server.Server) Io.Cancelable!void { sv.serve() catch |err| switch (err) { error.Canceled => return error.Canceled, else => std.debug.panic("serve: {s}", .{@errorName(err)}), }; } }.f; var group: Io.Group = .init; defer group.cancel(io); try group.concurrent(io, serve, .{&server});
var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); const a = arena.allocator();
// A Forgejo droplet is handed its job and its runner. const fj = try store.createDroplet(.{ .tier = "s", .queued_at = 1, .token = "fj-token", .work = .{ .forgejo = .{ .forge = "ocjtech", .handle = "handle-1", .runner = .{ .id = 7, .uuid = "uuid-7", .token = "runner-secret" } } }, }, 2); try store.dropletCreated(fj, 555, "s-2vcpu-4gb", "snap"); { const r = try dropletCall(io, sock_path, .post, "/droplet/v1/claim", "fj-token", "{\"uptime_seconds\":20,\"boot_report\":\"blame\"}"); defer gpa.free(r.body); try testing.expectEqual(@as(u16, 200), r.status); const got = try std.json.parseFromSliceLeaky(api.droplet.Assignment, a, try a.dupe(u8, r.body), .{ .allocate = .alloc_always }); try testing.expectEqualStrings("https://git.jcollie.dev", got.forgejo.url); try testing.expectEqualStrings("runner-secret", got.forgejo.runner_token); try testing.expectEqualStrings("handle-1", got.forgejo.handle); try testing.expectEqualStrings("nixos-do-s", got.forgejo.label); try testing.expectEqualStrings("runner-image", got.forgejo.image); try testing.expectEqualStrings("max-jobs = auto\n", got.forgejo.nix_config); } const claimed = (try store.getDroplet(a, fj)).?; try testing.expectEqual(RunStore.DropletState.claimed, claimed.state); try testing.expect(claimed.booted_at.? == claimed.agent_at.? - 20); // Radicle's endpoints are not a Forgejo droplet's. { const r = try dropletCall(io, sock_path, .get, "/droplet/v1/job", "fj-token", null); defer gpa.free(r.body); try testing.expectEqual(@as(u16, 404), r.status); } { const r = try dropletCall(io, sock_path, .post, "/droplet/v1/done", "fj-token", "{\"exit_code\":0}"); defer gpa.free(r.body); try testing.expectEqual(@as(u16, 204), r.status); } try testing.expectEqual(RunStore.DropletState.done, (try store.getDroplet(a, fj)).?.state); // A droplet that is done has nothing more to claim. { const r = try dropletCall(io, sock_path, .post, "/droplet/v1/claim", "fj-token", "{}"); defer gpa.free(r.body); try testing.expectEqual(@as(u16, 410), r.status); } // Nor does one that is gone, or a stranger. try store.dropletGone(fj, 100); for ([_][]const u8{ "fj-token", "nobody" }) |token| { const r = try dropletCall(io, sock_path, .post, "/droplet/v1/claim", token, "{}"); defer gpa.free(r.body); try testing.expectEqual(@as(u16, 401), r.status); }
// A Radicle droplet is handed its run, and may then act for it. const run = try store.create(.{ .rid = "rad:z3QNJRPpssgFMdfjV8Pgsopix3qE4", .commit = "0d2b0335d245f58375385a9ebb076a72d9398a48", .event = "push", .ref = "main", .tier = "l", .image = null, .shell = "make\n", .source = "tar!" }, 3); const rad = try store.createDroplet(.{ .tier = "l", .queued_at = 3, .token = "rad-token", .work = .{ .radicle = run } }, 4); try store.dropletCreated(rad, 556, "s-4vcpu-8gb", "snap"); try testing.expect(try store.provisioned(run, 556, 4)); { const r = try dropletCall(io, sock_path, .post, "/droplet/v1/claim", "rad-token", "{}"); defer gpa.free(r.body); try testing.expectEqualStrings(try std.fmt.allocPrint(a, "{{\"radicle\":{d}}}", .{run}), r.body); } { const r = try dropletCall(io, sock_path, .get, "/droplet/v1/job", "rad-token", null); defer gpa.free(r.body); try testing.expectEqual(@as(u16, 200), r.status); const job_ = try std.json.parseFromSliceLeaky(Job, a, try a.dupe(u8, r.body), .{ .allocate = .alloc_always }); try testing.expectEqualStrings("make\n", job_.shell); } try testing.expect((try store.getDroplet(a, rad)).?.work_started_at != null); // Done without a result: the run is failed, and says why. { const r = try dropletCall(io, sock_path, .post, "/droplet/v1/done", "rad-token", "{\"exit_code\":125}"); defer gpa.free(r.body); try testing.expectEqual(@as(u16, 204), r.status); } const failed = (try store.get(a, run)).?; try testing.expectEqual(@as(?RunStore.Result, .@"error"), failed.result); try testing.expect(std.mem.indexOf(u8, failed.reason.?, "125") != null); // and the run's endpoints close with it { const r = try dropletCall(io, sock_path, .get, "/droplet/v1/source", "rad-token", null); defer gpa.free(r.body); try testing.expectEqual(@as(u16, 404), r.status); }}
test "the status API, over a real socket and a real database" { const testing = std.testing; const gpa = testing.allocator; var threaded: Io.Threaded = .init(gpa, .{}); defer threaded.deinit(); const io = threaded.io();
var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); var db_buf: [128]u8 = undefined; const db_path = try std.fmt.bufPrintZ(&db_buf, ".zig-cache/tmp/{s}/runs.db", .{tmp.sub_path}); var sock_buf: [128]u8 = undefined; const sock_path = try std.fmt.bufPrint(&sock_buf, ".zig-cache/tmp/{s}/s.sock", .{tmp.sub_path}); var bare_buf: [128]u8 = undefined; const bare_path = try std.fmt.bufPrint(&bare_buf, ".zig-cache/tmp/{s}/n.sock", .{tmp.sub_path});
var store = try RunStore.open(gpa, io, db_path); defer store.deinit(); var board: StatusBoard = .{}; defer board.deinit(); var want: [32]u8 = undefined; std.crypto.hash.sha2.Sha256.hash("status-secret", &want, .{}); var service: Service = .{ .io = io, .config = test_config, .store = &store, .tier_names = &.{ "s", "l" }, .board = &board, .status_token_sha256 = want, }; // One with no token, which has no `/status` at all. var bare: Service = .{ .io = io, .config = test_config, .store = &store, .tier_names = &.{ "s", "l" } };
var listener = try unix.Listener.listen(io, sock_path); defer listener.deinit(io); var bare_listener = try unix.Listener.listen(io, bare_path); defer bare_listener.deinit(io); var server: http.server.Server = .init(io, gpa, listener.listener(), .init(&service, public), .{}); var bare_server: http.server.Server = .init(io, gpa, bare_listener.listener(), .init(&bare, public), .{}); const serve = struct { fn f(sv: *http.server.Server) Io.Cancelable!void { sv.serve() catch |err| switch (err) { error.Canceled => return error.Canceled, else => std.debug.panic("serve: {s}", .{@errorName(err)}), }; } }.f; var group: Io.Group = .init; defer group.cancel(io); try group.concurrent(io, serve, .{&server}); try group.concurrent(io, serve, .{&bare_server});
var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); const a = arena.allocator();
// A droplet at work on a Forgejo job, one whose work is over, a Radicle // run waiting, and a job the forge lists that has nothing yet. const t = service.now(); const fj = try store.createDroplet(.{ .tier = "s", .queued_at = t - 60, .token = "fj-token", .work = .{ .forgejo = .{ .forge = "ocjtech", .handle = "at-work", .runner = .{ .id = 7, .uuid = "uuid-7", .token = "runner-secret" } } }, }, t - 50); try store.dropletCreated(fj, 555, "s-2vcpu-4gb", "snap"); const over = try store.createDroplet(.{ .tier = "s", .queued_at = t - 600, .token = "over-token", .work = .{ .forgejo = .{ .forge = "ocjtech", .handle = "over", .runner = .{ .id = 8, .uuid = "uuid-8", .token = "x" } } }, }, t - 500); try store.dropletCreated(over, 556, "s-2vcpu-4gb", "snap"); try store.dropletDone(over, 3, t - 100); try store.dropletGone(over, t - 90); const queued = try store.create(.{ .rid = "rad:z3QNJRPpssgFMdfjV8Pgsopix3qE4", .commit = "0d2b0335d245f58375385a9ebb076a72d9398a48", .event = "push", .ref = "main", .tier = "l", .image = null, .shell = "make\n", .source = "tar!" }, t - 30); try board.publish(io, gpa, .{ .at = t, .forges = &.{.{ .name = "ocjtech", .url = "https://git.jcollie.dev", .last_poll = t, .last_ok = t }}, .jobs = &.{ .{ .forge = "ocjtech", .handle = "at-work", .id = 1, .name = "check", .status = "running", .tier = "s", .first_seen = t - 60 }, .{ .forge = "ocjtech", .handle = "waits", .id = 2, .name = "build", .status = "waiting", .tier = "s", .first_seen = t - 20 }, }, .backoff = &.{.{ .key = "ocjtech/waits", .failures = 2, .until = t + 120 }}, .standing = &.{ 1, 0 }, });
// No token, the wrong one, and a droplet's are all refused, and the // status token opens nothing of a droplet's. { const r = try adapterCall(io, sock_path, .get, "/status", null); defer gpa.free(r.body); try testing.expectEqual(@as(u16, 401), r.status); } for ([_][]const u8{ "wrong", "fj-token" }) |token| { const r = try dropletCall(io, sock_path, .get, "/status", token, null); defer gpa.free(r.body); try testing.expectEqual(@as(u16, 401), r.status); } { const r = try dropletCall(io, sock_path, .post, "/droplet/v1/claim", "status-secret", "{}"); defer gpa.free(r.body); try testing.expectEqual(@as(u16, 401), r.status); } { const r = try dropletCall(io, sock_path, .post, "/status", "status-secret", "{}"); defer gpa.free(r.body); try testing.expectEqual(@as(u16, 405), r.status); }
{ const r = try dropletCall(io, sock_path, .get, "/status", "status-secret", null); defer gpa.free(r.body); try testing.expectEqual(@as(u16, 200), r.status); const got = try api.status.parse(a, try a.dupe(u8, r.body)); try testing.expectEqual(@as(?i64, t), got.snapshot_at);
try testing.expectEqual(@as(usize, 2), got.pending.len); try testing.expectEqual(queued, got.pending[0].work.radicle.id); try testing.expectEqualStrings("waits", got.pending[1].work.forgejo.handle); try testing.expectEqual(@as(u32, 2), got.pending[1].backoff.?.failures);
try testing.expectEqual(@as(usize, 1), got.running.len); try testing.expectEqualStrings(try std.fmt.allocPrint(a, "ci-droplet-{d}", .{fj}), got.running[0].name); try testing.expectEqual(@as(?u64, 555), got.running[0].do_id); try testing.expectEqualStrings("check", got.running[0].work.forgejo.name.?);
try testing.expectEqual(@as(usize, 1), got.finished.len); try testing.expectEqual(@as(?i64, 3), got.finished[0].exit_code); try testing.expectEqual(api.status.DropletState.gone, got.finished[0].state);
try testing.expectEqual(@as(u32, 1), got.tiers[0].live); try testing.expectEqual(@as(?u32, 1), got.tiers[0].standing); } // A window that ends before the droplet's work did leaves it out. { const r = try dropletCall(io, sock_path, .get, "/status?since_hours=0", "status-secret", null); defer gpa.free(r.body); const got = try api.status.parse(a, try a.dupe(u8, r.body)); try testing.expectEqual(@as(usize, 0), got.finished.len); } { const r = try dropletCall(io, sock_path, .get, "/status?limit=many", "status-secret", null); defer gpa.free(r.body); try testing.expectEqual(@as(u16, 400), r.status); }
// Unconfigured, there is nothing there, whoever asks. { const r = try dropletCall(io, bare_path, .get, "/status", "status-secret", null); defer gpa.free(r.body); try testing.expectEqual(@as(u16, 404), r.status); }}
test "webhook signatures" { // RFC 4231 test case 2. try std.testing.expect(validSignature("Jefe", "what do ya want for nothing?", "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843")); try std.testing.expect(!validSignature("Jefe", "what do ya want for nothing?", "5BDCC146BF60754E6A042426089575C75A003F089D2739839DEC58B964EC3843")); try std.testing.expect(!validSignature("Jefe", "what do ya want for nothing!", "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843")); try std.testing.expect(!validSignature("Jefe", "what do ya want for nothing?", "5bdcc146")); try std.testing.expect(!validSignature("Jefe", "what do ya want for nothing?", ""));}
test "webhooks prompt a poll, and a Forgejo droplet's done does too" { const testing = std.testing; const gpa = testing.allocator; var threaded: Io.Threaded = .init(gpa, .{}); defer threaded.deinit(); const io = threaded.io();
var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); var db_buf: [128]u8 = undefined; const db_path = try std.fmt.bufPrintZ(&db_buf, ".zig-cache/tmp/{s}/runs.db", .{tmp.sub_path}); var sock_buf: [128]u8 = undefined; const sock_path = try std.fmt.bufPrint(&sock_buf, ".zig-cache/tmp/{s}/w.sock", .{tmp.sub_path});
var store = try RunStore.open(gpa, io, db_path); defer store.deinit(); var prompts = [_]std.atomic.Value(i64){.init(0)}; var wake: Io.Event = .unset; var service: Service = .{ .io = io, .config = test_config, .store = &store, .tier_names = &.{ "s", "l" }, .wake = &wake, .prompts = &prompts, .webhook_secrets = &.{"hush"}, };
var listener = try unix.Listener.listen(io, sock_path); defer listener.deinit(io); var server: http.server.Server = .init(io, gpa, listener.listener(), .init(&service, public), .{}); const serve = struct { fn f(sv: *http.server.Server) Io.Cancelable!void { sv.serve() catch |err| switch (err) { error.Canceled => return error.Canceled, else => std.debug.panic("serve: {s}", .{@errorName(err)}), }; } }.f; var group: Io.Group = .init; defer group.cancel(io); try group.concurrent(io, serve, .{&server});
const Hook = struct { fn call(iof: Io, path: []const u8, target: []const u8, event: []const u8, signature: ?[]const u8, body: []const u8) !u16 { const alloc = std.testing.allocator; var conn: http.http1.client.Connection = try .init(iof, alloc, try unix.connect(iof, alloc, path, .{}), .{}); defer conn.deinit(); var fields: [2]http.protocol.Headers.Field = undefined; var n: usize = 0; fields[n] = .{ .name = "x-forgejo-event-type", .value = event }; n += 1; if (signature) |sig| { fields[n] = .{ .name = "x-forgejo-signature", .value = sig }; n += 1; } const response = try conn.send(.{ .method = .post, .target = target, .host = "localhost", .headers = .initBorrowed(fields[0..n]), .body = .{ .exact = body.len }, .content = body, }); const got = try conn.readAll(response, 64 * 1024); alloc.free(got); return response.status; } fn sign(secret: []const u8, body: []const u8) [64]u8 { const Hmac = std.crypto.auth.hmac.sha2.HmacSha256; var mac: [Hmac.mac_length]u8 = undefined; Hmac.create(&mac, body, secret); return std.fmt.bytesToHex(mac, .lower); } };
const body = "{\"ref\":\"refs/heads/main\"}"; const good = Hook.sign("hush", body); const target = "/forgejo/ocjtech/webhook";
// Unsigned, badly signed, or for a forge with no webhook: refused, and // nothing prompted. try testing.expectEqual(@as(u16, 401), try Hook.call(io, sock_path, target, "push", null, body)); const wrong = Hook.sign("guess", body); try testing.expectEqual(@as(u16, 401), try Hook.call(io, sock_path, target, "push", &wrong, body)); try testing.expectEqual(@as(u16, 404), try Hook.call(io, sock_path, "/forgejo/codeberg/webhook", "push", &good, body)); try testing.expectEqual(@as(i64, 0), prompts[0].load(.acquire)); try testing.expect(!wake.isSet());
// Signed, but not an event that makes runs: accepted and ignored. try testing.expectEqual(@as(u16, 204), try Hook.call(io, sock_path, target, "issues", &good, body)); try testing.expectEqual(@as(i64, 0), prompts[0].load(.acquire));
// A signed push prompts the forge and wakes the scheduler. try testing.expectEqual(@as(u16, 204), try Hook.call(io, sock_path, target, "push", &good, body)); try testing.expect(prompts[0].load(.acquire) > 0); try testing.expect(wake.isSet()); wake.reset(); prompts[0].store(0, .release);
// Too big to read: refused. const big = try gpa.alloc(u8, max_webhook_len + 1); defer gpa.free(big); @memset(big, 'x'); const big_sig = Hook.sign("hush", big); try testing.expectEqual(@as(u16, 413), try Hook.call(io, sock_path, target, "push", &big_sig, big));
// A Forgejo droplet saying it is done prompts its forge too. const fj = try store.createDroplet(.{ .tier = "s", .queued_at = 1, .token = "fj-token", .work = .{ .forgejo = .{ .forge = "ocjtech", .handle = "h", .runner = .{ .id = 7, .uuid = "u", .token = "t" } } }, }, 2); try store.dropletCreated(fj, 555, "s-2vcpu-4gb", "snap"); { const r = try dropletCall(io, sock_path, .post, "/droplet/v1/done", "fj-token", "{\"exit_code\":0}"); defer gpa.free(r.body); try testing.expectEqual(@as(u16, 204), r.status); } try testing.expect(prompts[0].load(.acquire) > 0); try testing.expect(wake.isSet());}
test "a warm droplet's claim waits for the work it is given" { const testing = std.testing; const gpa = testing.allocator; var threaded: Io.Threaded = .init(gpa, .{}); defer threaded.deinit(); const io = threaded.io();
var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); var db_buf: [128]u8 = undefined; const db_path = try std.fmt.bufPrintZ(&db_buf, ".zig-cache/tmp/{s}/runs.db", .{tmp.sub_path}); var sock_buf: [128]u8 = undefined; const sock_path = try std.fmt.bufPrint(&sock_buf, ".zig-cache/tmp/{s}/c.sock", .{tmp.sub_path});
var store = try RunStore.open(gpa, io, db_path); defer store.deinit(); var service: Service = .{ .io = io, .config = test_config, .store = &store, .tier_names = &.{ "s", "l" } };
var listener = try unix.Listener.listen(io, sock_path); defer listener.deinit(io); var server: http.server.Server = .init(io, gpa, listener.listener(), .init(&service, public), .{}); const serve = struct { fn f(sv: *http.server.Server) Io.Cancelable!void { sv.serve() catch |err| switch (err) { error.Canceled => return error.Canceled, else => std.debug.panic("serve: {s}", .{@errorName(err)}), }; } }.f; var group: Io.Group = .init; defer group.cancel(io); try group.concurrent(io, serve, .{&server});
const warm = try store.createDroplet(.{ .tier = "s", .queued_at = null, .token = "warm-token", .work = .pool }, 1); try store.dropletCreated(warm, 555, "s-2vcpu-4gb", "snap");
// The scheduler hands it a job two seconds into its wait. const giver = struct { fn f(s: *RunStore, iof: Io, id: u64) Io.Cancelable!void { try Io.sleep(iof, .fromSeconds(2), .awake); _ = s.assignForgejo(id, .{ .forge = "ocjtech", .handle = "late", .runner = .{ .id = 9, .uuid = "u9", .token = "t9" } }, 3) catch unreachable; } }.f; try group.concurrent(io, giver, .{ &store, io, warm });
var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); const r = try dropletCall(io, sock_path, .post, "/droplet/v1/claim", "warm-token", "{\"uptime_seconds\":15}"); defer gpa.free(r.body); try testing.expectEqual(@as(u16, 200), r.status); const got = try std.json.parseFromSliceLeaky(api.droplet.Assignment, arena.allocator(), try arena.allocator().dupe(u8, r.body), .{ .allocate = .alloc_always }); try testing.expectEqualStrings("late", got.forgejo.handle); try testing.expectEqualStrings("t9", got.forgejo.runner_token); try testing.expectEqual(RunStore.DropletState.claimed, (try store.getDroplet(arena.allocator(), warm)).?.state);}