// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! The one place this library talks to a network, kept small on purpose so //! that everything above it -- the resource types, the folder mapping, the //! pagination -- is pure and can be tested without a socket. //! //! Four things here are not what `std.http.Client.fetch` does on its own. //! //! The response body is read into a buffer of a fixed size rather than one that //! grows, so a server that answers with a gigabyte gets an error rather than //! the process' memory. A non-2xx response is turned into the error object //! Graph carries, rather than a bare status code. A failure that is a //! throttling failure is retried, because a mailbox walk runs into one as a //! matter of routine and the only correct response to it is to wait. //! //! And the fourth is why this drives `std.http.Client.request` by hand instead //! of calling `fetch`: **`Retry-After`**. Microsoft's throttling guidance is //! unusually specific about it -- "backing off requests using the `Retry-After` //! delay is the fastest way to recover from throttling, because Microsoft Graph //! continues to log resource usage while a client is being throttled" -- so a //! client that ignores the header and backs off on a schedule of its own is //! not merely slower, it is still accruing against the limit it is waiting out. //! `fetch` in 0.16 returns nothing but the status, and there is no way to reach //! a response header through it, so the request is assembled here. //! //! The exponential schedule is still here, because it is what to do when the //! header is absent, which Graph's own documentation says happens. const std = @import("std"); const ApiError = @import("ApiError.zig"); const log = std.log.scoped(.o365); /// The default ceiling on a response body, for the calls that return metadata: /// a folder list, a page of messages, a delta page. Generous; none of them are /// close to it. pub const default_max_response_bytes = 8 << 20; /// The ceiling for a MIME fetch, which returns a whole message. /// /// Exchange Online's default limit is 25 MB and a tenant may raise it to 150 /// MB. Unlike Gmail's `format=raw` the bytes are not base64 encoded -- `$value` /// returns the message itself -- so this needs no allowance for expansion. /// /// It is allocated up front, per request. On a system with lazy page allocation /// that costs an address range rather than memory, and the pages a small /// response never touches are never backed. pub const default_max_message_bytes = 160 << 20; pub const Error = error{ /// The transport failed: DNS, TCP, TLS, or a malformed HTTP response. RequestFailed, /// The body exceeded `max_response_bytes`. ResponseTooLarge, /// The server answered with a status this library does not accept, and the /// body was not a Graph error object either. `Diagnostics.status` holds /// what it was, and `Diagnostics.body` the first part of what it said. HttpStatus, /// The server answered with a Graph error object. `Diagnostics.api_error` /// holds it. ApiError, /// The access token was refused. Split out from `ApiError` because it is /// the one failure a caller holding a refresh token can do something /// about, and `Client` does: it refreshes and tries once more. Unauthorized, /// The request kept failing with something retryable until `max_attempts` /// ran out. `Diagnostics` describes the last attempt. TooManyRetries, } || std.Io.Cancelable || std.mem.Allocator.Error; /// Filled in on the way past, so that a failure can say what happened without /// every error having to carry a payload. Owned by the caller. pub const Diagnostics = struct { /// The allocator the strings below are made with. /// /// It lives here, rather than being handed to `reset`, because what this /// holds outlives the call that filled it in: `fetch` leaves the last /// response's `request-id` behind and clears it only when the *next* /// request starts. A `Diagnostics` that borrowed the allocator of /// whichever call happened to fill it in would, the moment that call was /// given an arena, be left pointing into pages the caller had since /// dropped -- and the next request's `reset` would free them a second /// time. Owning the allocator makes the mismatch unrepresentable. gpa: std.mem.Allocator, status: ?std.http.Status = null, api_error: ?ApiError = null, /// The first part of the body, for a failure that was neither a valid API /// error nor a status worth naming on its own. body: ?[]const u8 = null, /// What the last response's `Retry-After` header asked for, if it sent one. retry_after: ?std.Io.Duration = null, /// `request-id`, copied off the response header of the last attempt. /// /// Worth keeping separately from the one inside `api_error`: a failure /// that produced no error object at all still has one, and it is what a /// support request has to quote. request_id: ?[]const u8 = null, /// How many attempts were made. 1 unless something was retried. attempts: u32 = 0, /// Frees whatever the last failure put here and empties it. /// /// `fetch` calls this on the way in, so one `Diagnostics` can be reused /// across a whole session without each request's leftovers piling up. pub fn reset(d: *Diagnostics) void { if (d.body) |b| d.gpa.free(b); if (d.request_id) |r| d.gpa.free(r); if (d.api_error) |*e| e.deinit(); d.* = .{ .gpa = d.gpa }; } pub fn deinit(d: *Diagnostics) void { d.reset(); } /// Renders whatever is known about the failure, for a log line. pub fn format(d: *const Diagnostics, w: *std.Io.Writer) std.Io.Writer.Error!void { if (d.api_error) |*e| { try e.format(w); // The error object usually carries its own, but not always, and a // failure with no request id is one nobody can look up. if (e.request_id == null) { if (d.request_id) |r| try w.print(" (request-id {s})", .{r}); } return; } if (d.status) |s| { try w.print("HTTP {d} {s}", .{ @intFromEnum(s), s.phrase() orelse "" }); if (d.request_id) |r| try w.print(" (request-id {s})", .{r}); if (d.body) |b| try w.print(": {s}", .{b}); return; } try w.writeAll("no response"); } }; /// How hard to try again when Graph says to slow down. /// /// The schedule is the fallback. When the response carries `Retry-After` that /// is used instead, because Microsoft's guidance is explicit that it is the /// fastest way out of a throttle: usage keeps being logged while a client /// retries early, so an impatient client stays throttled longer than a patient /// one. /// /// The jitter on the fallback is not decoration: a program that walks a mailbox /// with several requests in flight and backs off by a fixed schedule /// synchronises them, and they all come back at once into the same limit. pub const Retry = struct { /// Total attempts, not retries. 1 disables retrying. max_attempts: u32 = 5, /// The first wait, when the server did not say. Doubles each time. initial_backoff: std.Io.Duration = .fromMilliseconds(500), /// The ceiling on a single computed wait, before jitter. max_backoff: std.Io.Duration = .fromSeconds(32), /// Whether to believe `Retry-After`. honor_retry_after: bool = true, /// The ceiling on a `Retry-After` this will actually wait out. /// /// Graph asks for seconds or tens of seconds, but the header is a number /// chosen by the far end, and a program that obeys it without a bound can /// be parked for a day by one that says `86400`. Past this, the wait is /// refused and the call fails with `TooManyRetries` -- which hands the /// decision back to the caller, who can see the clock and knows whether /// there is anything else to be doing. max_retry_after: std.Io.Duration = .fromSeconds(300), pub const none: Retry = .{ .max_attempts = 1 }; /// How long to wait before attempt number `attempt` (1-based, so the first /// retry is attempt 2 and waits `initial_backoff`). pub fn backoff(r: Retry, attempt: u32, rng: std.Random) std.Io.Duration { // The first attempt is not a retry, so it does not wait. Saturating // subtraction alone would make it wait `initial_backoff`. if (attempt < 2) return .fromNanoseconds(0); // Capped before the shift rather than after: 1 << 64 is undefined // behaviour, and `max_backoff` would have clamped it anyway. const doublings: u6 = @intCast(@min(attempt - 2, 16)); const base = @min( r.initial_backoff.toNanoseconds() *| (@as(i96, 1) << doublings), r.max_backoff.toNanoseconds(), ); // Full jitter: a wait uniform over [0, base]. It spreads a thundering // herd out rather than merely delaying it. const nanos: i96 = if (base <= 0) 0 else rng.uintLessThan(u64, @intCast(base + 1)); return .fromNanoseconds(nanos); } /// What to wait before `attempt`, given whatever the server asked for. /// /// `null` means do not wait at all but give up: the server asked for /// longer than `max_retry_after`. pub fn wait( r: Retry, attempt: u32, retry_after: ?std.Io.Duration, rng: std.Random, ) ?std.Io.Duration { if (r.honor_retry_after) { if (retry_after) |asked| { if (asked.toNanoseconds() > r.max_retry_after.toNanoseconds()) return null; // Not jittered, and deliberately: this is a specific // instruction from the service rather than a guess, and // shortening it would defeat the point. A little is added // rather than subtracted so that a client whose clock rounds // down does not come back a moment early and start the whole // wait again. if (asked.toNanoseconds() <= 0) return .fromMilliseconds(100); return .fromNanoseconds(asked.toNanoseconds() + std.time.ns_per_ms * 250); } } return r.backoff(attempt, rng); } }; pub const Request = struct { method: std.http.Method = .GET, uri: std.Uri, /// The request body, already encoded. `content_type` must be set with it. payload: ?[]const u8 = null, content_type: ?[]const u8 = null, /// The value of an `Authorization` header, complete with its scheme. authorization: ?[]const u8 = null, /// What to send as `Accept`. `application/json` for everything but a MIME /// fetch, which wants `text/plain` -- though Graph sends the message /// either way. accept: []const u8 = "application/json", /// Anything else. `Prefer: odata.maxpagesize=N` is the one this library /// sends, since Graph takes the page size as a header rather than as a /// query parameter. extra_headers: []const std.http.Header = &.{}, user_agent: []const u8, max_response_bytes: usize = default_max_response_bytes, retry: Retry = .{}, /// Where the jitter comes from. It does not have to be cryptographically /// secure -- nothing is being kept secret -- but it does have to differ /// between processes, or the spreading does not spread. rng: ?std.Random = null, }; /// The most headers `attemptOnce` assembles: authorization, accept, and /// whatever `extra_headers` holds. const max_extra_headers = 8; /// Performs `request` and returns the body, allocated from `gpa` and owned by /// the caller. /// /// A 2xx status returns the body. Anything else is an error, with /// `diagnostics` filled in: the Graph error object where the server sent one, /// the status otherwise. /// /// `gpa` is for what this returns and for the scratch space it needs along the /// way, and nothing else: it may be an arena the caller drops as soon as it has /// read the body. Everything left behind in `diagnostics` is allocated from /// `Diagnostics.gpa` instead, because it stays there until the next request. pub fn fetch( io: std.Io, gpa: std.mem.Allocator, request: Request, diagnostics: *Diagnostics, ) Error![]u8 { if (request.extra_headers.len + 2 > max_extra_headers) return error.RequestFailed; diagnostics.reset(); // A fixed buffer rather than a growing one: this is the cap, and it is // enforced by there being nowhere else for the bytes to go. const buffer = try gpa.alloc(u8, request.max_response_bytes); defer gpa.free(buffer); // A seed, not a secret: the jitter exists to keep concurrent clients from // backing off in lockstep, and the clock is enough to tell them apart. // `Request.rng` is how a caller that wants better supplies it. const nanos: u96 = @bitCast(std.Io.Timestamp.now(io, .real).nanoseconds); var fallback: std.Random.DefaultPrng = .init(@truncate(nanos)); const rng = request.rng orelse fallback.random(); var attempt: u32 = 1; while (true) : (attempt += 1) { diagnostics.reset(); diagnostics.attempts = attempt; const outcome = attemptOnce(io, gpa, request, buffer, diagnostics) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.Canceled => return error.Canceled, error.ResponseTooLarge => return error.ResponseTooLarge, // A transport failure is retried too: a connection reset in the // middle of a long walk is far more common than a broken server, // and the request has not been applied. error.RequestFailed => if (attempt < request.retry.max_attempts) { if (!try sleepBeforeRetry(io, request.retry, attempt + 1, null, rng)) { return error.RequestFailed; } continue; } else return error.RequestFailed, }; switch (outcome) { .ok => |body| return body, .failed => |status| { const retry_after = diagnostics.retry_after; if (diagnostics.api_error) |*e| { if (e.isAuthFailure(status)) return error.Unauthorized; if (e.isRetryable(status)) { if (attempt >= request.retry.max_attempts) return error.TooManyRetries; log.debug("{f}: attempt {d} of {d}, backing off", .{ diagnostics, attempt, request.retry.max_attempts, }); if (!try sleepBeforeRetry( io, request.retry, attempt + 1, retry_after, rng, )) return error.TooManyRetries; continue; } return error.ApiError; } // No error object: something in front of Graph. A 401 still // means what it means, and a 429 or 5xx is still worth waiting // out. if (status == .unauthorized) return error.Unauthorized; const retryable = status == .too_many_requests or @intFromEnum(status) == 509 or status.class() == .server_error; if (retryable) { if (attempt >= request.retry.max_attempts) return error.TooManyRetries; if (!try sleepBeforeRetry( io, request.retry, attempt + 1, retry_after, rng, )) return error.TooManyRetries; continue; } return error.HttpStatus; }, } } } /// Waits, and says whether waiting was agreed to. `false` means the server /// asked for longer than `Retry.max_retry_after` and the call should give up. fn sleepBeforeRetry( io: std.Io, retry: Retry, attempt: u32, retry_after: ?std.Io.Duration, rng: std.Random, ) std.Io.Cancelable!bool { const duration = retry.wait(attempt, retry_after, rng) orelse { const asked: std.Io.Duration = retry_after orelse .fromNanoseconds(0); log.warn("asked to wait {d} seconds, which is longer than this will", .{ @divTrunc(asked.toNanoseconds(), std.time.ns_per_s), }); return false; }; if (duration.toNanoseconds() <= 0) return true; try std.Io.sleep(io, duration, .awake); return true; } const Outcome = union(enum) { ok: []u8, failed: std.http.Status, }; const AttemptError = error{ RequestFailed, ResponseTooLarge } || std.Io.Cancelable || std.mem.Allocator.Error; fn attemptOnce( io: std.Io, gpa: std.mem.Allocator, request: Request, buffer: []u8, diagnostics: *Diagnostics, ) AttemptError!Outcome { var client: std.http.Client = .{ .io = io, .allocator = gpa }; defer client.deinit(); var extra: [max_extra_headers]std.http.Header = undefined; var extra_len: usize = 0; if (request.authorization) |value| { extra[extra_len] = .{ .name = "Authorization", .value = value }; extra_len += 1; } extra[extra_len] = .{ .name = "Accept", .value = request.accept }; extra_len += 1; for (request.extra_headers) |h| { extra[extra_len] = h; extra_len += 1; } var req = client.request(request.method, request.uri, .{ .headers = .{ .user_agent = .{ .override = request.user_agent }, .content_type = if (request.content_type) |ct| .{ .override = ct } else .default, // The body is what is wanted, not a gzip stream this would then // have to inflate into the same fixed buffer. .accept_encoding = .{ .override = "identity" }, }, .extra_headers = extra[0..extra_len], // An API endpoint does not redirect, and following one would resend // the access token to wherever it pointed. `unhandled` rather than // `not_allowed` so that a 3xx arrives as a status to report instead of // as a transport error with nothing to say. .redirect_behavior = .unhandled, // One request per connection. The pool would be worth having for a // mailbox walk, but the client is created and destroyed per attempt so // there is nothing for it to pool into, and a half-used connection // surviving a failed attempt is a subtler thing than this needs. .keep_alive = false, }) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.Canceled => return error.Canceled, else => |e| { log.debug("{t} {f}: {t}", .{ request.method, request.uri, e }); return error.RequestFailed; }, }; defer req.deinit(); if (request.payload) |payload| { req.transfer_encoding = .{ .content_length = payload.len }; var body = req.sendBodyUnflushed(&.{}) catch return error.RequestFailed; body.writer.writeAll(payload) catch return error.RequestFailed; body.end() catch return error.RequestFailed; if (req.connection) |c| c.flush() catch return error.RequestFailed; } else { req.sendBodiless() catch return error.RequestFailed; } var response = req.receiveHead(&.{}) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.Canceled => return error.Canceled, else => |e| { log.debug("{t} {f}: {t}", .{ request.method, request.uri, e }); return error.RequestFailed; }, }; const status = response.head.status; diagnostics.status = status; // Everything wanted from the head is taken *now*, because initialising the // body reader invalidates the strings it points into -- `reader` calls // `invalidateStrings` on the way past. Reading `Retry-After` after the // body would read whatever the body overwrote it with. { var headers = response.head.iterateHeaders(); while (headers.next()) |header| { if (std.ascii.eqlIgnoreCase(header.name, "retry-after")) { diagnostics.retry_after = parseRetryAfter(header.value); } else if (std.ascii.eqlIgnoreCase(header.name, "request-id") or std.ascii.eqlIgnoreCase(header.name, "client-request-id")) { if (diagnostics.request_id == null and header.value.len > 0) { // `diagnostics.gpa`, not `gpa`: this outlives the call. diagnostics.request_id = try diagnostics.gpa.dupe(u8, header.value); } } } } var body_writer: std.Io.Writer = .fixed(buffer); var transfer_buffer: [4096]u8 = undefined; // `identity` was asked for, and Graph honours it, but a proxy in the way // may not -- and `reader` does not decompress, so believing it blindly // would hand the JSON parser a gzip stream. // // Both of these live in the function's scope rather than in the branch // that fills them in, and that is not tidiness: `readerDecompressing` // keeps pointers to both for as long as the body is being read, so a // decompressor declared inside the `blk` below would dangle the moment the // block ended, and a buffer freed by a `defer` inside it would be freed // before the first byte was read. var decompress: std.http.Decompress = undefined; var decompress_buffer: []u8 = &.{}; defer gpa.free(decompress_buffer); const reader = switch (response.head.content_encoding) { .identity => response.reader(&transfer_buffer), .compress => return error.RequestFailed, else => |encoding| blk: { decompress_buffer = try gpa.alloc(u8, switch (encoding) { .zstd => std.compress.zstd.default_window_len, else => std.compress.flate.max_window_len, }); break :blk response.readerDecompressing( &transfer_buffer, &decompress, decompress_buffer, ); }, }; _ = reader.streamRemaining(&body_writer) catch |err| switch (err) { // With a fixed writer there is only one way writing the body can fail, // and that is running out of it. error.WriteFailed => return error.ResponseTooLarge, else => { log.debug("{t} {f}: reading the body failed", .{ request.method, request.uri }); return error.RequestFailed; }, }; const body = body_writer.buffered(); if (status.class() != .success) { // Both of these are kept until the next request resets them, so both // come from the diagnostics' own allocator rather than the call's. if (ApiError.parse(diagnostics.gpa, body)) |parsed| { diagnostics.api_error = parsed; } else |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.NotAnError => diagnostics.body = try diagnostics.gpa.dupe( u8, body[0..@min(body.len, 512)], ), } return .{ .failed = status }; } return .{ .ok = try gpa.dupe(u8, body) }; } /// Reads a `Retry-After` value. RFC 9110 permits either a count of seconds or /// an HTTP date; Graph sends the seconds and this reads only those, because an /// HTTP date would have to be believed against this machine's clock and a /// clock that is wrong is one of the things being recovered from. pub fn parseRetryAfter(value: []const u8) ?std.Io.Duration { const trimmed = std.mem.trim(u8, value, " \t"); if (trimmed.len == 0) return null; const seconds = std.fmt.parseInt(u32, trimmed, 10) catch return null; return .fromSeconds(seconds); } const testing = std.testing; test "backoff doubles and is capped" { var prng: std.Random.DefaultPrng = .init(0); const rng = prng.random(); const retry: Retry = .{ .initial_backoff = .fromMilliseconds(500), .max_backoff = .fromSeconds(32), }; // Full jitter makes each wait a sample from [0, base], so what is asserted // is the ceiling rather than the value. for ([_]struct { u32, i96 }{ .{ 2, std.time.ns_per_ms * 500 }, .{ 3, std.time.ns_per_s * 1 }, .{ 4, std.time.ns_per_s * 2 }, .{ 8, std.time.ns_per_s * 32 }, // Long past the cap, and nowhere near overflowing the shift. .{ 40, std.time.ns_per_s * 32 }, }) |case| { const attempt, const ceiling = case; for (0..64) |_| { const got = retry.backoff(attempt, rng).toNanoseconds(); try testing.expect(got >= 0); try testing.expect(got <= ceiling); } } } test "the first attempt never waits" { var prng: std.Random.DefaultPrng = .init(1); const retry: Retry = .{}; try testing.expectEqual(@as(i96, 0), retry.backoff(1, prng.random()).toNanoseconds()); } test "Retry-After beats the schedule" { var prng: std.Random.DefaultPrng = .init(2); const rng = prng.random(); const retry: Retry = .{ .initial_backoff = .fromMilliseconds(500) }; // Ten seconds is what the throttling reference's own example asks for, and // it is twenty times what the schedule would have waited. Obeying it is // the point: Graph keeps logging usage against a client that comes back // early, so the impatient client stays throttled longer. const waited = retry.wait(2, .fromSeconds(10), rng).?; try testing.expect(waited.toNanoseconds() >= 10 * std.time.ns_per_s); // And not much longer: a quarter second of slack against a clock that // rounds down, not a doubling. try testing.expect(waited.toNanoseconds() < 11 * std.time.ns_per_s); } test "a Retry-After that is absurd is refused rather than obeyed" { var prng: std.Random.DefaultPrng = .init(3); const rng = prng.random(); const retry: Retry = .{ .max_retry_after = .fromSeconds(300) }; try testing.expect(retry.wait(2, .fromSeconds(299), rng) != null); // A day. Obeying this parks the process until tomorrow on the say-so of // the far end. try testing.expectEqual(@as(?std.Io.Duration, null), retry.wait(2, .fromSeconds(86400), rng)); } test "Retry-After can be ignored on purpose" { var prng: std.Random.DefaultPrng = .init(4); const rng = prng.random(); const retry: Retry = .{ .honor_retry_after = false, .initial_backoff = .fromMilliseconds(500), .max_backoff = .fromMilliseconds(500), }; const waited = retry.wait(2, .fromSeconds(600), rng).?; try testing.expect(waited.toNanoseconds() <= 500 * std.time.ns_per_ms); } test "a Retry-After of zero still pauses" { var prng: std.Random.DefaultPrng = .init(5); const retry: Retry = .{}; // Coming straight back would be a spin, and the header saying `0` is not // an invitation to one. const waited = retry.wait(2, .fromSeconds(0), prng.random()).?; try testing.expect(waited.toNanoseconds() > 0); } test "parsing the header" { try testing.expectEqual( @as(i96, 10) * std.time.ns_per_s, parseRetryAfter("10").?.toNanoseconds(), ); try testing.expectEqual( @as(i96, 0), parseRetryAfter(" 0 ").?.toNanoseconds(), ); // An HTTP date is legal per RFC 9110 and is deliberately not read: it // would have to be believed against a local clock that may be the reason // for the failure in the first place. try testing.expectEqual( @as(?std.Io.Duration, null), parseRetryAfter("Wed, 21 Oct 2015 07:28:00 GMT"), ); try testing.expectEqual(@as(?std.Io.Duration, null), parseRetryAfter("")); try testing.expectEqual(@as(?std.Io.Duration, null), parseRetryAfter("-5")); try testing.expectEqual(@as(?std.Io.Duration, null), parseRetryAfter("soon")); } test "diagnostics render the request id even with no error object" { var d: Diagnostics = .{ .gpa = testing.allocator, .status = .bad_gateway, .request_id = null, .body = null, }; d.request_id = try testing.allocator.dupe(u8, "abc-123"); d.body = try testing.allocator.dupe(u8, "bad gateway"); defer d.reset(); var buf: [256]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); try d.format(&w); try testing.expectEqualStrings( "HTTP 502 Bad Gateway (request-id abc-123): bad gateway", w.buffered(), ); } test "an empty diagnostics says so rather than pretending" { const d: Diagnostics = .{ .gpa = testing.allocator }; var buf: [64]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); try d.format(&w); try testing.expectEqualStrings("no response", w.buffered()); } test { _ = ApiError; }