// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // 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()); }