Something went wrong. Try again.
Ephemeral DigitalOcean droplets for Forgejo Actions and Radicle CI, from one daemon
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! JSON over HTTPS, the one shape every API this daemon talks to shares://! DigitalOcean's, and each forge's.//!//! Names are resolved by zig-dns-client rather than the standard library, and//! that resolver reads `/etc/hosts` -- which matters, because the host this//! runs on pins the forge's name to its private address there, and a lookup//! that skipped the file would send every poll out to the internet and back.
const std = @import("std");const Io = std.Io;const Allocator = std.mem.Allocator;
const http = @import("http");const http_io = @import("http_io");const dns_client = @import("dns_client");
pub const droplet = @import("droplet_protocol.zig");pub const status = @import("status_protocol.zig");
/// How the token is presented. DigitalOcean wants `Bearer`, Forgejo `token`.pub const Scheme = enum { bearer, token,
fn prefix(scheme: Scheme) []const u8 { return switch (scheme) { .bearer => "Bearer ", .token => "token ", }; }};
pub const Response = struct { status: std.http.Status, /// The body as it arrived, owned by the arena the request was given. body: []const u8,
/// The body if the status is 2xx, else `error.HttpStatus`, with the /// status and the start of the body logged: an API's refusal usually says /// why, and "it failed" without that is an afternoon. pub fn ok(r: Response, what: []const u8) error{HttpStatus}![]const u8 { if (r.status.class() == .success) return r.body; log.err("{s}: {d} {s}", .{ what, @intFromEnum(r.status), r.body[0..@min(r.body.len, 300)] }); return error.HttpStatus; }
/// `ok`, then the body parsed as `T`, ignoring fields `T` does not name: /// these are other people's APIs, and they grow. pub fn json(r: Response, comptime T: type, arena: Allocator, what: []const u8) !T { const body = try r.ok(what); return std.json.parseFromSliceLeaky(T, arena, body, .{ .ignore_unknown_fields = true, .allocate = .alloc_always, }) catch |err| { log.err("{s}: unreadable response ({s}): {s}", .{ what, @errorName(err), body[0..@min(body.len, 300)] }); return err; }; }};
const log = std.log.scoped(.api);
/// A client for one API: a base URL and a credential.////// Not safe to share between tasks, because `http_io.Client` is not; one each/// is cheap.pub const Client = struct { http: http_io.Client, base_url: []const u8, token: []const u8, scheme: Scheme,
pub fn init(io: Io, gpa: Allocator, base_url: []const u8, token: []const u8, scheme: Scheme) Client { return .{ .http = .{ .io = io, .gpa = gpa, .resolver = dns_client.HostLookup.lookup, }, .base_url = base_url, .token = token, .scheme = scheme, }; }
pub fn deinit(c: *Client) void { c.http.deinit(); }
/// Sends `payload`, if any, as JSON to `base_url ++ path`, and hands back /// the status and body. Everything allocated lives in `arena`. pub fn request( c: *Client, arena: Allocator, method: http.protocol.Method, path: []const u8, payload: ?[]const u8, ) !Response { const url = try std.mem.concat(arena, u8, &.{ c.base_url, path }); // No credential, no header: an `Authorization` of the scheme alone // ends in a space, which is not a valid field value. const privileged: []const http.protocol.Headers.Field = if (c.token.len == 0) &.{} else &.{ .{ .name = "authorization", .value = try std.mem.concat(arena, u8, &.{ c.scheme.prefix(), c.token }), }, };
var body: Io.Writer.Allocating = .init(arena); var result = try c.http.fetch(.{ .location = .{ .url = url }, .method = method, .payload = payload, .response_writer = &body.writer, .extra_headers = &.{ // A bare client identifies itself to nobody, and Cloudflare -- // in front of Codeberg -- refuses what it cannot identify. .{ .name = "user-agent", .value = "ci-autoscaler/0.0.0" }, .{ .name = "accept", .value = "application/json" }, .{ .name = "content-type", .value = "application/json" }, }, // Stops at a redirect to another origin, so a credential is never // handed to whoever a server names. .privileged_headers = privileged, }); defer result.deinit();
return .{ .status = result.status, .body = body.written() }; }};
test { std.testing.refAllDecls(@This());}