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

zat.dev/zds

atproto pds · mirror of https://tangled.org/zat.dev/zds

0
0
560 lines · 19.2 KB Raw History
const std = @import("std");
const httpz = @import("httpz");
const router = @import("../http/router.zig");
const store = @import("../storage/store.zig");
const log = @import("../core/log.zig");
const request_context = @import("request_context.zig");

const Io = std.Io;
const Route = router.Route;

const SAMPLE_COUNT = 512;
const SLOW_COUNT = 32;
const LABEL_LEN = 192;
const ROUTE_COUNT = @typeInfo(Route).@"enum".field_names.len;
const METHOD_COUNT = @typeInfo(Method).@"enum".field_names.len;

pub const Method = enum {
    get,
    head,
    post,
    options,
    other,

    pub fn fromHttpz(method: httpz.Method) Method {
        return switch (method) {
            .GET => .get,
            .HEAD => .head,
            .POST => .post,
            .OPTIONS => .options,
            else => .other,
        };
    }

    pub fn label(method: Method) []const u8 {
        return switch (method) {
            .get => "GET",
            .head => "HEAD",
            .post => "POST",
            .options => "OPTIONS",
            .other => "OTHER",
        };
    }
};

pub const Class = enum {
    local,
    proxy,
    unknown,

    pub fn label(class: Class) []const u8 {
        return switch (class) {
            .local => "local",
            .proxy => "proxy",
            .unknown => "unknown",
        };
    }
};

/// What a request was for, as the stats page charts traffic.
pub const Kind = enum(u8) {
    reads,
    writes,
    sync,
    proxy,
    sign_in,

    pub fn label(kind: Kind) []const u8 {
        return switch (kind) {
            .reads => "reads",
            .writes => "writes",
            .sync => "sync & export",
            .proxy => "appview proxy",
            .sign_in => "sign-in",
        };
    }
};
pub const kind_count = @typeInfo(Kind).@"enum".field_names.len;

const write_paths = [_][]const u8{
    "/xrpc/com.atproto.repo.createRecord", "/xrpc/com.atproto.repo.putRecord",  "/xrpc/com.atproto.repo.deleteRecord",
    "/xrpc/com.atproto.repo.applyWrites",  "/xrpc/com.atproto.repo.uploadBlob", "/xrpc/com.atproto.repo.importRepo",
};
const sign_in_paths = [_][]const u8{
    "/xrpc/com.atproto.server.createSession", "/xrpc/com.atproto.server.refreshSession", "/xrpc/com.atproto.server.deleteSession",
    "/xrpc/com.atproto.server.createAccount",
};

/// Each route's kind, from the endpoint table: proxied calls are `proxy`,
/// the sync group is `sync`, record and blob writes are `writes`, OAuth and
/// session routes are `sign_in`, and everything else is `reads`.
const route_kinds: [ROUTE_COUNT]Kind = blk: {
    @setEvalBranchQuota(200_000);
    var kinds: [ROUTE_COUNT]Kind = @splat(.reads);
    for (router.endpoints) |endpoint| {
        const index = @backingInt(endpoint.route);
        if (std.mem.eql(u8, endpoint.group, "sync")) kinds[index] = .sync;
        if (std.mem.eql(u8, endpoint.group, "oauth")) kinds[index] = .sign_in;
        for (write_paths) |path| if (std.mem.eql(u8, endpoint.path, path)) {
            kinds[index] = .writes;
        };
        for (sign_in_paths) |path| if (std.mem.eql(u8, endpoint.path, path)) {
            kinds[index] = .sign_in;
        };
    }
    kinds[@backingInt(Route.proxy_xrpc)] = .proxy;
    break :blk kinds;
};

pub fn kindOf(route: Route, class: Class) Kind {
    if (class == .proxy) return .proxy;
    return route_kinds[@backingInt(route)];
}

/// Latency buckets double from 128µs: bucket 0 is under 128µs, bucket i
/// covers [2^(i+6), 2^(i+7)) µs, and the last holds everything from 32s up.
pub const bucket_count = 19;

pub fn bucketOf(elapsed_us: u32) usize {
    if (elapsed_us < 128) return 0;
    return @min(bucket_count - 1, @as(usize, std.math.log2_int(u32, elapsed_us)) - 6);
}

/// The bucket's lower edge in microseconds.
pub fn bucketFloorUs(bucket: usize) u64 {
    return if (bucket == 0) 0 else @as(u64, 1) << @intCast(bucket + 6);
}

