1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
//! 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,
));
}