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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Gmail's batch endpoint: whole HTTP requests inside one `multipart/mixed`//! body, and the whole HTTP responses to them inside one `multipart/mixed`//! reply.//!//! It is worth having for the first sync of a large mailbox, where the cost//! is round trips rather than bytes: `users.messages.list` gives a page of//! 500 ids and each one then wants its own request, over its own TLS//! handshake, one at a time. Fifty of them in a single request is fifty times//! fewer of those.//!//! It does **not** make them cheaper. Google is explicit that "a set of n//! requests batched together counts toward your usage limit as n requests,//! not as one request", so a batch runs into the same quota at the same rate//! and the same backoff still applies to it.//!//! ## The shape//!//! ```http//! POST /batch/gmail/v1 HTTP/1.1//! Content-Type: multipart/mixed; boundary=batch_zig_gmail_0123...//!//! --batch_zig_gmail_0123...//! Content-Type: application/http//! Content-Transfer-Encoding: binary//! Content-ID: <0>//!//! GET /gmail/v1/users/me/messages/m1?format=raw HTTP/1.1//!//! --batch_zig_gmail_0123...--//! ```//!//! The reply is the same shape with `HTTP/1.1 200 OK` and a body where the//! request line was, and `Content-ID: <response-0>` naming which call each//! part answers. Google is explicit that the calls may be executed in any//! order, so that number is the only thing that pairs a reply with what asked//! for it -- which is why `writeRequest` numbers the calls rather than//! letting a caller choose the label. A message id in a header is a string//! from a mailbox going into a place where a `>` would end the field, and the//! index is a number this library wrote.//!//! ## The trap//!//! **A batch whose every call failed still comes back 200.** The statuses are//! inside the parts, so an expired access token produces one successful HTTP//! response containing fifty 401s rather than a 401. Nothing that looks at//! the outer status will notice, which is why `Client` looks at the inner//! ones before it believes them.//!//! ## What is parsed//!//! Enough of RFC 2046 to read what this endpoint sends, and no more. The//! boundary is taken from the body itself rather than from the response's//! `Content-Type`, because `std.http.Client.fetch` in 0.16 hands back the//! status and nothing else; a multipart body begins with its own delimiter,//! so it is there to be read. What that costs is a preamble: anything before//! the first delimiter other than blank lines is refused rather than skipped,//! since a parser that went looking for a delimiter further down could find//! one inside a message instead.
const std = @import("std");
/// Where a batch goes. Not under `/gmail/v1/users/<id>/` like every other/// call: the batch endpoint belongs to the service rather than to a mailbox,/// and the user id is in each call inside it.pub const path = "/batch/gmail/v1";
/// Google's ceiling. A batch with more calls than this is refused whole.pub const max_calls = 100;
/// What Google recommends instead of `max_calls`: a hundred calls arriving at/// once is what provokes the rate limiter that batching was meant to get out/// from under.pub const recommended_calls = 50;
pub const content_type_prefix = "multipart/mixed; boundary=";
/// One call inside a batch.pub const Call = struct { method: std.http.Method = .GET, /// The path and query of the call, from the root of the service: /// `/gmail/v1/users/me/messages/m1?format=raw`. Not a URL -- the host is /// the one the batch itself was sent to. target: []const u8, /// The call's body, already encoded. `content_type` goes with it. payload: ?[]const u8 = null, content_type: []const u8 = "application/json",};
/// `batch_zig_gmail_` and 128 bits of hexadecimal.pub const boundary_len = boundary_prefix.len + 32;
const boundary_prefix = "batch_zig_gmail_";
/// Writes a boundary that cannot occur in what it separates.////// It has to be unpredictable rather than merely unique, because the parts/// are not escaped in any way: a payload containing the boundary would end/// the part early, and 128 random bits chosen after that payload exists is/// what makes it impossible to arrange. Nothing is being kept secret, so the/// generator does not have to be a cryptographic one -- `Client.rng`, or the/// clock.pub fn randomBoundary(rng: std.Random, buf: *[boundary_len]u8) []const u8 { var bytes: [16]u8 = undefined; rng.bytes(&bytes); @memcpy(buf[0..boundary_prefix.len], boundary_prefix); @memcpy(buf[boundary_prefix.len..], &std.fmt.bytesToHex(bytes, .lower)); return buf;}
/// `multipart/mixed; boundary=...`, written into caller-owned scratch space.pub fn contentType(buf: *[content_type_prefix.len + boundary_len]u8, boundary: []const u8) []const u8 { @memcpy(buf[0..content_type_prefix.len], content_type_prefix); @memcpy(buf[content_type_prefix.len..][0..boundary.len], boundary); return buf[0 .. content_type_prefix.len + boundary.len];}
/// Writes the request body for `calls`, which must not be longer than/// `max_calls`.////// Each call is numbered by its position, and that number comes back on the/// reply that answers it.pub fn writeRequest( w: *std.Io.Writer, boundary: []const u8, calls: []const Call,) std.Io.Writer.Error!void { for (calls, 0..) |call, index| { try w.print("--{s}\r\n", .{boundary}); try w.writeAll("Content-Type: application/http\r\n"); try w.writeAll("Content-Transfer-Encoding: binary\r\n"); try w.print("Content-ID: <{d}>\r\n\r\n", .{index});
try w.print("{s} {s} HTTP/1.1\r\n", .{ @tagName(call.method), call.target }); if (call.payload) |payload| { try w.print("Content-Type: {s}\r\n", .{call.content_type}); try w.print("Content-Length: {d}\r\n", .{payload.len}); try w.writeAll("\r\n"); try w.writeAll(payload); try w.writeAll("\r\n"); } else { // The blank line that ends the call's headers. The CRLF before // the next delimiter is the delimiter's own. try w.writeAll("\r\n"); } } try w.print("--{s}--\r\n", .{boundary});}
/// Whether `boundary` occurs anywhere in what the batch would carry, which is/// the one way a boundary can fail to separate anything.////// With a boundary from `randomBoundary` this cannot happen; it is checked/// anyway because the alternative to checking is a batch that is silently/// truncated at whatever byte collided.pub fn collides(boundary: []const u8, calls: []const Call) bool { for (calls) |call| { if (std.mem.find(u8, call.target, boundary) != null) return true; if (call.payload) |payload| { if (std.mem.find(u8, payload, boundary) != null) return true; } } return false;}
/// One part of a batch response: the reply to one of the calls.pub const Reply = struct { /// Which call this answers, from the `Content-ID` Google echoed back. /// `null` when the part carried none, or carried one that was not a /// number this library could have written. index: ?usize, status: std.http.Status, /// The reply's body, borrowed from the response the iterator was given. body: []const u8,};
pub const ParseError = error{ /// The response was not a `multipart/mixed` body that begins with its own /// delimiter. MalformedBatch,};
/// Walks the parts of a batch response.////// A part that is not a reply at all -- no status line, no headers -- is/// skipped rather than ending the walk, on the same principle as everything/// else here: one unreadable answer out of fifty should cost one answer.pub fn iterate(body: []const u8) ParseError!Iterator { const delimiter = try findDelimiter(body); var parts = std.mem.splitSequence(u8, body, delimiter); // Whatever came before the first delimiter, which `findDelimiter` has // already established is nothing. _ = parts.next(); // Read ahead *before* the iterator is built: a struct initializer copies // `parts` as it stands when that field is written, so advancing it in the // next field would leave the copy one part behind and every part would be // returned twice. const first = parts.next(); return .{ .parts = parts, .pending = first };}
pub const Iterator = struct { parts: std.mem.SplitIterator(u8, .sequence), /// The next part, read ahead, because a part is only a whole part if /// something follows it. `null` ends the walk. pending: ?[]const u8, /// Set when the body ran out before the closing delimiter, which means /// the last part was cut in half and was not returned. A caller that /// asked for fifty and got forty is not told which forty by this -- it is /// told by the forty, since the ten it did not hear about are the ten /// whose reply never arrived. truncated: bool = false,
pub fn next(it: *Iterator) ?Reply { while (it.pending) |chunk| { it.pending = it.parts.next(); // The closing delimiter is the boundary with two more dashes on // it, so the part after it starts with them and is the epilogue. if (std.mem.startsWith(u8, chunk, "--")) { it.pending = null; return null; } // Nothing followed this one, so the delimiter that would have // ended it never arrived and whatever is in it is half of a // reply rather than a short one. if (it.pending == null) { it.truncated = true; return null; } if (parsePart(trimOneNewline(chunk))) |reply| return reply; } return null; }};
/// The delimiter this body is separated by: its first non-blank line, which/// in a multipart body is `--` and the boundary.fn findDelimiter(body: []const u8) ParseError![]const u8 { var lines = std.mem.splitScalar(u8, body, '\n'); while (lines.next()) |raw| { const line = std.mem.trimEnd(u8, raw, "\r \t"); // Google's batch responses begin with an empty line before the // first delimiter. if (line.len == 0) continue; // Two dashes and at least one byte of boundary. A line of exactly // `--` would split the body at every dash pair in it. if (line.len <= 2 or !std.mem.startsWith(u8, line, "--")) return error.MalformedBatch; return line; } return error.MalformedBatch;}
/// The part's `Content-ID`, and the reply inside it.fn parsePart(part: []const u8) ?Reply { const headers, const reply = splitAtBlankLine(part) orelse return null; const status_line, const rest = splitAtNewline(reply);
return .{ .index = replyIndex(headerValue(headers, "Content-ID")), .status = parseStatus(status_line) orelse return null, // A reply with headers and no blank line after them has no body, // which is what a 204 looks like. The body itself is taken as it // stands -- Google's JSON ends with a newline of its own, and the one // the delimiter contributed has already been trimmed off the part. .body = if (splitAtBlankLine(rest)) |split| split[1] else "", };}
/// `HTTP/1.1 404 Not Found` -> 404.fn parseStatus(line: []const u8) ?std.http.Status { if (!std.mem.startsWith(u8, line, "HTTP/")) return null; const after_version = std.mem.findScalar(u8, line, ' ') orelse return null; const code = std.mem.trim(u8, line[after_version + 1 ..], " \t"); const end = std.mem.findScalar(u8, code, ' ') orelse code.len; // Anything that does not fit the enum's u10 is not a status. const number = std.fmt.parseInt(u10, code[0..end], 10) catch return null; return @enumFromInt(number);}
/// `<response-7>` -> 7, which is the position of the call this answers.fn replyIndex(content_id: ?[]const u8) ?usize { var value = content_id orelse return null; value = std.mem.trim(u8, value, "<> \t"); // Google's own prefix. A part with a bare number is accepted too, since // the prefix is documentation rather than protocol. if (std.mem.startsWith(u8, value, "response-")) value = value["response-".len..]; return std.fmt.parseInt(usize, value, 10) catch null;}
fn headerValue(headers: []const u8, name: []const u8) ?[]const u8 { var lines = std.mem.splitScalar(u8, headers, '\n'); while (lines.next()) |raw| { const line = std.mem.trimEnd(u8, raw, "\r"); const colon = std.mem.findScalar(u8, line, ':') orelse continue; const found = std.mem.trim(u8, line[0..colon], " \t"); if (!std.ascii.eqlIgnoreCase(found, name)) continue; return std.mem.trim(u8, line[colon + 1 ..], " \t"); } return null;}
/// Splits at the blank line that ends a block of headers. CRLF is what this/// protocol uses; bare LF is accepted because a hand-written fixture is the/// other thing that reaches here.fn splitAtBlankLine(text: []const u8) ?struct { []const u8, []const u8 } { // A block with no headers in it at all is the blank line and nothing // before it, which no amount of looking for two line endings will find. if (std.mem.startsWith(u8, text, "\r\n")) return .{ "", text[2..] }; if (std.mem.startsWith(u8, text, "\n")) return .{ "", text[1..] }; if (std.mem.find(u8, text, "\r\n\r\n")) |i| return .{ text[0..i], text[i + 4 ..] }; if (std.mem.find(u8, text, "\n\n")) |i| return .{ text[0..i], text[i + 2 ..] }; return null;}
fn splitAtNewline(text: []const u8) struct { []const u8, []const u8 } { const i = std.mem.findScalar(u8, text, '\n') orelse return .{ std.mem.trimEnd(u8, text, "\r"), "" }; return .{ std.mem.trimEnd(u8, text[0..i], "\r"), text[i + 1 ..] };}
/// Drops one leading and one trailing line ending, which are the delimiter's/// rather than the part's.fn trimOneNewline(text: []const u8) []const u8 { var out = text; if (std.mem.startsWith(u8, out, "\r\n")) { out = out[2..]; } else if (std.mem.startsWith(u8, out, "\n")) { out = out[1..]; } if (std.mem.endsWith(u8, out, "\r\n")) { out = out[0 .. out.len - 2]; } else if (std.mem.endsWith(u8, out, "\n")) { out = out[0 .. out.len - 1]; } return out;}
const testing = std.testing;
test "a request is one part per call, numbered" { var buf: std.Io.Writer.Allocating = .init(testing.allocator); defer buf.deinit();
try writeRequest(&buf.writer, "BOUND", &.{ .{ .target = "/gmail/v1/users/me/messages/m1?format=raw" }, .{ .target = "/gmail/v1/users/me/messages/m2?format=raw" }, });
try testing.expectEqualStrings( "--BOUND\r\n" ++ "Content-Type: application/http\r\n" ++ "Content-Transfer-Encoding: binary\r\n" ++ "Content-ID: <0>\r\n\r\n" ++ "GET /gmail/v1/users/me/messages/m1?format=raw HTTP/1.1\r\n\r\n" ++ "--BOUND\r\n" ++ "Content-Type: application/http\r\n" ++ "Content-Transfer-Encoding: binary\r\n" ++ "Content-ID: <1>\r\n\r\n" ++ "GET /gmail/v1/users/me/messages/m2?format=raw HTTP/1.1\r\n\r\n" ++ "--BOUND--\r\n", buf.written(), );}
test "a call with a body carries its length" { var buf: std.Io.Writer.Allocating = .init(testing.allocator); defer buf.deinit();
try writeRequest(&buf.writer, "B", &.{.{ .method = .POST, .target = "/gmail/v1/users/me/messages/batchModify", .payload = "{\"ids\":[\"m1\"]}", }});
try testing.expect(std.mem.find(u8, buf.written(), "POST /gmail/v1/users/me/messages/batchModify HTTP/1.1\r\n") != null); try testing.expect(std.mem.find(u8, buf.written(), "Content-Type: application/json\r\n") != null); try testing.expect(std.mem.find(u8, buf.written(), "Content-Length: 14\r\n\r\n{\"ids\":[\"m1\"]}\r\n") != null);}
test "an empty batch is a body with nothing but the closing delimiter" { var buf: std.Io.Writer.Allocating = .init(testing.allocator); defer buf.deinit(); try writeRequest(&buf.writer, "B", &.{}); try testing.expectEqualStrings("--B--\r\n", buf.written());}
test "a boundary is unpredictable and does not collide" { var prng: std.Random.DefaultPrng = .init(7); var a: [boundary_len]u8 = undefined; var b: [boundary_len]u8 = undefined; const first = randomBoundary(prng.random(), &a); const second = randomBoundary(prng.random(), &b);
try testing.expectEqual(@as(usize, boundary_len), first.len); try testing.expect(std.mem.startsWith(u8, first, "batch_zig_gmail_")); try testing.expect(!std.mem.eql(u8, first, second));
var ct: [content_type_prefix.len + boundary_len]u8 = undefined; try testing.expectEqualStrings( "multipart/mixed; boundary=" ++ "batch_zig_gmail_", contentType(&ct, first)[0 .. content_type_prefix.len + boundary_prefix.len], );
try testing.expect(!collides(first, &.{.{ .target = "/gmail/v1/users/me/profile" }})); try testing.expect(collides("XY", &.{.{ .target = "/a/XY" }})); try testing.expect(collides("XY", &.{.{ .target = "/a", .payload = "..XY.." }}));}
/// What Google really sends, down to the empty line the body starts with.const google_response = "\r\n--batch_abc\r\n" ++ "Content-Type: application/http\r\n" ++ "Content-ID: <response-0>\r\n" ++ "\r\n" ++ "HTTP/1.1 200 OK\r\n" ++ "Content-Type: application/json; charset=UTF-8\r\n" ++ "\r\n" ++ "{\"id\":\"m1\"}\n" ++ "\r\n--batch_abc\r\n" ++ "Content-Type: application/http\r\n" ++ "Content-ID: <response-1>\r\n" ++ "\r\n" ++ "HTTP/1.1 404 Not Found\r\n" ++ "Content-Type: application/json; charset=UTF-8\r\n" ++ "\r\n" ++ "{\"error\":{\"code\":404}}\n" ++ "\r\n--batch_abc--\r\n";
test "a response is read back into replies" { var it = try iterate(google_response);
const first = it.next().?; try testing.expectEqual(@as(?usize, 0), first.index); try testing.expectEqual(std.http.Status.ok, first.status); try testing.expectEqualStrings("{\"id\":\"m1\"}\n", first.body);
const second = it.next().?; try testing.expectEqual(@as(?usize, 1), second.index); try testing.expectEqual(std.http.Status.not_found, second.status); try testing.expectEqualStrings("{\"error\":{\"code\":404}}\n", second.body);
try testing.expectEqual(@as(?Reply, null), it.next()); // And stays ended. try testing.expectEqual(@as(?Reply, null), it.next());}
test "the replies do not have to arrive in order" { // Google says the calls may be executed in any order, so the index is the // only thing that pairs a reply with the call that asked for it. const out_of_order = "\r\n--b\r\nContent-ID: <response-2>\r\n\r\nHTTP/1.1 200 OK\r\n\r\n{\"n\":2}" ++ "\r\n--b\r\nContent-ID: <response-0>\r\n\r\nHTTP/1.1 200 OK\r\n\r\n{\"n\":0}" ++ "\r\n--b--\r\n";
var it = try iterate(out_of_order); try testing.expectEqual(@as(?usize, 2), it.next().?.index); try testing.expectEqual(@as(?usize, 0), it.next().?.index); try testing.expectEqual(@as(?Reply, null), it.next());}
test "a part with no usable Content-ID has no index" { // What comes back for a call that was sent without one, and what comes // back if Google ever labels a part with something else. const unlabelled = "\r\n--b\r\nContent-ID: response-\r\n\r\nHTTP/1.1 200 OK\r\n\r\n{}" ++ "\r\n--b\r\nContent-Type: application/http\r\n\r\nHTTP/1.1 200 OK\r\n\r\n{}" ++ "\r\n--b\r\nContent-ID: <item1:12930812@barnyard.example.com>\r\n\r\nHTTP/1.1 200 OK\r\n\r\n{}" ++ "\r\n--b--\r\n";
var it = try iterate(unlabelled); for (0..3) |_| { const reply = it.next().?; try testing.expectEqual(@as(?usize, null), reply.index); try testing.expectEqual(std.http.Status.ok, reply.status); } try testing.expectEqual(@as(?Reply, null), it.next());}
test "a part that is not a reply costs one reply and not the walk" { const mixed = "\r\n--b\r\nContent-ID: <response-0>\r\n\r\nthis is not a status line\r\n\r\n{}" ++ "\r\n--b\r\nno blank line here" ++ "\r\n--b\r\nContent-ID: <response-2>\r\n\r\nHTTP/1.1 200 OK\r\n\r\n{\"n\":2}" ++ "\r\n--b--\r\n";
var it = try iterate(mixed); const reply = it.next().?; try testing.expectEqual(@as(?usize, 2), reply.index); try testing.expectEqualStrings("{\"n\":2}", reply.body); try testing.expectEqual(@as(?Reply, null), it.next());}
test "a reply with no body" { const empty = "\r\n--b\r\nContent-ID: <response-0>\r\n\r\nHTTP/1.1 204 No Content\r\n--b--\r\n"; var it = try iterate(empty); const reply = it.next().?; try testing.expectEqual(std.http.Status.no_content, reply.status); try testing.expectEqualStrings("", reply.body);}
test "a status this library has no name for is still a status" { const odd = "\r\n--b\r\n\r\nHTTP/1.1 599 Whatever\r\n\r\n{}\r\n--b--\r\n"; var it = try iterate(odd); try testing.expectEqual(@as(u10, 599), @intFromEnum(it.next().?.status));}
test "a body that is not multipart is refused" { try testing.expectError(error.MalformedBatch, iterate("")); try testing.expectError(error.MalformedBatch, iterate("\r\n\r\n")); try testing.expectError(error.MalformedBatch, iterate("{\"error\":{\"code\":500}}")); try testing.expectError(error.MalformedBatch, iterate("<html>502 Bad Gateway</html>")); // A delimiter of `--` alone would split the body at every pair of dashes // in it, so it is not one. try testing.expectError(error.MalformedBatch, iterate("--\r\nContent-ID: <response-0>\r\n"));}
test "a truncated response ends the walk rather than running off it" { // The connection died in the middle of the second part, so there is no // closing delimiter and the last part is half a reply. const truncated = "\r\n--b\r\nContent-ID: <response-0>\r\n\r\nHTTP/1.1 200 OK\r\n\r\n{\"n\":0}" ++ "\r\n--b\r\nContent-ID: <response-1>\r\n\r\nHTTP/1.1 200 O";
var it = try iterate(truncated); try testing.expectEqual(@as(?usize, 0), it.next().?.index); // Half a reply is not a reply: the call it belonged to is reported as one // that never came back, rather than as one that came back with nothing. try testing.expectEqual(@as(?Reply, null), it.next()); try testing.expect(it.truncated);}
test "a whole response is not truncated" { var it = try iterate(google_response); while (it.next()) |_| {} try testing.expect(!it.truncated);}