/// Counts, failures and a latency histogram; adding two is adding fields.
pub const Agg = struct {
    count: u32 = 0,
    failures: u32 = 0,
    hist: [bucket_count]u32 = @splat(0),

    pub fn add(self: *Agg, elapsed_us: u32, failed: bool) void {
        self.count +|= 1;
        if (failed) self.failures +|= 1;
        self.hist[bucketOf(elapsed_us)] +|= 1;
    }

    pub fn merge(self: *Agg, other: Agg) void {
        self.count +|= other.count;
        self.failures +|= other.failures;
        for (&self.hist, other.hist) |*mine, theirs| mine.* +|= theirs;
    }

    /// The `q` quantile, as the geometric middle of the bucket it falls in.
    pub fn quantileUs(self: Agg, q: f64) u64 {
        var total: u64 = 0;
        for (self.hist) |n| total += n;
        if (total == 0) return 0;
        const rank: u64 = @max(1, @as(u64, @intFromFloat(@ceil(q * @as(f64, @floatFromInt(total))))));
        var seen: u64 = 0;
        for (self.hist, 0..) |n, bucket| {
            seen += n;
            if (seen >= rank) {
                if (bucket == 0) return 64;
                const floor = bucketFloorUs(bucket);
                return floor + floor * 41 / 100; // ~ floor * sqrt(2)
            }
        }
        return bucketFloorUs(bucket_count - 1);
    }

    /// How many took at least `us` (to bucket resolution).
    pub fn atLeast(self: Agg, us: u64) u64 {
        var n: u64 = 0;
        for (self.hist, 0..) |c, bucket| {
            if (bucketFloorUs(bucket) >= us) n += c;
        }
        return n;
    }
};

pub const EndpointStats = struct {
    route: Route,
    method: Method,
    count: u64,
    failure_count: u64,
    avg_ms: f64,
    p50_ms: f64,
    p95_ms: f64,
    max_ms: f64,
};

pub const SlowRequest = struct {
    route: Route = .not_found,
    method: Method = .other,
    class: Class = .unknown,
    at_s: i64 = 0,
    elapsed_us: u32 = 0,
    status: u16 = 0,
    handler_failed: bool = false,
    label: [LABEL_LEN]u8 = @splat(0),
    label_len: usize = 0,

    pub fn labelText(self: *const SlowRequest) []const u8 {
        return self.label[0..self.label_len];
    }

    pub fn failed(self: *const SlowRequest) bool {
        return self.handler_failed or self.status >= 500;
    }
};

pub const Snapshot = struct {
    started_at_s: i64,
    uptime_s: u64,
    total_requests: u64,
    total_failures: u64,
    routes: [ROUTE_COUNT][METHOD_COUNT]EndpointStats,
    slow_requests: [SLOW_COUNT]SlowRequest,
    slow_len: usize,
};

const LatencyBuffer = struct {
    samples: [SAMPLE_COUNT]u32 = @splat(0),
    count: usize = 0,
    head: usize = 0,
    total_count: u64 = 0,
    failure_count: u64 = 0,

    fn record(self: *LatencyBuffer, elapsed_us: u32, failed: bool) void {
        self.samples[self.head] = elapsed_us;
        self.head = (self.head + 1) % SAMPLE_COUNT;
        if (self.count < SAMPLE_COUNT) self.count += 1;
        self.total_count += 1;
        if (failed) self.failure_count += 1;
    }
};

var global_io: ?Io = null;
var mutex: Io.Mutex = .init;
var started_at_s: i64 = 0;
var buffers: [ROUTE_COUNT][METHOD_COUNT]LatencyBuffer = @splat(@splat(.{}));
var slow_requests: [SLOW_COUNT]SlowRequest = @splat(.{});
var slow_next: usize = 0;
var slow_len: usize = 0;
var total_requests: u64 = 0;
var total_failures: u64 = 0;

/// Per-minute counts by kind and per-hour counts by route, added to the
/// database by the flusher. A slot keeps its time key and is zeroed when
/// drained, so a request landing after a drain still adds to the same row.
const MinuteSlot = struct { minute: i64 = -1, kinds: [kind_count]Agg = @splat(.{}) };
const HourSlot = struct {
    hour: i64 = -1,
    routes: [ROUTE_COUNT][METHOD_COUNT]Agg = @splat(@splat(.{})),
    apps: [app_slots]AppCount = @splat(.{}),
};

