// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The DigitalOcean API calls the daemon makes: list droplets by tag, create //! one, destroy one, and find the newest prepared snapshot. //! //! The token should be a custom-scoped one in a team of its own, which can see //! and delete only CI droplets. A leak then costs no more than that. const std = @import("std"); const Allocator = std.mem.Allocator; const datetime = @import("datetime"); const api = @import("api"); const DigitalOcean = @This(); client: *api.Client, pub const base_url = "https://api.digitalocean.com"; pub const Droplet = struct { id: u64, name: []const u8, /// UTC, as DigitalOcean writes it. created_at: datetime.Instant, tags: []const []const u8 = &.{}, /// `new`, then `active` once it is running. status: []const u8 = "", }; pub const Snapshot = struct { /// A string in this listing, though droplet creation wants a number. id: []const u8, name: []const u8, created_at: datetime.Instant, }; /// Every droplet carrying `tag`, following DigitalOcean's pagination. pub fn droplets(do: DigitalOcean, arena: Allocator, tag: []const u8) ![]Droplet { const Page = struct { droplets: []Droplet, links: ?struct { pages: ?struct { next: ?[]const u8 = null } = null } = null, }; var all: std.ArrayList(Droplet) = .empty; var page: u32 = 1; // Ten pages of two hundred is two thousand droplets, which is far past any // cap this will ever be given; running out of pages is a listing that has // gone wrong, and stopping is safer than walking the account forever. while (page <= 10) : (page += 1) { const path = try std.fmt.allocPrint(arena, "/v2/droplets?tag_name={s}&per_page=200&page={d}", .{ tag, page }); const response = try do.client.request(arena, .get, path, null); const parsed = try response.json(Page, arena, "list droplets"); try all.appendSlice(arena, parsed.droplets); const next = if (parsed.links) |l| if (l.pages) |p| p.next else null else null; if (next == null) break; } return all.items; } pub const Create = struct { name: []const u8, region: []const u8, size: []const u8, /// A snapshot's id or a stock image's slug. image: []const u8, ssh_keys: []const []const u8, tags: []const []const u8, user_data: []const u8, }; /// The request body for `create`, separate so that it can be tested and so /// that a dry run can log exactly what would have been sent. pub fn createBody(arena: Allocator, spec: Create) ![]const u8 { var out: std.Io.Writer.Allocating = .init(arena); var s: std.json.Stringify = .{ .writer = &out.writer }; try s.beginObject(); try s.objectField("name"); try s.write(spec.name); try s.objectField("region"); try s.write(spec.region); try s.objectField("size"); try s.write(spec.size); // An image id goes as a number and a slug as a string, which is how the // API documents the field. try s.objectField("image"); if (numeric(spec.image)) |id| try s.write(id) else try s.write(spec.image); // No vpc_uuid: DigitalOcean puts the droplet in the team's default VPC for // the region, and nothing it talks to is there. try s.objectField("ssh_keys"); try s.beginArray(); // Ids as numbers, fingerprints as strings. for (spec.ssh_keys) |key| if (numeric(key)) |id| try s.write(id) else try s.write(key); try s.endArray(); // Off by default on DigitalOcean; jobs that reach IPv6-only hosts need it. try s.objectField("ipv6"); try s.write(true); try s.objectField("tags"); try s.write(spec.tags); try s.objectField("user_data"); try s.write(spec.user_data); try s.endObject(); return out.written(); } fn numeric(text: []const u8) ?u64 { if (text.len == 0) return null; for (text) |c| if (c < '0' or c > '9') return null; return std.fmt.parseInt(u64, text, 10) catch null; } /// Creates a droplet and returns its id. A 422 -- the size is restricted, /// or the region has none to give -- is `error.Unprocessable`, so that a /// caller can try another size. pub fn create(do: DigitalOcean, arena: Allocator, spec: Create) !u64 { const body = try createBody(arena, spec); const response = try do.client.request(arena, .post, "/v2/droplets", body); if (response.status == .unprocessable_entity) { log.warn("create droplet ({s}): {s}", .{ spec.size, response.body[0..@min(response.body.len, 200)] }); return error.Unprocessable; } const parsed = try response.json(struct { droplet: struct { id: u64 } }, arena, "create droplet"); return parsed.droplet.id; } /// `create` with `spec.size`, then each of `fallbacks` in turn, for as long /// as DigitalOcean answers 422. Returns the droplet and the size it got. pub fn createAny(do: DigitalOcean, arena: Allocator, spec: Create, fallbacks: []const []const u8) !struct { id: u64, size: []const u8 } { var attempt = spec; var i: usize = 0; while (true) : (i += 1) { if (do.create(arena, attempt)) |id| { return .{ .id = id, .size = attempt.size }; } else |err| switch (err) { error.Unprocessable => { if (i >= fallbacks.len) return err; attempt.size = fallbacks[i]; }, else => return err, } } } const log = std.log.scoped(.digitalocean); pub fn destroy(do: DigitalOcean, arena: Allocator, id: u64) !void { const path = try std.fmt.allocPrint(arena, "/v2/droplets/{d}", .{id}); const response = try do.client.request(arena, .delete, path, null); // Already gone is what was wanted. if (response.status == .not_found) return; _ = try response.ok("destroy droplet"); } /// The newest droplet snapshot named `-*`, or null. /// /// Resolved each time rather than pinned in configuration: the builder makes /// a new snapshot whenever the runner image changes, and a pinned id would /// silently keep booting the stale one. pub fn newestSnapshot(do: DigitalOcean, arena: Allocator, prefix: []const u8) !?Snapshot { return newest(try do.snapshots(arena), prefix); } fn newest(all: []const Snapshot, prefix: []const u8) ?Snapshot { var best: ?Snapshot = null; for (all) |candidate| { if (!std.mem.startsWith(u8, candidate.name, prefix)) continue; if (!std.mem.startsWith(u8, candidate.name[prefix.len..], "-")) continue; if (best == null or candidate.created_at.timestamp > best.?.created_at.timestamp) best = candidate; } return best; } /// A droplet's `status`: `new`, `active`, `off` or `archive`. pub fn status(do: DigitalOcean, arena: Allocator, id: u64) ![]const u8 { const path = try std.fmt.allocPrint(arena, "/v2/droplets/{d}", .{id}); const response = try do.client.request(arena, .get, path, null); const parsed = try response.json(struct { droplet: struct { status: []const u8 } }, arena, "get droplet"); return parsed.droplet.status; } /// Starts a snapshot of a powered-off droplet, and returns the action's id. pub fn snapshot(do: DigitalOcean, arena: Allocator, id: u64, name: []const u8) !u64 { const path = try std.fmt.allocPrint(arena, "/v2/droplets/{d}/actions", .{id}); var body: std.Io.Writer.Allocating = .init(arena); try std.json.Stringify.value(.{ .type = "snapshot", .name = name }, .{}, &body.writer); const response = try do.client.request(arena, .post, path, body.written()); const parsed = try response.json(struct { action: struct { id: u64 } }, arena, "snapshot droplet"); return parsed.action.id; } /// An action's `status`: `in-progress`, `completed` or `errored`. pub fn actionStatus(do: DigitalOcean, arena: Allocator, id: u64) ![]const u8 { const path = try std.fmt.allocPrint(arena, "/v2/actions/{d}", .{id}); const response = try do.client.request(arena, .get, path, null); const parsed = try response.json(struct { action: struct { status: []const u8 } }, arena, "get action"); return parsed.action.status; } /// Every droplet snapshot in the team. pub fn snapshots(do: DigitalOcean, arena: Allocator) ![]Snapshot { const response = try do.client.request(arena, .get, "/v2/snapshots?resource_type=droplet&per_page=200", null); const parsed = try response.json(struct { snapshots: []Snapshot }, arena, "list snapshots"); return parsed.snapshots; } pub fn deleteSnapshot(do: DigitalOcean, arena: Allocator, id: []const u8) !void { const path = try std.fmt.allocPrint(arena, "/v2/snapshots/{s}", .{id}); const response = try do.client.request(arena, .delete, path, null); if (response.status == .not_found) return; _ = try response.ok("delete snapshot"); } /// The snapshots named `-*` beyond the newest `keep`, oldest last. /// Matching is on the exact prefix the builder writes, so a snapshot taken by /// hand or by anything else is never a candidate. pub fn surplus(arena: Allocator, all: []const Snapshot, prefix: []const u8, keep: usize) ![]const Snapshot { var ours: std.ArrayList(Snapshot) = .empty; for (all) |s| { if (std.mem.startsWith(u8, s.name, prefix) and std.mem.startsWith(u8, s.name[prefix.len..], "-")) try ours.append(arena, s); } std.mem.sort(Snapshot, ours.items, {}, struct { fn newer(_: void, a: Snapshot, b: Snapshot) bool { return a.created_at.timestamp > b.created_at.timestamp; } }.newer); return if (ours.items.len > keep) ours.items[keep..] else &.{}; } const testing = std.testing; test "a droplet listing parses, created_at as UTC" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const body = \\{"droplets":[{"id":1,"name":"fj-runner-2848","created_at":"2026-09-27T12:34:56Z", \\"tags":["ci-ephemeral","ci-ocjtech-s"],"memory":4096}],"links":{},"meta":{"total":1}} ; const response: api.Response = .{ .status = .ok, .body = body }; const parsed = try response.json(struct { droplets: []Droplet }, arena.allocator(), "test"); try testing.expectEqual(@as(i128, 1790512496) * std.time.ns_per_s, parsed.droplets[0].created_at.timestamp); try testing.expectEqualStrings("ci-ocjtech-s", parsed.droplets[0].tags[1]); } test "the create body" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const body = try createBody(arena.allocator(), .{ .name = "fj-runner-7", .region = "nyc3", .size = "s-2vcpu-4gb", .image = "123456", .ssh_keys = &.{ "71:25:77:e8", "42" }, .tags = &.{ "ci-ephemeral", "ci-ocjtech-s" }, .user_data = "#cloud-config\n", }); try testing.expectEqualStrings( \\{"name":"fj-runner-7","region":"nyc3","size":"s-2vcpu-4gb","image":123456,"ssh_keys":["71:25:77:e8",42],"ipv6":true,"tags":["ci-ephemeral","ci-ocjtech-s"],"user_data":"#cloud-config\n"} , body); const stock = try createBody(arena.allocator(), .{ .name = "fj-runner-7", .region = "nyc3", .size = "s-2vcpu-4gb", .image = "ubuntu-26-04-x64", .ssh_keys = &.{}, .tags = &.{}, .user_data = "", }); try testing.expect(std.mem.indexOf(u8, stock, "\"image\":\"ubuntu-26-04-x64\"") != null); } test "the newest snapshot with the prefix wins" { const at = struct { fn f(seconds: i64) datetime.Instant { return .{ .timestamp = @as(i128, seconds) * std.time.ns_per_s }; } }.f; const listed = [_]Snapshot{ .{ .id = "1", .name = "forgejo-runner-20260920", .created_at = at(100) }, .{ .id = "2", .name = "forgejo-runner-20260927", .created_at = at(200) }, .{ .id = "3", .name = "tack-runner-20260928", .created_at = at(300) }, // shares the prefix but is not a `-*` name .{ .id = "4", .name = "forgejo-runnerx-20260929", .created_at = at(400) }, }; try testing.expectEqualStrings("2", newest(&listed, "forgejo-runner").?.id); try testing.expectEqual(null, newest(&listed, "nothing")); } test "surplus snapshots are the oldest of ours" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); const at = struct { fn f(seconds: i64) datetime.Instant { return .{ .timestamp = @as(i128, seconds) * std.time.ns_per_s }; } }.f; const all = [_]Snapshot{ .{ .id = "1", .name = "forgejo-runner-1", .created_at = at(100) }, .{ .id = "3", .name = "forgejo-runner-3", .created_at = at(300) }, .{ .id = "2", .name = "forgejo-runner-2", .created_at = at(200) }, .{ .id = "9", .name = "hand-made", .created_at = at(50) }, }; const extra = try surplus(arena.allocator(), &all, "forgejo-runner", 2); try testing.expectEqual(@as(usize, 1), extra.len); try testing.expectEqualStrings("1", extra[0].id); try testing.expectEqual(@as(usize, 0), (try surplus(arena.allocator(), &all, "forgejo-runner", 5)).len); } test { std.testing.refAllDecls(@This()); }