//! Streaming `com.atproto.sync.getRepo` fetches for whole-network bootstrap. //! //! The XRPC convenience client materializes response bodies in one contiguous //! allocation. Full repo exports are not bounded protocol messages, so that is //! the wrong ownership shape here. This module drains the HTTP body directly //! into a scratch file beside the archive, mmaps it read-only, and returns a //! borrowed byte slice. The scratch file is deleted on every success/failure //! path; stale files from a process crash are removed at bootstrap startup. const std = @import("std"); const cli = @import("../../runtime/cli.zig"); const Io = std.Io; const Allocator = std.mem.Allocator; var fetch_seq: std.atomic.Value(u64) = .init(0); pub const attempt_timeout: Io.Clock.Duration = .{ .raw = Io.Duration.fromSeconds(5 * 60), .clock = .awake, }; pub const low_speed_bytes_per_second: u64 = 1000; pub const low_speed_seconds: u16 = 30; pub const TransferProgress = struct { body_started: std.atomic.Value(bool) = .init(false), body_finished: std.atomic.Value(bool) = .init(false), bytes: std.atomic.Value(u64) = .init(0), }; pub const Outcome = union(enum) { ok: FetchedCar, rate_limited: ?u64, not_found, unavailable, transient, permanent, }; /// Normalized authority of the server that produced the final response after /// redirects. Default ports are removed; non-default ports are retained. pub const FinalHost = struct { buf: [std.Io.net.HostName.max_len + 7]u8 = undefined, len: usize = 0, pub fn slice(self: *const FinalHost) []const u8 { return self.buf[0..self.len]; } }; pub const FetchedCar = struct { allocator: Allocator, dir: Io.Dir, name: []u8, file: Io.File, mmap: ?Io.File.MemoryMap, bytes: []const u8, /// Preparation may release the mapping before repository emission. The /// scratch file remains open until the prepared attempt is fully handled. pub fn unmap(self: *FetchedCar, io: Io) void { if (self.mmap) |*mmap| mmap.destroy(io); self.mmap = null; self.bytes = &.{}; } pub fn deinit(self: *FetchedCar, io: Io) void { self.unmap(io); self.file.close(io); self.dir.deleteFile(io, self.name) catch {}; self.dir.close(io); self.allocator.free(self.name); self.* = undefined; } }; /// Remove scratch files left by a killed process. `fetchOnce` creates the /// directory lazily on the first actual fetch; eagerly recreating it on every /// steady-state startup would resurrect the lifecycle's deleted `backfill/` /// tree even when there is no repair work. pub fn resetScratch(io: Io, scratch_dir: []const u8) !void { var cwd = Io.Dir.cwd(); try cwd.deleteTree(io, scratch_dir); } /// One HTTP attempt. Retry policy belongs to the caller so 429s have a /// separate budget from ordinary transient failures, matching upstream. pub fn fetchOnce( allocator: Allocator, io: Io, scratch_dir: []const u8, relay_http: []const u8, did: []const u8, final_host: *FinalHost, ) !Outcome { return fetchOnceTracked(allocator, io, scratch_dir, relay_http, did, final_host, null); } pub fn fetchOnceTracked( allocator: Allocator, io: Io, scratch_dir: []const u8, relay_http: []const u8, did: []const u8, final_host: *FinalHost, progress: ?*TransferProgress, ) !Outcome { const url = try std.fmt.allocPrint(allocator, "{s}/xrpc/com.atproto.sync.getRepo?did={s}", .{ relay_http, did }); defer allocator.free(url); var client: std.http.Client = .{ .allocator = allocator, .io = io }; defer client.deinit(); const now = Io.Clock.real.now(io); try client.ca_bundle.rescan(allocator, io, now); @import("websocket").distrustCompromisedKeys(&client.ca_bundle); client.now = now; var request = try client.request(.GET, try std.Uri.parse(url), .{ .headers = .{ // The hot path: millions of getRepo calls land directly on PDSes // after the relay redirect. This is the request an operator sees. .user_agent = .{ .override = cli.userAgent() }, }, .keep_alive = false, .redirect_behavior = std.http.Client.Request.RedirectBehavior.init(3), }); defer request.deinit(); try request.sendBodiless(); var redirect_buf: [8 * 1024]u8 = undefined; var response = try request.receiveHead(&redirect_buf); try captureFinalHost(request.uri, final_host); if (response.head.status != .ok) return classifyErrorResponse(io, &response); var dir = try Io.Dir.cwd().createDirPathOpen(io, scratch_dir, .{}); errdefer dir.close(io); const seq = fetch_seq.fetchAdd(1, .monotonic); const name = try std.fmt.allocPrint(allocator, "repo-{d}.car", .{seq}); errdefer allocator.free(name); var file = try dir.createFile(io, name, .{ .read = true, .truncate = true }); errdefer { file.close(io); dir.deleteFile(io, name) catch {}; } var write_buf: [64 * 1024]u8 = undefined; var writer = Io.File.Writer.initStreaming(file, io, &write_buf); // Accept compression: PDSes serve gzip and it is ~2.5x smaller on the wire. // `reader` alone returns the *raw* body, so it must be paired with an // explicit Decompress or a gzip response would reach the CAR parser as // gzip bytes. Upstream gets this for free from Go's net/http. var decompress: std.http.Decompress = undefined; var decompress_buf: [std.compress.flate.max_window_len]u8 = undefined; // The transfer buffer feeds the decompressor its compressed input; a // zero-length one aborts the process on the first gzip response rather // than returning an error. var transfer_buf: [8 * 1024]u8 = undefined; const reader = response.readerDecompressing(&transfer_buf, &decompress, &decompress_buf); if (progress) |p| p.body_started.store(true, .release); var read_buf: [64 * 1024]u8 = undefined; while (true) { var slices = [_][]u8{&read_buf}; const n = reader.readVec(&slices) catch |err| switch (err) { error.EndOfStream => break, else => return err, }; if (n == 0) continue; try writer.interface.writeAll(read_buf[0..n]); if (progress) |p| _ = p.bytes.fetchAdd(n, .monotonic); } if (progress) |p| p.body_finished.store(true, .release); try writer.end(); const file_len = try file.length(io); if (file_len == 0) return error.EmptyCar; var mmap = try Io.File.MemoryMap.create(io, file, .{ .len = @intCast(file_len), .protection = .{ .read = true, .write = false }, .offset = 0, }); errdefer mmap.destroy(io); return .{ .ok = .{ .allocator = allocator, .dir = dir, .name = name, .file = file, .mmap = mmap, .bytes = mmap.memory[0..@intCast(file_len)], } }; } /// Run one getRepo attempt behind a hard deadline. Upstream gives each CAR /// download five minutes; cancellation interrupts the next network or file I/O /// point and all partial-file cleanup remains owned by `fetchOnce`. pub fn fetch( allocator: Allocator, io: Io, scratch_dir: []const u8, relay_http: []const u8, did: []const u8, final_host: *FinalHost, ) !Outcome { const Task = struct { allocator: Allocator, io: Io, scratch_dir: []const u8, relay_http: []const u8, did: []const u8, final_host: *FinalHost, progress: *TransferProgress, done: Io.Event = .unset, result: ?(anyerror!Outcome) = null, fn run(self: *@This()) void { self.result = fetchOnceTracked(self.allocator, self.io, self.scratch_dir, self.relay_http, self.did, self.final_host, self.progress); self.done.set(self.io); } }; var progress: TransferProgress = .{}; var task: Task = .{ .allocator = allocator, .io = io, .scratch_dir = scratch_dir, .relay_http = relay_http, .did = did, .final_host = final_host, .progress = &progress, }; var future = try io.concurrent(Task.run, .{&task}); try waitForTransfer(io, &task.done, &future, &progress); _ = future.await(io); return try task.result.?; } pub fn waitForTransfer(io: Io, done: *Io.Event, future: *Io.Future(void), progress: *TransferProgress) !void { return waitForTransferPolicy( io, done, future, progress, .{ .raw = Io.Duration.fromSeconds(1), .clock = .awake }, low_speed_bytes_per_second, low_speed_seconds, 5 * 60, ); } fn waitForTransferPolicy( io: Io, done: *Io.Event, future: *Io.Future(void), progress: *TransferProgress, sample_interval: Io.Clock.Duration, minimum_bytes: u64, maximum_slow_samples: u16, maximum_samples: u16, ) !void { var prior_bytes: u64 = 0; var slow_samples: u16 = 0; var samples: u16 = 0; while (true) { done.waitTimeout(io, .{ .duration = sample_interval }) catch |err| switch (err) { error.Timeout => { samples += 1; if (progress.body_started.load(.acquire) and !progress.body_finished.load(.acquire)) { const current = progress.bytes.load(.monotonic); if (current - prior_bytes < minimum_bytes) slow_samples += 1 else slow_samples = 0; prior_bytes = current; if (slow_samples >= maximum_slow_samples) { _ = future.cancel(io); return error.TransferTooSlow; } } if (samples >= maximum_samples) { _ = future.cancel(io); return error.AttemptTimeout; } continue; }, else => { _ = future.cancel(io); return err; }, }; return; } } fn fetchWithTimeout( allocator: Allocator, io: Io, scratch_dir: []const u8, relay_http: []const u8, did: []const u8, final_host: *FinalHost, timeout: Io.Clock.Duration, ) !Outcome { const Task = struct { allocator: Allocator, io: Io, scratch_dir: []const u8, relay_http: []const u8, did: []const u8, final_host: *FinalHost, done: Io.Event = .unset, result: ?(anyerror!Outcome) = null, fn run(self: *@This()) void { self.result = fetchOnce(self.allocator, self.io, self.scratch_dir, self.relay_http, self.did, self.final_host); self.done.set(self.io); } }; var task: Task = .{ .allocator = allocator, .io = io, .scratch_dir = scratch_dir, .relay_http = relay_http, .did = did, .final_host = final_host, }; var future = try io.concurrent(Task.run, .{&task}); task.done.waitTimeout(io, .{ .duration = timeout }) catch |err| switch (err) { error.Timeout => { _ = future.cancel(io); return error.AttemptTimeout; }, else => { _ = future.cancel(io); return err; }, }; _ = future.await(io); return try task.result.?; } pub fn captureFinalHost(uri: std.Uri, out: *FinalHost) !void { var host_buf: [std.Io.net.HostName.max_len]u8 = undefined; const host = try (uri.host orelse return error.UriMissingHost).toRaw(&host_buf); const default_port: ?u16 = if (std.ascii.eqlIgnoreCase(uri.scheme, "https")) 443 else if (std.ascii.eqlIgnoreCase(uri.scheme, "http")) 80 else null; const include_port = uri.port != null and uri.port != default_port; const normalized = if (include_port) try std.fmt.bufPrint(&out.buf, "{s}:{d}", .{ host, uri.port.? }) else blk: { if (host.len > out.buf.len) return error.NoSpaceLeft; for (host, out.buf[0..host.len]) |c, *dst| dst.* = std.ascii.toLower(c); break :blk out.buf[0..host.len]; }; if (include_port) { for (normalized) |*c| c.* = std.ascii.toLower(c.*); } out.len = normalized.len; } fn classifyErrorResponse(io: Io, response: *std.http.Client.Response) !Outcome { const status = response.head.status; const retry_after = retryAfter(io, response.head); var body_buf: [64 * 1024]u8 = undefined; var writer = Io.Writer.fixed(&body_buf); // Must decompress here too: `classifyError` matches on the body *text*, so a // gzipped error body read raw would silently fail every pattern and // misclassify a known error as unknown. var decompress: std.http.Decompress = undefined; var decompress_buf: [std.compress.flate.max_window_len]u8 = undefined; // The transfer buffer feeds the decompressor its compressed input; a // zero-length one aborts the process on the first gzip response rather // than returning an error. var transfer_buf: [8 * 1024]u8 = undefined; const reader = response.readerDecompressing(&transfer_buf, &decompress, &decompress_buf); _ = reader.streamRemaining(&writer) catch {}; const body = writer.buffered(); return classifyError(status, body, retry_after); } fn classifyError(status: std.http.Status, body: []const u8, retry_after: ?u64) Outcome { if (status == .too_many_requests) return .{ .rate_limited = retry_after }; if (status.class() == .server_error) return .transient; var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const parsed = std.json.parseFromSliceLeaky(std.json.Value, arena.allocator(), body, .{}) catch return if (status == .not_found) .not_found else .permanent; const name = if (parsed == .object and parsed.object.get("error") != null and parsed.object.get("error").? == .string) parsed.object.get("error").?.string else ""; const message = if (parsed == .object and parsed.object.get("message") != null and parsed.object.get("message").? == .string) parsed.object.get("message").?.string else ""; if (std.mem.eql(u8, name, "RepoNotFound") or (std.mem.eql(u8, name, "NotFound") and containsRepoNotFound(message))) return .not_found; if (std.mem.eql(u8, name, "RepoDeactivated") or std.mem.eql(u8, name, "RepoSuspended") or std.mem.eql(u8, name, "RepoTakendown")) return .unavailable; return if (status.class() == .server_error) .transient else .permanent; } fn retryAfter(io: Io, head: std.http.Client.Response.Head) ?u64 { // AT Protocol rate limits use an absolute Unix RateLimit-Reset and it // takes precedence over Retry-After upstream. var headers = head.iterateHeaders(); while (headers.next()) |header| { if (std.ascii.eqlIgnoreCase(header.name, "ratelimit-reset")) { const reset = std.fmt.parseInt(i64, std.mem.trim(u8, header.value, " \t"), 10) catch break; const now = Io.Timestamp.now(io, .real).toSeconds(); return @intCast(@max(reset - now, 1)); } } var it = head.iterateHeaders(); while (it.next()) |header| { if (std.ascii.eqlIgnoreCase(header.name, "retry-after")) return std.fmt.parseInt(u64, std.mem.trim(u8, header.value, " \t"), 10) catch null; } return null; } fn containsRepoNotFound(message: []const u8) bool { var lower_buf: [256]u8 = undefined; const n = @min(message.len, lower_buf.len); for (message[0..n], lower_buf[0..n]) |c, *out| out.* = std.ascii.toLower(c); return std.mem.indexOf(u8, lower_buf[0..n], "repo not found") != null; } test "final host normalization retains only non-default ports" { var host: FinalHost = .{}; try captureFinalHost(try std.Uri.parse("https://PDS.Example.COM/xrpc/foo"), &host); try std.testing.expectEqualStrings("pds.example.com", host.slice()); try captureFinalHost(try std.Uri.parse("https://PDS.Example.COM:8443/xrpc/foo"), &host); try std.testing.expectEqualStrings("pds.example.com:8443", host.slice()); try captureFinalHost(try std.Uri.parse("http://PDS.Example.COM:80/xrpc/foo"), &host); try std.testing.expectEqualStrings("pds.example.com", host.slice()); } test "classifies production repo terminal errors" { try std.testing.expect(containsRepoNotFound("Repo not found")); try std.testing.expect(containsRepoNotFound("the repo NOT FOUND here")); try std.testing.expect(!containsRepoNotFound("record not found")); try std.testing.expect(classifyError(.bad_request, "{\"error\":\"RepoNotFound\"}", null) == .not_found); try std.testing.expect(classifyError(.bad_request, "{\"error\":\"NotFound\",\"message\":\"Repo not found\"}", null) == .not_found); try std.testing.expect(classifyError(.bad_request, "{\"error\":\"NotFound\",\"message\":\"Record not found\"}", null) == .permanent); inline for (&.{ "RepoDeactivated", "RepoSuspended", "RepoTakendown" }) |name| { var buf: [96]u8 = undefined; const body = try std.fmt.bufPrint(&buf, "{{\"error\":\"{s}\"}}", .{name}); try std.testing.expect(classifyError(.bad_request, body, null) == .unavailable); } const limited = classifyError(.too_many_requests, "", 17); try std.testing.expectEqual(@as(?u64, 17), limited.rate_limited); try std.testing.expect(classifyError(.service_unavailable, "", null) == .transient); } test "stalled getRepo is canceled at the attempt deadline" { var threaded: Io.Threaded = .init(std.testing.allocator, .{}); defer threaded.deinit(); const io = threaded.io(); var server = (Io.net.IpAddress{ .ip4 = .loopback(0) }).listen(io, .{ .reuse_address = true }) catch unreachable; defer server.deinit(io); const Stall = struct { fn run(s: *Io.net.Server, task_io: Io) !void { var stream = try s.accept(task_io); defer stream.close(task_io); try task_io.sleep(Io.Duration.fromSeconds(30), .awake); } }; var stall = try io.concurrent(Stall.run, .{ &server, io }); defer _ = stall.cancel(io) catch {}; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var scratch: [Io.Dir.max_path_bytes]u8 = undefined; const scratch_len = try tmp.dir.realPath(io, &scratch); var url_buf: [96]u8 = undefined; const url = try std.fmt.bufPrint(&url_buf, "http://127.0.0.1:{d}", .{server.socket.address.getPort()}); const timeout: Io.Clock.Duration = .{ .raw = Io.Duration.fromMilliseconds(25), .clock = .awake }; var final_host: FinalHost = .{}; try std.testing.expectError( error.AttemptTimeout, fetchWithTimeout(std.testing.allocator, io, scratch[0..scratch_len], url, "did:plc:stalled", &final_host, timeout), ); } test "trickling getRepo is canceled by the low speed guard" { const testing = std.testing; var threaded: Io.Threaded = .init(testing.allocator, .{}); defer threaded.deinit(); const io = threaded.io(); var server = (Io.net.IpAddress{ .ip4 = .loopback(0) }).listen(io, .{ .reuse_address = true }) catch unreachable; defer server.deinit(io); const Fixture = struct { fn run(listener: *Io.net.Server, task_io: Io) !void { var stream = try listener.accept(task_io); defer stream.close(task_io); var read_buf: [4096]u8 = undefined; var write_buf: [4096]u8 = undefined; var reader = stream.reader(task_io, &read_buf); var writer = stream.writer(task_io, &write_buf); var http_server = std.http.Server.init(&reader.interface, &writer.interface); _ = try http_server.receiveHead(); try writer.interface.writeAll( "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.ipld.car\r\nContent-Length: 10000\r\nConnection: close\r\n\r\n", ); try writer.interface.flush(); while (true) { writer.interface.writeByte(0) catch return; writer.interface.flush() catch return; task_io.sleep(Io.Duration.fromMilliseconds(5), .awake) catch return; } } }; var server_future = try io.concurrent(Fixture.run, .{ &server, io }); defer _ = server_future.cancel(io) catch {}; var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); var scratch: [Io.Dir.max_path_bytes]u8 = undefined; const scratch_len = try tmp.dir.realPath(io, &scratch); var url_buf: [96]u8 = undefined; const url = try std.fmt.bufPrint(&url_buf, "http://127.0.0.1:{d}", .{server.socket.address.getPort()}); var final_host: FinalHost = .{}; var progress: TransferProgress = .{}; const Fetch = struct { allocator: Allocator, io: Io, scratch: []const u8, url: []const u8, host: *FinalHost, progress: *TransferProgress, done: Io.Event = .unset, result: ?(anyerror!Outcome) = null, fn run(self: *@This()) void { self.result = fetchOnceTracked( self.allocator, self.io, self.scratch, self.url, "did:plc:trickle", self.host, self.progress, ); self.done.set(self.io); } }; var fetch_task: Fetch = .{ .allocator = testing.allocator, .io = io, .scratch = scratch[0..scratch_len], .url = url, .host = &final_host, .progress = &progress, }; var fetch_future = try io.concurrent(Fetch.run, .{&fetch_task}); try testing.expectError(error.TransferTooSlow, waitForTransferPolicy( io, &fetch_task.done, &fetch_future, &progress, .{ .raw = Io.Duration.fromMilliseconds(10), .clock = .awake }, 100, 3, 100, )); }