/// Authenticated requests per account and app in an hour. A PDS has few
/// accounts and each uses a few apps; past this many pairs an hour the
/// rest go uncounted until the next drain frees the slots.
const app_slots = 64;
const AppCount = struct {
    did: [128]u8 = undefined,
    did_len: usize = 0,
    app: [128]u8 = undefined,
    app_len: usize = 0,
    count: u32 = 0,

    fn matches(self: *const AppCount, did: []const u8, app: []const u8) bool {
        return std.mem.eql(u8, self.did[0..self.did_len], did) and std.mem.eql(u8, self.app[0..self.app_len], app);
    }
};

fn countApp(slot: *HourSlot, did: []const u8, app: []const u8) void {
    var free: ?*AppCount = null;
    for (&slot.apps) |*entry| {
        if (entry.did_len == 0) {
            if (free == null) free = entry;
            continue;
        }
        if (entry.matches(did, app)) {
            entry.count +|= 1;
            return;
        }
    }
    const entry = free orelse return;
    entry.did_len = did.len;
    @memcpy(entry.did[0..did.len], did);
    entry.app_len = app.len;
    @memcpy(entry.app[0..app.len], app);
    entry.count = 1;
}
var minute_slots: [4]MinuteSlot = @splat(.{});
var hour_slots: [2]HourSlot = @splat(.{});

pub fn init(io: Io) void {
    global_io = io;
    started_at_s = timestampSeconds(io);
}

pub fn start() i64 {
    const io = global_io orelse return 0;
    return Io.Timestamp.now(io, .awake).toMicroseconds();
}

pub fn record(route: Route, method: httpz.Method, class: Class, label: []const u8, start_us: i64, status: u16, handler_failed: bool) void {
    const io = global_io orelse return;
    const now_us = Io.Timestamp.now(io, .awake).toMicroseconds();
    const elapsed_us: u32 = @intCast(@min(@max(0, now_us - start_us), std.math.maxInt(u32)));
    const method_key = Method.fromHttpz(method);
    const failed = handler_failed or status >= 500;

    mutex.lockUncancelable(io);
    defer mutex.unlock(io);

    buffers[@backingInt(route)][@backingInt(method_key)].record(elapsed_us, failed);
    const now_s = timestampSeconds(io);
    minuteSlot(@divFloor(now_s, 60)).kinds[@backingInt(kindOf(route, class))].add(elapsed_us, failed);
    const hour_slot = hourSlot(@divFloor(now_s, 3600));
    hour_slot.routes[@backingInt(route)][@backingInt(method_key)].add(elapsed_us, failed);
    if (request_context.caller()) |who| countApp(hour_slot, who.did, who.app);
    total_requests += 1;
    if (failed) total_failures += 1;

    if (elapsed_us >= 250 * std.time.us_per_ms or failed) {
        var slow: SlowRequest = .{
            .route = route,
            .method = method_key,
            .class = class,
            .at_s = timestampSeconds(io),
            .elapsed_us = elapsed_us,
            .status = status,
            .handler_failed = handler_failed,
        };
        slow.label_len = @min(label.len, LABEL_LEN);
        @memcpy(slow.label[0..slow.label_len], label[0..slow.label_len]);
        slow_requests[slow_next] = slow;
        slow_next = (slow_next + 1) % SLOW_COUNT;
        if (slow_len < SLOW_COUNT) slow_len += 1;
    }
}

pub fn snapshot() Snapshot {
    const io = global_io orelse return emptySnapshot();
    mutex.lockUncancelable(io);
    defer mutex.unlock(io);

    var routes: [ROUTE_COUNT][METHOD_COUNT]EndpointStats = undefined;
    for (&routes, 0..) |*method_stats, route_idx| {
        for (method_stats, 0..) |*stats, method_idx| {
            stats.* = summarize(@fromBackingInt(@intCast(route_idx)), @fromBackingInt(@intCast(method_idx)), buffers[route_idx][method_idx]);
        }
    }

    var slow: [SLOW_COUNT]SlowRequest = @splat(.{});
    for (0..slow_len) |i| {
        const idx = (slow_next + SLOW_COUNT - slow_len + i) % SLOW_COUNT;
        slow[i] = slow_requests[idx];
    }

    const now_s = timestampSeconds(io);
    return .{
        .started_at_s = started_at_s,
        .uptime_s = @intCast(@max(0, now_s - started_at_s)),
        .total_requests = total_requests,
        .total_failures = total_failures,
        .routes = routes,
        .slow_requests = slow,
        .slow_len = slow_len,
    };
}

