// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The Gmail API, over an OAuth 2.0 token that this keeps alive. //! //! ## Where the credentials come from //! //! This library does not do OAuth; `zig-oidc` does, and this holds one of its //! `Client`s and one of its `TokenSet`s. Signing in is that library's job and //! happens once, before any of this: //! //! ```zig //! var listener = try oidc.loopback.Listener.listen(io, .{}); //! defer listener.deinit(io); //! const redirect_uri = try listener.redirectUri(gpa); //! defer gpa.free(redirect_uri); //! //! const oauth: oidc.Client = .{ //! .provider = .google, //! .client_id = client_id, //! .client_secret = client_secret, //! .redirect_uri = redirect_uri, //! .scopes = &.{ "openid", "email", gmail.scopes.readonly }, //! }; //! //! const rng: std.Random.IoSource = .{ .io = io }; //! // `access_type=offline` is Google's, and without it there is no refresh //! // token and the grant dies in an hour. //! var authorization = try oauth.authorize(gpa, rng.interface(), .{ //! .extra = &.{.{ .name = "access_type", .value = "offline" }}, //! }); //! defer authorization.deinit(); //! // ... send the user to authorization.url, then: //! var redirect = try listener.wait(io, gpa, .{}); //! defer redirect.deinit(); //! var tokens = try oauth.exchange(io, gpa, &authorization, redirect.query, &d); //! defer tokens.deinit(); //! //! var client: gmail.Client = .{ .oauth = oauth, .tokens = &tokens }; //! ``` //! //! ## Keeping them alive //! //! An access token lasts an hour and a mailbox walk lasts longer, so every //! call here refreshes on its own when the token is within `refresh_leeway` of //! expiring, and again if a call comes back 401 anyway -- which happens when //! the user revokes access, or when the clock this machine is keeping is not //! Google's. //! //! A refresh produces a *new* refresh token often enough that dropping it //! breaks the next run, so set `on_refresh` to write the token set back to //! wherever it is kept. `TokenStore` is that, for a file. const Client = @This(); const std = @import("std"); const oidc = @import("oidc"); const ApiError = @import("ApiError.zig"); const History = @import("History.zig"); const Label = @import("Label.zig"); const Message = @import("Message.zig"); const Profile = @import("Profile.zig"); const batch = @import("batch.zig"); const http = @import("http.zig"); const json = @import("json.zig"); const log = std.log.scoped(.gmail); /// The OAuth client the tokens were minted by, and which will refresh them. /// Its `provider` should be `.google`. oauth: oidc.Client, /// The tokens. Borrowed and mutated: a refresh replaces what is behind this /// pointer, so it must outlive the client and must not be shared with /// anything that is reading it at the same time. tokens: *oidc.TokenSet, /// Whose mailbox. `me` is the authenticated user and is almost always right; /// a service account with domain-wide delegation puts an address here. user_id: []const u8 = "me", user_agent: []const u8 = "zig-gmail", /// Where the API is. A test points this at a loopback socket. base_url: []const u8 = "https://gmail.googleapis.com", /// How early to treat the access token as expired. Enough slack that a call /// is not started with a token that dies while it is in flight. refresh_leeway: std.Io.Duration = .fromSeconds(300), max_response_bytes: usize = http.default_max_response_bytes, /// The separate, much larger ceiling for `getMessage`, which can return a /// whole message. See `http.default_max_message_bytes`. max_message_bytes: usize = http.default_max_message_bytes, /// The ceiling for a batch response, which holds one body per call in it. /// See `http.default_max_batch_bytes`. max_batch_bytes: usize = http.default_max_batch_bytes, retry: http.Retry = .{}, /// Where the retry jitter comes from. Not a secret, but it must differ /// between processes or backing off does not spread anything out. rng: ?std.Random = null, /// Called after every successful refresh, with the merged token set. on_refresh: ?RefreshHook = null, /// What to do with a token set that has just been refreshed. /// /// An error here fails the API call that triggered the refresh, deliberately: /// a rotated refresh token that was not written down is one the next run does /// not have, and finding that out now is better than finding it out tomorrow. pub const RefreshHook = struct { context: ?*anyopaque = null, func: *const fn (context: ?*anyopaque, tokens: *const oidc.TokenSet) anyerror!void, }; pub const Diagnostics = struct { /// What the last API call said. http: http.Diagnostics = .{}, /// What the last *refresh* said, which is a different server with a /// different error vocabulary. `invalid_grant` here means the grant is /// gone -- revoked, or expired from disuse -- and the user has to sign in /// again. oauth: oidc.Client.Diagnostics = .{}, pub fn reset(d: *Diagnostics, gpa: std.mem.Allocator) void { d.http.reset(gpa); d.oauth.reset(gpa); } pub fn deinit(d: *Diagnostics, gpa: std.mem.Allocator) void { d.reset(gpa); } /// The API error, when the failure was one. pub fn apiError(d: *const Diagnostics) ?*const ApiError { if (d.http.api_error) |*e| return e; return null; } pub fn format(d: *const Diagnostics, w: *std.Io.Writer) std.Io.Writer.Error!void { if (d.oauth.message()) |m| return m.format(w); return d.http.format(w); } }; pub const Error = http.Error || error{ /// `base_url` or a path built from it is not a URL. InvalidEndpoint, /// The response was 2xx but was not the JSON this expected. Malformed, /// The access token has expired and there is no refresh token to spend. /// The user has to sign in again. NoRefreshToken, /// The refresh was refused. `Diagnostics.oauth` says why; `invalid_grant` /// means the grant itself is gone. RefreshFailed, /// `on_refresh` returned an error. The tokens in memory are the new ones; /// whatever was supposed to persist them did not. RefreshHookFailed, }; /// What a batch can fail with on top of everything else. pub const BatchError = Error || error{ /// More calls than `batch.max_calls`, which Google refuses whole rather /// than truncating. Send them in chunks of `batch.recommended_calls`. TooManyCalls, /// A call's body contains the boundary that was supposed to separate it /// from the others, eight independently chosen boundaries running. /// /// The boundary is 128 random bits picked after the payloads exist, so /// this cannot be reached by accident or arranged on purpose; it is an /// error rather than an assertion because silently sending a batch that /// ends at whatever byte collided would be worse. BoundaryCollision, }; // -- authentication --------------------------------------------------------- /// Refreshes the access token if it is expired or about to be, and returns /// whether it did. /// /// Every call here does this on its own, so a caller only needs it to force /// the issue -- at the start of a long run, say, so that a refresh failure /// surfaces before an hour of work rather than after it. pub fn refreshIfNeeded( c: *Client, io: std.Io, gpa: std.mem.Allocator, diagnostics: *Diagnostics, ) Error!bool { if (!c.tokens.isExpired(io, c.refresh_leeway)) return false; try c.forceRefresh(io, gpa, diagnostics); return true; } /// Spends the refresh token whether or not the access token looks expired. pub fn forceRefresh( c: *Client, io: std.Io, gpa: std.mem.Allocator, diagnostics: *Diagnostics, ) Error!void { const refresh_token = c.tokens.refresh_token orelse return error.NoRefreshToken; var refreshed = c.oauth.refresh(io, gpa, refresh_token, &diagnostics.oauth) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, else => { log.debug("refresh failed: {t}", .{err}); return error.RefreshFailed; }, }; { // `replaceWithRefreshed` consumes `refreshed` and frees it, so this // errdefer is scoped to the one call that can fail before it does. // Left armed for the rest of the function it would free the token set // a second time, which is what the hook-failure path did. errdefer refreshed.deinit(); // The response routinely omits the refresh token (keep the old one) // and occasionally rotates it (use the new one). Both are handled // here rather than by assignment, which is the bug this call exists // to prevent. try c.tokens.replaceWithRefreshed(&refreshed); } if (c.on_refresh) |hook| { hook.func(hook.context, c.tokens) catch |err| { // Logged as well as returned: `RefreshHookFailed` erases which // error the hook actually hit, and that is the useful part. log.warn("could not persist refreshed tokens: {t}", .{err}); return error.RefreshHookFailed; }; } } // -- the API ---------------------------------------------------------------- /// `users.getProfile`. The cheapest call there is, which also makes it the /// way to check that a token works. pub fn getProfile( c: *Client, io: std.Io, gpa: std.mem.Allocator, diagnostics: *Diagnostics, ) Error!Response(Profile) { var body = try c.getJson(io, gpa, "profile", null, c.max_response_bytes, diagnostics); errdefer body.deinit(); return .{ .value = Profile.fromJson(body.root) catch return error.Malformed, .owned = body, }; } /// `users.labels.list`. Not paginated: Gmail returns every label at once, /// which it can because a mailbox has tens of them rather than thousands. pub fn listLabels( c: *Client, io: std.Io, gpa: std.mem.Allocator, diagnostics: *Diagnostics, ) Error!Response([]const Label) { var body = try c.getJson(io, gpa, "labels", null, c.max_response_bytes, diagnostics); errdefer body.deinit(); const alloc = body.arena.allocator(); const items = json.array(body.root, "labels") orelse &.{}; var list: std.ArrayList(Label) = .empty; try list.ensureTotalCapacityPrecise(alloc, items.len); for (items) |item| { const l = Label.fromJson(item) catch |err| switch (err) { error.Malformed => continue, error.OutOfMemory => return error.OutOfMemory, }; list.appendAssumeCapacity(l); } return .{ .value = try list.toOwnedSlice(alloc), .owned = body }; } /// `users.labels.get`, which is how the message and thread counts are had: /// `listLabels` leaves them out. pub fn getLabel( c: *Client, io: std.Io, gpa: std.mem.Allocator, label_id: []const u8, diagnostics: *Diagnostics, ) Error!Response(Label) { const path = try resourcePath(gpa, "labels", label_id); defer gpa.free(path); var body = try c.getJson(io, gpa, path, null, c.max_response_bytes, diagnostics); errdefer body.deinit(); return .{ .value = Label.fromJson(body.root) catch return error.Malformed, .owned = body, }; } /// Builds the id-to-name table a message needs to render its `label_ids` as /// something a person would recognise. /// /// System labels get `Label.SystemId.conventionalName`, so `INBOX` comes back /// as `inbox`; user labels keep the names their owner gave them. Which labels /// are worth keeping is the application's decision and not this one's, so /// every label is in here and none are filtered out. pub fn labelMap( c: *Client, io: std.Io, gpa: std.mem.Allocator, diagnostics: *Diagnostics, ) Error!LabelMap { var labels = try c.listLabels(io, gpa, diagnostics); // The arena the names live in becomes the map's. errdefer labels.deinit(); var map: std.StringArrayHashMapUnmanaged([]const u8) = .empty; const alloc = labels.owned.arena.allocator(); try map.ensureTotalCapacity(alloc, labels.value.len); for (labels.value) |l| map.putAssumeCapacity(l.id, l.conventionalName()); return .{ .map = map, .owned = labels.owned }; } pub const LabelMap = struct { map: std.StringArrayHashMapUnmanaged([]const u8), owned: Owned, /// The name for a label id, borrowed from the map. `null` for an id the /// mailbox has no label for, which happens when a label is deleted /// between the listing and the message that still mentions it. pub fn get(m: *const LabelMap, label_id: []const u8) ?[]const u8 { return m.map.get(label_id); } pub fn count(m: *const LabelMap) usize { return m.map.count(); } pub fn deinit(m: *LabelMap) void { m.owned.deinit(); m.* = undefined; } }; pub const Format = enum { /// Ids, labels, snippet and dates. No headers and no body. minimal, /// The MIME tree with the bodies decoded. full, /// The whole RFC 5322 message in `Message.raw`. raw, /// Headers but no body. The only format the `gmail.metadata` scope can /// ask for. metadata, /// The wire spelling, which is the lowercase name. pub fn toString(f: Format) []const u8 { return @tagName(f); } }; pub const GetMessageOptions = struct { format: Format = .full, /// With `format = .metadata`, return only these headers. Empty means all /// of them. Naming the two or three that are wanted turns a message /// fetch into a fraction of the bytes. metadata_headers: []const []const u8 = &.{}, }; /// `users.messages.get`. pub fn getMessage( c: *Client, io: std.Io, gpa: std.mem.Allocator, message_id: []const u8, options: GetMessageOptions, diagnostics: *Diagnostics, ) Error!Response(Message) { const path = try resourcePath(gpa, "messages", message_id); defer gpa.free(path); var qb: oidc.QueryBuilder = .init(gpa); defer qb.deinit(); try qb.add("format", options.format.toString()); for (options.metadata_headers) |h| try qb.add("metadataHeaders", h); var body = try c.getJson(io, gpa, path, qb.written(), c.max_message_bytes, diagnostics); errdefer body.deinit(); return .{ .value = Message.fromJson(body.arena.allocator(), body.root) catch |err| switch (err) { error.Malformed => return error.Malformed, error.OutOfMemory => return error.OutOfMemory, }, .owned = body, }; } pub const ListMessagesOptions = struct { /// A Gmail search query, the same syntax the search box takes: /// `after:1700000000`, `-in:chat`, `has:attachment`. q: ?[]const u8 = null, /// Only messages carrying all of these labels. label_ids: []const []const u8 = &.{}, /// Gmail leaves spam and trash out unless asked. A mirror of the mailbox /// wants them; a reader of the inbox does not. include_spam_trash: bool = false, /// Per page. Gmail's maximum is 500 and its default is 100. max_results: u32 = 500, /// Where to resume. A long walk that is interrupted stores /// `MessageIterator.next_page_token` and starts again here -- which is /// why this library keeps no state file of its own. page_token: ?[]const u8 = null, }; /// One page of `users.messages.list`. /// /// The messages in it are stubs: `id` and `thread_id` and nothing else, which /// is all the API sends. Fetching each one is `getMessage`. pub fn listMessages( c: *Client, io: std.Io, gpa: std.mem.Allocator, options: ListMessagesOptions, diagnostics: *Diagnostics, ) Error!Page(Message) { var qb: oidc.QueryBuilder = .init(gpa); defer qb.deinit(); var num_buf: [24]u8 = undefined; try qb.add("maxResults", decimal(&num_buf, options.max_results)); if (options.include_spam_trash) try qb.add("includeSpamTrash", "true"); try qb.addOptional("q", options.q); try qb.addOptional("pageToken", options.page_token); for (options.label_ids) |l| try qb.add("labelIds", l); var body = try c.getJson(io, gpa, "messages", qb.written(), c.max_response_bytes, diagnostics); errdefer body.deinit(); const alloc = body.arena.allocator(); const items = json.array(body.root, "messages") orelse &.{}; var list: std.ArrayList(Message) = .empty; try list.ensureTotalCapacityPrecise(alloc, items.len); for (items) |item| { const m = Message.fromJson(alloc, item) catch |err| switch (err) { error.Malformed => continue, error.OutOfMemory => return error.OutOfMemory, }; list.appendAssumeCapacity(m); } return .{ .items = try list.toOwnedSlice(alloc), .next_page_token = json.nonEmptyString(body.root, "nextPageToken"), .result_size_estimate = json.unsigned(body.root, "resultSizeEstimate"), .owned = body, }; } /// Walks every page of `users.messages.list`. pub fn messageIterator(c: *Client, options: ListMessagesOptions) MessageIterator { return .{ .client = c, .options = options, .next_page_token = options.page_token }; } pub const MessageIterator = struct { client: *Client, options: ListMessagesOptions, /// The token for the page *after* the one currently loaded, and the whole /// of what has to be stored to resume this walk later. `null` once the /// last page has been loaded. next_page_token: ?[]const u8, page: ?Page(Message) = null, index: usize = 0, started: bool = false, /// The next message stub, or `null` at the end of the mailbox. /// /// **The result is borrowed from the iterator** and stays valid only until /// the next call to `next`, which frees the page it came out of. Anything /// that outlives the loop body -- an id going into a list -- must be /// copied. pub fn next( it: *MessageIterator, io: std.Io, gpa: std.mem.Allocator, diagnostics: *Diagnostics, ) Error!?Message { while (true) { if (it.page) |p| { if (it.index < p.items.len) { defer it.index += 1; return p.items[it.index]; } if (it.next_page_token == null) return null; } else if (it.started) { return null; } var options = it.options; options.page_token = it.next_page_token; var page = try it.client.listMessages(io, gpa, options, diagnostics); errdefer page.deinit(); // The token is read before the old page is freed, because it is // borrowed from the *new* page's arena -- and dropped after, // because the old page's arena is where the previous one lived. const token = page.next_page_token; if (it.page) |*old| old.deinit(); it.page = page; it.next_page_token = token; it.index = 0; it.started = true; // An empty page with a token is not the end: Gmail returns one // when a query filters out everything on that page. if (page.items.len == 0 and token == null) return null; } } pub fn deinit(it: *MessageIterator) void { if (it.page) |*p| p.deinit(); it.* = undefined; } }; pub const ListHistoryOptions = struct { /// Required, and the whole point: everything that happened after this /// point in the sequence. It comes from `Profile.history_id` or from the /// largest `History.id` of the previous run. start_history_id: u64, /// Only changes involving this label. label_id: ?[]const u8 = null, /// Which kinds of change to report. Empty means all of them. history_types: []const HistoryType = &.{}, /// Per page. Gmail's maximum is 500 and its default is 100. max_results: u32 = 500, page_token: ?[]const u8 = null, }; pub const HistoryType = enum { messageAdded, messageDeleted, labelAdded, labelRemoved, }; /// One page of `users.history.list`. /// /// `error.HistoryTooOld` is the one to handle: Gmail keeps about a week of /// history, and a `start_history_id` older than that is gone. It is not /// retryable and it is not a bug -- it means the incremental path is /// unavailable and the mailbox has to be listed in full. pub fn listHistory( c: *Client, io: std.Io, gpa: std.mem.Allocator, options: ListHistoryOptions, diagnostics: *Diagnostics, ) (Error || error{HistoryTooOld})!Page(History) { var qb: oidc.QueryBuilder = .init(gpa); defer qb.deinit(); var start_buf: [24]u8 = undefined; var max_buf: [24]u8 = undefined; try qb.add("startHistoryId", decimal(&start_buf, options.start_history_id)); try qb.add("maxResults", decimal(&max_buf, options.max_results)); try qb.addOptional("labelId", options.label_id); try qb.addOptional("pageToken", options.page_token); for (options.history_types) |t| try qb.add("historyTypes", @tagName(t)); var body = c.getJson(io, gpa, "history", qb.written(), c.max_response_bytes, diagnostics) catch |err| switch (err) { error.ApiError => { // A 404 from this endpoint is not "no such mailbox", it is "that // history id has aged out". Nothing else here returns 404. if (diagnostics.http.status == .not_found) return error.HistoryTooOld; return error.ApiError; }, else => |e| return e, }; errdefer body.deinit(); const alloc = body.arena.allocator(); const items = json.array(body.root, "history") orelse &.{}; var list: std.ArrayList(History) = .empty; try list.ensureTotalCapacityPrecise(alloc, items.len); for (items) |item| { const h = History.fromJson(alloc, item) catch |err| switch (err) { error.Malformed => continue, error.OutOfMemory => return error.OutOfMemory, }; list.appendAssumeCapacity(h); } return .{ .items = try list.toOwnedSlice(alloc), .next_page_token = json.nonEmptyString(body.root, "nextPageToken"), // The mailbox's current history id, which is what to store *after* // the whole walk -- not the largest id seen, which would miss // anything that happened during it. .history_id = json.unsigned64(body.root, "historyId"), .owned = body, }; } /// Walks every page of `users.history.list`. pub fn historyIterator(c: *Client, options: ListHistoryOptions) HistoryIterator { return .{ .client = c, .options = options, .next_page_token = options.page_token }; } pub const HistoryIterator = struct { client: *Client, options: ListHistoryOptions, next_page_token: ?[]const u8, /// The mailbox's history id as of the last page fetched. Store this when /// the walk finishes; it is where the next run starts. history_id: ?u64 = null, page: ?Page(History) = null, index: usize = 0, started: bool = false, /// The next history record. Borrowed, and invalidated by the following /// call to `next`; see `MessageIterator.next`. pub fn next( it: *HistoryIterator, io: std.Io, gpa: std.mem.Allocator, diagnostics: *Diagnostics, ) (Error || error{HistoryTooOld})!?History { while (true) { if (it.page) |p| { if (it.index < p.items.len) { defer it.index += 1; return p.items[it.index]; } if (it.next_page_token == null) return null; } else if (it.started) { return null; } var options = it.options; options.page_token = it.next_page_token; var page = try it.client.listHistory(io, gpa, options, diagnostics); errdefer page.deinit(); const token = page.next_page_token; const history_id = page.history_id; if (it.page) |*old| old.deinit(); it.page = page; it.next_page_token = token; if (history_id) |h| it.history_id = h; it.index = 0; it.started = true; if (page.items.len == 0 and token == null) return null; } } pub fn deinit(it: *HistoryIterator) void { if (it.page) |*p| p.deinit(); it.* = undefined; } }; // -- batches ---------------------------------------------------------------- /// `users.messages.get`, many at a time, in one request. /// /// This is what makes the first sync of a large mailbox bearable: a page of /// `listMessages` is 500 ids and each one otherwise wants its own round trip. /// It does not make them cheaper -- Google counts a batch of fifty as fifty /// calls against the quota, and `error.TooManyRetries` still means the same /// thing -- it makes them one round trip instead of fifty. /// /// ```zig /// var ids: std.ArrayList([]const u8) = .empty; /// // ... fill it from `messageIterator`, copying each id ... /// /// var start: usize = 0; /// while (start < ids.items.len) { /// const end = @min(start + gmail.batch.recommended_calls, ids.items.len); /// var got = try client.batchGetMessages(io, gpa, ids.items[start..end], .{}, &d); /// defer got.deinit(); /// for (got.items) |item| { /// const message = item.value orelse { /// std.log.warn("{f}", .{item}); /// continue; /// }; /// // ... /// } /// start = end; /// } /// ``` /// /// **A call that failed is not retried.** The outer request succeeded, so the /// backoff in `http` never sees the failure; a part that came back 429 or 503 /// is one to ask for again, and the ids to ask for are the ones whose /// `Item.value` is `null`. The exception is a token that has expired, which /// arrives as every part failing 401 and is spent on one refresh here, the /// same as it would be for a single call. /// /// `message_ids` may hold at most `batch.max_calls`, and wants to hold at most /// `batch.recommended_calls`. pub fn batchGetMessages( c: *Client, io: std.Io, gpa: std.mem.Allocator, message_ids: []const []const u8, options: GetMessageOptions, diagnostics: *Diagnostics, ) BatchError!Batch(Message) { if (message_ids.len > batch.max_calls) return error.TooManyCalls; var arena: std.heap.ArenaAllocator = .init(gpa); errdefer arena.deinit(); const alloc = arena.allocator(); // One query string for every call in the batch, since the format is the // whole of what varies and it does not vary per message. var qb: oidc.QueryBuilder = .init(gpa); defer qb.deinit(); try qb.add("format", options.format.toString()); for (options.metadata_headers) |h| try qb.add("metadataHeaders", h); const calls = try alloc.alloc(batch.Call, message_ids.len); const items = try alloc.alloc(Batch(Message).Item, message_ids.len); for (message_ids, calls, items) |id, *call, *item| { const path = try resourcePath(alloc, "messages", id); call.* = .{ .target = try c.buildTarget(alloc, path, qb.written()) }; // Copied, because the reason to ask for a message id back is to say // which one failed, and the caller's list may be a page that has // since been freed. item.* = .{ .id = try alloc.dupe(u8, id) }; } try c.batchInto(io, gpa, alloc, calls, Message, items, diagnostics); return .{ .items = items, .arena = arena }; } /// A batch of anything, with each reply left as the JSON it arrived as. /// /// The way to reach an endpoint this library has no method for -- and the way /// it would reach one it has no *reason* for, since a batch of /// `users.labels.get` is the only other read worth making fifty of. Each /// call's `target` is a path from the root of the service, which is what /// `Client` would have built for it: /// /// ```zig /// var got = try client.batchJson(io, gpa, &.{ /// .{ .target = "/gmail/v1/users/me/labels/INBOX" }, /// .{ .target = "/gmail/v1/users/me/labels/SENT" }, /// }, &d); /// defer got.deinit(); /// ``` /// /// `Item.id` is the call's target, since that is the only name it has. pub fn batchJson( c: *Client, io: std.Io, gpa: std.mem.Allocator, calls: []const batch.Call, diagnostics: *Diagnostics, ) BatchError!Batch(std.json.Value) { if (calls.len > batch.max_calls) return error.TooManyCalls; var arena: std.heap.ArenaAllocator = .init(gpa); errdefer arena.deinit(); const alloc = arena.allocator(); const items = try alloc.alloc(Batch(std.json.Value).Item, calls.len); for (calls, items) |call, *item| item.* = .{ .id = try alloc.dupe(u8, call.target) }; try c.batchInto(io, gpa, alloc, calls, std.json.Value, items, diagnostics); return .{ .items = items, .arena = arena }; } /// What a batch comes back as: one item per call, in the order the calls were /// made whatever order the replies arrived in. pub fn Batch(comptime T: type) type { return struct { items: []const Item, arena: std.heap.ArenaAllocator, pub const Item = struct { /// What the call asked for: a message id, or a call's target. id: []const u8, /// The status on the reply's own status line. `null` when no part /// of the response named this call at all, which is what a /// response that was cut short looks like from here. status: ?std.http.Status = null, /// What the call returned, when it succeeded. value: ?T = null, /// Google's error object, when the call failed and sent one. /// /// It lives in the batch's arena and must not be `deinit`ed on /// its own; freeing the batch frees it. err: ?ApiError = null, /// Whether this call returned what it was asked for. A `false` /// with no `err` and a 2xx `status` means the reply was not the /// JSON this expected -- the same thing `error.Malformed` means /// for a call made on its own. pub fn ok(i: Item) bool { return i.value != null; } pub fn format(i: *const Item, w: *std.Io.Writer) std.Io.Writer.Error!void { try w.print("{s}: ", .{i.id}); if (i.err) |*e| return e.format(w); const status = i.status orelse return w.writeAll("no reply"); try w.print("HTTP {d} {s}", .{ @backingInt(status), status.phrase() orelse "" }); if (i.value == null) try w.writeAll(" (unreadable)"); } }; /// How many of the calls returned what they were asked for. pub fn okCount(b: *const @This()) usize { var n: usize = 0; for (b.items) |item| n += @intFromBool(item.ok()); return n; } pub fn deinit(b: *@This()) void { b.arena.deinit(); b.* = undefined; } }; } /// Sends `calls` and fills `items` in from the replies. /// /// `items` holds one entry per call already, and `alloc` is the arena those /// entries live in: everything read out of the response is allocated from it, /// because a parsed message outliving the arena its strings are in is the one /// way this could go wrong quietly. fn batchInto( c: *Client, io: std.Io, gpa: std.mem.Allocator, alloc: std.mem.Allocator, calls: []const batch.Call, comptime T: type, items: []Batch(T).Item, diagnostics: *Diagnostics, ) BatchError!void { std.debug.assert(items.len == calls.len); // An empty batch is a request Google refuses, and there is nothing to ask // it for anyway. if (calls.len == 0) return; const body = try c.batchSend(io, gpa, calls, diagnostics); defer gpa.free(body); var replies = batch.iterate(body) catch return error.Malformed; var position: usize = 0; while (replies.next()) |reply| : (position += 1) { // The `Content-ID` is what pairs a reply with its call, because the // calls may be executed in any order. Position is the fallback for a // part that carried none, which is Google's documented behaviour for // a request that carried none and not something this sends. const index = reply.index orelse position; if (index >= items.len) continue; const item = &items[index]; item.status = reply.status; if (reply.status.class() == .success) { item.value = parseValue(T, alloc, reply.body) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.Malformed => continue, }; } else { item.err = ApiError.parseLeaky(alloc, reply.body) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, // A failure that is not a Google error object: the status is // all there is to say about it, and it is already recorded. error.NotAnError => continue, }; } } if (replies.truncated) { // Saturating, because a server that sent more parts than there were // calls is exactly the sort of server that would also cut one in // half, and a panic in the logging would be a poor way to find out. log.warn("the batch response ended mid-part; {d} calls have no reply", .{ items.len -| position, }); } } fn parseValue(comptime T: type, alloc: std.mem.Allocator, body: []const u8) error{ OutOfMemory, Malformed }!T { const root = std.json.parseFromSliceLeaky(std.json.Value, alloc, body, .{}) catch return error.Malformed; if (root != .object) return error.Malformed; return switch (T) { std.json.Value => root, Message => try Message.fromJson(alloc, root), else => @compileError("no batch parser for " ++ @typeName(T)), }; } /// Sends one batch, refreshing the access token beforehand if it is due -- /// and again if every call in it came back 401. /// /// That second one is the difference between this and every other call here. /// A batch whose calls all failed is still a successful HTTP response, so an /// expired token arrives as one 200 containing fifty 401s rather than as a /// 401, and nothing that looks at the outer status would spend the refresh /// token. The alternative is a sync that appears to run and fetches nothing. fn batchSend( c: *Client, io: std.Io, gpa: std.mem.Allocator, calls: []const batch.Call, diagnostics: *Diagnostics, ) BatchError![]u8 { _ = try c.refreshIfNeeded(io, gpa, diagnostics); const body = c.batchOnce(io, gpa, calls, diagnostics) catch |err| switch (err) { // The outer request was refused, which is something in front of the // API rather than the batch itself. error.Unauthorized => { log.debug("401 on the batch itself with a token that looked good; refreshing", .{}); try c.forceRefresh(io, gpa, diagnostics); return c.batchOnce(io, gpa, calls, diagnostics); }, else => |e| return e, }; if (!allUnauthorized(body)) return body; gpa.free(body); log.debug("every call in the batch came back 401; refreshing", .{}); try c.forceRefresh(io, gpa, diagnostics); return c.batchOnce(io, gpa, calls, diagnostics); } /// Whether every reply in `body` is a 401, which is what an access token that /// has expired looks like from inside a batch. /// /// Every one rather than any one: a single 401 out of fifty is a call that /// asked for something this grant may not have, and spending the refresh /// token on it would not help. fn allUnauthorized(body: []const u8) bool { var replies = batch.iterate(body) catch return false; var seen: usize = 0; while (replies.next()) |reply| : (seen += 1) { if (reply.status != .unauthorized) return false; } return seen > 0; } fn batchOnce( c: *Client, io: std.Io, gpa: std.mem.Allocator, calls: []const batch.Call, diagnostics: *Diagnostics, ) BatchError![]u8 { // A seed, not a secret; the same reasoning as in `http.fetch`. const nanos: u96 = @bitCast(std.Io.Timestamp.now(io, .real).nanoseconds); var fallback: std.Random.DefaultPrng = .init(@truncate(nanos)); const rng = c.rng orelse fallback.random(); var boundary_buf: [batch.boundary_len]u8 = undefined; var boundary = batch.randomBoundary(rng, &boundary_buf); var tries: u8 = 0; while (batch.collides(boundary, calls)) : (tries += 1) { if (tries == 8) return error.BoundaryCollision; boundary = batch.randomBoundary(rng, &boundary_buf); } var payload: std.Io.Writer.Allocating = .init(gpa); defer payload.deinit(); batch.writeRequest(&payload.writer, boundary, calls) catch return error.OutOfMemory; var content_type_buf: [batch.content_type_prefix.len + batch.boundary_len]u8 = undefined; const content_type = batch.contentType(&content_type_buf, boundary); const url = try c.buildBatchUrl(gpa); defer gpa.free(url); return c.sendOnce(io, gpa, .{ .method = .POST, .url = url, .payload = payload.written(), .content_type = content_type, .max_response_bytes = c.max_batch_bytes, }, diagnostics); } // -- plumbing --------------------------------------------------------------- /// A parsed response body and the arena everything in it points into. pub const Owned = struct { arena: std.heap.ArenaAllocator, root: std.json.Value, pub fn deinit(o: *Owned) void { o.arena.deinit(); o.* = undefined; } }; /// A single resource, and the memory its strings live in. pub fn Response(comptime T: type) type { return struct { value: T, owned: Owned, pub fn deinit(r: *@This()) void { r.owned.deinit(); r.* = undefined; } }; } /// One page of a listing, and the memory its contents live in. pub fn Page(comptime T: type) type { return struct { items: []const T, /// Ask for the next page with this. `null` at the end of the listing. next_page_token: ?[]const u8 = null, /// `users.messages.list` only: Gmail's guess at the total, which is a /// guess and can move between pages. result_size_estimate: ?u32 = null, /// `users.history.list` only. history_id: ?u64 = null, owned: Owned, pub fn deinit(p: *@This()) void { p.owned.deinit(); p.* = undefined; } }; } /// Does one GET against `/gmail/v1/users//`, refreshing the /// token first if it is due and once more if the call is refused anyway. fn getJson( c: *Client, io: std.Io, gpa: std.mem.Allocator, path: []const u8, query: ?[]const u8, max_response_bytes: usize, diagnostics: *Diagnostics, ) Error!Owned { _ = try c.refreshIfNeeded(io, gpa, diagnostics); const body = c.getOnce(io, gpa, path, query, max_response_bytes, diagnostics) catch |err| switch (err) { // The token was refused despite looking valid -- a revoked grant, or // a clock that disagrees with Google's. One refresh, one more try, // and then the failure is real. error.Unauthorized => blk: { log.debug("401 with a token that looked good; refreshing", .{}); try c.forceRefresh(io, gpa, diagnostics); break :blk try c.getOnce(io, gpa, path, query, max_response_bytes, diagnostics); }, else => |e| return e, }; defer gpa.free(body); var arena: std.heap.ArenaAllocator = .init(gpa); errdefer arena.deinit(); const root = std.json.parseFromSliceLeaky( std.json.Value, arena.allocator(), body, .{}, ) catch return error.Malformed; if (root != .object) return error.Malformed; return .{ .arena = arena, .root = root }; } fn getOnce( c: *Client, io: std.Io, gpa: std.mem.Allocator, path: []const u8, query: ?[]const u8, max_response_bytes: usize, diagnostics: *Diagnostics, ) Error![]u8 { const url = try c.buildUrl(gpa, path, query); defer gpa.free(url); return c.sendOnce(io, gpa, .{ .url = url, .max_response_bytes = max_response_bytes, }, diagnostics); } /// One request, with the token on it. Everything that reaches the network /// from this file goes through here. const Send = struct { method: std.http.Method = .GET, /// The whole URL, already built: `getOnce` builds one under /// `/gmail/v1/users//` and `batchOnce` builds the one that is not. url: []const u8, payload: ?[]const u8 = null, content_type: ?[]const u8 = null, max_response_bytes: usize, }; fn sendOnce( c: *Client, io: std.Io, gpa: std.mem.Allocator, send: Send, diagnostics: *Diagnostics, ) Error![]u8 { const uri = std.Uri.parse(send.url) catch return error.InvalidEndpoint; const authorization = try c.tokens.authorizationHeader(gpa); defer gpa.free(authorization); return http.fetch(io, gpa, .{ .method = send.method, .uri = uri, .payload = send.payload, .content_type = send.content_type, .authorization = authorization, .user_agent = c.user_agent, .max_response_bytes = send.max_response_bytes, .retry = c.retry, .rng = c.rng, }, &diagnostics.http); } fn buildUrl( c: *const Client, gpa: std.mem.Allocator, path: []const u8, query: ?[]const u8, ) std.mem.Allocator.Error![]u8 { var buf: std.Io.Writer.Allocating = .init(gpa); errdefer buf.deinit(); // Writing to an `Allocating` can only fail by the allocator failing, // which is why every one of these maps its error to `OutOfMemory`. buf.writer.writeAll(std.mem.trimEnd(u8, c.base_url, "/")) catch return error.OutOfMemory; c.writeTarget(&buf.writer, path, query) catch return error.OutOfMemory; return buf.toOwnedSlice(); } /// The batch endpoint, which is the one URL here that is not under /// `/gmail/v1/users//`: a batch belongs to the service, and the user id /// is in each call inside it. fn buildBatchUrl(c: *const Client, gpa: std.mem.Allocator) std.mem.Allocator.Error![]u8 { return std.mem.concat(gpa, u8, &.{ std.mem.trimEnd(u8, c.base_url, "/"), batch.path }); } /// `/gmail/v1/users//[?query]`, which is a URL's path and /// query and is also exactly what goes on the request line of a call inside a /// batch. fn writeTarget( c: *const Client, w: *std.Io.Writer, path: []const u8, query: ?[]const u8, ) std.Io.Writer.Error!void { try w.writeAll("/gmail/v1/users/"); // `me` needs no encoding and an address does: an `@` is legal in a path // segment, but a `+` in an address is not what it looks like. try oidc.QueryBuilder.encode(w, c.user_id); try w.writeByte('/'); try w.writeAll(path); if (query) |q| { if (q.len > 0) { try w.writeByte('?'); try w.writeAll(q); } } } /// The same, allocated: what a call inside a batch is addressed by. fn buildTarget( c: *const Client, alloc: std.mem.Allocator, path: []const u8, query: ?[]const u8, ) std.mem.Allocator.Error![]u8 { var buf: std.Io.Writer.Allocating = .init(alloc); errdefer buf.deinit(); c.writeTarget(&buf.writer, path, query) catch return error.OutOfMemory; return buf.toOwnedSlice(); } /// `/` with the id percent-encoded. /// /// Gmail's ids are opaque, so nothing here may assume they are the /// hexadecimal they happen to look like. An id carrying a `/` or a `?` /// unencoded would not merely fail -- it would address a different endpoint. fn resourcePath( gpa: std.mem.Allocator, collection: []const u8, id: []const u8, ) std.mem.Allocator.Error![]u8 { var buf: std.Io.Writer.Allocating = .init(gpa); errdefer buf.deinit(); buf.writer.writeAll(collection) catch return error.OutOfMemory; buf.writer.writeByte('/') catch return error.OutOfMemory; oidc.QueryBuilder.encode(&buf.writer, id) catch return error.OutOfMemory; return buf.toOwnedSlice(); } /// Formats a number into caller-owned scratch space. `QueryBuilder.add` /// copies what it is given, so the buffer only has to outlive the call. fn decimal(buf: []u8, value: u64) []const u8 { // 20 digits is the widest a u64 gets, and every caller passes 24. return std.fmt.bufPrint(buf, "{d}", .{value}) catch unreachable; } test { _ = ApiError; _ = batch; _ = History; _ = Label; _ = Message; _ = Profile; _ = http; _ = json; }