// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! `ci-autoscaler adapter`: what radicle-ci-broker runs for each event. //! //! It reads the broker's trigger request from standard input, takes the //! commit's `.radicle/droplet.yaml` and a tarball of its tree out of the //! node's storage, and hands the three to the daemon over its Unix socket. //! Then it prints `triggered`, waits for the run to end, prints `finished`, //! and exits. Standard output carries the protocol and nothing else; the log //! goes to standard error, which the broker keeps. //! //! Only this touches the node's storage, which is why it runs as the broker's //! user: the daemon never needs to read a repository, only to be handed one. //! //! The environment says where things are: //! //! * `RAD_HOME` -- the node's home, which the broker's service sets. //! * `CI_AUTOSCALER_SOCKET` -- the daemon's socket, by default //! `/run/ci-autoscaler/adapter.sock`. //! * `CI_AUTOSCALER_GIT` -- the git to run, by default `git` on `PATH`. const std = @import("std"); const Io = std.Io; const Allocator = std.mem.Allocator; const http = @import("http"); const broker = @import("broker.zig"); const DropletSpec = @import("DropletSpec.zig"); const Service = @import("Service.zig"); const unix = @import("unix.zig"); const log = std.log.scoped(.adapter); pub fn main(init: std.process.Init, arena: Allocator) !void { const io = init.io; const env = init.environ_map; var stdout_buffer: [4096]u8 = undefined; var stdout_file: Io.File.Writer = .init(.stdout(), io, &stdout_buffer); const stdout = &stdout_file.interface; var stdin_buffer: [64 * 1024]u8 = undefined; var stdin_file: Io.File.Reader = .init(.stdin(), io, &stdin_buffer); // One JSON document, which radicle-ci-broker 0.32 writes and then closes // standard input on without a line break after it. So the end of input // ends the request as well as a newline does; a request cut short is // still caught, as JSON that does not parse. const line = try stdin_file.interface.takeDelimiterExclusive('\n'); const trigger = broker.parseTrigger(arena, std.mem.trimEnd(u8, line, "\r\n")) catch |err| { log.err("the trigger request could not be read: {s}", .{@errorName(err)}); return err; }; log.info("{s} {s} at {s}", .{ trigger.rid, @tagName(trigger.event), trigger.commit }); const rad_home = env.get("RAD_HOME") orelse return error.NoRadHome; const socket = env.get("CI_AUTOSCALER_SOCKET") orelse "/run/ci-autoscaler/adapter.sock"; const git = env.get("CI_AUTOSCALER_GIT") orelse "git"; // A repository's storage is a bare git repository named for its id, // without the `rad:` in front; `validRid` has already made sure that is // safe to put in a path. const storage = try std.fs.path.join(arena, &.{ rad_home, "storage", trigger.rid["rad:".len..] }); const git_dir = try std.mem.concat(arena, u8, &.{ "--git-dir=", storage }); const spec = try gitOutput(io, arena, &.{ git, git_dir, "show", try std.mem.concat(arena, u8, &.{ trigger.commit, ":", DropletSpec.path }) }, DropletSpec.max_len); const source = try gitOutput(io, arena, &.{ git, git_dir, "archive", "--format=tar.gz", trigger.commit }, Service.max_source_len); const encoded = try arena.alloc(u8, std.base64.standard.Encoder.calcSize(source.len)); _ = std.base64.standard.Encoder.encode(encoded, source); var body: Io.Writer.Allocating = .init(arena); try std.json.Stringify.value(Service.Submission{ .rid = trigger.rid, .commit = trigger.commit, .event = trigger.event, .ref = trigger.ref, .spec = spec, .source = encoded, }, .{}, &body.writer); const submitted_body = try call(io, init.gpa, arena, socket, .post, "/runs", body.written()); const submitted = try std.json.parseFromSliceLeaky(Service.Submitted, arena, submitted_body, .{ .allocate = .alloc_always }); var id_buf: [20]u8 = undefined; try broker.writeTriggered(stdout, try std.fmt.bufPrint(&id_buf, "{d}", .{submitted.id}), submitted.info_url); try stdout.flush(); log.info("run {d}: {s}", .{ submitted.id, submitted.info_url }); const wait_path = try std.fmt.allocPrint(arena, "/runs/{d}/wait", .{submitted.id}); const result = while (true) { // A daemon that restarts mid-run is waited out rather than given up // on: the run is in its database and carries on without it. Only the // broker's own time limit ends this. const waited_body = call(io, init.gpa, arena, socket, .get, wait_path, null) catch |err| { log.warn("waiting for run {d}: {s}; trying again", .{ submitted.id, @errorName(err) }); try Io.sleep(io, .fromSeconds(10), .awake); continue; }; const waited = try std.json.parseFromSliceLeaky(Service.Waited, arena, waited_body, .{ .allocate = .alloc_always }); if (waited.result) |r| break r; }; log.info("run {d}: {s}", .{ submitted.id, @tagName(result) }); try broker.writeFinished(stdout, result == .success); try stdout.flush(); } fn gitOutput(io: Io, arena: Allocator, argv: []const []const u8, limit: usize) ![]const u8 { const result = try std.process.run(arena, io, .{ .argv = argv, .stdout_limit = .limited(limit), .stderr_limit = .limited(64 * 1024), }); if (result.term != .exited or result.term.exited != 0) { log.err("{s} {s}: {s}", .{ argv[0], argv[2], std.mem.trimEnd(u8, result.stderr, "\n") }); return error.GitFailed; } return result.stdout; } /// One request over the daemon's socket, on a connection of its own, and the /// body of a 2xx answer. fn call(io: Io, gpa: Allocator, arena: Allocator, socket: []const u8, method: http.protocol.Method, target: []const u8, content: ?[]const u8) ![]const u8 { var conn: http.http1.client.Connection = try .init(io, gpa, try unix.connect(io, gpa, socket, .{}), .{}); 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, }); const body = try conn.readAll(response, 1024 * 1024); defer gpa.free(body); if (response.status < 200 or response.status > 299) { log.err("{s} {s}: {d} {s}", .{ method.name, target, response.status, body }); return error.HttpStatus; } return arena.dupe(u8, body); }