Something went wrong. Try again.
A Gmail API client library for Zig: labels, messages, and the mailbox history that turns a second sync into an update.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! The one place this library talks to a network, kept small on purpose so//! that everything above it -- the resource types, the label mapping, the//! pagination -- is pure and can be tested without a socket.//!//! Three things here are not what `std.http.Client.fetch` does on its own.//! The response body is read into a buffer of a fixed size rather than one//! that grows, so a server that answers with a gigabyte gets an error rather//! than the process' memory. A non-2xx response is turned into the error//! object Google's APIs carry, rather than a bare status code. And a failure//! that is a quota failure is retried with exponential backoff, because a//! mailbox walk runs into one as a matter of routine and the only correct//! response to it is to wait.
const std = @import("std");
const ApiError = @import("ApiError.zig");
const log = std.log.scoped(.gmail);
/// The default ceiling on a response body, for the calls that return/// metadata: a label list, a page of message ids, a history page. Generous;/// none of them are close to it.pub const default_max_response_bytes = 4 << 20;
/// The ceiling for `users.messages.get`, which can return a whole message./// Gmail accepts messages up to 25 MB, `format=raw` sends them base64url/// encoded, and base64 is four bytes out for three in, so the response can be/// a little over 34 MB before the JSON around it.////// It is allocated up front, per request. On a system with lazy page/// allocation that costs an address range rather than memory, and the pages a/// small response never touches are never backed.pub const default_max_message_bytes = 48 << 20;
/// The ceiling for a batch response, which is as many message bodies as were/// asked for in one request. Larger than `default_max_message_bytes` because/// a batch holds several messages, and not fifty times larger because a batch/// of fifty whole messages is not what the endpoint is for: ask for/// `format = .metadata` there, or ask for fewer. `error.ResponseTooLarge`/// from a batch means exactly that.pub const default_max_batch_bytes = 64 << 20;
pub const Error = error{ /// The transport failed: DNS, TCP, TLS, or a malformed HTTP response. RequestFailed, /// The body exceeded `max_response_bytes`. ResponseTooLarge, /// The server answered with a status this library does not accept, and /// the body was not a Google error object either. `Diagnostics.status` /// holds what it was, and `Diagnostics.body` the first part of what it /// said. HttpStatus, /// The server answered with a Google API error object. /// `Diagnostics.api_error` holds it. ApiError, /// The access token was refused. Split out from `ApiError` because it is /// the one failure a caller holding a refresh token can do something /// about, and `Client` does: it refreshes and tries once more. Unauthorized, /// The request kept failing with something retryable until `max_attempts` /// ran out. `Diagnostics` describes the last attempt. TooManyRetries,} || std.Io.Cancelable || std.mem.Allocator.Error;
/// Filled in on the way past, so that a failure can say what happened without/// every error having to carry a payload. Owned by the caller.pub const Diagnostics = struct { status: ?std.http.Status = null, api_error: ?ApiError = null, /// The first part of the body, for a failure that was neither a valid /// API error nor a status worth naming on its own. body: ?[]const u8 = null, /// How many attempts were made. 1 unless something was retried. attempts: u32 = 0,
/// Frees whatever the last failure put here and empties it. /// /// `fetch` calls this on the way in, so one `Diagnostics` can be reused /// across a whole session without each request's leftovers piling up. pub fn reset(d: *Diagnostics, gpa: std.mem.Allocator) void { if (d.body) |b| gpa.free(b); if (d.api_error) |*e| e.deinit(); d.* = .{}; }
pub fn deinit(d: *Diagnostics, gpa: std.mem.Allocator) void { d.reset(gpa); }
/// Renders whatever is known about the failure, for a log line. pub fn format(d: *const Diagnostics, w: *std.Io.Writer) std.Io.Writer.Error!void { if (d.api_error) |*e| return e.format(w); if (d.status) |s| { try w.print("HTTP {d} {s}", .{ @intFromEnum(s), s.phrase() orelse "" }); if (d.body) |b| try w.print(": {s}", .{b}); return; } try w.writeAll("no response"); }};
/// How hard to try again when the API says to slow down.////// Google's guidance for these APIs is exponential backoff with jitter, and/// the jitter is not decoration: a program that walks a mailbox with several/// requests in flight and backs off by a fixed schedule synchronises them,/// and they all come back at once into the same limit.////// `std.http.Client.fetch` in 0.16 hands back only the status, so a/// `Retry-After` header cannot be read here even when the server sends one./// The schedule below is what is left, and it is what Google documents/// anyway.pub const Retry = struct { /// Total attempts, not retries. 1 disables retrying. max_attempts: u32 = 5, /// The first wait. Doubles each time. initial_backoff: std.Io.Duration = .fromMilliseconds(500), /// The ceiling on a single wait, before jitter. max_backoff: std.Io.Duration = .fromSeconds(32),
pub const none: Retry = .{ .max_attempts = 1 };
/// How long to wait before attempt number `attempt` (1-based, so the /// first retry is attempt 2 and waits `initial_backoff`). pub fn backoff(r: Retry, attempt: u32, rng: std.Random) std.Io.Duration { // The first attempt is not a retry, so it does not wait. Saturating // subtraction alone would make it wait `initial_backoff`. if (attempt < 2) return .fromNanoseconds(0); // Capped before the shift rather than after: 1 << 64 is undefined // behaviour, and `max_backoff` would have clamped it anyway. const doublings: u6 = @intCast(@min(attempt - 2, 16)); const base = @min( r.initial_backoff.toNanoseconds() *| (@as(i96, 1) << doublings), r.max_backoff.toNanoseconds(), ); // Full jitter: a wait uniform over [0, base]. It spreads a thundering // herd out rather than merely delaying it. const nanos: i96 = if (base <= 0) 0 else rng.uintLessThan(u64, @intCast(base + 1)); return .fromNanoseconds(nanos); }};
pub const Request = struct { method: std.http.Method = .GET, uri: std.Uri, /// The request body, already encoded. `content_type` must be set with it. payload: ?[]const u8 = null, content_type: ?[]const u8 = null, /// The value of an `Authorization` header, complete with its scheme. authorization: ?[]const u8 = null, user_agent: []const u8, max_response_bytes: usize = default_max_response_bytes, retry: Retry = .{}, /// Where the jitter comes from. It does not have to be cryptographically /// secure -- nothing is being kept secret -- but it does have to differ /// between processes, or the spreading does not spread. rng: ?std.Random = null,};
/// Performs `request` and returns the body, allocated from `gpa` and owned by/// the caller.////// A 2xx status returns the body. Anything else is an error, with/// `diagnostics` filled in: the Google error object where the server sent/// one, the status otherwise.pub fn fetch( io: std.Io, gpa: std.mem.Allocator, request: Request, diagnostics: *Diagnostics,) Error![]u8 { diagnostics.reset(gpa);
// A fixed buffer rather than a growing one: this is the cap, and it is // enforced by there being nowhere else for the bytes to go. const buffer = try gpa.alloc(u8, request.max_response_bytes); defer gpa.free(buffer);
// A seed, not a secret: the jitter exists to keep concurrent clients from // backing off in lockstep, and the clock is enough to tell them apart. // `Request.rng` is how a caller that wants better supplies it. const nanos: u96 = @bitCast(std.Io.Timestamp.now(io, .real).nanoseconds); var fallback: std.Random.DefaultPrng = .init(@truncate(nanos)); const rng = request.rng orelse fallback.random();
var attempt: u32 = 1; while (true) : (attempt += 1) { diagnostics.reset(gpa); diagnostics.attempts = attempt;
const outcome = attemptOnce(io, gpa, request, buffer, diagnostics) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.ResponseTooLarge => return error.ResponseTooLarge, // A transport failure is retried too: a connection reset in the // middle of a long walk is far more common than a broken server, // and the request has not been applied. error.RequestFailed => if (attempt < request.retry.max_attempts) { try sleepBeforeRetry(io, request.retry, attempt + 1, rng); continue; } else return error.RequestFailed, };
switch (outcome) { .ok => |body| return body, .failed => |status| { if (diagnostics.api_error) |*e| { if (e.isAuthFailure(status)) return error.Unauthorized; if (e.isRetryable(status) and attempt < request.retry.max_attempts) { log.debug("{f}: attempt {d} of {d}, backing off", .{ diagnostics, attempt, request.retry.max_attempts, }); try sleepBeforeRetry(io, request.retry, attempt + 1, rng); continue; } if (e.isRetryable(status)) return error.TooManyRetries; return error.ApiError; }
// No error object: something in front of the API. A 401 still // means what it means, and a 5xx or 429 is still worth // waiting out. if (status == .unauthorized) return error.Unauthorized; const retryable = status == .too_many_requests or status.class() == .server_error; if (retryable and attempt < request.retry.max_attempts) { try sleepBeforeRetry(io, request.retry, attempt + 1, rng); continue; } if (retryable) return error.TooManyRetries; return error.HttpStatus; }, } }}
fn sleepBeforeRetry( io: std.Io, retry: Retry, attempt: u32, rng: std.Random,) std.Io.Cancelable!void { const wait = retry.backoff(attempt, rng); if (wait.toNanoseconds() <= 0) return; try std.Io.sleep(io, wait, .awake);}
const Outcome = union(enum) { ok: []u8, failed: std.http.Status,};
const AttemptError = error{ RequestFailed, ResponseTooLarge } || std.mem.Allocator.Error;
fn attemptOnce( io: std.Io, gpa: std.mem.Allocator, request: Request, buffer: []u8, diagnostics: *Diagnostics,) AttemptError!Outcome { var body_writer: std.Io.Writer = .fixed(buffer);
var client: std.http.Client = .{ .io = io, .allocator = gpa }; defer client.deinit();
var extra: [1]std.http.Header = undefined; var extra_len: usize = 0; if (request.authorization) |value| { extra[extra_len] = .{ .name = "Authorization", .value = value }; extra_len += 1; }
const result = client.fetch(.{ .method = request.method, .location = .{ .uri = request.uri }, .headers = .{ .user_agent = .{ .override = request.user_agent }, .content_type = if (request.content_type) |ct| .{ .override = ct } else .default, // The JSON is what is wanted, not a gzip stream this would then // have to inflate into the same fixed buffer. .accept_encoding = .{ .override = "identity" }, }, .extra_headers = extra[0..extra_len], .payload = request.payload, .response_writer = &body_writer, // An API endpoint does not redirect, and following one would resend // the access token to wherever it pointed. .redirect_behavior = .not_allowed, }) catch |err| switch (err) { // With a fixed writer there is only one way writing the body can // fail, and that is running out of it. error.WriteFailed => return error.ResponseTooLarge, error.OutOfMemory => return error.OutOfMemory, else => |e| { log.debug("{s} {f}: {t}", .{ @tagName(request.method), request.uri, e }); return error.RequestFailed; }, };
diagnostics.status = result.status; const body = body_writer.buffered();
if (result.status.class() != .success) { if (ApiError.parse(gpa, body)) |parsed| { diagnostics.api_error = parsed; } else |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.NotAnError => diagnostics.body = try gpa.dupe(u8, body[0..@min(body.len, 512)]), } return .{ .failed = result.status }; }
return .{ .ok = try gpa.dupe(u8, body) };}
const testing = std.testing;
test "backoff doubles and is capped" { var prng: std.Random.DefaultPrng = .init(0); const rng = prng.random(); const retry: Retry = .{ .initial_backoff = .fromMilliseconds(500), .max_backoff = .fromSeconds(32), };
// Full jitter makes each wait a sample from [0, base], so what is // asserted is the ceiling rather than the value. for ([_]struct { u32, i96 }{ .{ 2, std.time.ns_per_ms * 500 }, .{ 3, std.time.ns_per_s * 1 }, .{ 4, std.time.ns_per_s * 2 }, .{ 8, std.time.ns_per_s * 32 }, // Long past the cap, and nowhere near overflowing the shift. .{ 40, std.time.ns_per_s * 32 }, }) |case| { const attempt, const ceiling = case; for (0..64) |_| { const got = retry.backoff(attempt, rng).toNanoseconds(); try testing.expect(got >= 0); try testing.expect(got <= ceiling); } }}
test "the first attempt never waits" { var prng: std.Random.DefaultPrng = .init(1); const retry: Retry = .{}; try testing.expectEqual(@as(i96, 0), retry.backoff(1, prng.random()).toNanoseconds());}
test { _ = ApiError;}