// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Several requests in one round trip, through Graph's `$batch` endpoint. //! //! A mailbox walk is a listing followed by a fetch per message, and the fetches //! are where the time goes: forty thousand messages is forty thousand round //! trips, and at even fifty milliseconds each that is a little over half an //! hour spent waiting rather than transferring. `$batch` takes up to twenty //! requests in one POST, which turns that into two thousand. //! //! ```zig //! var batch = client.batch(gpa); //! defer batch.deinit(); //! //! for (ids) |id| _ = try batch.getMessage(id, .{ .select = o365.Client.walk_select }); //! //! var results = try batch.send(io, &d); //! defer results.deinit(); //! //! for (results.responses) |r| { //! if (!r.ok()) continue; //! const message: o365.Message = try .fromJson(results.allocator(), r.body.?); //! } //! ``` //! //! ## What it is not //! //! **Not a free speedup.** Three things about `$batch` are easy to get wrong, //! and all three are handled here because otherwise a batching client is //! *worse* than a serial one rather than faster. //! //! **A 200 on the batch says nothing about what is in it.** The envelope //! succeeds whenever it could be parsed; every individual request carries its //! own status, and a batch of twenty 403s is a 200. `Response.ok` is the check //! that matters, and `send` never reports an error for a failure that happened //! *inside* the batch -- those are in the results, one per request. //! //! **Responses come back in whatever order the service found convenient.** The //! reference is explicit that the `id` is there to correlate them, and that //! being free to reorder is how the service goes faster. `send` sorts them back //! into the order the requests were added, so a caller never has to think about //! it; `Results.get` is there for the cases that would rather look one up. //! //! **A throttled request inside a batch is retried by nobody.** This is the one //! that bites. Outside a batch, `http.zig` sees a 429 and waits out the //! `Retry-After`; inside one, the 429 is a *field in a successful response*, so //! every layer below this is satisfied and the request is simply lost. Graph's //! own guidance is to retry the failed entries in a new batch after the longest //! `Retry-After` among them, and `send` does exactly that -- see `retry`. //! //! ## The twenty-request limit //! //! It is a hard limit, and a batch with more in it is rejected outright. A //! caller need not care: requests are added without limit and `send` posts them //! in chunks of `max_per_batch`, stitching the results back together. //! //! ## Bodies that are not JSON //! //! A batched response body is a JSON value when the request produced JSON, and //! a base64 string when it did not -- which is how a `/$value` MIME fetch comes //! back. `Response.raw` decodes that. Whether Graph will serve `$value` inside //! a batch at all is a question this library cannot settle from here, so //! `getMime` on this type is offered and documented as unverified rather than //! promised; `Client.getMime` is the one that is known to work. const Batch = @This(); const std = @import("std"); const oidc = @import("oidc"); const ApiError = @import("ApiError.zig"); const Client = @import("Client.zig"); const Message = @import("Message.zig"); const http = @import("http.zig"); const json = @import("json.zig"); const odata = @import("odata.zig"); const log = std.log.scoped(.o365); /// Graph's hard limit on requests in one `$batch`. A batch carrying more is /// rejected with a 400 rather than truncated. pub const max_per_batch = 20; client: *Client, gpa: std.mem.Allocator, /// The requests, in the order they were added. Everything in them is owned by /// this arena. arena: std.heap.ArenaAllocator, requests: std.ArrayList(Entry) = .empty, /// How the throttled entries of a batch are retried. Separate from /// `Client.retry`, which governs the POST of the envelope itself: this one /// governs the requests *inside* it, which no other layer can see. retry: Retry = .{}, pub const Entry = struct { /// The correlation id, assigned by `add` as the decimal index the request /// was added at -- which is what lets `send` put the responses back in the /// order they were asked for. /// /// It is not a caller's to set. Whatever is here when `add` is called is /// discarded, because two entries sharing an id fail the whole batch with a /// 400 and the ordering would have nothing to key on. id: []const u8 = "", method: std.http.Method = .GET, /// Relative to the version root: `/me/messages/`, never /// `https://graph.microsoft.com/v1.0/me/...`. `Client.buildBatchUrl` /// spells it correctly. url: []const u8, headers: []const Header = &.{}, /// Already-encoded JSON. When this is set a `Content-Type` header is sent /// with it, which the reference requires. body: ?[]const u8 = null, /// Ids of entries that must run first. A dependant of a failed request /// fails with 424. /// /// The reference's own advice is that a batch should be either fully /// sequential or fully parallel, so this is for the former and most /// callers want neither. depends_on: []const []const u8 = &.{}, }; pub const Header = struct { name: []const u8, value: []const u8, }; /// How hard to retry the entries a batch reported as throttled. pub const Retry = struct { /// Total passes over a set of requests, not retries. 1 disables retrying /// the inner entries, which loses them. max_attempts: u32 = 4, /// The ceiling on a wait asked for by an entry's `Retry-After`. Past this, /// the entry is given back throttled rather than waited out -- the same /// bargain `http.Retry.max_retry_after` strikes, and for the same reason. max_retry_after: std.Io.Duration = .fromSeconds(300), /// What to wait when an entry came back throttled and said nothing about /// how long for. fallback_backoff: std.Io.Duration = .fromSeconds(5), pub const none: Retry = .{ .max_attempts = 1 }; }; pub const Error = Client.Error || error{ /// The `$batch` endpoint answered 200 with something that was not a batch /// response. MalformedBatch, /// A batch was still throttled after `Retry.max_attempts` passes, or an /// entry asked to be retried after longer than `Retry.max_retry_after`. /// The entries that did succeed are lost with it; lower the batch size or /// try again later. BatchThrottled, /// Part of a request -- its URL, a header, or its body -- was not valid /// UTF-8, and so cannot go into a JSON string. /// /// This is checked rather than left to the encoder because of how /// `std.json` fails at it: handed a `[]const u8` that is not valid UTF-8, /// `std.json.fmt` does not error, it **silently writes a JSON array of /// byte values** instead of a string. The envelope stays valid JSON, Graph /// rejects the entry with a 400, and nothing anywhere says why. Found by /// `tests/fuzz.zig`. InvalidRequest, }; pub fn init(client: *Client, gpa: std.mem.Allocator) Batch { return .{ .client = client, .gpa = gpa, .arena = .init(gpa), }; } pub fn deinit(b: *Batch) void { b.requests.deinit(b.gpa); b.arena.deinit(); b.* = undefined; } pub fn count(b: *const Batch) usize { return b.requests.items.len; } /// Adds a request and returns the id it was given, which is the decimal index /// it was added at. /// /// Everything in `entry` is copied, so nothing the caller passes has to outlive /// the call. An `id` on the entry is ignored -- ids are this type's business, /// because they are what the ordering depends on. /// /// Fails with `error.InvalidRequest` for anything that cannot go into a JSON /// string; see that error for why the check is here rather than in the encoder. pub fn add(b: *Batch, entry: Entry) (std.mem.Allocator.Error || error{InvalidRequest})![]const u8 { // A JSON string holds Unicode, so arbitrary bytes genuinely cannot go in // one -- there is nothing to escape them to. Rejecting is the only honest // answer, and it is far better than the array `std.json` would write. if (!std.unicode.utf8ValidateSlice(entry.url)) return error.InvalidRequest; for (entry.headers) |h| { if (!std.unicode.utf8ValidateSlice(h.name)) return error.InvalidRequest; if (!std.unicode.utf8ValidateSlice(h.value)) return error.InvalidRequest; } for (entry.depends_on) |d| { if (!std.unicode.utf8ValidateSlice(d)) return error.InvalidRequest; } // The body is written through as it stands, so it has to be valid JSON // text; this catches the half of that which is cheap to check. if (entry.body) |body| { if (!std.unicode.utf8ValidateSlice(body)) return error.InvalidRequest; } const alloc = b.arena.allocator(); const id = try std.fmt.allocPrint(alloc, "{d}", .{b.requests.items.len}); var headers: std.ArrayList(Header) = .empty; try headers.ensureTotalCapacityPrecise(alloc, entry.headers.len); for (entry.headers) |h| headers.appendAssumeCapacity(.{ .name = try alloc.dupe(u8, h.name), .value = try alloc.dupe(u8, h.value), }); var depends: std.ArrayList([]const u8) = .empty; try depends.ensureTotalCapacityPrecise(alloc, entry.depends_on.len); for (entry.depends_on) |d| depends.appendAssumeCapacity(try alloc.dupe(u8, d)); try b.requests.append(b.gpa, .{ .id = id, .method = entry.method, .url = try alloc.dupe(u8, entry.url), .headers = try headers.toOwnedSlice(alloc), .body = if (entry.body) |body| try alloc.dupe(u8, body) else null, .depends_on = try depends.toOwnedSlice(alloc), }); return id; } /// Queues `GET /me/messages/`, with the same options `Client.getMessage` /// takes. Returns the correlation id. pub fn getMessage( b: *Batch, message_id: []const u8, options: Client.GetMessageOptions, ) (std.mem.Allocator.Error || error{InvalidRequest})![]const u8 { const path = try Client.resourcePath(b.gpa, "messages", message_id, null); defer b.gpa.free(path); var q: odata.Query = .init(b.gpa); defer q.deinit(); try q.addCommaSeparated("$select", options.select); const url = try b.client.buildBatchUrl(b.gpa, path, q.written()); defer b.gpa.free(url); // The body content type is a `Prefer` header outside a batch and a header // on the entry inside one; there is nowhere else for it to go. if (options.body_type) |body_type| { var prefer_buf: [64]u8 = undefined; const prefer = std.fmt.bufPrint( &prefer_buf, "outlook.body-content-type=\"{t}\"", .{body_type}, ) catch return error.OutOfMemory; return b.add(.{ .url = url, .headers = &.{.{ .name = "Prefer", .value = prefer }}, }); } return b.add(.{ .url = url }); } /// Queues `GET /me/messages//$value`, the RFC 5322 bytes. /// /// **Unverified against the real service.** A batched response body that is not /// JSON comes back base64 encoded, which `Response.raw` decodes, and that is /// what this should produce -- but whether Graph serves `$value` inside a batch /// rather than answering with a redirect is not something the test suite here /// can settle, because the only Graph it talks to is the one a few hundred /// lines away in `tests/e2e.zig`. `Client.getMime` is the one that is known to /// work; check `Response.status` before believing this. pub fn getMime( b: *Batch, message_id: []const u8, ) (std.mem.Allocator.Error || error{InvalidRequest})![]const u8 { const path = try Client.resourcePath(b.gpa, "messages", message_id, "$value"); defer b.gpa.free(path); const url = try b.client.buildBatchUrl(b.gpa, path, null); defer b.gpa.free(url); return b.add(.{ .url = url }); } /// One request's answer. pub const Response = struct { /// The correlation id, which is the index the request was added at. id: []const u8, status: std.http.Status, /// The body, when it was JSON. Borrowed from the `Results` arena. body: ?std.json.Value = null, /// The body as it arrived, when it was not JSON: Graph base64-encodes such /// a body, and this is it decoded. Borrowed from the `Results` arena. raw: ?[]const u8 = null, content_type: ?[]const u8 = null, /// What this entry's own `Retry-After` header asked for, when it was /// throttled. retry_after: ?std.Io.Duration = null, /// Whether this request succeeded. **The check that matters**: the batch /// around it returns 200 whether or not any of its contents did. pub fn ok(r: *const Response) bool { return r.status.class() == .success; } /// Whether the service asked for this one to be sent again later. `send` /// has already done that up to `Retry.max_attempts`, so seeing it here /// means the retries ran out. pub fn throttled(r: *const Response) bool { return r.status == .too_many_requests; } /// Whether this entry was not run because something it dependend on /// failed. Graph reports that as 424. pub fn failedDependency(r: *const Response) bool { return @intFromEnum(r.status) == 424; } /// The error object in the body, parsed. Owned by the caller. /// /// Not parsed up front, because most callers of a large batch care only /// whether each entry worked and parsing an error object per failure would /// be work done for nothing. pub fn apiError(r: *const Response, gpa: std.mem.Allocator) ?ApiError { const body = r.body orelse return null; var buf: std.Io.Writer.Allocating = .init(gpa); defer buf.deinit(); std.json.Stringify.value(body, .{}, &buf.writer) catch return null; return ApiError.parse(gpa, buf.written()) catch null; } }; /// The answers to a whole batch, and the memory they live in. pub const Results = struct { /// One per request, **in the order the requests were added** -- not the /// order the service answered in. responses: []const Response, /// How many separate POSTs it took: one per twenty requests, plus one per /// retry pass. round_trips: u32 = 0, arena: std.heap.ArenaAllocator, /// The arena the bodies live in, for parsing one into a resource. pub fn allocator(r: *Results) std.mem.Allocator { return r.arena.allocator(); } /// The response with this correlation id, or `null`. pub fn get(r: *const Results, id: []const u8) ?*const Response { for (r.responses) |*response| { if (std.mem.eql(u8, response.id, id)) return response; } return null; } /// How many entries succeeded. pub fn okCount(r: *const Results) usize { var n: usize = 0; for (r.responses) |response| { if (response.ok()) n += 1; } return n; } pub fn deinit(r: *Results) void { r.arena.deinit(); r.* = undefined; } }; /// Sends every queued request and returns the answers in the order they were /// added. /// /// An error here means the *envelope* failed -- the POST was refused, the token /// is gone, the response was not a batch. A request that failed inside a /// successful batch is not an error: it is a `Response` with a status on it, /// which is the whole point of the endpoint. pub fn send(b: *Batch, io: std.Io, diagnostics: *Client.Diagnostics) Error!Results { var arena: std.heap.ArenaAllocator = .init(b.gpa); errdefer arena.deinit(); const alloc = arena.allocator(); const collected = try alloc.alloc(?Response, b.requests.items.len); @memset(collected, null); var round_trips: u32 = 0; // In chunks, because twenty is a hard limit and a caller should not have to // count. var start: usize = 0; while (start < b.requests.items.len) : (start += max_per_batch) { const end = @min(start + max_per_batch, b.requests.items.len); try b.sendChunk( io, alloc, b.requests.items[start..end], collected, &round_trips, diagnostics, ); } // Every slot is filled: a request whose answer the service never mentioned // is reported as one rather than silently dropped, because a mailbox walk // that quietly skips a message is worse than one that says it could not // fetch it. const responses = try alloc.alloc(Response, b.requests.items.len); for (collected, 0..) |maybe, i| { responses[i] = maybe orelse .{ .id = b.requests.items[i].id, // 500: the service was asked and did not answer for this one. .status = .internal_server_error, }; } return .{ .responses = responses, .round_trips = round_trips, .arena = arena }; } /// Posts one chunk of at most `max_per_batch`, retrying whatever came back /// throttled until it stops or the attempts run out. fn sendChunk( b: *Batch, io: std.Io, alloc: std.mem.Allocator, chunk: []const Entry, collected: []?Response, round_trips: *u32, diagnostics: *Client.Diagnostics, ) Error!void { // Which of `chunk` still need an answer. Starts as all of them and shrinks // to whatever came back throttled. var pending: std.ArrayList(usize) = .empty; defer pending.deinit(b.gpa); try pending.ensureTotalCapacityPrecise(b.gpa, chunk.len); for (0..chunk.len) |i| pending.appendAssumeCapacity(i); var attempt: u32 = 1; while (true) : (attempt += 1) { const body = try b.encode(chunk, pending.items); defer b.gpa.free(body); const response = try b.post(io, body, diagnostics); defer b.gpa.free(response); round_trips.* += 1; var parsed: std.ArrayList(Response) = .empty; defer parsed.deinit(b.gpa); try b.decode(alloc, response, &parsed); var still_throttled: std.ArrayList(usize) = .empty; errdefer still_throttled.deinit(b.gpa); var longest: ?std.Io.Duration = null; for (parsed.items) |r| { // The id is the index into the whole batch, which is what makes // this lookup a parse rather than a search. const index = std.fmt.parseInt(usize, r.id, 10) catch continue; if (index >= collected.len) continue; if (r.throttled() and attempt < b.retry.max_attempts) { // Find it in `chunk` so the next pass can resend just this one. for (chunk, 0..) |entry, i| { if (std.mem.eql(u8, entry.id, r.id)) { try still_throttled.append(b.gpa, i); break; } } if (r.retry_after) |asked| { if (longest == null or asked.toNanoseconds() > longest.?.toNanoseconds()) { longest = asked; } } // Recorded anyway, so that a run which exhausts its attempts // still reports the throttling rather than a blank. collected[index] = r; continue; } collected[index] = r; } if (still_throttled.items.len == 0) { still_throttled.deinit(b.gpa); return; } // Graph's guidance for a batch: retry the failed entries in a new batch // after the longest `Retry-After` among them. Waiting the longest, and // not the shortest, is the point -- coming back for the others early // accrues against the same limit. const wait = longest orelse b.retry.fallback_backoff; if (wait.toNanoseconds() > b.retry.max_retry_after.toNanoseconds()) { log.warn("a batch entry asked to wait {d}s, which is longer than this will", .{ @divTrunc(wait.toNanoseconds(), std.time.ns_per_s), }); still_throttled.deinit(b.gpa); return; } log.debug("{d} of {d} batch entries throttled; waiting {d}s", .{ still_throttled.items.len, chunk.len, @divTrunc(wait.toNanoseconds(), std.time.ns_per_s), }); if (wait.toNanoseconds() > 0) try std.Io.sleep(io, wait, .awake); pending.clearRetainingCapacity(); try pending.appendSlice(b.gpa, still_throttled.items); still_throttled.deinit(b.gpa); } } /// The `{"requests":[...]}` envelope for the entries of `chunk` named by /// `which`. Owned by the caller. fn encode(b: *Batch, chunk: []const Entry, which: []const usize) Error![]u8 { var buf: std.Io.Writer.Allocating = .init(b.gpa); errdefer buf.deinit(); const w = &buf.writer; // Written rather than built through `std.json.Stringify` of a value tree, // because an entry's `body` is already-encoded JSON text and would have to // be re-parsed to go into one. w.writeAll("{\"requests\":[") catch return error.OutOfMemory; for (which, 0..) |index, n| { const entry = chunk[index]; if (n > 0) w.writeByte(',') catch return error.OutOfMemory; w.print("{{\"id\":{f},\"method\":\"{t}\",\"url\":{f}", .{ std.json.fmt(entry.id, .{}), entry.method, std.json.fmt(entry.url, .{}), }) catch return error.OutOfMemory; if (entry.depends_on.len > 0) { w.writeAll(",\"dependsOn\":[") catch return error.OutOfMemory; for (entry.depends_on, 0..) |d, i| { if (i > 0) w.writeByte(',') catch return error.OutOfMemory; w.print("{f}", .{std.json.fmt(d, .{})}) catch return error.OutOfMemory; } w.writeByte(']') catch return error.OutOfMemory; } // The reference requires a `Content-Type` alongside a body, so it is // added here rather than left to the caller to remember. const needs_content_type = entry.body != null; if (entry.headers.len > 0 or needs_content_type) { w.writeAll(",\"headers\":{") catch return error.OutOfMemory; var wrote_any = false; for (entry.headers) |h| { if (wrote_any) w.writeByte(',') catch return error.OutOfMemory; w.print("{f}:{f}", .{ std.json.fmt(h.name, .{}), std.json.fmt(h.value, .{}), }) catch return error.OutOfMemory; wrote_any = true; } if (needs_content_type and !hasHeader(entry.headers, "content-type")) { if (wrote_any) w.writeByte(',') catch return error.OutOfMemory; w.writeAll("\"Content-Type\":\"application/json\"") catch return error.OutOfMemory; } w.writeByte('}') catch return error.OutOfMemory; } if (entry.body) |body| { // Already JSON text, so it goes in as it stands. w.writeAll(",\"body\":") catch return error.OutOfMemory; w.writeAll(body) catch return error.OutOfMemory; } w.writeByte('}') catch return error.OutOfMemory; } w.writeAll("]}") catch return error.OutOfMemory; return buf.toOwnedSlice(); } fn hasHeader(headers: []const Header, name: []const u8) bool { for (headers) |h| { if (std.ascii.eqlIgnoreCase(h.name, name)) return true; } return false; } /// POSTs one envelope to `$batch`. Owned by the caller. fn post(b: *Batch, io: std.Io, body: []const u8, diagnostics: *Client.Diagnostics) Error![]u8 { const url = try b.client.batchUrl(b.gpa); defer b.gpa.free(url); return b.client.getRaw(io, b.gpa, url, .{ .method = .POST, .payload = body, .content_type = "application/json", // A batch of twenty message fetches is twenty bodies in one response, // so it gets the larger ceiling rather than the metadata one. .max_response_bytes = b.client.max_message_bytes, }, diagnostics); } /// Reads a `{"responses":[...]}` envelope. fn decode( b: *Batch, alloc: std.mem.Allocator, body: []const u8, out: *std.ArrayList(Response), ) Error!void { const root = std.json.parseFromSliceLeaky(std.json.Value, alloc, body, .{}) catch return error.MalformedBatch; if (root != .object) return error.MalformedBatch; const items = json.array(root, "responses") orelse return error.MalformedBatch; try out.ensureTotalCapacityPrecise(b.gpa, items.len); for (items) |item| { if (item != .object) continue; const id = json.nonEmptyString(item, "id") orelse continue; const status: std.http.Status = status: { const code = json.unsigned(item, "status") orelse break :status .internal_server_error; break :status @enumFromInt(std.math.cast(u10, code) orelse 500); }; var content_type: ?[]const u8 = null; var retry_after: ?std.Io.Duration = null; if (json.object(item, "headers")) |headers| { if (headers == .object) { var it = headers.object.iterator(); while (it.next()) |kv| { const value = switch (kv.value_ptr.*) { .string => |s| s, else => continue, }; if (std.ascii.eqlIgnoreCase(kv.key_ptr.*, "content-type")) { content_type = value; } else if (std.ascii.eqlIgnoreCase(kv.key_ptr.*, "retry-after")) { retry_after = http.parseRetryAfter(value); } } } } // A body that is JSON arrives as a JSON value; one that is not arrives // as a base64 string, which is how a `$value` fetch would come back. var value: ?std.json.Value = null; var raw: ?[]const u8 = null; if (item.object.get("body")) |member| { switch (member) { .null => {}, .string => |s| raw = json.decodeBase64(alloc, s) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, // Not base64 after all. Hand back the string as it stands // rather than nothing: it is more likely to be a readable // error than a mystery. error.InvalidBase64 => s, }, else => value = member, } } out.appendAssumeCapacity(.{ .id = id, .status = status, .body = value, .raw = raw, .content_type = content_type, .retry_after = retry_after, }); } } /// `encode` over every queued request, for the fuzz targets and the tests /// below. Not part of the API: `send` is how an envelope reaches the wire. pub fn encodeForTest(b: *Batch) Error![]u8 { var which = try b.gpa.alloc(usize, b.requests.items.len); defer b.gpa.free(which); for (0..b.requests.items.len) |i| which[i] = i; return b.encode(b.requests.items, which); } /// `decode`, for the same reason. pub fn decodeForTest( b: *Batch, alloc: std.mem.Allocator, body: []const u8, out: *std.ArrayList(Response), ) Error!void { return b.decode(alloc, body, out); } const testing = std.testing; test "the envelope is the shape the reference documents" { var client: Client = .{ .gpa = testing.allocator, .oauth = undefined, .tokens = undefined }; var b: Batch = .init(&client, testing.allocator); defer b.deinit(); _ = try b.add(.{ .url = "/me/messages/m1" }); _ = try b.add(.{ .url = "/me/messages/m2", .method = .GET }); const body = try b.encode(b.requests.items, &.{ 0, 1 }); defer testing.allocator.free(body); try testing.expectEqualStrings( \\{"requests":[{"id":"0","method":"GET","url":"/me/messages/m1"}, ++ \\{"id":"1","method":"GET","url":"/me/messages/m2"}]} , body); } test "a body brings a Content-Type with it" { var client: Client = .{ .gpa = testing.allocator, .oauth = undefined, .tokens = undefined }; var b: Batch = .init(&client, testing.allocator); defer b.deinit(); _ = try b.add(.{ .method = .POST, .url = "/me/messages/m1/move", .body = "{\"destinationId\":\"archive\"}", }); const body = try b.encode(b.requests.items, &.{0}); defer testing.allocator.free(body); // The reference requires it whenever a body is present, and forgetting it // is a 400 on that entry rather than on the batch. try testing.expect(std.mem.indexOf(u8, body, "\"Content-Type\":\"application/json\"") != null); try testing.expect(std.mem.indexOf(u8, body, "\"body\":{\"destinationId\":\"archive\"}") != null); try testing.expect(std.mem.indexOf(u8, body, "\"method\":\"POST\"") != null); } test "a caller's own Content-Type is not doubled" { var client: Client = .{ .gpa = testing.allocator, .oauth = undefined, .tokens = undefined }; var b: Batch = .init(&client, testing.allocator); defer b.deinit(); _ = try b.add(.{ .method = .POST, .url = "/me/x", .headers = &.{.{ .name = "content-type", .value = "text/plain" }}, .body = "\"hi\"", }); const body = try b.encode(b.requests.items, &.{0}); defer testing.allocator.free(body); try testing.expect(std.mem.indexOf(u8, body, "text/plain") != null); try testing.expect(std.mem.indexOf(u8, body, "application/json") == null); } test "dependsOn is written when it is there and left out when it is not" { var client: Client = .{ .gpa = testing.allocator, .oauth = undefined, .tokens = undefined }; var b: Batch = .init(&client, testing.allocator); defer b.deinit(); const first = try b.add(.{ .url = "/me/a" }); _ = try b.add(.{ .url = "/me/b", .depends_on = &.{first} }); const body = try b.encode(b.requests.items, &.{ 0, 1 }); defer testing.allocator.free(body); try testing.expect(std.mem.indexOf(u8, body, "\"dependsOn\":[\"0\"]") != null); // And the first entry, which depends on nothing, does not carry an empty // array -- Graph rejects some empty members rather than ignoring them. const first_entry = body[0..std.mem.indexOf(u8, body, "/me/b").?]; try testing.expect(std.mem.indexOf(u8, first_entry, "dependsOn") == null); } test "an id or a URL with a quote in it cannot break out of the envelope" { var client: Client = .{ .gpa = testing.allocator, .oauth = undefined, .tokens = undefined }; var b: Batch = .init(&client, testing.allocator); defer b.deinit(); // Graph ids are opaque. One carrying a quote, escaped into the JSON, must // stay one string rather than becoming a second member. _ = try b.add(.{ .url = "/me/messages/a\"},{\"id\":\"evil" }); const body = try b.encode(b.requests.items, &.{0}); defer testing.allocator.free(body); try testing.expect(std.mem.indexOf(u8, body, "\"id\":\"evil\"") == null); // It still parses, and as exactly one request. var parsed = try std.json.parseFromSlice(std.json.Value, testing.allocator, body, .{}); defer parsed.deinit(); try testing.expectEqual(@as(usize, 1), parsed.value.object.get("requests").?.array.items.len); } const TestDecode = struct { arena: std.heap.ArenaAllocator, responses: std.ArrayList(Response), batch: Batch, client: Client, fn init(text: []const u8) !TestDecode { var t: TestDecode = .{ .arena = .init(testing.allocator), .responses = .empty, .client = .{ .gpa = testing.allocator, .oauth = undefined, .tokens = undefined }, .batch = undefined, }; t.batch = .init(&t.client, testing.allocator); errdefer t.arena.deinit(); try t.batch.decode(t.arena.allocator(), text, &t.responses); return t; } fn deinit(t: *TestDecode) void { t.responses.deinit(testing.allocator); t.batch.deinit(); t.arena.deinit(); } }; test "the response shape the reference documents" { var t = try TestDecode.init( \\{"responses":[ \\ {"id":"1","status":200, \\ "headers":{"Cache-Control":"no-cache","Content-Type":"application/json"}, \\ "body":{"id":"m1","subject":"hello"}}, \\ {"id":"2","status":403, \\ "headers":{"Content-Type":"application/json"}, \\ "body":{"error":{"code":"Authorization_RequestDenied", \\ "message":"Insufficient privileges to complete the operation."}}}]} ); defer t.deinit(); try testing.expectEqual(@as(usize, 2), t.responses.items.len); const first = t.responses.items[0]; try testing.expect(first.ok()); try testing.expectEqualStrings("m1", json.string(first.body.?, "id").?); try testing.expectEqualStrings("application/json", first.content_type.?); const second = t.responses.items[1]; try testing.expect(!second.ok()); try testing.expect(!second.throttled()); var api = second.apiError(testing.allocator).?; defer api.deinit(); try testing.expectEqualStrings("Authorization_RequestDenied", api.code.?); try testing.expect(api.isPermissionFailure(second.status)); } test "a throttled entry carries its own Retry-After" { var t = try TestDecode.init( \\{"responses":[{"id":"0","status":429, \\ "headers":{"Retry-After":"17","Content-Type":"application/json"}, \\ "body":{"error":{"code":"TooManyRequests","message":"Please retry again later."}}}]} ); defer t.deinit(); const r = t.responses.items[0]; // The whole reason this type exists: outside a batch `http.zig` would have // seen this and waited. Inside one it is a field in a 200, and nothing // below here can see it. try testing.expect(r.throttled()); try testing.expect(!r.ok()); try testing.expectEqual(@as(i96, 17) * std.time.ns_per_s, r.retry_after.?.toNanoseconds()); } test "a failed dependency is its own thing" { var t = try TestDecode.init( \\{"responses":[{"id":"0","status":424,"body":{}}]} ); defer t.deinit(); try testing.expect(t.responses.items[0].failedDependency()); try testing.expect(!t.responses.items[0].ok()); } test "a body that is not JSON comes back decoded" { var t = try TestDecode.init( \\{"responses":[{"id":"0","status":200, \\ "headers":{"Content-Type":"text/plain"}, \\ "body":"U3ViamVjdDogaGkKCmJvZHkK"}]} ); defer t.deinit(); const r = t.responses.items[0]; try testing.expectEqual(@as(?std.json.Value, null), r.body); try testing.expectEqualStrings("Subject: hi\n\nbody\n", r.raw.?); } test "a string body that is not base64 is handed back as it stands" { var t = try TestDecode.init( \\{"responses":[{"id":"0","status":500,"body":"!!! not base64 !!!"}]} ); defer t.deinit(); try testing.expectEqualStrings("!!! not base64 !!!", t.responses.items[0].raw.?); } test "junk among the responses is skipped, not fatal" { var t = try TestDecode.init( \\{"responses":[{"id":"0","status":200},7,null,{"no":"id"}, \\ {"id":"3","status":"not a number"},{"id":"4","status":200}]} ); defer t.deinit(); try testing.expectEqual(@as(usize, 3), t.responses.items.len); // A status that is not a number reads as a server error rather than as a // success, which is the safe direction. try testing.expect(!t.responses.items[1].ok()); try testing.expectEqualStrings("4", t.responses.items[2].id); } test "something that is not a batch response at all" { var client: Client = .{ .gpa = testing.allocator, .oauth = undefined, .tokens = undefined }; var b: Batch = .init(&client, testing.allocator); defer b.deinit(); var arena: std.heap.ArenaAllocator = .init(testing.allocator); defer arena.deinit(); for ([_][]const u8{ "not json", "[]", "{}", "{\"responses\":7}", "null" }) |text| { var out: std.ArrayList(Response) = .empty; defer out.deinit(testing.allocator); try testing.expectError( error.MalformedBatch, b.decode(arena.allocator(), text, &out), ); } } test "bytes that cannot go in a JSON string are refused, not silently mangled" { var client: Client = .{ .gpa = testing.allocator, .oauth = undefined, .tokens = undefined }; var b: Batch = .init(&client, testing.allocator); defer b.deinit(); // Found by `tests/fuzz.zig`. `std.json.fmt` writes a `[]const u8` that is // not valid UTF-8 as `[255,254]` -- an array, not a string -- so the // envelope would stay valid JSON and Graph would reject the entry with a // 400 that says nothing about why. try testing.expectError(error.InvalidRequest, b.add(.{ .url = "/me/messages/\xff\xfe" })); try testing.expectError(error.InvalidRequest, b.add(.{ .url = "/me/a", .headers = &.{.{ .name = "X", .value = "\x80" }}, })); try testing.expectError(error.InvalidRequest, b.add(.{ .url = "/me/a", .body = "{\"x\":\"\xc3\"}", })); // Nothing was added by any of them. try testing.expectEqual(@as(usize, 0), b.count()); // `getMessage` is *not* exposed to this, and the reason is worth keeping: // it percent-encodes the id on its way into the path, so a byte that could // not go into a JSON string becomes `%FF`, which can. The raw `add` is the // way in for a URL the caller assembled itself. const id = try b.getMessage("m\xff1", .{}); try testing.expectEqualStrings("0", id); // And valid UTF-8 outside ASCII is fine, because that really is a string. _ = try b.add(.{ .url = "/me/mailFolders/Posteingang/messages" }); _ = try b.add(.{ .url = "/me/mailFolders/\u{e9}t\u{e9}/messages" }); const body = try b.encodeForTest(); defer testing.allocator.free(body); var parsed = try std.json.parseFromSlice(std.json.Value, testing.allocator, body, .{}); defer parsed.deinit(); const requests = parsed.value.object.get("requests").?.array.items; try testing.expectEqual(@as(usize, 3), requests.len); // Strings, not arrays of byte values -- which is what this whole check is // about. for (requests) |r| try testing.expect(r.object.get("url").? == .string); try testing.expect(std.mem.indexOf(u8, requests[0].object.get("url").?.string, "%FF") != null); } test "requests are copied, so nothing has to outlive the call" { var client: Client = .{ .gpa = testing.allocator, .oauth = undefined, .tokens = undefined }; var b: Batch = .init(&client, testing.allocator); defer b.deinit(); { var url_buf: [32]u8 = undefined; const url = try std.fmt.bufPrint(&url_buf, "/me/messages/{s}", .{"m1"}); var header_buf: [32]u8 = undefined; const value = try std.fmt.bufPrint(&header_buf, "{s}", .{"eventual"}); _ = try b.add(.{ .url = url, .headers = &.{.{ .name = "ConsistencyLevel", .value = value }}, }); // Both buffers go out of scope here. @memset(&url_buf, 0); @memset(&header_buf, 0); } const body = try b.encode(b.requests.items, &.{0}); defer testing.allocator.free(body); try testing.expect(std.mem.indexOf(u8, body, "/me/messages/m1") != null); try testing.expect(std.mem.indexOf(u8, body, "eventual") != null); } test { _ = ApiError; _ = http; _ = json; _ = odata; }