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
//! Durable per-PDS diagnostic aggregates.
//!
//! `host/<bucket>` is derived metadata, updated in the same RocksDB batch as
//! its source `repo/<did>` transition. The shape mirrors upstream Jetstream's
//! HostStatus contract: current lifecycle counts plus a bounded, cumulative
//! failure history that survives a later successful retry.
const std = @import("std");
const Allocator = std.mem.Allocator;
pub const max_error_samples = 5;
pub const max_error_bytes = 1024;
const encoding_version: u8 = 1;
pub const RepoStatus = enum(u8) {
not_started,
pending,
complete,
failed,
unavailable,
};
pub const ErrorClass = enum(u8) {
unknown,
http_429,
http_5xx,
timeout,
car,
// Kept only for backward decoding of Stream's v4 repo rows. New
// unclassified failures use `unknown`, matching upstream Jetstream.
transport,
local_write,
// Appended to preserve the durable v4 RepoState ordinals above.
did_resolution,
invalid_pds,
verification,
};
pub const ErrorSample = struct {
did: []const u8,
attempted_us: i64,
class: ErrorClass,
message: []const u8,
};
pub const Status = struct {
host: []const u8 = "",
total: u64 = 0,
active: u64 = 0,
by_status: [@typeInfo(RepoStatus).@"enum".field_names.len]u64 = @splat(0),
last_attempt_us: i64 = 0,
latest_error: []const u8 = "",
latest_error_class: ErrorClass = .unknown,
error_counts: [@typeInfo(ErrorClass).@"enum".field_names.len]u64 = @splat(0),
recent_errors: []ErrorSample = &.{},
pub fn count(self: Status, status: RepoStatus) u64 {
return self.by_status[@backingInt(status)];
}
pub fn deinit(self: *Status, allocator: Allocator) void {
if (self.host.len > 0) allocator.free(@constCast(self.host));
if (self.latest_error.len > 0) allocator.free(@constCast(self.latest_error));
for (self.recent_errors) |sample| {
if (sample.did.len > 0) allocator.free(@constCast(sample.did));
if (sample.message.len > 0) allocator.free(@constCast(sample.message));
}
if (self.recent_errors.len > 0) allocator.free(self.recent_errors);
self.* = .{};
}
};
pub fn normalizeAuthority(allocator: Allocator, raw: []const u8) ![]u8 {
const trimmed = std.mem.trim(u8, raw, " \t\r\n");
if (trimmed.len == 0) return "";
var normalized = try std.ascii.allocLowerString(allocator, trimmed);
if (std.mem.startsWith(u8, normalized, "[") and std.mem.endsWith(u8, normalized, "]:443")) {
const bare = try allocator.dupe(u8, normalized[1 .. normalized.len - 5]);
allocator.free(normalized);
return bare;
}
if (std.mem.endsWith(u8, normalized, ":443") and
std.mem.count(u8, normalized, ":") == 1)
{
normalized = try allocator.realloc(normalized, normalized.len - 4);
}
return normalized;
}
pub fn applyTransition(status: *Status, first_in_bucket: bool, old_active: bool, new_active: bool, old: RepoStatus, next: RepoStatus) void {
if (first_in_bucket) {
status.total += 1;
if (new_active) status.active += 1;
status.by_status[@backingInt(next)] += 1;
return;
}
if (old_active != new_active) {
if (new_active) status.active += 1 else status.active -|= 1;
}
if (old == next) return;
status.by_status[@backingInt(old)] -|= 1;
status.by_status[@backingInt(next)] += 1;
}
pub fn remove(status: *Status, active: bool, lifecycle: RepoStatus) void {
status.total -|= 1;
if (active) status.active -|= 1;
status.by_status[@backingInt(lifecycle)] -|= 1;
}
pub fn recordError(status: *Status, allocator: Allocator, did: []const u8, attempted_us: i64, class: ErrorClass, raw_message: []const u8) !void {
const message = raw_message[0..@min(raw_message.len, max_error_bytes)];
const next_latest = if (message.len > 0) try allocator.dupe(u8, message) else "";
errdefer if (next_latest.len > 0) allocator.free(@constCast(next_latest));
const next_did = if (did.len > 0) try allocator.dupe(u8, did) else "";
errdefer if (next_did.len > 0) allocator.free(@constCast(next_did));
const next_message = if (message.len > 0) try allocator.dupe(u8, message) else "";
errdefer if (next_message.len > 0) allocator.free(@constCast(next_message));
const retained = @min(status.recent_errors.len, max_error_samples - 1);
const next = try allocator.alloc(ErrorSample, retained + 1);
errdefer allocator.free(next);
if (status.latest_error.len > 0) allocator.free(@constCast(status.latest_error));
status.latest_error = next_latest;
status.latest_error_class = class;
status.error_counts[@backingInt(class)] += 1;
next[0] = .{
.did = next_did,
.attempted_us = attempted_us,
.class = class,
.message = next_message,
};
for (status.recent_errors[0..retained], 0..) |sample, i| next[i + 1] = sample;
for (status.recent_errors[retained..]) |sample| {
if (sample.did.len > 0) allocator.free(@constCast(sample.did));
if (sample.message.len > 0) allocator.free(@constCast(sample.message));
}
if (status.recent_errors.len > 0) allocator.free(status.recent_errors);
status.recent_errors = next;
}
pub fn encode(allocator: Allocator, status: Status) ![]u8 {
if (status.latest_error.len > std.math.maxInt(u16) or status.recent_errors.len > max_error_samples)
return error.InvalidHostStatus;
var len: usize = 1 + 8 + 8 + 8 * status.by_status.len + 8 + 1 + 8 * status.error_counts.len + 2 + 1 + status.latest_error.len;
for (status.recent_errors) |sample| {
if (sample.did.len > std.math.maxInt(u16) or sample.message.len > std.math.maxInt(u16))
return error.InvalidHostStatus;
len += 8 + 1 + 2 + 2 + sample.did.len + sample.message.len;
}
const out = try allocator.alloc(u8, len);
var at: usize = 0;
out[at] = encoding_version;
at += 1;
writeInt(u64, out, &at, status.total);
writeInt(u64, out, &at, status.active);
for (status.by_status) |value| writeInt(u64, out, &at, value);
writeInt(i64, out, &at, status.last_attempt_us);
out[at] = @backingInt(status.latest_error_class);
at += 1;
for (status.error_counts) |value| writeInt(u64, out, &at, value);
writeInt(u16, out, &at, @intCast(status.latest_error.len));
out[at] = @intCast(status.recent_errors.len);
at += 1;
@memcpy(out[at..][0..status.latest_error.len], status.latest_error);
at += status.latest_error.len;
for (status.recent_errors) |sample| {
writeInt(i64, out, &at, sample.attempted_us);
out[at] = @backingInt(sample.class);
at += 1;
writeInt(u16, out, &at, @intCast(sample.did.len));
writeInt(u16, out, &at, @intCast(sample.message.len));
@memcpy(out[at..][0..sample.did.len], sample.did);
at += sample.did.len;
@memcpy(out[at..][0..sample.message.len], sample.message);
at += sample.message.len;
}
std.debug.assert(at == out.len);
return out;
}
pub fn decode(allocator: Allocator, host: []const u8, bytes: []const u8) !Status {
var at: usize = 0;
if (bytes.len < 1 or bytes[at] != encoding_version) return error.InvalidHostStatus;
at += 1;
var out: Status = .{ .host = if (host.len > 0) try allocator.dupe(u8, host) else "" };
errdefer out.deinit(allocator);
out.total = try readInt(u64, bytes, &at);
out.active = try readInt(u64, bytes, &at);
for (&out.by_status) |*value| value.* = try readInt(u64, bytes, &at);
out.last_attempt_us = try readInt(i64, bytes, &at);
if (at >= bytes.len or bytes[at] >= @typeInfo(ErrorClass).@"enum".field_names.len) return error.InvalidHostStatus;
out.latest_error_class = @fromBackingInt(@intCast(bytes[at]));
at += 1;
for (&out.error_counts) |*value| value.* = try readInt(u64, bytes, &at);
const latest_len = try readInt(u16, bytes, &at);
if (at >= bytes.len) return error.InvalidHostStatus;
const sample_count = bytes[at];
at += 1;
if (sample_count > max_error_samples or latest_len > bytes.len - at) return error.InvalidHostStatus;
if (latest_len > 0) out.latest_error = try allocator.dupe(u8, bytes[at..][0..latest_len]);
at += latest_len;
if (sample_count > 0) out.recent_errors = try allocator.alloc(ErrorSample, sample_count);
var initialized: usize = 0;
errdefer {
for (out.recent_errors[0..initialized]) |sample| {
if (sample.did.len > 0) allocator.free(@constCast(sample.did));
if (sample.message.len > 0) allocator.free(@constCast(sample.message));
}
if (out.recent_errors.len > 0) {
allocator.free(out.recent_errors);
out.recent_errors = &.{};
}
}
while (initialized < sample_count) : (initialized += 1) {
const attempted_us = try readInt(i64, bytes, &at);
if (at >= bytes.len or bytes[at] >= @typeInfo(ErrorClass).@"enum".field_names.len) return error.InvalidHostStatus;
const class: ErrorClass = @fromBackingInt(@intCast(bytes[at]));
at += 1;
const did_len = try readInt(u16, bytes, &at);
const message_len = try readInt(u16, bytes, &at);
if (@as(usize, did_len) + @as(usize, message_len) > bytes.len - at) return error.InvalidHostStatus;
const did = if (did_len > 0) try allocator.dupe(u8, bytes[at..][0..did_len]) else "";
at += did_len;
errdefer if (did.len > 0) allocator.free(@constCast(did));
const message = if (message_len > 0) try allocator.dupe(u8, bytes[at..][0..message_len]) else "";
at += message_len;
out.recent_errors[initialized] = .{ .did = did, .attempted_us = attempted_us, .class = class, .message = message };
}
if (at != bytes.len) return error.InvalidHostStatus;
return out;
}
fn writeInt(comptime T: type, out: []u8, at: *usize, value: T) void {
std.mem.writeInt(T, out[at.*..][0..@sizeOf(T)], value, .little);
at.* += @sizeOf(T);
}
fn readInt(comptime T: type, bytes: []const u8, at: *usize) !T {
if (bytes.len -| at.* < @sizeOf(T)) return error.InvalidHostStatus;
const value = std.mem.readInt(T, bytes[at.*..][0..@sizeOf(T)], .little);
at.* += @sizeOf(T);
return value;
}
test "host status round trips bounded cumulative diagnostics" {
const testing = std.testing;
var status: Status = .{ .host = try testing.allocator.dupe(u8, "pds.example") };
defer status.deinit(testing.allocator);
applyTransition(&status, true, false, true, .not_started, .failed);
for (0..7) |i| {
var message: [1100]u8 = @splat('x');
message[0] = @intCast('0' + i);
try recordError(&status, testing.allocator, "did:plc:test", @intCast(i), .http_5xx, &message);
}
const bytes = try encode(testing.allocator, status);
defer testing.allocator.free(bytes);
var decoded = try decode(testing.allocator, "pds.example", bytes);
defer decoded.deinit(testing.allocator);
try testing.expectEqual(@as(u64, 1), decoded.total);
try testing.expectEqual(@as(u64, 1), decoded.active);
try testing.expectEqual(@as(u64, 1), decoded.count(.failed));
try testing.expectEqual(@as(u64, 7), decoded.error_counts[@backingInt(ErrorClass.http_5xx)]);
try testing.expectEqual(@as(usize, 5), decoded.recent_errors.len);
try testing.expectEqual(@as(i64, 6), decoded.recent_errors[0].attempted_us);
try testing.expectEqual(@as(i64, 2), decoded.recent_errors[4].attempted_us);
try testing.expectEqual(@as(usize, max_error_bytes), decoded.latest_error.len);
}
test "authority normalization matches upstream host buckets" {
const testing = std.testing;
for ([_]struct { raw: []const u8, want: []const u8 }{
.{ .raw = " PDS.EXAMPLE:443 ", .want = "pds.example" },
.{ .raw = "pds.example:8443", .want = "pds.example:8443" },
.{ .raw = "[2001:DB8::1]:443", .want = "2001:db8::1" },
.{ .raw = "[2001:DB8::1]:8443", .want = "[2001:db8::1]:8443" },
}) |case| {
const got = try normalizeAuthority(testing.allocator, case.raw);
defer if (got.len > 0) testing.allocator.free(got);
try testing.expectEqualStrings(case.want, got);
}
}