~ knotless Search/
↑↓ move↵ open⇧↵ all results

zat.dev/stream

jetstream v2 in zig · mirror of https://tangled.org/zat.dev/stream

0
0
283 lines · 12.0 KB Raw History
//! 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);
    }
}