// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The daemon's configuration: one JSON file, written by the NixOS module. //! //! Secrets are not in it. They arrive as systemd credentials, named here and //! read from `$CREDENTIALS_DIRECTORY`, so the file can sit in the Nix store. //! //! Unknown fields are an error rather than ignored: a misspelt option that //! was silently dropped would leave its default in force with nothing to say //! so, and the defaults here include spending limits. const std = @import("std"); const tags = @import("tags.zig"); const Config = @This(); /// DigitalOcean region every droplet is created in. region: []const u8, /// The image to boot when no prepared snapshot exists yet: a stock slug. base_image: []const u8, /// Snapshots named `-*` are prepared images, and the newest /// is booted in preference to `base_image`. snapshot_prefix: []const u8, /// Account SSH keys put on every droplet, by fingerprint or numeric id. A /// fingerprint names the same key in every team, where an id only means /// something in the team that issued it. ssh_keys: []const []const u8 = &.{}, /// DNS resolvers every droplet uses, in order, as IP addresses: a resolver /// in the droplets' own VPC whose cache stays warm across jobs, say. Written /// into the droplet's systemd-resolved configuration and into podman's, so /// that the job's containers use them too. Empty leaves the image's own. resolvers: []const []const u8 = &.{}, /// Tried by the job's containers after `resolvers`, so that a resolver that /// is down costs a timeout rather than a failed job. fallback_resolvers: []const []const u8 = &.{}, /// The container image jobs run in. runner_image: []const u8, /// The static forgejo-runner binary a droplet booted from `base_image` /// downloads, and the SHA-256 it is checked against before it runs. runner_binary_url: []const u8, runner_binary_sha256: []const u8, /// Handed to every step of every Forgejo job as `NIX_CONFIG`, merged by Nix /// over the job image's own nix.conf: the fleet's binary cache, and build /// parallelism suited to a machine that runs one job and nothing else. job_nix_config: []const u8 = "", /// A droplet older than this is destroyed whatever it is doing. max_lifetime_seconds: i64 = 7200, /// How long a droplet is left alone before "its runner is missing" or "its /// job is gone" can be believed: a runner registered moments ago may not be /// in a listing yet. grace_seconds: i64 = 120, /// How often the scheduler wakes. Each source is polled on its own interval; /// this is only the resolution of those intervals. tick_seconds: i64 = 5, /// The size the snapshot builder boots, and how many of the newest /// `-*` snapshots it keeps. builder_size: []const u8 = "s-2vcpu-4gb", snapshot_keep: u32 = 2, /// Recognise the Python provisioners' `forgejo-ephemeral--` /// tags as well, so their droplets are counted and reaped. For the cutover. legacy_tags: bool = false, /// Log what would be created and destroyed, and do neither. dry_run: bool = false, /// The address the droplet API and the run pages listen on, for a reverse /// proxy to put on the internet. listen: []const u8 = "[::1]:8094", /// The address that proxy serves them at, as a droplet and a browser reach /// it: `https://ci.example.org`, with no trailing slash. Every droplet asks /// here for its work. public_url: []const u8, /// The static `ci-agent` binary every droplet downloads and runs. agent: []const u8, /// The SQLite database of droplets and runs. database: []const u8 = "/var/lib/ci-autoscaler/state.db", /// Where `/metrics` is served for Prometheus, or null for nowhere. Not the /// public listener: it is for the monitoring host, not the internet. metrics_listen: ?[]const u8 = null, /// The systemd credential holding the bearer token `GET /status` asks for, /// on the public listener. Null serves no `/status`. status_credential: ?[]const u8 = null, /// A droplet whose agent has not asked for its work this long after it was /// created never booted. boot_timeout_seconds: i64 = 900, /// A running Radicle droplet silent for this long is gone. heartbeat_timeout_seconds: i64 = 300, /// How long finished runs, their logs, and the record of destroyed droplets /// are kept. retention_days: i64 = 90, /// How long a tier stays warm after work last started in it: while it does, /// its `warm` idle droplets are kept booted and waiting, and afterwards they /// are destroyed. Jobs come in bursts -- the rest of a workflow, the next /// push -- so this is how long a burst is expected to last. warm_linger_seconds: i64 = 900, tiers: []const Tier, forges: []const Forge = &.{}, /// Radicle CI, through radicle-ci-broker and `ci-autoscaler adapter`. Null /// for none. radicle: ?Radicle = null, pub const Radicle = struct { /// Where the adapter reaches the daemon, when systemd has not passed the /// socket in already. adapter_socket: []const u8 = "/run/ci-autoscaler/adapter.sock", /// The broker's HTML reports, served under `/reports/`, or null. report_dir: ?[]const u8 = null, }; pub const Tier = struct { /// `s`, `m`, `l`: the suffix of the `runs-on` label, and the /// `.radicle/droplet.yaml` `tier`. name: []const u8, /// A DigitalOcean size slug. size: []const u8, /// Sizes to try in turn when DigitalOcean refuses `size` with a 422 -- /// "Size is not available in this region" when a region runs short, or /// "currently restricted" for an account tier. The same vCPUs and memory /// in another class, so the job gets what it asked for. fallback_sizes: []const []const u8 = &.{}, /// How many droplets of this tier may exist at once, across every source. /// A spending limit as much as a concurrency one. max: u32, /// How many idle droplets to keep booted and waiting while the tier is /// warm (see `warm_linger_seconds`), so that the next piece of work /// starts in seconds rather than waiting for DigitalOcean to make a /// droplet. Each still runs one job and is then destroyed. They count /// against `max`, and queued work always comes first. warm: u32 = 0, }; pub const Forge = struct { /// A short name, used in tags: lowercase letters and digits. name: []const u8, /// The address every job sees as its server, and the one /// `actions/checkout` clones from. The runner reports whatever it was /// configured with and discards the forge's own ROOT_URL. url: []const u8, /// `admin` needs instance admin rights; `user` is the same runner API for /// an ordinary account, which is what a shared forge like Codeberg allows. scope: Scope = .admin, /// The systemd credential holding the API token. credential: []const u8, poll_seconds: i64 = 15, /// The systemd credential holding the secret this forge's webhooks are /// signed with, or null for no webhook. A signed `push`, `create`, /// `release`, `pull_request`, `pull_request_sync` or `workflow_dispatch` /// delivered to `/forgejo//webhook` makes the daemon /// poll this forge a few times over the next seconds, since a workflow /// run is made from the same event. It never provisions from the payload. webhook_credential: ?[]const u8 = null, /// A job asking for `` is one of ours. label_prefix: []const u8 = "nixos-do-", }; pub const Scope = enum { admin, user }; pub const Error = error{InvalidConfig}; /// Parses and checks `text`. Everything returned lives in `arena`. pub fn parse(arena: std.mem.Allocator, text: []const u8, diagnostic: *[]const u8) (Error || std.mem.Allocator.Error)!Config { const config = std.json.parseFromSliceLeaky(Config, arena, text, .{ .ignore_unknown_fields = false, .allocate = .alloc_always, }) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, else => { diagnostic.* = @errorName(err); return error.InvalidConfig; }, }; try config.check(diagnostic); return config; } fn check(config: Config, diagnostic: *[]const u8) Error!void { const fail = struct { fn f(d: *[]const u8, message: []const u8) Error { d.* = message; return error.InvalidConfig; } }.f; if (config.tiers.len == 0) return fail(diagnostic, "no tiers"); for (config.tiers, 0..) |tier, i| { if (!tags.validName(tier.name)) return fail(diagnostic, "a tier name is not lowercase letters and digits"); for (config.tiers[0..i]) |other| if (std.mem.eql(u8, tier.name, other.name)) return fail(diagnostic, "two tiers have the same name"); } for (config.forges, 0..) |forge, i| { if (!tags.validName(forge.name)) return fail(diagnostic, "a forge name is not lowercase letters and digits"); if (std.mem.eql(u8, forge.name, "radicle")) return fail(diagnostic, "`radicle` is reserved for Radicle runs"); if (std.mem.eql(u8, forge.name, "pool")) return fail(diagnostic, "`pool` is reserved for idle droplets"); for (config.forges[0..i]) |other| if (std.mem.eql(u8, forge.name, other.name)) return fail(diagnostic, "two forges have the same name"); if (forge.poll_seconds < 1) return fail(diagnostic, "a forge's poll_seconds is below 1"); if (!std.mem.startsWith(u8, forge.url, "https://")) return fail(diagnostic, "a forge URL is not https"); } if (config.runner_binary_sha256.len != 64) return fail(diagnostic, "runner_binary_sha256 is not 64 hex digits"); for (config.runner_binary_sha256) |c| switch (c) { '0'...'9', 'a'...'f' => {}, else => return fail(diagnostic, "runner_binary_sha256 is not lowercase hex"), }; // Plain HTTP only on loopback, where there is nobody on the path to read // a droplet's token; that is for trying the daemon out. const loopback = std.mem.startsWith(u8, config.public_url, "http://127.0.0.1:") or std.mem.startsWith(u8, config.public_url, "http://[::1]:") or std.mem.startsWith(u8, config.public_url, "http://localhost:"); if (!std.mem.startsWith(u8, config.public_url, "https://") and !loopback) return fail(diagnostic, "public_url is not https"); if (std.mem.endsWith(u8, config.public_url, "/")) return fail(diagnostic, "public_url ends in a slash"); _ = std.Io.net.IpAddress.parseLiteral(config.listen) catch return fail(diagnostic, "listen is not an address and port"); if (config.metrics_listen) |m| _ = std.Io.net.IpAddress.parseLiteral(m) catch return fail(diagnostic, "metrics_listen is not an address and port"); for (config.resolvers) |r| _ = std.Io.net.IpAddress.parse(r, 53) catch return fail(diagnostic, "a resolver is not an IP address"); for (config.fallback_resolvers) |r| _ = std.Io.net.IpAddress.parse(r, 53) catch return fail(diagnostic, "a fallback resolver is not an IP address"); if (config.resolvers.len + config.fallback_resolvers.len > 3) return fail(diagnostic, "more than three resolvers, which is all a resolv.conf can use"); for (config.tiers) |tier| if (tier.warm > tier.max) return fail(diagnostic, "a tier keeps more droplets warm than its max"); if (config.warm_linger_seconds < 0) return fail(diagnostic, "warm_linger_seconds is negative"); if (config.boot_timeout_seconds < 1) return fail(diagnostic, "boot_timeout_seconds is below 1"); if (config.heartbeat_timeout_seconds < 1) return fail(diagnostic, "heartbeat_timeout_seconds is below 1"); if (config.tick_seconds < 1) return fail(diagnostic, "tick_seconds is below 1"); if (config.grace_seconds < 0) return fail(diagnostic, "grace_seconds is negative"); if (config.max_lifetime_seconds <= config.grace_seconds) return fail(diagnostic, "max_lifetime_seconds is not above grace_seconds"); } pub fn findTier(config: Config, name: []const u8) ?Tier { for (config.tiers) |t| if (std.mem.eql(u8, t.name, name)) return t; return null; } const testing = std.testing; const example = \\{ \\ "region": "nyc3", \\ "base_image": "ubuntu-26-04-x64", \\ "snapshot_prefix": "forgejo-runner", \\ "ssh_keys": ["71:25:77:e8:e6:2c:73:56:40:47:a3:b6:55:07:40:96"], \\ "runner_image": "git.jcollie.dev/jeff/nixos-runner:50-1-0dbdc124", \\ "runner_binary_url": "https://code.forgejo.org/forgejo/runner/releases/download/v13.1.0/forgejo-runner-13.1.0-linux-amd64", \\ "runner_binary_sha256": "29dae21e93f0eab5cdf3564008d44603c74770b41a4f4f1aceed172c774bc376", \\ "public_url": "https://ci.example.org", \\ "agent": "/run/current-system/sw/bin/ci-agent", \\ "tiers": [ \\ { "name": "s", "size": "s-2vcpu-4gb", "max": 5 }, \\ { "name": "l", "size": "s-8vcpu-16gb", "max": 1 } \\ ], \\ "forges": [ \\ { "name": "ocjtech", "url": "https://git.jcollie.dev", "credential": "forge-ocjtech" }, \\ { "name": "codeberg", "url": "https://codeberg.org", "scope": "user", "credential": "forge-codeberg", "poll_seconds": 60 } \\ ] \\} ; test "the example parses" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); var diagnostic: []const u8 = ""; const config = try parse(arena.allocator(), example, &diagnostic); try testing.expectEqual(@as(usize, 2), config.forges.len); try testing.expectEqual(Scope.user, config.forges[1].scope); try testing.expectEqual(@as(i64, 15), config.forges[0].poll_seconds); try testing.expectEqual(@as(u32, 1), config.findTier("l").?.max); try testing.expectEqual(null, config.findTier("m")); } test "a misspelt option is refused" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); var diagnostic: []const u8 = ""; const text = try std.mem.replaceOwned(u8, arena.allocator(), example, "\"region\"", "\"regoin\""); try testing.expectError(error.InvalidConfig, parse(arena.allocator(), text, &diagnostic)); } test "the droplet API must be https, except on loopback" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); var diagnostic: []const u8 = ""; const plain = try std.mem.replaceOwned(u8, arena.allocator(), example, "https://ci.example.org", "http://ci.example.org"); try testing.expectError(error.InvalidConfig, parse(arena.allocator(), plain, &diagnostic)); const local = try std.mem.replaceOwned(u8, arena.allocator(), example, "https://ci.example.org", "http://[::1]:8094"); _ = try parse(arena.allocator(), local, &diagnostic); } test "a forge may not be called radicle" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); var diagnostic: []const u8 = ""; const text = try std.mem.replaceOwned(u8, arena.allocator(), example, "\"codeberg\"", "\"radicle\""); try testing.expectError(error.InvalidConfig, parse(arena.allocator(), text, &diagnostic)); try testing.expectEqualStrings("`radicle` is reserved for Radicle runs", diagnostic); } test { std.testing.refAllDecls(@This()); }