fn emptySnapshot() Snapshot {
    var routes: [ROUTE_COUNT][METHOD_COUNT]EndpointStats = undefined;
    for (&routes, 0..) |*method_stats, route_idx| {
        for (method_stats, 0..) |*stats, method_idx| {
            stats.* = .{
                .route = @fromBackingInt(@intCast(route_idx)),
                .method = @fromBackingInt(@intCast(method_idx)),
                .count = 0,
                .failure_count = 0,
                .avg_ms = 0,
                .p50_ms = 0,
                .p95_ms = 0,
                .max_ms = 0,
            };
        }
    }
    return .{
        .started_at_s = 0,
        .uptime_s = 0,
        .total_requests = 0,
        .total_failures = 0,
        .routes = routes,
        .slow_requests = @splat(.{}),
        .slow_len = 0,
    };
}

fn summarize(route: Route, method: Method, buffer: LatencyBuffer) EndpointStats {
    if (buffer.count == 0) {
        return .{
            .route = route,
            .method = method,
            .count = 0,
            .failure_count = buffer.failure_count,
            .avg_ms = 0,
            .p50_ms = 0,
            .p95_ms = 0,
            .max_ms = 0,
        };
    }

    var sorted: [SAMPLE_COUNT]u32 = undefined;
    @memcpy(sorted[0..buffer.count], buffer.samples[0..buffer.count]);
    std.mem.sort(u32, sorted[0..buffer.count], {}, std.sort.asc(u32));

    var sum: u64 = 0;
    for (sorted[0..buffer.count]) |value| sum += value;
    const p95_idx = @min(buffer.count - 1, (buffer.count * 95) / 100);

    return .{
        .route = route,
        .method = method,
        .count = buffer.total_count,
        .failure_count = buffer.failure_count,
        .avg_ms = @as(f64, @floatFromInt(sum)) / @as(f64, @floatFromInt(buffer.count)) / 1000.0,
        .p50_ms = @as(f64, @floatFromInt(sorted[buffer.count / 2])) / 1000.0,
        .p95_ms = @as(f64, @floatFromInt(sorted[p95_idx])) / 1000.0,
        .max_ms = @as(f64, @floatFromInt(sorted[buffer.count - 1])) / 1000.0,
    };
}

fn minuteSlot(minute: i64) *MinuteSlot {
    var oldest = &minute_slots[0];
    for (&minute_slots) |*slot| {
        if (slot.minute == minute) return slot;
        if (slot.minute < oldest.minute) oldest = slot;
    }
    oldest.* = .{ .minute = minute };
    return oldest;
}

fn hourSlot(hour: i64) *HourSlot {
    var oldest = &hour_slots[0];
    for (&hour_slots) |*slot| {
        if (slot.hour == hour) return slot;
        if (slot.hour < oldest.hour) oldest = slot;
    }
    oldest.* = .{ .hour = hour };
    return oldest;
}

/// Takes everything counted since the last drain, as rows to add to the
/// database, and zeroes the slots.
pub fn drain(allocator: std.mem.Allocator) !store.TelemetryRows {
    var minutes: std.ArrayList(store.TelemetryMinute) = .empty;
    var hours: std.ArrayList(store.TelemetryHour) = .empty;
    var apps: std.ArrayList(store.TelemetryApp) = .empty;
    const io = global_io orelse return .{ .minutes = &.{}, .hours = &.{}, .apps = &.{} };
    mutex.lockUncancelable(io);
    defer mutex.unlock(io);
    for (&minute_slots) |*slot| {
        if (slot.minute < 0) continue;
        for (&slot.kinds, 0..) |*agg, kind| {
            if (agg.count == 0) continue;
            try minutes.append(allocator, .{ .minute = slot.minute, .kind = @intCast(kind), .count = agg.count, .failures = agg.failures, .hist = agg.hist });
            agg.* = .{};
        }
    }
    for (&hour_slots) |*slot| {
        if (slot.hour < 0) continue;
        for (&slot.routes, 0..) |*methods, route| for (methods, 0..) |*agg, method| {
            if (agg.count == 0) continue;
            try hours.append(allocator, .{
                .hour = slot.hour,
                .route = @tagName(@as(Route, @fromBackingInt(@intCast(route)))),
                .method = @as(Method, @fromBackingInt(@intCast(method))).label(),
                .count = agg.count,
                .failures = agg.failures,
                .hist = agg.hist,
            });
            agg.* = .{};
        };
        for (&slot.apps) |*entry| {
            if (entry.did_len == 0) continue;
            try apps.append(allocator, .{
                .hour = slot.hour,
                .did = try allocator.dupe(u8, entry.did[0..entry.did_len]),
                .app = try allocator.dupe(u8, entry.app[0..entry.app_len]),
                .count = entry.count,
            });
            entry.* = .{};
        }
    }
    return .{ .minutes = try minutes.toOwnedSlice(allocator), .hours = try hours.toOwnedSlice(allocator), .apps = try apps.toOwnedSlice(allocator) };
}

