# zig-gmail A Gmail API client for Zig: labels, messages, and the mailbox history that turns a second run into an update rather than another full download. It was pulled out of [allthemail][], where it had grown a hand-written OAuth implementation, four resource parsers and a page-token state file all in the same directory. The OAuth half left first and became [zig-oidc][]; this is the rest of it, with the parsers rewritten to survive what Gmail actually sends. The API documentation is generated from the doc comments — which is where most of the explanation lives — and published at . [allthemail]: https://git.jcollie.dev/jeff/allthemail [zig-oidc]: https://git.jcollie.dev/jeff/zig-oidc ## What it does - **Reads a mailbox**: `users.getProfile`, `users.labels.list` and `.get`, `users.messages.list` and `.get`, `users.history.list`. Listings come as iterators that page on their own. - **Fetches fifty messages in one request.** Gmail's batch endpoint is `multipart/mixed` with whole HTTP requests inside it, and it is what makes the first sync of a large mailbox bearable: a page of ids is 500 round trips otherwise. `Client.batchGetMessages` sends one and pairs each reply with the id that asked for it. - **Keeps the access token alive.** An access token lasts an hour and a mailbox walk lasts longer, so every call refreshes when the token is nearly expired — and once more if a call comes back 401 anyway, which is what a revoked grant or a skewed clock looks like. - **Waits when Gmail says to wait.** A quota failure is retried with exponential backoff and full jitter; a permission failure is not, and neither is `dailyLimitExceeded`, whose quota resets at midnight Pacific and will not improve for being asked again. - **Parses leniently, on purpose.** Gmail omits empty fields rather than sending `null`, adds new ones without warning, and sends its 64-bit numbers as quoted decimal strings. A `std.json.parseFromSlice` into a struct fails on a real mailbox in two different ways; `src/json.zig` says more. - **Says what went wrong.** `ApiError` is Google's error object with the two questions worth asking of it — is this worth retrying, and is this the token. - **Remembers between runs.** `TokenStore` is a refresh token in a 0600 file, replaced atomically, written again whenever Google rotates it. ## What it does not - **No OAuth.** Signing in is [zig-oidc][]'s job and this takes one of its `Client`s and one of its `TokenSet`s already filled in. Keeping the two apart is what lets each be tested against something that is not Google. - **No writing.** No sending, no drafts, no modifying labels, no settings, no push notifications. Reading a mailbox is what this does. `Client.batchJson` will carry a `POST` if a caller builds one, since a batch is the shape that makes that worth doing, but nothing here composes one. - **No opinion about which labels matter.** `Client.labelMap` gives system labels their conventional lowercase names (`INBOX` becomes `inbox`) and leaves user labels alone. Which ones are worth keeping, and what a `CATEGORY_PROMOTIONS` should become in a local mail store, is the application's decision — it was allthemail's, and it stayed there. ## Using it ```console $ zig fetch --save git+https://git.jcollie.dev/jeff/zig-gmail.git ``` ```zig const gmail_dep = b.dependency("gmail", .{ .target = target, .optimize = optimize }); exe.root_module.addImport("gmail", gmail_dep.module("gmail")); ``` Signing in, which happens once and is zig-oidc's half: ```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 = gmail.provider, .client_id = client_id, .client_secret = client_secret, .redirect_uri = redirect_uri, .scopes = gmail.scopes.mirror, }; const rng: std.Random.IoSource = .{ .io = io }; // `access_type=offline` is Google's own, and not optional: without it there // is no refresh token and the grant dies in an hour. var authorization = try oauth.authorize(gpa, rng.interface(), .{ .prompt = "consent", .extra = &.{.{ .name = "access_type", .value = "offline" }}, }); defer authorization.deinit(); std.debug.print("open this: {s}\n", .{authorization.url}); var redirect = try listener.wait(io, gpa, .{}); defer redirect.deinit(); var d: gmail.Client.Diagnostics = .{}; defer d.deinit(gpa); var tokens = try oauth.exchange(io, gpa, &authorization, redirect.query, &d.oauth); defer tokens.deinit(); ``` Reading the mailbox, which is this half: ```zig var store: gmail.TokenStore = .{ .dir = cache_dir, .path = "tokens.json", .io = io }; try store.save(&tokens); var client: gmail.Client = .{ .oauth = oauth, .tokens = &tokens, // Written back after every refresh, including the rotated refresh token // that would otherwise be lost when the process exits. .on_refresh = store.refreshHook(), }; var labels = try client.labelMap(io, gpa, &d); defer labels.deinit(); var it = client.messageIterator(.{ .q = "-in:chat", .include_spam_trash = true }); defer it.deinit(); while (try it.next(io, gpa, &d)) |stub| { var message = try client.getMessage(io, gpa, stub.id, .{ .format = .raw }, &d); defer message.deinit(); // message.value.raw is the whole RFC 5322 message, ready for a maildir. for (message.value.label_ids) |id| { if (labels.get(id)) |name| { /* tag it */ } } } ``` The stub `it.next` returns is borrowed from the iterator and is invalidated by the following call, so an id that outlives the loop body has to be copied. ### Fetching them fifty at a time One message per request is one round trip per message, which is the whole cost of a first sync. The batch endpoint puts fifty of them in one: ```zig 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], .{ .format = .raw, }, &d); defer got.deinit(); for (got.items) |item| { const message = item.value orelse { // The call failed on its own; the batch did not. `item.id` is // what to ask for again. std.log.warn("{f}", .{item}); continue; }; // message.raw is the whole RFC 5322 message. } start = end; } ``` Three things about it are Gmail's rather than this library's: 1. **It is not cheaper, only fewer round trips.** Google counts a batch of fifty as fifty calls against the quota, and recommends batches of no more than fifty for exactly that reason. `batch.max_calls` is the hard limit of 100, and a batch larger than that is refused here rather than by Google, which refuses the whole thing. 2. **A call that failed is not retried.** The outer request succeeded, so the backoff 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 `value` is `null`. 3. **A batch whose every call failed still comes back 200.** An expired access token arrives as one successful response containing fifty 401s rather than as a 401. That one is handled: a batch where every call was refused is spent on one refresh and sent again, the same as a single call would be. ### Synchronising twice The second run is the reason `history` exists, and it has two rules that are Gmail's rather than this library's: 1. **Remember the history id from before the walk, not after it.** `profile` gives it; anything that happens during a walk that takes an hour is otherwise missed. 2. **Handle `error.HistoryTooOld`.** Gmail keeps about a week of history, and an id older than that is answered with 404. It is not a failure to retry — it means the incremental path is gone and the mailbox has to be listed in full. It is a distinct error for exactly that reason. ```zig var profile = try client.getProfile(io, gpa, &d); defer profile.deinit(); const checkpoint = profile.value.history_id.?; // store this before walking // ... and next time: var changes = client.historyIterator(.{ .start_history_id = stored }); defer changes.deinit(); while (changes.next(io, gpa, &d) catch |err| switch (err) { error.HistoryTooOld => return fullResync(), else => |e| return e, }) |record| { var c = record.changes(); while (c.next()) |change| { /* change.messageId() was touched */ } } // changes.history_id is where the next run starts. ``` Neither run stores a page token or a history id on this library's behalf. `MessageIterator.next_page_token` and `HistoryIterator.history_id` are exposed so that an application can put them wherever it keeps its state — which is what allthemail was doing with two files under `$XDG_STATE_HOME`, and is not something a library should be deciding. ### Scopes `gmail.scopes` has them spelled correctly, and the tiers matter: everything that can see the content of a message is **restricted**, and Google requires a security assessment before an app using one may be published. A program that only needs to know which messages exist and what they are labelled should ask for `scopes.labels` and `scopes.metadata` and stop there — and then `getMessage` works with `.format = .metadata` and nothing else, which is enforced by Google rather than by this. ## The command line client `zig build run` builds a program that reads a real mailbox. It is how the library is checked against actual Gmail; everything in `tests/` talks to a Gmail written a hundred lines away. ```console $ zig build run -- login --client-id ... --client-secret "$(cat secret)" $ zig build run -- profile --client-id ... --client-secret ... $ zig build run -- labels --client-id ... --client-secret ... $ zig build run -- messages --query "newer_than:2d" --limit 20 --client-id ... --client-secret ... $ zig build run -- get 18c1f2a3b4c5d6e7 --format raw --client-id ... --client-secret ... > message.eml $ zig build run -- get 18c1f2a3b4c5d6e7 18c1f2a3b4c5d6e8 --client-id ... --client-secret ... $ zig build run -- history --since 8800112233 --client-id ... --client-secret ... ``` The store defaults to `$XDG_CACHE_HOME/zig-gmail/tokens.json`. It holds a refresh token, so it is written 0600 and belongs somewhere that stays that way. ## Building and testing Everything comes out of the Nix flake: ```console $ nix develop $ zig build test --summary all # 95 tests $ zig build # the command line client $ zig build docs-serve # the API documentation, at :8000 ``` The tests are in three layers. The unit tests beside each source file check what a response turns into and never open a socket. `tests/e2e.zig` stands up a Gmail on a loopback socket and runs the client against it — that is where the things that are not in any one function show up: that pagination stops, that an expired token is refreshed *before* the call rather than after it fails, that a 401 arriving anyway is spent on one refresh and not a loop, that a quota failure is waited out and a permission failure is not, and that a batch in which every call was refused is spent on one refresh. `tests/fuzz.zig` states what the parsers must do with input nobody wrote. ```console $ zig build fuzz-run # a minute per target $ zig build fuzz-run -- --seconds 600 --target message ``` That loop exists because Zig 0.16.0's own fuzzer cannot be used here: it needs a patched standard library to compile at all, and then leaves its coverage table empty. `flake.nix` and `tools/fuzz.zig` say more. It found one real inconsistency while this was being written — a `threadId` of `""` was taken literally, producing a message that claimed to belong to a thread that could not be looked up, where an absent one correctly falls back to the message's own id. ### Dependencies There is one, zig-oidc, and it is fetched by the Zig package manager. A Nix build has no network, so `build.zig.zon.nix` is generated from the manifest by [zon2nix][] and committed; regenerate it whenever the manifest changes: ```console $ nix develop -c zon2nix --16 --nix=build.zig.zon.nix build.zig.zon ``` [zon2nix]: https://git.jcollie.dev/jeff/zon2nix ## Where this lives Three places carry the same history. The Forgejo instance is the web-visible one: ```console $ git clone https://git.jcollie.dev/jeff/zig-gmail.git ``` - Forgejo: - Tangled: - Documentation: It is also on the Radicle network, where the repository's identifier is ``` rad:z3PUwmL9aZSRVYqrtAWubHcVcdNee ``` and ```console $ rad clone rad:z3PUwmL9aZSRVYqrtAWubHcVcdNee ``` fetches it from any node that seeds it. A Radicle repository is findable only by that identifier, so it is written out here rather than linked. Any of the three is the whole project. ## License MIT. The project follows the [REUSE](https://reuse.software/) specification; `reuse lint` passes.