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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
//! Per-repository backfill state in the shared metadata database.
//!
//! `repo/<did>` is the point-read keyspace used by bootstrap and merge.
//! Aggregate status counts live at `backfill/counts`; a status transition
//! updates the row and counts in one synced RocksDB batch.
const std = @import("std");
const rocksdb = @import("rocksdb");
const host_store = @import("host_store.zig");
const meta_store = @import("../../storage/meta_store.zig");
const Io = std.Io;
const Allocator = std.mem.Allocator;
const repo_prefix = "repo/";
const counts_key = "backfill/counts";
const host_prefix = "host/";
const handle_prefix = "handle/";
const hosts_version_key = "backfill/host-status-version";
const hosts_version: u8 = 1;
const handles_version_key = "backfill/handle-index-version";
const handles_version: u8 = 1;
const encoding_version: u8 = 5;
const header_len = 84;
const v4_header_len = 52;
const legacy_header_len = 14;
pub const Status = host_store.RepoStatus;
pub const ErrorClass = host_store.ErrorClass;
pub const HostStatus = host_store.Status;
pub const HostErrorSample = host_store.ErrorSample;
pub fn classifyAttemptError(err: anyerror) ErrorClass {
return switch (err) {
error.AttemptTimeout, error.TransferTooSlow => .timeout,
error.MissingBlock, error.IncompleteCar, error.InvalidCar, error.InvalidCommit, error.InvalidCommitRev, error.EmptyCar => .car,
error.SignatureVerificationFailed => .verification,
error.ArchiveAppendFailed => .local_write,
else => .unknown,
};
}
/// Convert a resolved PDS service endpoint to upstream's durable host bucket.
/// Malformed or non-HTTP endpoints are retained in the explicit invalid-pds
/// bucket so selected-backfill diagnostics never silently lose the account.
pub fn hostFromPDS(allocator: Allocator, endpoint: []const u8) ![]u8 {
const uri = std.Uri.parse(std.mem.trim(u8, endpoint, " \t\r\n")) catch
return allocator.dupe(u8, "invalid-pds");
if (!std.ascii.eqlIgnoreCase(uri.scheme, "http") and !std.ascii.eqlIgnoreCase(uri.scheme, "https"))
return allocator.dupe(u8, "invalid-pds");
var host_buf: [std.Io.net.HostName.max_len]u8 = undefined;
const host_component = uri.host orelse return allocator.dupe(u8, "invalid-pds");
const host = host_component.toRaw(&host_buf) catch return allocator.dupe(u8, "invalid-pds");
if (host.len == 0) return allocator.dupe(u8, "invalid-pds");
const bare_host = if (host.len >= 2 and host[0] == '[' and host[host.len - 1] == ']')
host[1 .. host.len - 1]
else
host;
const default_port: ?u16 = if (std.ascii.eqlIgnoreCase(uri.scheme, "https")) 443 else 80;
const raw = if (uri.port != null and uri.port != default_port)
if (std.mem.indexOfScalar(u8, bare_host, ':') != null)
try std.fmt.allocPrint(allocator, "[{s}]:{d}", .{ bare_host, uri.port.? })
else
try std.fmt.allocPrint(allocator, "{s}:{d}", .{ bare_host, uri.port.? })
else
try allocator.dupe(u8, bare_host);
defer allocator.free(raw);
return host_store.normalizeAuthority(allocator, raw);
}
pub const RepoState = struct {
status: Status,
active: bool = true,
/// Owned by the caller when returned from `get`; literals passed to put
/// remain caller-owned.
rev: []const u8 = "",
/// Latest known repo revision. This equals `rev` at initial backfill and
/// advances independently as captured live events are merged.
latest_rev: []const u8 = "",
host: []const u8 = "",
handle: []const u8 = "",
pds: []const u8 = "",
last_error: []const u8 = "",
error_class: ErrorClass = .unknown,
attempts: u32 = 0,
last_attempt_us: i64 = 0,
started_us: i64 = 0,
completed_us: i64 = 0,
retry_count: u32 = 0,
next_attempt_us: i64 = 0,
updated_us: i64 = 0,
record_count: i64 = 0,
total_bytes: i64 = 0,
};
pub const Transition = struct { did: []const u8, state: RepoState };
pub const RevUpdate = struct { did: []const u8, rev: []const u8 };
pub const Store = struct {
allocator: Allocator,
io: Io,
meta: *meta_store.Store,
mu: Io.Mutex = .init,
pub fn init(allocator: Allocator, io: Io, meta: *meta_store.Store) !Store {
var self: Store = .{ .allocator = allocator, .io = io, .meta = meta };
if (try meta.getAlloc(allocator, counts_key)) |bytes| {
allocator.free(bytes);
} else {
try self.rebuildCounts();
}
try self.ensureHostStatuses();
try self.ensureHandleIndex();
// A durable not_started row means the previous process died after
// dispatch and before completion. Defer it to the merge pending pass;
// never re-download it into the low bootstrap sequence range.
const interrupted = try self.collectByStatus(allocator, .not_started);
defer self.freeDids(allocator, interrupted);
if (interrupted.len > 0) {
const transitions = try allocator.alloc(Transition, interrupted.len);
defer allocator.free(transitions);
var n: usize = 0;
for (interrupted) |did| {
const state = (try self.get(allocator, did)).?;
defer self.freeState(allocator, state);
// Inactive repos are deliberately discovered as not_started
// but never dispatched. Only active not_started rows can be
// crash-interrupted downloads that need merge-time repair.
if (!state.active) continue;
transitions[n] = .{ .did = did, .state = .{
.status = .pending,
.active = true,
.rev = state.rev,
.latest_rev = state.latest_rev,
.host = state.host,
.handle = state.handle,
.pds = state.pds,
.last_error = state.last_error,
.error_class = state.error_class,
.attempts = state.attempts,
.last_attempt_us = state.last_attempt_us,
.started_us = state.started_us,
.completed_us = state.completed_us,
.retry_count = state.retry_count,
.next_attempt_us = state.next_attempt_us,
.updated_us = state.updated_us,
.record_count = state.record_count,
.total_bytes = state.total_bytes,
} };
n += 1;
}
try self.putMany(transitions[0..n]);
}
return self;
}
pub fn deinit(_: *Store) void {}
pub fn get(self: *Store, allocator: Allocator, did: []const u8) !?RepoState {
const key = try repoKey(self.allocator, did);
defer self.allocator.free(key);
const bytes = try self.meta.getAlloc(allocator, key) orelse return null;
errdefer allocator.free(bytes);
const state = try decode(bytes);
const rev = if (state.rev.len > 0) try allocator.dupe(u8, state.rev) else "";
errdefer if (rev.len > 0) allocator.free(@constCast(rev));
const latest_rev = if (state.latest_rev.len > 0) try allocator.dupe(u8, state.latest_rev) else "";
errdefer if (latest_rev.len > 0) allocator.free(@constCast(latest_rev));
const host = if (state.host.len > 0) try allocator.dupe(u8, state.host) else "";
errdefer if (host.len > 0) allocator.free(@constCast(host));
const handle = if (state.handle.len > 0) try allocator.dupe(u8, state.handle) else "";
errdefer if (handle.len > 0) allocator.free(@constCast(handle));
const pds = if (state.pds.len > 0) try allocator.dupe(u8, state.pds) else "";
errdefer if (pds.len > 0) allocator.free(@constCast(pds));
const last_error = if (state.last_error.len > 0) try allocator.dupe(u8, state.last_error) else "";
allocator.free(bytes);
return .{
.status = state.status,
.active = state.active,
.rev = rev,
.latest_rev = latest_rev,
.host = host,
.handle = handle,
.pds = pds,
.last_error = last_error,
.error_class = state.error_class,
.attempts = state.attempts,
.last_attempt_us = state.last_attempt_us,
.started_us = state.started_us,
.completed_us = state.completed_us,
.retry_count = state.retry_count,
.next_attempt_us = state.next_attempt_us,
.updated_us = state.updated_us,
.record_count = state.record_count,
.total_bytes = state.total_bytes,
};
}
pub fn freeState(_: *Store, allocator: Allocator, state: RepoState) void {
if (state.rev.len > 0) allocator.free(@constCast(state.rev));
if (state.latest_rev.len > 0) allocator.free(@constCast(state.latest_rev));
if (state.host.len > 0) allocator.free(@constCast(state.host));
if (state.handle.len > 0) allocator.free(@constCast(state.handle));
if (state.pds.len > 0) allocator.free(@constCast(state.pds));
if (state.last_error.len > 0) allocator.free(@constCast(state.last_error));
}
/// A repository row and its aggregate count transition commit together.
pub fn put(self: *Store, did: []const u8, state: RepoState) !void {
try self.putMany(&.{.{ .did = did, .state = state }});
}
/// Commit multiple repository transitions and aggregate counts in one
/// synced batch. Used by the archive durable-batch boundary.
pub fn putMany(self: *Store, transitions: []const Transition) !void {
if (transitions.len == 0) return;
self.mu.lockUncancelable(self.io);
defer self.mu.unlock(self.io);
var counts = try self.loadCounts();
var writes = self.meta.batch();
defer writes.deinit();
var hosts = std.StringHashMap(HostStatus).init(self.allocator);
defer {
var values = hosts.valueIterator();
while (values.next()) |status| status.deinit(self.allocator);
hosts.deinit();
}
for (transitions) |transition| {
const row_key = try repoKey(self.allocator, transition.did);
defer self.allocator.free(row_key);
const old_bytes = try self.meta.getAlloc(self.allocator, row_key);
defer if (old_bytes) |b| self.allocator.free(b);
var had_old = false;
var old: RepoState = .{ .status = .not_started };
if (old_bytes) |bytes| {
old = try decode(bytes);
had_old = true;
if (counts[@backingInt(old.status)] > 0) counts[@backingInt(old.status)] -= 1;
}
counts[@backingInt(transition.state.status)] += 1;
const old_host = if (had_old) try host_store.normalizeAuthority(self.allocator, old.host) else "";
defer if (old_host.len > 0) self.allocator.free(old_host);
const new_host = try host_store.normalizeAuthority(self.allocator, transition.state.host);
defer if (new_host.len > 0) self.allocator.free(new_host);
if (old_host.len > 0 and !std.mem.eql(u8, old_host, new_host)) {
const old_status = try self.cachedHost(&hosts, old_host);
host_store.remove(old_status, old.active, old.status);
}
if (new_host.len > 0) {
const diagnostic = try self.cachedHost(&hosts, new_host);
const first = !had_old or !std.mem.eql(u8, old_host, new_host);
host_store.applyTransition(
diagnostic,
first,
if (had_old) old.active else false,
transition.state.active,
if (had_old) old.status else transition.state.status,
transition.state.status,
);
if (transition.state.last_attempt_us != 0)
diagnostic.last_attempt_us = transition.state.last_attempt_us;
const new_failure = transition.state.status == .failed and transition.state.last_error.len > 0 and
(!had_old or old.last_attempt_us != transition.state.last_attempt_us or old.attempts != transition.state.attempts or
!std.mem.eql(u8, old.last_error, transition.state.last_error));
if (new_failure)
try host_store.recordError(diagnostic, self.allocator, transition.did, transition.state.last_attempt_us, transition.state.error_class, transition.state.last_error);
}
if (!had_old or !handlesEqual(old.handle, transition.state.handle)) {
if (had_old) try self.stageHandleDeleteIfMatches(&writes, old.handle, transition.did);
try stageHandleSet(self.allocator, &writes, transition.state.handle, transition.did);
}
var canonical = transition.state;
canonical.host = new_host;
const value = try encode(self.allocator, canonical);
defer self.allocator.free(value);
writes.put(row_key, value);
}
var counts_bytes: [@sizeOf(Counts)]u8 = undefined;
encodeCounts(&counts_bytes, counts);
writes.put(counts_key, &counts_bytes);
var host_values = hosts.valueIterator();
while (host_values.next()) |status| {
const key = try hostKey(self.allocator, status.host);
defer self.allocator.free(key);
const value = try host_store.encode(self.allocator, status.*);
defer self.allocator.free(value);
writes.put(key, value);
}
try writes.commitDurable();
}
/// Bounded by PDS hosts, not network accounts. Returned rows own all
/// strings and must be released with `freeHostStatuses`.
pub fn listHostStatuses(self: *Store, allocator: Allocator) ![]HostStatus {
var out: std.ArrayList(HostStatus) = .empty;
errdefer {
for (out.items) |*status| status.deinit(allocator);
out.deinit(allocator);
}
var err_data: ?rocksdb.Data = null;
defer if (err_data) |e| e.deinit();
var it = self.meta.iterator(host_prefix);
defer it.deinit();
while (try it.next(&err_data)) |entry| {
const key = entry[0].data;
if (!std.mem.startsWith(u8, key, host_prefix)) break;
try out.append(allocator, try host_store.decode(allocator, key[host_prefix.len..], entry[1].data));
}
return out.toOwnedSlice(allocator);
}
pub fn freeHostStatuses(_: *Store, allocator: Allocator, statuses: []HostStatus) void {
for (statuses) |*status| status.deinit(allocator);
allocator.free(statuses);
}
/// Lookup through the durable declared-handle index. Like upstream, this
/// operator convenience is normalized but is not bidirectionally verified.
pub fn lookupDIDByHandle(self: *Store, allocator: Allocator, handle: []const u8) !?[]u8 {
const key = try handleKey(self.allocator, handle) orelse return null;
defer self.allocator.free(key);
return self.meta.getAlloc(allocator, key);
}
/// Upstream's per-source merge commit: advance the source cursor and
/// refresh only top-level latest revision/time in one synced metadata
/// batch. Backfill `rev` and every lifecycle/identity field are preserved.
pub fn commitMergeSource(self: *Store, cursor_key: []const u8, next_idx: u64, updates: []const RevUpdate, updated_us: i64) !void {
self.mu.lockUncancelable(self.io);
defer self.mu.unlock(self.io);
var writes = self.meta.batch();
defer writes.deinit();
var cursor_bytes: [9]u8 = undefined;
cursor_bytes[0] = 1;
std.mem.writeInt(u64, cursor_bytes[1..9], next_idx, .little);
writes.put(cursor_key, &cursor_bytes);
for (updates) |update| {
const key = try repoKey(self.allocator, update.did);
defer self.allocator.free(key);
const bytes = try self.meta.getAlloc(self.allocator, key) orelse continue;
defer self.allocator.free(bytes);
var state = try decode(bytes);
state.latest_rev = update.rev;
state.updated_us = updated_us;
const encoded = try encode(self.allocator, state);
defer self.allocator.free(encoded);
writes.put(key, encoded);
}
try writes.commitDurable();
}
/// Compatibility with the former buffered store. Writes are already
/// synchronously durable, so there is nothing left to flush.
pub fn flush(_: *Store) !void {}
pub fn count(self: *Store) u32 {
const counts = self.loadCounts() catch return 0;
var total: u64 = 0;
for (counts) |n| total += n;
return @intCast(@min(total, std.math.maxInt(u32)));
}
pub fn collectByStatus(self: *Store, allocator: Allocator, status: Status) ![][]const u8 {
var out: std.ArrayList([]const u8) = .empty;
errdefer {
for (out.items) |did| allocator.free(did);
out.deinit(allocator);
}
var err_data: ?rocksdb.Data = null;
defer if (err_data) |e| e.deinit();
var it = self.meta.iterator(repo_prefix);
defer it.deinit();
while (try it.next(&err_data)) |entry| {
const key = entry[0].data;
if (!std.mem.startsWith(u8, key, repo_prefix)) break;
if ((try decode(entry[1].data)).status == status)
try out.append(allocator, try allocator.dupe(u8, key[repo_prefix.len..]));
}
return out.toOwnedSlice(allocator);
}
/// Stream repositories with `status` without materializing the set.
/// Upstream's retry scan yields one candidate at a time straight off the
/// store iterator; collecting every failed DID first is a whole-network
/// memory hazard. `did` and `state` borrow the iterator's buffers and are
/// only valid for the duration of the call.
pub fn streamByStatus(
self: *Store,
status: Status,
ctx: anytype,
comptime yield: fn (@TypeOf(ctx), []const u8, RepoState) anyerror!void,
) !void {
var err_data: ?rocksdb.Data = null;
defer if (err_data) |e| e.deinit();
var it = self.meta.iterator(repo_prefix);
defer it.deinit();
while (try it.next(&err_data)) |entry| {
const key = entry[0].data;
if (!std.mem.startsWith(u8, key, repo_prefix)) break;
const state = try decode(entry[1].data);
if (state.status != status) continue;
try yield(ctx, key[repo_prefix.len..], state);
}
}
pub fn freeDids(_: *Store, allocator: Allocator, dids: []const []const u8) void {
for (dids) |did| allocator.free(did);
allocator.free(dids);
}
pub fn countByStatus(self: *Store, status: Status) u32 {
const counts = self.loadCounts() catch return 0;
return @intCast(@min(counts[@backingInt(status)], std.math.maxInt(u32)));
}
fn rebuildCounts(self: *Store) !void {
var counts: Counts = @splat(0);
var err_data: ?rocksdb.Data = null;
defer if (err_data) |e| e.deinit();
var it = self.meta.iterator(repo_prefix);
defer it.deinit();
while (try it.next(&err_data)) |entry| {
if (!std.mem.startsWith(u8, entry[0].data, repo_prefix)) break;
const state = try decode(entry[1].data);
counts[@backingInt(state.status)] += 1;
}
var bytes: [@sizeOf(Counts)]u8 = undefined;
encodeCounts(&bytes, counts);
try self.meta.putDurable(counts_key, &bytes);
}
fn ensureHostStatuses(self: *Store) !void {
if (try self.meta.getAlloc(self.allocator, hosts_version_key)) |version| {
defer self.allocator.free(version);
if (version.len == 1 and version[0] == hosts_version) return;
return error.UnsupportedHostStatusVersion;
}
var hosts = std.StringHashMap(HostStatus).init(self.allocator);
defer {
var values = hosts.valueIterator();
while (values.next()) |status| status.deinit(self.allocator);
hosts.deinit();
}
var err_data: ?rocksdb.Data = null;
defer if (err_data) |e| e.deinit();
var it = self.meta.iterator(repo_prefix);
defer it.deinit();
while (try it.next(&err_data)) |entry| {
if (!std.mem.startsWith(u8, entry[0].data, repo_prefix)) break;
const state = try decode(entry[1].data);
const host = try host_store.normalizeAuthority(self.allocator, state.host);
defer if (host.len > 0) self.allocator.free(host);
if (host.len == 0) continue;
const status = try self.cachedHost(&hosts, host);
host_store.applyTransition(status, true, false, state.active, state.status, state.status);
if (state.last_attempt_us != 0) status.last_attempt_us = @max(status.last_attempt_us, state.last_attempt_us);
if (state.status == .failed and state.last_error.len > 0)
try host_store.recordError(status, self.allocator, entry[0].data[repo_prefix.len..], state.last_attempt_us, state.error_class, state.last_error);
}
var writes = self.meta.batch();
defer writes.deinit();
var values = hosts.valueIterator();
while (values.next()) |status| {
const key = try hostKey(self.allocator, status.host);
defer self.allocator.free(key);
const value = try host_store.encode(self.allocator, status.*);
defer self.allocator.free(value);
writes.put(key, value);
}
writes.put(hosts_version_key, &.{hosts_version});
try writes.commitDurable();
}
fn ensureHandleIndex(self: *Store) !void {
if (try self.meta.getAlloc(self.allocator, handles_version_key)) |version| {
defer self.allocator.free(version);
if (version.len == 1 and version[0] == handles_version) return;
return error.UnsupportedHandleIndexVersion;
}
var writes = self.meta.batch();
defer writes.deinit();
var err_data: ?rocksdb.Data = null;
defer if (err_data) |e| e.deinit();
var it = self.meta.iterator(repo_prefix);
defer it.deinit();
while (try it.next(&err_data)) |entry| {
if (!std.mem.startsWith(u8, entry[0].data, repo_prefix)) break;
const state = try decode(entry[1].data);
try stageHandleSet(self.allocator, &writes, state.handle, entry[0].data[repo_prefix.len..]);
}
writes.put(handles_version_key, &.{handles_version});
try writes.commitDurable();
}
fn stageHandleDeleteIfMatches(self: *Store, writes: *meta_store.Batch, handle: []const u8, did: []const u8) !void {
const key = try handleKey(self.allocator, handle) orelse return;
defer self.allocator.free(key);
const indexed = try self.meta.getAlloc(self.allocator, key) orelse return;
defer self.allocator.free(indexed);
if (std.mem.eql(u8, indexed, did)) writes.delete(key);
}
fn cachedHost(self: *Store, cache: *std.StringHashMap(HostStatus), normalized_host: []const u8) !*HostStatus {
if (cache.getPtr(normalized_host)) |status| return status;
const key = try hostKey(self.allocator, normalized_host);
defer self.allocator.free(key);
const bytes = try self.meta.getAlloc(self.allocator, key);
defer if (bytes) |value| self.allocator.free(value);
var status = if (bytes) |value|
try host_store.decode(self.allocator, normalized_host, value)
else
HostStatus{ .host = try self.allocator.dupe(u8, normalized_host) };
errdefer status.deinit(self.allocator);
const result = try cache.getOrPut(status.host);
std.debug.assert(!result.found_existing);
result.value_ptr.* = status;
return result.value_ptr;
}
fn loadCounts(self: *Store) !Counts {
const bytes = try self.meta.getAlloc(self.allocator, counts_key) orelse return error.MissingCounts;
defer self.allocator.free(bytes);
if (bytes.len != @sizeOf(Counts)) return error.InvalidCounts;
var counts: Counts = undefined;
for (&counts, 0..) |*n, i| n.* = std.mem.readInt(u64, bytes[i * 8 ..][0..8], .little);
return counts;
}
};
const Counts = [@typeInfo(Status).@"enum".field_names.len]u64;
fn encodeCounts(out: *[@sizeOf(Counts)]u8, counts: Counts) void {
for (counts, 0..) |n, i| std.mem.writeInt(u64, out[i * 8 ..][0..8], n, .little);
}
fn repoKey(allocator: Allocator, did: []const u8) ![]u8 {
return std.mem.concat(allocator, u8, &.{ repo_prefix, did });
}
fn hostKey(allocator: Allocator, host: []const u8) ![]u8 {
return std.mem.concat(allocator, u8, &.{ host_prefix, host });
}
fn handleKey(allocator: Allocator, handle: []const u8) !?[]u8 {
const normalized = std.mem.trim(u8, handle, " \t\r\n");
if (normalized.len == 0) return null;
const out = try allocator.alloc(u8, handle_prefix.len + normalized.len);
@memcpy(out[0..handle_prefix.len], handle_prefix);
for (normalized, out[handle_prefix.len..]) |byte, *dst| dst.* = std.ascii.toLower(byte);
return out;
}
fn handlesEqual(a: []const u8, b: []const u8) bool {
return std.ascii.eqlIgnoreCase(std.mem.trim(u8, a, " \t\r\n"), std.mem.trim(u8, b, " \t\r\n"));
}
fn stageHandleSet(allocator: Allocator, writes: *meta_store.Batch, handle: []const u8, did: []const u8) !void {
const key = try handleKey(allocator, handle) orelse return;
defer allocator.free(key);
writes.put(key, did);
}
fn encode(allocator: Allocator, state: RepoState) ![]u8 {
if (state.host.len > std.math.maxInt(u16) or state.handle.len > std.math.maxInt(u16) or
state.pds.len > std.math.maxInt(u16) or state.last_error.len > std.math.maxInt(u16) or
state.rev.len > std.math.maxInt(u32) or state.latest_rev.len > std.math.maxInt(u32))
return error.RepoStateFieldTooLong;
const out = try allocator.alloc(u8, header_len + state.rev.len + state.latest_rev.len + state.host.len + state.handle.len + state.pds.len + state.last_error.len);
out[0] = encoding_version;
out[1] = @backingInt(state.status);
out[2] = @intFromBool(state.active);
std.mem.writeInt(u32, out[3..7], state.retry_count, .little);
std.mem.writeInt(i64, out[7..15], state.next_attempt_us, .little);
std.mem.writeInt(u32, out[15..19], state.attempts, .little);
std.mem.writeInt(i64, out[19..27], state.last_attempt_us, .little);
std.mem.writeInt(i64, out[27..35], state.started_us, .little);
std.mem.writeInt(i64, out[35..43], state.completed_us, .little);
std.mem.writeInt(i64, out[43..51], state.updated_us, .little);
std.mem.writeInt(i64, out[51..59], state.record_count, .little);
std.mem.writeInt(i64, out[59..67], state.total_bytes, .little);
std.mem.writeInt(u32, out[67..71], @intCast(state.rev.len), .little);
std.mem.writeInt(u32, out[71..75], @intCast(state.latest_rev.len), .little);
std.mem.writeInt(u16, out[75..77], @intCast(state.host.len), .little);
std.mem.writeInt(u16, out[77..79], @intCast(state.handle.len), .little);
std.mem.writeInt(u16, out[79..81], @intCast(state.pds.len), .little);
std.mem.writeInt(u16, out[81..83], @intCast(state.last_error.len), .little);
out[83] = @backingInt(state.error_class);
var offset: usize = header_len;
@memcpy(out[offset..][0..state.rev.len], state.rev);
offset += state.rev.len;
@memcpy(out[offset..][0..state.latest_rev.len], state.latest_rev);
offset += state.latest_rev.len;
@memcpy(out[offset..][0..state.host.len], state.host);
offset += state.host.len;
@memcpy(out[offset..][0..state.handle.len], state.handle);
offset += state.handle.len;
@memcpy(out[offset..][0..state.pds.len], state.pds);
offset += state.pds.len;
@memcpy(out[offset..][0..state.last_error.len], state.last_error);
return out;
}
fn decode(bytes: []const u8) !RepoState {
if (bytes.len >= legacy_header_len and bytes[0] == 2) {
if (bytes[1] >= @typeInfo(Status).@"enum".field_names.len) return error.InvalidRepoState;
return .{
.status = @fromBackingInt(@intCast(bytes[1])),
.active = true,
.retry_count = std.mem.readInt(u32, bytes[2..6], .little),
.next_attempt_us = std.mem.readInt(i64, bytes[6..14], .little),
.rev = bytes[legacy_header_len..],
.latest_rev = bytes[legacy_header_len..],
};
}
if (bytes.len >= 15 and bytes[0] == 3) {
if (bytes[1] >= @typeInfo(Status).@"enum".field_names.len) return error.InvalidRepoState;
return .{
.status = @fromBackingInt(@intCast(bytes[1])),
.active = bytes[2] != 0,
.retry_count = std.mem.readInt(u32, bytes[3..7], .little),
.next_attempt_us = std.mem.readInt(i64, bytes[7..15], .little),
.rev = bytes[15..],
.latest_rev = bytes[15..],
};
}
if (bytes.len >= v4_header_len and bytes[0] == 4) {
if (bytes[1] >= @typeInfo(Status).@"enum".field_names.len) return error.InvalidRepoState;
if (bytes[51] >= @typeInfo(ErrorClass).@"enum".field_names.len) return error.InvalidRepoState;
const rev_len = std.mem.readInt(u32, bytes[43..47], .little);
const host_len = std.mem.readInt(u16, bytes[47..49], .little);
const error_len = std.mem.readInt(u16, bytes[49..51], .little);
const total = v4_header_len + @as(usize, rev_len) + @as(usize, host_len) + @as(usize, error_len);
if (total != bytes.len) return error.InvalidRepoState;
const rev_end = v4_header_len + rev_len;
const host_end = rev_end + host_len;
return .{
.status = @fromBackingInt(@intCast(bytes[1])),
.active = bytes[2] != 0,
.rev = bytes[v4_header_len..rev_end],
.latest_rev = bytes[v4_header_len..rev_end],
.host = bytes[rev_end..host_end],
.last_error = bytes[host_end..total],
.error_class = @fromBackingInt(@intCast(bytes[51])),
.retry_count = std.mem.readInt(u32, bytes[3..7], .little),
.next_attempt_us = std.mem.readInt(i64, bytes[7..15], .little),
.attempts = std.mem.readInt(u32, bytes[15..19], .little),
.last_attempt_us = std.mem.readInt(i64, bytes[19..27], .little),
.started_us = std.mem.readInt(i64, bytes[27..35], .little),
.completed_us = std.mem.readInt(i64, bytes[35..43], .little),
};
}
if (bytes.len < header_len or bytes[0] != encoding_version) return error.InvalidRepoState;
if (bytes[1] >= @typeInfo(Status).@"enum".field_names.len) return error.InvalidRepoState;
if (bytes[83] >= @typeInfo(ErrorClass).@"enum".field_names.len) return error.InvalidRepoState;
const rev_len = std.mem.readInt(u32, bytes[67..71], .little);
const latest_rev_len = std.mem.readInt(u32, bytes[71..75], .little);
const host_len = std.mem.readInt(u16, bytes[75..77], .little);
const handle_len = std.mem.readInt(u16, bytes[77..79], .little);
const pds_len = std.mem.readInt(u16, bytes[79..81], .little);
const error_len = std.mem.readInt(u16, bytes[81..83], .little);
const total = header_len + @as(usize, rev_len) + @as(usize, latest_rev_len) + @as(usize, host_len) + @as(usize, handle_len) + @as(usize, pds_len) + @as(usize, error_len);
if (total != bytes.len) return error.InvalidRepoState;
const rev_end = header_len + rev_len;
const latest_rev_end = rev_end + latest_rev_len;
const host_end = latest_rev_end + host_len;
const handle_end = host_end + handle_len;
const pds_end = handle_end + pds_len;
return .{
.status = @fromBackingInt(@intCast(bytes[1])),
.active = bytes[2] != 0,
.rev = bytes[header_len..rev_end],
.latest_rev = bytes[rev_end..latest_rev_end],
.host = bytes[latest_rev_end..host_end],
.handle = bytes[host_end..handle_end],
.pds = bytes[handle_end..pds_end],
.last_error = bytes[pds_end..total],
.error_class = @fromBackingInt(@intCast(bytes[83])),
.retry_count = std.mem.readInt(u32, bytes[3..7], .little),
.next_attempt_us = std.mem.readInt(i64, bytes[7..15], .little),
.attempts = std.mem.readInt(u32, bytes[15..19], .little),
.last_attempt_us = std.mem.readInt(i64, bytes[19..27], .little),
.started_us = std.mem.readInt(i64, bytes[27..35], .little),
.completed_us = std.mem.readInt(i64, bytes[35..43], .little),
.updated_us = std.mem.readInt(i64, bytes[43..51], .little),
.record_count = std.mem.readInt(i64, bytes[51..59], .little),
.total_bytes = std.mem.readInt(i64, bytes[59..67], .little),
};
}
test "rows and counts are durable and atomically updated" {
const testing = std.testing;
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var path_buf: [std.fs.max_path_bytes]u8 = undefined;
const path_len = try tmp.dir.realPath(testing.io, &path_buf);
var meta = try meta_store.Store.open(testing.allocator, path_buf[0..path_len]);
defer meta.deinit();
var store = try Store.init(testing.allocator, testing.io, &meta);
defer store.deinit();
try store.put("did:plc:aaa", .{ .status = .not_started });
try store.put("did:plc:bbb", .{
.status = .complete,
.active = false,
.rev = "3lrev",
.latest_rev = "3llatest",
.host = "pds.example",
.handle = "Alice.Test",
.pds = "https://pds.example",
.last_error = "previous timeout",
.error_class = .timeout,
.attempts = 2,
.last_attempt_us = 17,
.updated_us = 18,
.record_count = 42,
.total_bytes = 1024,
});
try store.put("did:plc:aaa", .{ .status = .failed });
try testing.expectEqual(@as(u32, 2), store.count());
try testing.expectEqual(@as(u32, 1), store.countByStatus(.complete));
try testing.expectEqual(@as(u32, 1), store.countByStatus(.failed));
const bbb = (try store.get(testing.allocator, "did:plc:bbb")).?;
defer store.freeState(testing.allocator, bbb);
try testing.expectEqual(Status.complete, bbb.status);
try testing.expect(!bbb.active);
try testing.expectEqualStrings("3lrev", bbb.rev);
try testing.expectEqualStrings("3llatest", bbb.latest_rev);
try testing.expectEqualStrings("pds.example", bbb.host);
try testing.expectEqualStrings("Alice.Test", bbb.handle);
try testing.expectEqualStrings("https://pds.example", bbb.pds);
try testing.expectEqualStrings("previous timeout", bbb.last_error);
try testing.expectEqual(ErrorClass.timeout, bbb.error_class);
try testing.expectEqual(@as(u32, 2), bbb.attempts);
try testing.expectEqual(@as(i64, 17), bbb.last_attempt_us);
try testing.expectEqual(@as(i64, 18), bbb.updated_us);
try testing.expectEqual(@as(i64, 42), bbb.record_count);
try testing.expectEqual(@as(i64, 1024), bbb.total_bytes);
const indexed = (try store.lookupDIDByHandle(testing.allocator, " @ignored "));
try testing.expect(indexed == null);
const alice = (try store.lookupDIDByHandle(testing.allocator, " alice.TEST ")).?;
defer testing.allocator.free(alice);
try testing.expectEqualStrings("did:plc:bbb", alice);
const failed = try store.collectByStatus(testing.allocator, .failed);
defer store.freeDids(testing.allocator, failed);
try testing.expectEqual(@as(usize, 1), failed.len);
try testing.expectEqualStrings("did:plc:aaa", failed[0]);
try store.put("did:plc:interrupted", .{ .status = .not_started });
try store.put("did:plc:inactive", .{ .status = .not_started, .active = false });
var reopened = try Store.init(testing.allocator, testing.io, &meta);
defer reopened.deinit();
const interrupted = (try reopened.get(testing.allocator, "did:plc:interrupted")).?;
defer reopened.freeState(testing.allocator, interrupted);
try testing.expectEqual(Status.pending, interrupted.status);
const inactive = (try reopened.get(testing.allocator, "did:plc:inactive")).?;
defer reopened.freeState(testing.allocator, inactive);
try testing.expectEqual(Status.not_started, inactive.status);
try testing.expect(!inactive.active);
}
test "repo transitions atomically maintain durable upstream-shaped host diagnostics" {
const testing = std.testing;
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var path_buf: [std.fs.max_path_bytes]u8 = undefined;
const path_len = try tmp.dir.realPath(testing.io, &path_buf);
var meta = try meta_store.Store.open(testing.allocator, path_buf[0..path_len]);
defer meta.deinit();
var store = try Store.init(testing.allocator, testing.io, &meta);
defer store.deinit();
try store.put("did:plc:hosted", .{
.status = .failed,
.host = " PDS-A.EXAMPLE:443 ",
.last_error = "HTTP 503 first",
.error_class = .http_5xx,
.attempts = 1,
.last_attempt_us = 10,
});
try store.put("did:plc:hosted", .{
.status = .failed,
.host = "pds-a.example",
.last_error = "HTTP 503 second",
.error_class = .http_5xx,
.attempts = 2,
.last_attempt_us = 20,
});
try store.put("did:plc:hosted", .{
.status = .complete,
.active = false,
.host = "pds-a.example",
.attempts = 0,
.last_attempt_us = 30,
});
var hosts = try store.listHostStatuses(testing.allocator);
defer store.freeHostStatuses(testing.allocator, hosts);
try testing.expectEqual(@as(usize, 1), hosts.len);
try testing.expectEqualStrings("pds-a.example", hosts[0].host);
try testing.expectEqual(@as(u64, 1), hosts[0].total);
try testing.expectEqual(@as(u64, 0), hosts[0].active);
try testing.expectEqual(@as(u64, 1), hosts[0].count(.complete));
try testing.expectEqual(@as(u64, 0), hosts[0].count(.failed));
try testing.expectEqual(@as(u64, 2), hosts[0].error_counts[@backingInt(ErrorClass.http_5xx)]);
try testing.expectEqual(@as(usize, 2), hosts[0].recent_errors.len);
try testing.expectEqualStrings("HTTP 503 second", hosts[0].recent_errors[0].message);
try store.put("did:plc:hosted", .{
.status = .complete,
.active = false,
.host = "pds-b.example:8443",
.last_attempt_us = 40,
});
store.freeHostStatuses(testing.allocator, hosts);
hosts = try store.listHostStatuses(testing.allocator);
const a = for (hosts) |*host| {
if (std.mem.eql(u8, host.host, "pds-a.example")) break host;
} else return error.MissingOldHost;
const b = for (hosts) |*host| {
if (std.mem.eql(u8, host.host, "pds-b.example:8443")) break host;
} else return error.MissingNewHost;
try testing.expectEqual(@as(u64, 0), a.total);
try testing.expectEqual(@as(u64, 0), a.count(.complete));
try testing.expectEqual(@as(u64, 2), a.error_counts[@backingInt(ErrorClass.http_5xx)]);
try testing.expectEqual(@as(u64, 1), b.total);
try testing.expectEqual(@as(u64, 1), b.count(.complete));
// Simulate upgrading a pre-host-aggregate database. The migration rebuilds
// current counts from repo rows in one synced batch; historical samples
// cannot be invented and begin accumulating from this point forward.
try meta.deleteDurable(hosts_version_key);
try meta.deleteDurable("host/pds-a.example");
try meta.deleteDurable("host/pds-b.example:8443");
var migrated = try Store.init(testing.allocator, testing.io, &meta);
defer migrated.deinit();
const rebuilt = try migrated.listHostStatuses(testing.allocator);
defer migrated.freeHostStatuses(testing.allocator, rebuilt);
try testing.expectEqual(@as(usize, 1), rebuilt.len);
try testing.expectEqualStrings("pds-b.example:8443", rebuilt[0].host);
try testing.expectEqual(@as(u64, 1), rebuilt[0].total);
try testing.expectEqual(@as(u64, 1), rebuilt[0].count(.complete));
}
test "repo transitions atomically maintain the normalized declared-handle index" {
const testing = std.testing;
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var path_buf: [std.fs.max_path_bytes]u8 = undefined;
const path_len = try tmp.dir.realPath(testing.io, &path_buf);
var meta = try meta_store.Store.open(testing.allocator, path_buf[0..path_len]);
defer meta.deinit();
var store = try Store.init(testing.allocator, testing.io, &meta);
defer store.deinit();
try store.put("did:plc:alice", .{ .status = .complete, .handle = " Alice.Test " });
var did = (try store.lookupDIDByHandle(testing.allocator, "ALICE.test")).?;
try testing.expectEqualStrings("did:plc:alice", did);
testing.allocator.free(did);
// Moving a DID removes its old index only when that index still names it.
try store.put("did:plc:bob", .{ .status = .complete, .handle = "alice.test" });
try store.put("did:plc:alice", .{ .status = .complete, .handle = "alice.new" });
did = (try store.lookupDIDByHandle(testing.allocator, "alice.test")).?;
try testing.expectEqualStrings("did:plc:bob", did);
testing.allocator.free(did);
did = (try store.lookupDIDByHandle(testing.allocator, "alice.new")).?;
try testing.expectEqualStrings("did:plc:alice", did);
testing.allocator.free(did);
try store.put("did:plc:alice", .{ .status = .complete, .handle = "" });
try testing.expect(try store.lookupDIDByHandle(testing.allocator, "alice.new") == null);
// Rebuilding from repo/<did> rows is deterministic and survives restart.
try meta.deleteDurable(handles_version_key);
try meta.deleteDurable("handle/alice.test");
var rebuilt = try Store.init(testing.allocator, testing.io, &meta);
defer rebuilt.deinit();
did = (try rebuilt.lookupDIDByHandle(testing.allocator, "alice.test")).?;
defer testing.allocator.free(did);
try testing.expectEqualStrings("did:plc:bob", did);
}
test "merge source commit refreshes only latest repo state with its cursor" {
const testing = std.testing;
var tmp = testing.tmpDir(.{});
defer tmp.cleanup();
var path_buf: [std.fs.max_path_bytes]u8 = undefined;
const path_len = try tmp.dir.realPath(testing.io, &path_buf);
var meta = try meta_store.Store.open(testing.allocator, path_buf[0..path_len]);
defer meta.deinit();
var store = try Store.init(testing.allocator, testing.io, &meta);
defer store.deinit();
try store.put("did:plc:known", .{
.status = .complete,
.rev = "backfill-rev",
.latest_rev = "old-live-rev",
.handle = "known.test",
.pds = "https://pds.example",
.record_count = 9,
});
try store.commitMergeSource("merge/next_source_idx", 7, &.{
.{ .did = "did:plc:known", .rev = "new-live-rev" },
// Upstream deliberately does not synthesize malformed lifecycle rows
// for accounts absent from the bootstrap status map.
.{ .did = "did:plc:unknown", .rev = "ignored" },
}, 1234);
const cursor = (try meta.getAlloc(testing.allocator, "merge/next_source_idx")).?;
defer testing.allocator.free(cursor);
try testing.expectEqual(@as(usize, 9), cursor.len);
try testing.expectEqual(@as(u8, 1), cursor[0]);
try testing.expectEqual(@as(u64, 7), std.mem.readInt(u64, cursor[1..9], .little));
const known = (try store.get(testing.allocator, "did:plc:known")).?;
defer store.freeState(testing.allocator, known);
try testing.expectEqualStrings("backfill-rev", known.rev);
try testing.expectEqualStrings("new-live-rev", known.latest_rev);
try testing.expectEqual(@as(i64, 1234), known.updated_us);
try testing.expectEqualStrings("known.test", known.handle);
try testing.expectEqualStrings("https://pds.example", known.pds);
try testing.expectEqual(@as(i64, 9), known.record_count);
try testing.expect(try store.get(testing.allocator, "did:plc:unknown") == null);
}
test "v4 rows migrate latest revision without losing lifecycle state" {
const testing = std.testing;
var bytes: [v4_header_len + 3 + 4 + 5]u8 = @splat(0);
bytes[0] = 4;
bytes[1] = @backingInt(Status.complete);
bytes[2] = 1;
std.mem.writeInt(u32, bytes[43..47], 3, .little);
std.mem.writeInt(u16, bytes[47..49], 4, .little);
std.mem.writeInt(u16, bytes[49..51], 5, .little);
bytes[51] = @backingInt(ErrorClass.timeout);
@memcpy(bytes[52..55], "rev");
@memcpy(bytes[55..59], "host");
@memcpy(bytes[59..64], "error");
const state = try decode(&bytes);
try testing.expectEqualStrings("rev", state.rev);
try testing.expectEqualStrings("rev", state.latest_rev);
try testing.expectEqualStrings("host", state.host);
try testing.expectEqualStrings("error", state.last_error);
try testing.expectEqual(ErrorClass.timeout, state.error_class);
}
test "failure classes match upstream diagnostic buckets" {
const testing = std.testing;
try testing.expectEqual(ErrorClass.timeout, classifyAttemptError(error.TransferTooSlow));
try testing.expectEqual(ErrorClass.car, classifyAttemptError(error.InvalidCommit));
try testing.expectEqual(ErrorClass.verification, classifyAttemptError(error.SignatureVerificationFailed));
try testing.expectEqual(ErrorClass.local_write, classifyAttemptError(error.ArchiveAppendFailed));
try testing.expectEqual(ErrorClass.unknown, classifyAttemptError(error.ConnectionResetByPeer));
}
test "resolved PDS endpoints produce upstream host buckets" {
const testing = std.testing;
const default_https = try hostFromPDS(testing.allocator, "HTTPS://PDS.EXAMPLE:443");
defer testing.allocator.free(default_https);
try testing.expectEqualStrings("pds.example", default_https);
const custom = try hostFromPDS(testing.allocator, "http://PDS.EXAMPLE:8080/path");
defer testing.allocator.free(custom);
try testing.expectEqualStrings("pds.example:8080", custom);
const ipv6 = try hostFromPDS(testing.allocator, "https://[2001:DB8::1]:8443");
defer testing.allocator.free(ipv6);
try testing.expectEqualStrings("[2001:db8::1]:8443", ipv6);
const default_ipv6 = try hostFromPDS(testing.allocator, "https://[2001:DB8::1]:443");
defer testing.allocator.free(default_ipv6);
try testing.expectEqualStrings("2001:db8::1", default_ipv6);
const invalid = try hostFromPDS(testing.allocator, "javascript:wat");
defer testing.allocator.free(invalid);
try testing.expectEqualStrings("invalid-pds", invalid);
}