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
//! One bounded getRepo network/CAR attempt.
//!
//! Upstream's attempt deadline covers the redirected response stream and
//! LoadCompleteFromCAR, but not handler emission or durable writes. Keeping
//! those boundaries here prevents a syntactically complete but structurally
//! partial CAR from escaping the timeout/retry policy.
const std = @import("std");
const zat = @import("zat");
const fetched_car = @import("fetched_car.zig");
const repos = @import("repos.zig");
const segment = @import("../../storage/segment.zig");
const Io = std.Io;
const Allocator = std.mem.Allocator;
fn prepareOwned(parse_allocator: Allocator, source: []const u8) !repos.PreparedRepo {
const owned_car = try parse_allocator.dupe(u8, source);
return repos.prepareRepo(parse_allocator, owned_car);
}
pub const Prepared = struct {
fetched: fetched_car.FetchedCar,
repo: repos.PreparedRepo,
pub fn deinit(self: *Prepared, io: Io) void {
self.fetched.deinit(io);
self.* = undefined;
}
};
pub const Outcome = union(enum) {
ok: Prepared,
rate_limited: ?u64,
not_found,
unavailable,
transient,
permanent,
fn deinit(self: *Outcome, io: Io) void {
switch (self.*) {
.ok => |*prepared| prepared.deinit(io),
else => {},
}
}
};
pub fn fetch(
allocator: Allocator,
parse_allocator: Allocator,
io: Io,
scratch_dir: []const u8,
relay_http: []const u8,
did: []const u8,
final_host: *fetched_car.FinalHost,
) !Outcome {
const Task = struct {
allocator: Allocator,
parse_allocator: Allocator,
io: Io,
scratch_dir: []const u8,
relay_http: []const u8,
did: []const u8,
final_host: *fetched_car.FinalHost,
progress: *fetched_car.TransferProgress,
done: Io.Event = .unset,
result: ?(anyerror!Outcome) = null,
fn run(self: *@This()) void {
self.result = self.runAttempt();
self.done.set(self.io);
}
fn runAttempt(self: *@This()) !Outcome {
var outcome = try fetched_car.fetchOnceTracked(
self.allocator,
self.io,
self.scratch_dir,
self.relay_http,
self.did,
self.final_host,
self.progress,
);
return switch (outcome) {
.ok => |*fetched| blk: {
errdefer fetched.deinit(self.io);
// Upstream's LoadCompleteFromCAR owns the loaded repository
// through handler emission. Do the same here: scratch stays
// the network/download shape, while the bounded parse
// allocator owns every byte the lazy MST and record rows can
// reference. Carrying borrowed mmap slices into concurrent
// archive appends made an unmap/lifetime error a segfault.
//
// That ownership is what `prepareOwned`'s dupe provides, per
// worker. This used to also run under a single process-wide
// mutex, which was not required by the ownership rule above
// and serialized every worker's parse behind one core:
// upstream parses concurrently across all backfill workers
// and holds no such lock. It capped whole-network backfill
// at ~4 repos/s against upstream's documented ~16 hours.
const prepared = try prepareOwned(self.parse_allocator, fetched.bytes);
fetched.unmap(self.io);
break :blk .{ .ok = .{ .fetched = fetched.*, .repo = prepared } };
},
.rate_limited => |delay| .{ .rate_limited = delay },
.not_found => .not_found,
.unavailable => .unavailable,
.transient => .transient,
.permanent => .permanent,
};
}
};
var progress: fetched_car.TransferProgress = .{};
var task: Task = .{
.allocator = allocator,
.parse_allocator = parse_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});
fetched_car.waitForTransfer(io, &task.done, &future, &progress) catch |wait_err| {
// cancel() has joined the attempt. If CPU-bound preparation crossed
// the deadline before observing cancellation, reclaim the completed
// outcome here.
if (task.result) |attempt| if (attempt) |value| {
var owned = value;
owned.deinit(io);
} else |_| {};
return wait_err;
};
_ = future.await(io);
return try task.result.?;
}
test "prepared repo emission owns the CAR after its source is destroyed" {
const testing = std.testing;
var prepared_arena = std.heap.ArenaAllocator.init(testing.allocator);
defer prepared_arena.deinit();
const prepared_alloc = prepared_arena.allocator();
var prepared: repos.PreparedRepo = undefined;
{
var source_arena = std.heap.ArenaAllocator.init(testing.allocator);
defer source_arena.deinit();
const source = source_arena.allocator();
const payload = try source.dupe(u8, "source-backed opaque record");
const record_cid = try zat.cbor.Cid.forDagCbor(source, payload);
var tree = zat.mst.Mst.init(source);
try tree.put("app.bsky.feed.post/3k2abcdefghij", record_cid);
const data_cid = try tree.rootCid();
const keypair = try zat.Keypair.fromSecretKey(.p256, @splat(29));
const did = try keypair.did(source);
const signed = try zat.signCommit(source, .{
.did = did,
.rev = "3k2abcdefghij",
.data = data_cid,
}, &keypair);
var blocks: std.ArrayList(zat.car.Block) = .empty;
try blocks.append(source, .{ .cid_raw = signed.cid.raw, .data = signed.bytes });
try tree.collectBlocks(&blocks);
try blocks.append(source, .{ .cid_raw = record_cid.raw, .data = payload });
const car_bytes = try zat.car.writeAlloc(source, .{
.roots = &.{signed.cid},
.blocks = blocks.items,
});
prepared = try prepareOwned(prepared_alloc, car_bytes);
}
var drops: repos.DropCounts = .{};
const Sink = struct {
rows: usize = 0,
fn emit(self: *@This(), event: segment.Event) anyerror!void {
try std.testing.expectEqualStrings("source-backed opaque record", event.payload);
self.rows += 1;
}
};
var sink: Sink = .{};
_ = try repos.emitPrepared(
prepared_alloc,
&prepared,
"",
1,
.create,
&drops,
&sink,
Sink.emit,
);
try testing.expectEqual(@as(usize, 1), sink.rows);
}