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
//! collection index resyncer — updates collection index on #sync events
//!
//! a #sync event means a repo discontinuity (migration, rebase, bulk import).
//! the collection index may be stale for that DID. this worker fetches
//! describeRepo from the PDS to get the current collection list, then
//! replaces the index entries for that DID.
//!
//! runs on pool_io — enqueue() is called from frame worker threads,
//! background worker is a plain std.Thread.
const std = @import("std");
const Io = std.Io;
const http = std.http;
const collection_index_mod = @import("index.zig");
const Allocator = std.mem.Allocator;
const log = std.log.scoped(.resync);
const queue_capacity = 4096;
const ResyncItem = struct {
did_buf: [128]u8,
did_len: u8,
host_buf: [256]u8,
host_len: u16,
fn did(self: *const ResyncItem) []const u8 {
return self.did_buf[0..self.did_len];
}
fn hostname(self: *const ResyncItem) []const u8 {
return self.host_buf[0..self.host_len];
}
};
pub const Resyncer = struct {
allocator: Allocator,
/// pool_io (Threaded) — used for all synchronization AND the HTTP client.
/// this struct must never touch the Evented io.
io: Io,
collection_index: *collection_index_mod.CollectionIndex,
// bounded ring buffer queue
queue: [queue_capacity]ResyncItem,
head: usize,
tail: usize,
len: usize,
mutex: Io.Mutex,
cond: Io.Condition,
running: std.atomic.Value(bool),
thread: ?std.Thread,
// stats
processed: std.atomic.Value(u64),
failed: std.atomic.Value(u64),
dropped: std.atomic.Value(u64),
pub fn init(
allocator: Allocator,
io: Io,
collection_index: *collection_index_mod.CollectionIndex,
) Resyncer {
return .{
.allocator = allocator,
.io = io,
.collection_index = collection_index,
.queue = undefined,
.head = 0,
.tail = 0,
.len = 0,
.mutex = Io.Mutex.init,
.cond = Io.Condition.init,
.running = .{ .raw = false },
.thread = null,
.processed = .{ .raw = 0 },
.failed = .{ .raw = 0 },
.dropped = .{ .raw = 0 },
};
}
/// start the background worker thread.
pub fn start(self: *Resyncer) !void {
self.running.store(true, .release);
self.thread = try std.Thread.spawn(.{}, run, .{self});
}
/// enqueue a DID for resync. non-blocking, drops if queue full or inputs too long.
/// called from frame worker threads (plain std.Thread).
pub fn enqueue(self: *Resyncer, did: []const u8, hostname: []const u8) void {
if (did.len == 0 or did.len > 128 or hostname.len == 0 or hostname.len > 256) return;
self.mutex.lockUncancelable(self.io);
defer self.mutex.unlock(self.io);
if (self.len >= queue_capacity) {
_ = self.dropped.fetchAdd(1, .monotonic);
return;
}
var item: ResyncItem = .{
.did_buf = undefined,
.did_len = @intCast(did.len),
.host_buf = undefined,
.host_len = @intCast(hostname.len),
};
@memcpy(item.did_buf[0..did.len], did);
@memcpy(item.host_buf[0..hostname.len], hostname);
self.queue[self.tail] = item;
self.tail = (self.tail + 1) % queue_capacity;
self.len += 1;
self.cond.signal(self.io);
}
/// dequeue one item. blocks until available or shutdown.
fn dequeue(self: *Resyncer) ?ResyncItem {
self.mutex.lockUncancelable(self.io);
defer self.mutex.unlock(self.io);
while (self.len == 0 and self.running.load(.acquire)) {
self.cond.waitUncancelable(self.io, &self.mutex);
}
if (self.len == 0) return null;
const item = self.queue[self.head];
self.head = (self.head + 1) % queue_capacity;
self.len -= 1;
return item;
}
fn run(self: *Resyncer) void {
log.info("resync worker started", .{});
var client: http.Client = .{ .allocator = self.allocator, .io = self.io };
defer client.deinit();
while (self.running.load(.acquire)) {
const item = self.dequeue() orelse continue;
self.processItem(&client, &item);
// brief pause between items
self.io.sleep(Io.Duration.fromMilliseconds(50), .awake) catch {};
}
log.info("resync worker stopped (processed={d}, failed={d}, dropped={d})", .{
self.processed.load(.monotonic),
self.failed.load(.monotonic),
self.dropped.load(.monotonic),
});
}
fn processItem(self: *Resyncer, client: *http.Client, item: *const ResyncItem) void {
const did = item.did();
const hostname = item.hostname();
const token = self.collection_index.beginResync(did) catch {
_ = self.failed.fetchAdd(1, .monotonic);
return;
};
defer self.collection_index.cancelResync(token);
// fetch describeRepo from PDS
var url_buf: [512]u8 = undefined;
const url = std.fmt.bufPrint(&url_buf, "https://{s}/xrpc/com.atproto.repo.describeRepo?repo={s}", .{ hostname, did }) catch {
_ = self.failed.fetchAdd(1, .monotonic);
return;
};
var aw: std.Io.Writer.Allocating = .init(self.allocator);
defer aw.deinit();
const result = client.fetch(.{
.location = .{ .url = url },
.response_writer = &aw.writer,
.method = .GET,
}) catch |err| {
log.debug("resync: describeRepo failed for {s} on {s}: {s}", .{ did, hostname, @errorName(err) });
_ = self.failed.fetchAdd(1, .monotonic);
return;
};
if (result.status != .ok) {
log.debug("resync: describeRepo {d} for {s} on {s}", .{ @backingInt(result.status), did, hostname });
_ = self.failed.fetchAdd(1, .monotonic);
return;
}
const body = aw.written();
const applied = self.applySnapshot(did, token, body) catch |err| {
log.debug("resync: snapshot failed for {s}: {s}", .{ did, @errorName(err) });
_ = self.failed.fetchAdd(1, .monotonic);
return;
};
switch (applied) {
.replaced => {},
.merged => {
if (self.running.load(.acquire)) self.enqueue(did, hostname);
return;
},
.superseded => return,
}
_ = self.processed.fetchAdd(1, .monotonic);
log.debug("resync: {s} — collections replaced", .{did});
}
fn applySnapshot(self: *Resyncer, did: []const u8, token: u64, body: []const u8) !collection_index_mod.CollectionIndex.ResyncResult {
const parsed = try std.json.parseFromSlice(DescribeRepoResponse, self.allocator, body, .{ .ignore_unknown_fields = true });
defer parsed.deinit();
if (!std.mem.eql(u8, parsed.value.did, did)) return error.UnexpectedRepository;
return self.collection_index.finishResync(did, token, parsed.value.collections);
}
pub fn queueDepth(self: *Resyncer) usize {
self.mutex.lockUncancelable(self.io);
defer self.mutex.unlock(self.io);
return self.len;
}
pub fn stop(self: *Resyncer) void {
self.running.store(false, .release);
self.cond.signal(self.io);
}
pub fn deinit(self: *Resyncer) void {
self.stop();
if (self.thread) |t| t.join();
self.thread = null;
}
const DescribeRepoResponse = struct {
did: []const u8,
collections: []const []const u8,
};
};
// --- tests ---
test "Resyncer init and enqueue" {
// just test the queue mechanics, not the HTTP or index parts
var r: Resyncer = .{
.allocator = std.testing.allocator,
.io = std.testing.io,
.collection_index = undefined, // not used in this test
.queue = undefined,
.head = 0,
.tail = 0,
.len = 0,
.mutex = Io.Mutex.init,
.cond = Io.Condition.init,
.running = .{ .raw = true },
.thread = null,
.processed = .{ .raw = 0 },
.failed = .{ .raw = 0 },
.dropped = .{ .raw = 0 },
};
// enqueue and dequeue
r.enqueue("did:plc:test123", "pds.example.com");
try std.testing.expectEqual(@as(usize, 1), r.queueDepth());
const item = r.dequeue().?;
try std.testing.expectEqualStrings("did:plc:test123", item.did());
try std.testing.expectEqualStrings("pds.example.com", item.hostname());
try std.testing.expectEqual(@as(usize, 0), r.queueDepth());
}
test "Resyncer drops when full" {
var r: Resyncer = .{
.allocator = std.testing.allocator,
.io = std.testing.io,
.collection_index = undefined,
.queue = undefined,
.head = 0,
.tail = 0,
.len = queue_capacity, // pretend full
.mutex = Io.Mutex.init,
.cond = Io.Condition.init,
.running = .{ .raw = true },
.thread = null,
.processed = .{ .raw = 0 },
.failed = .{ .raw = 0 },
.dropped = .{ .raw = 0 },
};
r.enqueue("did:plc:test", "pds.example.com");
try std.testing.expectEqual(@as(u64, 1), r.dropped.load(.monotonic));
}
test "Resyncer rejects oversized inputs" {
var r: Resyncer = .{
.allocator = std.testing.allocator,
.io = std.testing.io,
.collection_index = undefined,
.queue = undefined,
.head = 0,
.tail = 0,
.len = 0,
.mutex = Io.Mutex.init,
.cond = Io.Condition.init,
.running = .{ .raw = true },
.thread = null,
.processed = .{ .raw = 0 },
.failed = .{ .raw = 0 },
.dropped = .{ .raw = 0 },
};
// empty DID
r.enqueue("", "pds.example.com");
try std.testing.expectEqual(@as(usize, 0), r.queueDepth());
// empty hostname
r.enqueue("did:plc:test", "");
try std.testing.expectEqual(@as(usize, 0), r.queueDepth());
}
test "resync: malformed or mismatched snapshots preserve committed membership" {
const t = std.testing;
var dir = t.tmpDir(.{});
defer dir.cleanup();
const path = try dir.dir.realPathFileAlloc(t.io, ".", t.allocator);
defer t.allocator.free(path);
var ci = try collection_index_mod.CollectionIndex.open(t.allocator, t.io, path);
defer ci.deinit();
try ci.enableBatching(.{ .delay_ns = 0 });
const resyncer = try t.allocator.create(Resyncer);
defer t.allocator.destroy(resyncer);
resyncer.* = .init(t.allocator, t.io, &ci);
const did = "did:plc:alice";
try ci.addCollection(did, "app.bsky.feed.post");
for ([_][]const u8{
"{}",
"{\"did\":\"did:plc:alice\"}",
"{\"did\":\"did:plc:alice\",\"collections\":null}",
"{\"did\":\"did:plc:bob\",\"collections\":[]}",
}) |body| {
const token = try ci.beginResync(did);
if (resyncer.applySnapshot(did, token, body)) |_| return error.ExpectedInvalidSnapshot else |_| {}
ci.cancelResync(token);
try t.expect(try ci.hasCollectionsChecked(did));
}
const token = try ci.beginResync(did);
try t.expectEqual(collection_index_mod.CollectionIndex.ResyncResult.replaced, try resyncer.applySnapshot(did, token, "{\"did\":\"did:plc:alice\",\"collections\":[]}"));
try t.expect(!(try ci.hasCollectionsChecked(did)));
}