/// Seconds between writes of the counters to the database.
const flush_seconds = 20;
var flusher_started = std.atomic.Value(bool).init(false);

/// Writes the counters to the database every 20s, so history outlives a
/// restart; at most the last 20s are lost with the process.
pub fn startFlusher() void {
    if (flusher_started.cmpxchgStrong(false, true, .acq_rel, .acquire) != null) return;
    const thread = std.Thread.spawn(.{}, flushLoop, .{}) catch |err| {
        flusher_started.store(false, .release);
        log.err("telemetry flusher spawn failed error={s}\n", .{@errorName(err)});
        return;
    };
    thread.detach();
}

fn flushLoop() void {
    const io = global_io orelse return;
    var last_prune: i64 = 0;
    while (true) {
        io.sleep(Io.Duration.fromSeconds(flush_seconds), .awake) catch {};
        var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
        defer arena.deinit();
        const rows = drain(arena.allocator()) catch continue;
        store.addTelemetry(rows) catch |err| log.err("telemetry flush failed error={s}\n", .{@errorName(err)});
        const now_s = timestampSeconds(io);
        if (now_s - last_prune >= 3600) {
            store.pruneTelemetry(now_s) catch |err| log.err("telemetry prune failed error={s}\n", .{@errorName(err)});
            if (store.storageSnapshot()) |sizes| {
                store.recordStorageSnapshot(@divFloor(now_s, 3600), sizes) catch |err| log.err("telemetry storage snapshot failed error={s}\n", .{@errorName(err)});
            } else |err| log.err("telemetry storage snapshot failed error={s}\n", .{@errorName(err)});
            last_prune = now_s;
        }
    }
}

fn timestampSeconds(io: Io) i64 {
    return @intCast(@divFloor(Io.Timestamp.now(io, .real).nanoseconds, std.time.ns_per_s));
}

test "latency buckets double from 128us and quantiles land in the right bucket" {
    try std.testing.expectEqual(@as(usize, 0), bucketOf(0));
    try std.testing.expectEqual(@as(usize, 0), bucketOf(127));
    try std.testing.expectEqual(@as(usize, 1), bucketOf(128));
    try std.testing.expectEqual(@as(usize, 13), bucketOf(1_000_000));
    try std.testing.expectEqual(@as(usize, bucket_count - 1), bucketOf(std.math.maxInt(u32)));
    var agg: Agg = .{};
    for (0..95) |_| agg.add(500, false);
    for (0..5) |_| agg.add(2_000_000, true);
    try std.testing.expectEqual(@as(u32, 100), agg.count);
    try std.testing.expectEqual(@as(u32, 5), agg.failures);
    const p50 = agg.quantileUs(0.5);
    try std.testing.expect(p50 >= 256 and p50 < 1024);
    const p99 = agg.quantileUs(0.99);
    try std.testing.expect(p99 >= 1_048_576 and p99 < 4_194_304);
    try std.testing.expectEqual(@as(u64, 5), agg.atLeast(1_000_000));
    var other: Agg = .{};
    other.add(500, false);
    agg.merge(other);
    try std.testing.expectEqual(@as(u32, 101), agg.count);
}

test "routes map to the kind the stats page charts them as" {
    try std.testing.expectEqual(Kind.writes, kindOf(.repo_create_record, .local));
    try std.testing.expectEqual(Kind.sync, kindOf(.sync_get_repo, .local));
    try std.testing.expectEqual(Kind.sign_in, kindOf(.create_session, .local));
    try std.testing.expectEqual(Kind.proxy, kindOf(.proxy_xrpc, .proxy));
    try std.testing.expectEqual(Kind.reads, kindOf(.repo_get_record, .local));
}