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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! The error object a Google API returns instead of a result.//!//! It is not the OAuth 2.0 error object -- that one is flat and lives in//! `oidc.ErrorResponse`. This one is nested, and the part worth reading is//! usually not the top-level `message` but the `reason` on the first entry of//! `errors`, which is what distinguishes "you are going too fast" from "that//! mailbox does not exist".//!//! ```json//! {"error":{"code":429,"message":"User-rate limit exceeded.",//! "errors":[{"domain":"usageLimits","reason":"rateLimitExceeded",//! "message":"User-rate limit exceeded."}],//! "status":"RESOURCE_EXHAUSTED"}}//! ```//!//! Everything is optional, because a failure is exactly the situation in which//! a server is least likely to send what it promised: a proxy in front of the//! API answers 502 with HTML, and a token that has been revoked can come back//! with an empty body. `parse` reports that as `error.NotAnError` rather than//! inventing fields.//!//! There are two ways in. `parse` owns an arena and is freed by `deinit`,//! which is what a single failing call wants. `parseLeaky` borrows an//! allocator the caller already has, which is what a batch wants: fifty calls//! can fail separately, and fifty arenas to hold fifty error objects that all//! came out of the same response body would be fifty allocations to remember//! to free.
const ApiError = @This();
const std = @import("std");
/// The HTTP status, repeated inside the body. Trust the real status over this/// where they disagree.code: ?u32,/// A sentence meant for a developer, not a user.message: ?[]const u8,/// The canonical error code, as a name: `UNAUTHENTICATED`,/// `RESOURCE_EXHAUSTED`, `PERMISSION_DENIED`. Newer than `errors` and not/// always present.status: ?[]const u8,/// The individual failures. Usually one.details: []const Detail,
/// Where the strings above live, when this owns them. `null` for one parsed/// by `parseLeaky`, whose strings belong to the caller's allocator.arena: ?std.heap.ArenaAllocator,
pub const Detail = struct { /// `global`, or `usageLimits` for a quota failure. domain: ?[]const u8 = null, /// The machine-readable one: `rateLimitExceeded`, `userRateLimitExceeded`, /// `dailyLimitExceeded`, `authError`, `failedPrecondition`, `notFound`. reason: ?[]const u8 = null, message: ?[]const u8 = null, /// Which parameter was at fault, for a `badRequest`. location: ?[]const u8 = null, location_type: ?[]const u8 = null,};
pub const ParseError = error{ /// The body was not JSON, or was JSON with no `error` object in it. A /// non-2xx response that parses to this was not an API error but /// something in front of the API. NotAnError,} || std.mem.Allocator.Error;
pub fn parse(gpa: std.mem.Allocator, body: []const u8) ParseError!ApiError { var arena: std.heap.ArenaAllocator = .init(gpa); errdefer arena.deinit();
var parsed = try parseLeaky(arena.allocator(), body); parsed.arena = arena; return parsed;}
/// The same, into an allocator that outlives the result. What comes back owns/// nothing and must not be `deinit`ed.pub fn parseLeaky(alloc: std.mem.Allocator, body: []const u8) ParseError!ApiError { const root = std.json.parseFromSliceLeaky(std.json.Value, alloc, body, .{}) catch return error.NotAnError; if (root != .object) return error.NotAnError;
const err = root.object.get("error") orelse return error.NotAnError; // Google's *OAuth* endpoints put a bare string here -- `"error": // "invalid_grant"` -- which is the RFC 6749 shape and not this one. if (err != .object) return error.NotAnError;
var details: std.ArrayList(Detail) = .empty; if (err.object.get("errors")) |errors| { if (errors == .array) { try details.ensureTotalCapacityPrecise(alloc, errors.array.items.len); for (errors.array.items) |item| { if (item != .object) continue; details.appendAssumeCapacity(.{ .domain = string(item, "domain"), .reason = string(item, "reason"), .message = string(item, "message"), .location = string(item, "location"), .location_type = string(item, "locationType"), }); } } }
return .{ .code = integer(err, "code"), .message = string(err, "message"), .status = string(err, "status"), .details = try details.toOwnedSlice(alloc), .arena = null, };}
pub fn deinit(e: *ApiError) void { if (e.arena) |*arena| arena.deinit(); e.* = undefined;}
/// The `reason` of the first detail, which is the field worth branching on.pub fn reason(e: *const ApiError) ?[]const u8 { for (e.details) |d| if (d.reason) |r| return r; return null;}
/// Whether this failure is one that the same request might survive if it were/// sent again after a pause.////// Quota is the reason a Gmail client needs this at all: a mailbox walk runs/// into `userRateLimitExceeded` as a matter of routine, and it means "slow/// down", not "stop". `dailyLimitExceeded` is deliberately *not* retryable --/// the quota it names resets at midnight Pacific, and retrying inside a/// backoff loop only spends the next day's allowance on 403s.pub fn isRetryable(e: *const ApiError, status: std.http.Status) bool { if (status == .too_many_requests) return true; if (status.class() == .server_error) return true;
// 403 is the interesting one: it is both "your quota is gone" and "this // token may not do that", and only the reason separates them. if (status == .forbidden) { const r = e.reason() orelse return false; return std.mem.eql(u8, r, "rateLimitExceeded") or std.mem.eql(u8, r, "userRateLimitExceeded") or std.mem.eql(u8, r, "backendError"); } return false;}
/// Whether the access token is the problem, so that a caller holding a/// refresh token knows to spend it rather than to give up.pub fn isAuthFailure(e: *const ApiError, status: std.http.Status) bool { if (status == .unauthorized) return true; if (e.status) |s| if (std.mem.eql(u8, s, "UNAUTHENTICATED")) return true; const r = e.reason() orelse return false; return std.mem.eql(u8, r, "authError") or std.mem.eql(u8, r, "unauthorized");}
pub fn format(e: *const ApiError, w: *std.Io.Writer) std.Io.Writer.Error!void { if (e.code) |c| try w.print("{d} ", .{c}); try w.writeAll(e.message orelse "(no message)"); if (e.reason()) |r| try w.print(" [{s}]", .{r});}
fn string(v: std.json.Value, name: []const u8) ?[]const u8 { if (v != .object) return null; const member = v.object.get(name) orelse return null; return switch (member) { .string => |s| s, else => null, };}
fn integer(v: std.json.Value, name: []const u8) ?u32 { if (v != .object) return null; const member = v.object.get(name) orelse return null; return switch (member) { .integer => |i| std.math.cast(u32, i), else => null, };}
const testing = std.testing;
test "parses the nested shape" { var e: ApiError = try .parse(testing.allocator, \\{"error":{"code":429,"message":"User-rate limit exceeded.", \\ "errors":[{"domain":"usageLimits","reason":"userRateLimitExceeded", \\ "message":"User-rate limit exceeded."}], \\ "status":"RESOURCE_EXHAUSTED"}} ); defer e.deinit();
try testing.expectEqual(@as(?u32, 429), e.code); try testing.expectEqualStrings("User-rate limit exceeded.", e.message.?); try testing.expectEqualStrings("RESOURCE_EXHAUSTED", e.status.?); try testing.expectEqual(@as(usize, 1), e.details.len); try testing.expectEqualStrings("userRateLimitExceeded", e.reason().?); try testing.expectEqualStrings("usageLimits", e.details[0].domain.?);}
test "an error object can live in an arena the caller already has" { var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit();
var e: ApiError = try .parseLeaky(arena.allocator(), \\{"error":{"code":404,"message":"Not Found","errors":[{"reason":"notFound"}]}} ); try testing.expectEqualStrings("notFound", e.reason().?); // It owns nothing, which is how a batch holds one of these per failed // call without holding an arena per failed call. try testing.expect(e.arena == null); // And is still safe to hand to `deinit`, which has nothing to do. e.deinit();}
test "everything is optional" { var e: ApiError = try .parse(testing.allocator, "{\"error\":{}}"); defer e.deinit(); try testing.expectEqual(@as(?u32, null), e.code); try testing.expectEqual(@as(?[]const u8, null), e.message); try testing.expectEqual(@as(usize, 0), e.details.len); try testing.expectEqual(@as(?[]const u8, null), e.reason());}
test "not this shape" { try testing.expectError(error.NotAnError, ApiError.parse(testing.allocator, "<html>502</html>")); try testing.expectError(error.NotAnError, ApiError.parse(testing.allocator, "")); try testing.expectError(error.NotAnError, ApiError.parse(testing.allocator, "{}")); try testing.expectError(error.NotAnError, ApiError.parse(testing.allocator, "[1,2,3]")); // The OAuth shape, which `oidc.ErrorResponse` reads and this must not // claim: `error` is a string there, not an object. try testing.expectError( error.NotAnError, ApiError.parse(testing.allocator, "{\"error\":\"invalid_grant\"}"), );}
test "quota is retryable and the daily cap is not" { { var e: ApiError = try .parse(testing.allocator, \\{"error":{"code":403,"errors":[{"reason":"userRateLimitExceeded"}]}} ); defer e.deinit(); try testing.expect(e.isRetryable(.forbidden)); } { var e: ApiError = try .parse(testing.allocator, \\{"error":{"code":403,"errors":[{"reason":"dailyLimitExceeded"}]}} ); defer e.deinit(); try testing.expect(!e.isRetryable(.forbidden)); } { // A 403 that is a permission problem rather than a quota one. var e: ApiError = try .parse(testing.allocator, \\{"error":{"code":403,"errors":[{"reason":"insufficientPermissions"}]}} ); defer e.deinit(); try testing.expect(!e.isRetryable(.forbidden)); } { var e: ApiError = try .parse(testing.allocator, "{\"error\":{\"code\":503}}"); defer e.deinit(); try testing.expect(e.isRetryable(.service_unavailable)); try testing.expect(!e.isRetryable(.not_found)); }}
test "an expired token is recognised" { var e: ApiError = try .parse(testing.allocator, \\{"error":{"code":401,"message":"Invalid Credentials", \\ "errors":[{"domain":"global","reason":"authError"}], \\ "status":"UNAUTHENTICATED"}} ); defer e.deinit(); try testing.expect(e.isAuthFailure(.unauthorized)); try testing.expect(!e.isRetryable(.unauthorized));}
test "formats" { var e: ApiError = try .parse(testing.allocator, \\{"error":{"code":404,"message":"Not Found","errors":[{"reason":"notFound"}]}} ); defer e.deinit();
var buf: [128]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); try e.format(&w); try testing.expectEqualStrings("404 Not Found [notFound]", w.buffered());}