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
//! collection index backfill — discovers collections and imports DIDs from a source relay
//!
//! two collection discovery sources (unioned):
//! 1. lexicon garden llms.txt — ~700 known NSIDs
//! 2. RBC column family scan — firehose-observed collections already in the index
//!
//! progress tracked in postgres (backfill_progress table) for resumability.
//! triggered via POST /admin/backfill-collections, status via GET.
const std = @import("std");
const Io = std.Io;
const http = std.http;
const pg = @import("pg");
const collection_index_mod = @import("index.zig");
const event_log_mod = @import("../event_log.zig");
const Allocator = std.mem.Allocator;
const log = std.log.scoped(.backfill);
const FetchResult = struct {
dids: [][]const u8,
next_cursor: ?[]const u8,
};
pub const Backfiller = struct {
allocator: Allocator,
collection_index: *collection_index_mod.CollectionIndex,
persist: *event_log_mod.DiskPersist,
running: std.atomic.Value(bool),
thread: ?std.Thread,
source: []const u8,
io: Io,
shutdown: *std.atomic.Value(bool),
fn db(self: *Backfiller) *pg.Pool {
return self.persist.db;
}
pub fn init(
allocator: Allocator,
collection_index: *collection_index_mod.CollectionIndex,
persist: *event_log_mod.DiskPersist,
io: Io,
shutdown: *std.atomic.Value(bool),
) Backfiller {
return .{
.allocator = allocator,
.collection_index = collection_index,
.persist = persist,
.running = .{ .raw = false },
.thread = null,
.source = "",
.io = io,
.shutdown = shutdown,
};
}
pub fn isRunning(self: *Backfiller) bool {
return self.running.load(.acquire);
}
/// block until any in-progress backfill thread completes.
/// must be called before tearing down DiskPersist or CollectionIndex.
pub fn waitForCompletion(self: *Backfiller) void {
if (self.thread) |t| {
t.join();
self.thread = null;
}
}
/// start a backfill from the given source relay. returns error if already running.
pub fn start(self: *Backfiller, source: []const u8) !void {
if (self.running.cmpxchgStrong(false, true, .acq_rel, .acquire) != null) {
return error.AlreadyRunning;
}
errdefer self.running.store(false, .release);
self.source = try self.allocator.dupe(u8, source);
errdefer {
self.allocator.free(self.source);
self.source = "";
}
self.thread = std.Thread.spawn(.{}, run, .{self}) catch return error.SpawnFailed;
}
fn run(self: *Backfiller) void {
defer {
self.allocator.free(self.source);
self.source = "";
// note: do NOT clear self.thread here — waitForCompletion() needs
// the handle to join this thread before dp/ci teardown. the running
// flag gates start(), so a stale thread handle is harmless.
self.running.store(false, .release);
}
const pool = self.db();
// discover collections
const collections = self.discoverCollections() catch |err| {
log.err("collection discovery failed: {s}", .{@errorName(err)});
return;
};
defer {
for (collections) |c| self.allocator.free(c);
self.allocator.free(collections);
}
log.info("discovered {d} collections to backfill from {s}", .{ collections.len, self.source });
// insert progress rows (skip existing)
for (collections) |collection| {
_ = pool.exec(
"INSERT INTO backfill_progress (collection, source) VALUES ($1, $2) ON CONFLICT (collection, source) DO NOTHING",
.{ collection, self.source },
) catch |err| {
log.warn("failed to insert progress for {s}: {s}", .{ collection, @errorName(err) });
};
}
// backfill each collection
for (collections) |collection| {
if (self.shutdown.load(.acquire)) {
log.info("backfill interrupted by shutdown", .{});
return;
}
self.backfillCollection(collection) catch |err| {
log.warn("backfill failed for {s}: {s}", .{ collection, @errorName(err) });
};
}
log.info("backfill complete", .{});
}
fn discoverCollections(self: *Backfiller) ![][]const u8 {
var seen: std.StringHashMapUnmanaged(void) = .empty;
defer seen.deinit(self.allocator);
// source 1: lexicon garden
const garden = self.fetchLexiconGarden() catch |err| blk: {
log.warn("lexicon garden fetch failed: {s}", .{@errorName(err)});
break :blk &[_][]const u8{};
};
defer {
for (garden) |c| self.allocator.free(c);
self.allocator.free(garden);
}
for (garden) |c| {
if (!collection_index_mod.isValidCollection(c)) continue;
if (!seen.contains(c)) {
const duped = try self.allocator.dupe(u8, c);
errdefer self.allocator.free(duped);
try seen.put(self.allocator, duped, {});
}
}
// source 2: observed collections from RBC scan
const observed = self.collection_index.listKnownCollections(self.allocator) catch |err| blk: {
log.warn("RBC scan failed: {s}", .{@errorName(err)});
break :blk &[_][]const u8{};
};
defer {
for (observed) |c| self.allocator.free(c);
self.allocator.free(observed);
}
for (observed) |c| {
if (!collection_index_mod.isValidCollection(c)) continue;
if (!seen.contains(c)) {
const duped = try self.allocator.dupe(u8, c);
errdefer self.allocator.free(duped);
try seen.put(self.allocator, duped, {});
}
}
// collect into result
const result = try self.allocator.alloc([]const u8, seen.count());
var i: usize = 0;
var key_iter = seen.keyIterator();
while (key_iter.next()) |key| {
result[i] = key.*;
i += 1;
}
return result;
}
/// fetch NSIDs from https://lexicon.garden/llms.txt
/// parses lines matching `- [`<nsid>`](`
fn fetchLexiconGarden(self: *Backfiller) ![][]const u8 {
var client: http.Client = .{ .allocator = self.allocator, .io = self.io };
defer client.deinit();
const body = try fetchBody(self.allocator, &client, "https://lexicon.garden/llms.txt");
defer self.allocator.free(body);
var nsids: std.ArrayListUnmanaged([]const u8) = .empty;
defer nsids.deinit(self.allocator);
// parse lines like: - [`app.bsky.feed.post`](
var lines = std.mem.splitScalar(u8, body, '\n');
while (lines.next()) |line| {
// look for pattern: - [`<nsid>`](
const backtick_start = std.mem.indexOf(u8, line, "- [`") orelse continue;
const nsid_start = backtick_start + 4; // skip "- [`"
const rest = line[nsid_start..];
const backtick_end = std.mem.indexOf(u8, rest, "`](") orelse continue;
const nsid = rest[0..backtick_end];
// basic NSID validation: must contain at least one dot
if (!std.mem.containsAtLeast(u8, nsid, 1, ".")) continue;
// skip obviously non-record types (but include them anyway — they'll return empty)
const duped = try self.allocator.dupe(u8, nsid);
errdefer self.allocator.free(duped);
try nsids.append(self.allocator, duped);
}
log.info("lexicon garden: found {d} NSIDs", .{nsids.items.len});
return try nsids.toOwnedSlice(self.allocator);
}
fn backfillCollection(self: *Backfiller, collection: []const u8) !void {
const pool = self.db();
// single query: check completion, get cursor + count for resume
var cursor: ?[]const u8 = null;
defer if (cursor) |c| self.allocator.free(c);
var imported: i64 = 0;
{
var row = (pool.rowUnsafe(
"SELECT completed_at IS NOT NULL, cursor, imported_count FROM backfill_progress WHERE collection = $1 AND source = $2",
.{ collection, self.source },
) catch return error.DatabaseError) orelse return;
defer row.deinit() catch {};
if (row.get(bool, 0)) return; // already done
const saved_cursor = row.get([]const u8, 1);
imported = row.get(i64, 2);
if (saved_cursor.len > 0) {
cursor = try self.allocator.dupe(u8, saved_cursor);
log.info("{s}: resuming from cursor (imported {d} so far)", .{ collection, imported });
}
}
// reuse one HTTP client across all pages for this collection
var client: http.Client = .{ .allocator = self.allocator, .io = self.io };
defer client.deinit();
var page_count: usize = 0;
while (!self.shutdown.load(.acquire)) {
const fetch_result = self.fetchPage(&client, collection, cursor) catch |err| {
log.warn("{s}: fetch page failed: {s}", .{ collection, @errorName(err) });
break;
};
defer freeFetchResult(self.allocator, fetch_result);
try self.collection_index.addCollectionPage(fetch_result.dids, collection);
imported += @intCast(fetch_result.dids.len);
page_count += 1;
// update cursor in progress table
const new_cursor = fetch_result.next_cursor orelse "";
_ = pool.exec(
"UPDATE backfill_progress SET cursor = $1, imported_count = $2 WHERE collection = $3 AND source = $4",
.{ new_cursor, imported, collection, self.source },
) catch {};
if (fetch_result.next_cursor) |nc| {
// advance cursor
if (cursor) |old| self.allocator.free(old);
cursor = self.allocator.dupe(u8, nc) catch break;
// brief pause between pages
self.io.sleep(Io.Duration.fromMilliseconds(100), .awake) catch {};
} else {
// no more pages — mark complete
_ = pool.exec(
"UPDATE backfill_progress SET completed_at = now(), cursor = '', imported_count = $1 WHERE collection = $2 AND source = $3",
.{ imported, collection, self.source },
) catch {};
log.info("{s}: complete ({d} DIDs, {d} pages)", .{ collection, imported, page_count });
break;
}
}
}
fn fetchPage(self: *Backfiller, client: *http.Client, collection: []const u8, cursor: ?[]const u8) !FetchResult {
// build URL
var url_buf: [1024]u8 = undefined;
const url = if (cursor) |c|
std.fmt.bufPrint(&url_buf, "https://{s}/xrpc/com.atproto.sync.listReposByCollection?collection={s}&limit=1000&cursor={s}", .{ self.source, collection, c }) catch return error.UrlTooLong
else
std.fmt.bufPrint(&url_buf, "https://{s}/xrpc/com.atproto.sync.listReposByCollection?collection={s}&limit=1000", .{ self.source, collection }) catch return error.UrlTooLong;
const body = try fetchBody(self.allocator, client, url);
defer self.allocator.free(body);
return parsePage(self.allocator, body);
}
/// GET `url` and return the whole response body, owned by the caller.
fn fetchBody(allocator: Allocator, client: *http.Client, url: []const u8) ![]u8 {
var aw: std.Io.Writer.Allocating = .init(allocator);
defer aw.deinit();
const result = client.fetch(.{
.location = .{ .url = url },
.response_writer = &aw.writer,
.method = .GET,
}) catch return error.FetchFailed;
if (result.status != .ok) return error.FetchFailed;
return aw.toOwnedSlice();
}
/// parse: {"repos": [{"did": "..."}, ...], "cursor": "..."}
fn parsePage(allocator: Allocator, body: []const u8) !FetchResult {
const parsed = std.json.parseFromSlice(ListReposResponse, allocator, body, .{ .ignore_unknown_fields = true }) catch return error.ParseFailed;
defer parsed.deinit();
const repos = parsed.value.repos orelse return .{
.dids = try allocator.alloc([]const u8, 0),
.next_cursor = null,
};
var dids: std.ArrayListUnmanaged([]const u8) = .empty;
defer dids.deinit(allocator);
for (repos) |repo| {
const duped = allocator.dupe(u8, repo.did) catch continue;
dids.append(allocator, duped) catch {
allocator.free(duped);
continue;
};
}
const next_cursor = if (parsed.value.cursor) |c|
allocator.dupe(u8, c) catch null
else
null;
return .{
.dids = dids.toOwnedSlice(allocator) catch return error.OutOfMemory,
.next_cursor = next_cursor,
};
}
fn freeFetchResult(allocator: Allocator, result: FetchResult) void {
for (result.dids) |d| allocator.free(d);
allocator.free(result.dids);
if (result.next_cursor) |c| allocator.free(c);
}
const ListReposResponse = struct {
repos: ?[]const RepoEntry = null,
cursor: ?[]const u8 = null,
};
const RepoEntry = struct {
did: []const u8,
};
/// return status summary for the admin endpoint
pub fn getStatus(self: *Backfiller, allocator: Allocator) ![]u8 {
const pool = self.db();
var aw: Io.Writer.Allocating = .init(allocator);
defer aw.deinit();
const w = &aw.writer;
// query aggregate stats
var total: i64 = 0;
var completed: i64 = 0;
var total_imported: i64 = 0;
{
var row = (pool.rowUnsafe(
"SELECT COUNT(*)::bigint, COUNT(completed_at)::bigint, COALESCE(SUM(imported_count), 0)::bigint FROM backfill_progress",
.{},
) catch null) orelse null;
if (row) |*r| {
total = r.get(i64, 0);
completed = r.get(i64, 1);
total_imported = r.get(i64, 2);
r.deinit() catch {};
}
}
w.print("{{\"running\":{},\"total\":{d},\"completed\":{d},\"in_progress\":{d},\"total_imported\":{d},\"collections\":[", .{
self.isRunning(),
total,
completed,
total - completed,
total_imported,
}) catch return error.FormatError;
// per-collection detail
var result = pool.query(
"SELECT collection, source, cursor, imported_count, completed_at IS NOT NULL FROM backfill_progress ORDER BY collection, source",
.{},
) catch return error.DatabaseError;
defer result.deinit();
var first = true;
while (result.nextUnsafe() catch null) |dbrow| {
if (!first) w.writeByte(',') catch {};
first = false;
writeStatusRow(w, .{
.collection = dbrow.get([]const u8, 0),
.source = dbrow.get([]const u8, 1),
.cursor = dbrow.get([]const u8, 2),
.imported = dbrow.get(i64, 3),
.completed = dbrow.get(bool, 4),
}) catch {};
}
w.writeAll("]}") catch {};
return try aw.toOwnedSlice();
}
const StatusRow = struct { collection: []const u8, source: []const u8, cursor: []const u8, imported: i64, completed: bool };
/// One progress row as a JSON object. Collection names come from the
/// firehose and the index scan, so they are encoded as JSON strings, not
/// pasted: a name with a backslash or quote must not break the document.
fn writeStatusRow(w: *Io.Writer, row: StatusRow) !void {
try w.writeAll("{\"collection\":");
try std.json.Stringify.encodeJsonString(row.collection, .{}, w);
try w.writeAll(",\"source\":");
try std.json.Stringify.encodeJsonString(row.source, .{}, w);
try w.print(",\"imported\":{d},\"completed\":{}", .{ row.imported, row.completed });
if (row.cursor.len > 0 and !row.completed) {
try w.writeAll(",\"cursor\":");
try std.json.Stringify.encodeJsonString(row.cursor, .{}, w);
}
try w.writeByte('}');
}
};
test "a fetched page body is owned by the caller and freed with it" {
const t = std.testing;
var threaded = Io.Threaded.init(t.allocator, .{});
defer threaded.deinit();
const io = threaded.io();
const page_json = "{\"repos\":[{\"did\":\"did:plc:aaaaaaaaaaaaaaaaaaaaaaaa\"},{\"did\":\"did:plc:bbbbbbbbbbbbbbbbbbbbbbbb\"}],\"cursor\":\"did:plc:bbbbbbbbbbbbbbbbbbbbbbbb\"}";
const loopback = try Io.net.IpAddress.parseIp4("127.0.0.1", 0);
var server = try loopback.listen(io, .{ .reuse_address = true });
defer server.deinit(io);
const Serve = struct {
fn run(srv: *Io.net.Server, sio: Io, body: []const u8) void {
const stream = srv.accept(sio) catch return;
defer stream.close(sio);
var recv: [4096]u8 = undefined;
var send: [4096]u8 = undefined;
var reader = stream.reader(sio, &recv);
var writer = stream.writer(sio, &send);
var hs = http.Server.init(&reader.interface, &writer.interface);
var request = hs.receiveHead() catch return;
request.respond(body, .{ .keep_alive = false, .extra_headers = &.{.{ .name = "content-type", .value = "application/json" }} }) catch {};
}
};
const thread = try std.Thread.spawn(.{}, Serve.run, .{ &server, io, page_json });
defer thread.join();
var client: http.Client = .{ .allocator = t.allocator, .io = io };
defer client.deinit();
var url_buf: [160]u8 = undefined;
const url = try std.fmt.bufPrint(&url_buf, "http://127.0.0.1:{d}/xrpc/com.atproto.sync.listReposByCollection?collection=app.bsky.feed.post&limit=1000", .{server.socket.address.getPort()});
const body = try Backfiller.fetchBody(t.allocator, &client, url);
defer t.allocator.free(body);
try t.expectEqualStrings(page_json, body);
const page = try Backfiller.parsePage(t.allocator, body);
defer Backfiller.freeFetchResult(t.allocator, page);
try t.expectEqual(@as(usize, 2), page.dids.len);
try t.expectEqualStrings("did:plc:aaaaaaaaaaaaaaaaaaaaaaaa", page.dids[0]);
try t.expectEqualStrings("did:plc:bbbbbbbbbbbbbbbbbbbbbbbb", page.next_cursor.?);
}
test "a status row encodes collection names that would otherwise break the JSON" {
const t = std.testing;
var aw: Io.Writer.Allocating = .init(t.allocator);
defer aw.deinit();
try Backfiller.writeStatusRow(&aw.writer, .{ .collection = "app.bsky.feed.like\\", .source = "relay.waow.tech", .cursor = "did:plc:abc\"def", .imported = 7, .completed = false });
const parsed = try std.json.parseFromSlice(struct { collection: []const u8, source: []const u8, imported: i64, completed: bool, cursor: []const u8 }, t.allocator, aw.writer.buffered(), .{});
defer parsed.deinit();
try t.expectEqualStrings("app.bsky.feed.like\\", parsed.value.collection);
try t.expectEqualStrings("did:plc:abc\"def", parsed.value.cursor);
try t.expectEqual(@as(i64, 7), parsed.value.imported);
try t.expect(!parsed.value.completed);
aw.clearRetainingCapacity();
try Backfiller.writeStatusRow(&aw.writer, .{ .collection = "sh.tangled.repo", .source = "relay.waow.tech", .cursor = "did:plc:stale", .imported = 2, .completed = true });
try t.expectEqualStrings("{\"collection\":\"sh.tangled.repo\",\"source\":\"relay.waow.tech\",\"imported\":2,\"completed\":true}", aw.writer.buffered());
}