//! The operator stats page: request history from the telemetry tables, //! charted as server-rendered SVG. Positions are SVG attributes, so the page //! keeps a single hashed stylesheet and no inline styles or scripts. const std = @import("std"); const config = @import("../core/config.zig"); const http_api = @import("api.zig"); const router = @import("router.zig"); const store = @import("../storage/store.zig"); const sync = @import("../atproto/sync.zig"); const telemetry = @import("../internal/telemetry.zig"); const icons = @import("../internal/web/icons.zig"); const landing_assets = @import("landing/assets.zig"); const skin = @import("../internal/web/skin.zig"); /// The homepage's saved theme and accent, applied before paint. const appearance_js = @embedFile("../internal/web/appearance.js"); /// Range, tab and resident links swap the page in place instead of reloading it. const swap_js = @embedFile("../internal/web/swap.js"); const http = std.http; const Agg = telemetry.Agg; const Kind = telemetry.Kind; const kind_count = telemetry.kind_count; pub const Range = enum { hour, day, week, month, pub fn label(self: Range) []const u8 { return switch (self) { .hour => "1h", .day => "24h", .week => "7d", .month => "30d", }; } fn spanLabel(self: Range) []const u8 { return switch (self) { .hour => "past hour", .day => "past 24h", .week => "past 7 days", .month => "past 30 days", }; } /// Seconds per bar and bar count; the first two read minute rows, the /// rest hour rows. fn step(self: Range) i64 { return switch (self) { .hour => 60, .day => 15 * 60, .week => 2 * 3600, .month => 12 * 3600, }; } fn bars(self: Range) usize { return switch (self) { .hour => 60, .day => 96, .week => 84, .month => 60, }; } fn fromMinutes(self: Range) bool { return self == .hour or self == .day; } fn parse(text: []const u8) ?Range { for (std.enums.values(Range)) |range| if (std.mem.eql(u8, text, range.label())) return range; return null; } }; pub const Tab = enum { overview, repos, accounts, fn label(self: Tab) []const u8 { return switch (self) { .overview => "overview", .repos => "repos & sync", .accounts => "accounts & apps", }; } fn parse(text: []const u8) ?Tab { for (std.enums.values(Tab)) |tab| if (std.mem.eql(u8, text, @tagName(tab))) return tab; return null; } }; pub const View = struct { range: Range = .day, tab: Tab = .overview, /// A resident's handle or DID; the apps panel shows only theirs. resident: ?[]const u8 = null, now_s: i64, }; pub fn serve(request: *http_api.Request) !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); var range_buf: [8]u8 = undefined; var tab_buf: [16]u8 = undefined; var resident_buf: [256]u8 = undefined; const target = request.url.raw; const body = try render(arena.allocator(), .{ .range = Range.parse(http_api.queryParam(target, "range", &range_buf) orelse "") orelse .day, .tab = Tab.parse(http_api.queryParam(target, "tab", &tab_buf) orelse "") orelse .overview, .resident = http_api.queryParam(target, "resident", &resident_buf), .now_s = @intCast(store.nowMicros() / std.time.us_per_s), }); try http_api.respond(request, .ok, try icons.decorate(arena.allocator(), body), &html_headers); } /// Requests per bar and kind, plus every route's total, over the range. const History = struct { start_s: i64, step_s: i64, bars: [][kind_count]Agg, routes: []RouteTotal, }; const RouteTotal = struct { route: []const u8, method: []const u8, agg: Agg, }; fn load(allocator: std.mem.Allocator, view: View) !History { const step = view.range.step(); const count = view.range.bars(); const end = (@divFloor(view.now_s, step) + 1) * step; const start = end - step * @as(i64, @intCast(count)); const bars = try allocator.alloc([kind_count]Agg, count); for (bars) |*bar| bar.* = @splat(.{}); if (view.range.fromMinutes()) { for (try store.listTelemetryMinutes(allocator, @divFloor(start, 60), @divFloor(end, 60))) |row| { if (row.kind >= kind_count) continue; const index: usize = @intCast(@divFloor(row.minute * 60 - start, step)); bars[index][row.kind].merge(.{ .count = row.count, .failures = row.failures, .hist = row.hist }); } } var totals: std.ArrayList(RouteTotal) = .empty; const hours = try store.listTelemetryHours(allocator, @divFloor(start, 3600), @divFloor(end + 3599, 3600)); for (hours) |row| { const agg: Agg = .{ .count = row.count, .failures = row.failures, .hist = row.hist }; if (!view.range.fromMinutes()) { const route = std.meta.stringToEnum(router.Route, row.route) orelse .not_found; const kind = telemetry.kindOf(route, if (route == .proxy_xrpc) .proxy else .local); const index: usize = @intCast(@max(0, @divFloor(row.hour * 3600 - start, step))); if (index < count) bars[index][@backingInt(kind)].merge(agg); } for (totals.items) |*total| { if (std.mem.eql(u8, total.route, row.route) and std.mem.eql(u8, total.method, row.method)) { total.agg.merge(agg); break; } } else try totals.append(allocator, .{ .route = row.route, .method = row.method, .agg = agg }); } return .{ .start_s = start, .step_s = step, .bars = bars, .routes = totals.items }; } fn render(allocator: std.mem.Allocator, view: View) ![]const u8 { const history = try load(allocator, view); var out: std.Io.Writer.Allocating = .init(allocator); const w = &out.writer; var all: Agg = .{}; var by_kind: [kind_count]Agg = @splat(.{}); for (history.bars) |bar| for (bar, 0..) |agg, kind| { all.merge(agg); by_kind[kind].merge(agg); }; const snap = telemetry.snapshot(); try w.print( \\ \\ \\ \\ \\ \\stats · {s} \\{s} \\ \\ \\ \\
\\
\\ zds \\ \\
\\

stats

{s} , .{ host(), appearance_js, landing_assets.css, style, skin.statsStyle(), host() }); try w.writeAll("
"); for (std.enums.values(Range)) |range| { try w.print("{s}", .{ @tagName(view.tab), range.label(), if (range == view.range) " aria-current=\"page\"" else "", range.label() }); } try w.print("
up {s}
", .{try formatDuration(allocator, snap.uptime_s)}); for (std.enums.values(Tab)) |tab| { try w.print("{s}", .{ @tagName(tab), view.range.label(), if (tab == view.tab) " aria-current=\"page\"" else "", tab.label() }); } try w.writeAll("
"); switch (view.tab) { .overview => { try renderTiles(allocator, w, view, history, all, by_kind); try w.writeAll("
"); try renderTraffic(w, view, history); try renderLatency(w, view, history); try w.writeAll("
"); try renderRoutes(allocator, w, history, null, "slowest routes", 9); try w.writeAll("
"); try renderSummary(allocator, w, view, history, all); try renderRecentSlow(allocator, w, snap, view.now_s); }, .repos => try renderRepos(allocator, w, view, history, by_kind), .accounts => try renderAccounts(allocator, w, view, history, by_kind), } try w.writeAll("
"); try w.print("", .{swap_js}); try w.writeAll(skin.script()); try w.writeAll(""); return out.toOwnedSlice(); } fn renderTiles(allocator: std.mem.Allocator, w: *std.Io.Writer, view: View, history: History, all: Agg, by_kind: [kind_count]Agg) !void { const n = history.bars.len; const requests = try allocator.alloc(f64, n); const errors = try allocator.alloc(f64, n); const p95 = try allocator.alloc(f64, n); const writes = try allocator.alloc(f64, n); for (history.bars, 0..) |bar, i| { var merged: Agg = .{}; for (bar) |agg| merged.merge(agg); requests[i] = @floatFromInt(merged.count); errors[i] = @floatFromInt(merged.failures); p95[i] = if (merged.count == 0) 0 else @log10(@as(f64, @floatFromInt(merged.quantileUs(0.95)))); writes[i] = @floatFromInt(bar[@backingInt(Kind.writes)].count); } const write_agg = by_kind[@backingInt(Kind.writes)]; const error_rate = if (all.count == 0) 0 else @as(f64, @floatFromInt(all.failures)) * 100.0 / @as(f64, @floatFromInt(all.count)); try w.writeAll("
"); try tile(w, "requests", try std.fmt.allocPrint(allocator, "{f}", .{grouped(all.count)}), requests, "a", view.range.spanLabel()); try tile(w, "server errors", try std.fmt.allocPrint(allocator, "{f}", .{grouped(all.failures)}), errors, "c", try std.fmt.allocPrint(allocator, "{d:.2}% of requests", .{error_rate})); try tile(w, "p95 latency", try formatUs(allocator, all.quantileUs(0.95)), p95, "d", try std.fmt.allocPrint(allocator, "p50 {s}", .{try formatUs(allocator, all.quantileUs(0.5))})); try tile(w, "writes", try std.fmt.allocPrint(allocator, "{f}", .{grouped(write_agg.count)}), writes, "b", try std.fmt.allocPrint(allocator, "{f} server errors", .{grouped(write_agg.failures)})); try w.writeAll("
"); } fn tile(w: *std.Io.Writer, label: []const u8, value: []const u8, series: []const f64, tone: []const u8, note: []const u8) !void { try w.print("
{s}{s}{s}
", .{note}); } const kind_tones = [kind_count][]const u8{ "k0", "k1", "k2", "k3", "k5" }; fn renderTraffic(w: *std.Io.Writer, view: View, history: History) !void { var peak: u64 = 0; for (history.bars) |bar| { var total: u64 = 0; for (bar) |agg| total += agg.count; peak = @max(peak, total); } const top = niceCeiling(@max(peak, 1)); var first_seen: ?usize = null; for (history.bars, 0..) |bar, i| { var any: u64 = 0; for (bar) |agg| any += agg.count; if (any > 0) { first_seen = i; break; } } try w.print("

traffic requests per {s} · pink columns had server errors", .{stepLabel(view.range)}); // History starts with the release that records it; say so rather than // let an empty stretch read as an idle server. if (first_seen) |i| if (i > history.bars.len / 10) { try w.print(" · recorded since {s}", .{timeLabel(history.start_s + @as(i64, @intCast(i)) * history.step_s, view.range)}); }; try w.writeAll("

"); try w.writeAll("
"); try w.writeAll(""); const width = 600.0 / @as(f64, @floatFromInt(history.bars.len)); for (history.bars, 0..) |bar, i| { const x = @as(f64, @floatFromInt(i)) * width; var failures: u64 = 0; for (bar) |agg| failures += agg.failures; if (failures > 0) try w.print("", .{ x, width }); var y: f64 = 150; for (bar, 0..) |agg, kind| { if (agg.count == 0) continue; const h = @as(f64, @floatFromInt(agg.count)) / @as(f64, @floatFromInt(top)) * 150.0; y -= h; try w.print("{s}: {d} {s}", .{ kind_tones[kind], x + 0.3, y, @max(width - 0.6, 0.4), h, timeLabel(history.start_s + @as(i64, @intCast(i)) * history.step_s, view.range), agg.count, @as(Kind, @fromBackingInt(@intCast(kind))).label(), }); } } try w.print("{d}{d}
", .{ top, top / 2 }); try axis(w, view, history); try w.writeAll("
"); for (0..kind_count) |kind| try w.print("{s}", .{ kind_tones[kind], @as(Kind, @fromBackingInt(@intCast(kind))).label() }); try w.writeAll("
"); } /// Latency on a fixed log scale from 100µs to 10s, so gridlines sit at the /// same heights for every range. fn latencyY(us: u64) f64 { const v = @log10(@as(f64, @floatFromInt(@max(us, 100)))); return 110.0 - std.math.clamp((v - 2.0) / 5.0, 0, 1) * 110.0; } fn renderLatency(w: *std.Io.Writer, view: View, history: History) !void { try w.writeAll("

latency p50 and p95, log scale

"); try w.writeAll("
"); for ([_]u64{ 1_000, 10_000, 100_000, 1_000_000 }) |us| { try w.print("", .{ if (us == 1_000_000) " warn" else "", latencyY(us), latencyY(us) }); } const n = history.bars.len; inline for (.{ .{ 0.5, "p50" }, .{ 0.95, "p95" } }) |line| { try w.print(""); } try w.writeAll("1ms10ms100ms1s
"); try axis(w, view, history); } fn axis(w: *std.Io.Writer, view: View, history: History) !void { const n: i64 = @intCast(history.bars.len); try w.print("
{s}{s}now
", .{ timeLabel(history.start_s, view.range), timeLabel(history.start_s + @divFloor(n, 2) * history.step_s, view.range), }); } fn renderRoutes(allocator: std.mem.Allocator, w: *std.Io.Writer, history: History, only: ?Kind, title: []const u8, limit: usize) !void { var picked: std.ArrayList(RouteTotal) = .empty; for (history.routes) |total| { if (only) |kind| if (routeKind(total.route) != kind) continue; try picked.append(allocator, total); } const routes = picked.items; std.mem.sort(RouteTotal, routes, {}, struct { fn slower(_: void, a: RouteTotal, b: RouteTotal) bool { return a.agg.quantileUs(0.95) > b.agg.quantileUs(0.95); } }.slower); try w.print("

{s} bar is p95, tick is p50, log scale

", .{title}); if (routes.len == 0) { try w.writeAll("

no requests recorded in this range yet.

"); return; } try w.writeAll(""); } fn routeKind(name: []const u8) Kind { const route = std.meta.stringToEnum(router.Route, name) orelse return .reads; return telemetry.kindOf(route, if (route == .proxy_xrpc) .proxy else .local); } /// One kind's requests per bar, as single-colour columns. fn renderKindBars(w: *std.Io.Writer, view: View, history: History, kind: Kind, title: []const u8, note: []const u8) !void { var peak: u64 = 0; for (history.bars) |bar| peak = @max(peak, bar[@backingInt(kind)].count); const top = niceCeiling(@max(peak, 1)); try w.print("

{s} {s} per {s}

", .{ title, note, stepLabel(view.range) }); try w.writeAll("
"); const width = 600.0 / @as(f64, @floatFromInt(history.bars.len)); for (history.bars, 0..) |bar, i| { const agg = bar[@backingInt(kind)]; const x = @as(f64, @floatFromInt(i)) * width; if (agg.failures > 0) try w.print("", .{ x, width }); if (agg.count == 0) continue; const h = @as(f64, @floatFromInt(agg.count)) / @as(f64, @floatFromInt(top)) * 100.0; try w.print("{s}: {d}", .{ kind_tones[@backingInt(kind)], x + 0.3, 100.0 - h, @max(width - 0.6, 0.4), h, timeLabel(history.start_s + @as(i64, @intCast(i)) * history.step_s, view.range), agg.count, }); } try w.print("{d}{d}
", .{ top, top / 2 }); try axis(w, view, history); } fn renderRepos(allocator: std.mem.Allocator, w: *std.Io.Writer, view: View, history: History, by_kind: [kind_count]Agg) !void { const now_hour = @divFloor(view.now_s, 3600); const snapshots = try store.listStorageSnapshots(allocator, @divFloor(history.start_s, 3600), now_hour + 1); const current = try store.storageSnapshot(); var exports: Agg = .{}; for (history.routes) |total| if (std.mem.eql(u8, total.route, "sync_get_repo")) exports.merge(total.agg); const n = @max(snapshots.len, 2); const db_series = try allocator.alloc(f64, n); const record_series = try allocator.alloc(f64, n); for (0..n) |i| { const snap = if (snapshots.len == 0) current else snapshots[@min(i, snapshots.len - 1)]; db_series[i] = @floatFromInt(snap.db_bytes + snap.blob_bytes); record_series[i] = @floatFromInt(snap.records); } const sync_series = try allocator.alloc(f64, history.bars.len); for (history.bars, 0..) |bar, i| { sync_series[i] = @floatFromInt(bar[@backingInt(Kind.sync)].count); } const first = if (snapshots.len > 0) snapshots[0] else current; const record_change: i64 = @as(i64, @intCast(current.records)) - @as(i64, @intCast(first.records)); try w.writeAll("
"); try tile(w, "firehose", try std.fmt.allocPrint(allocator, "{d} open", .{sync.subscriberCount()}), sync_series, "b", try std.fmt.allocPrint(allocator, "{f} sync requests", .{grouped(by_kind[@backingInt(Kind.sync)].count)})); try tile(w, "repo exports", try std.fmt.allocPrint(allocator, "{f}", .{grouped(exports.count)}), sync_series, "d", try std.fmt.allocPrint(allocator, "p95 {s}", .{try formatUs(allocator, exports.quantileUs(0.95))})); try tile(w, "records", try std.fmt.allocPrint(allocator, "{f}", .{grouped(current.records)}), record_series, "a", try std.fmt.allocPrint(allocator, "{s}{d} in the {s}", .{ if (record_change >= 0) "+" else "", record_change, view.range.spanLabel() })); try tile(w, "storage", try formatBytes(allocator, current.db_bytes + current.blob_bytes), db_series, "c", try std.fmt.allocPrint(allocator, "database {s} · blobs {s}", .{ try formatBytes(allocator, current.db_bytes), try formatBytes(allocator, current.blob_bytes) })); try w.writeAll("
"); try renderKindBars(w, view, history, .writes, "writes", "records and blobs written"); try w.writeAll("
"); try renderRoutes(allocator, w, history, .writes, "by kind of write", 8); try w.writeAll("
"); try renderKindBars(w, view, history, .sync, "sync & export", "requests from relays and backfill"); try w.writeAll("
"); try renderRoutes(allocator, w, history, .sync, "sync routes", 8); try w.writeAll("
"); } fn renderAccounts(allocator: std.mem.Allocator, w: *std.Io.Writer, view: View, history: History, by_kind: [kind_count]Agg) !void { const residents = try store.listResidents(allocator, 24); var scoped: ?store.Resident = null; if (view.resident) |wanted| for (residents) |resident| { if (std.mem.eql(u8, resident.handle, wanted) or std.mem.eql(u8, resident.did, wanted)) scoped = resident; }; const app_step: i64 = @max(history.step_s, 3600); const span = history.step_s * @as(i64, @intCast(history.bars.len)); const app_bars: usize = @intCast(@divFloor(span + app_step - 1, app_step)); const app_start = @divFloor(view.now_s, app_step) * app_step + app_step - app_step * @as(i64, @intCast(app_bars)); const rows = try store.listTelemetryApps(allocator, @divFloor(app_start, 3600), @divFloor(view.now_s, 3600) + 1, if (scoped) |r| r.did else null); var names: std.ArrayList([]const u8) = .empty; var totals: std.ArrayList(u64) = .empty; for (rows) |row| { for (names.items, 0..) |name, i| { if (std.mem.eql(u8, name, row.app)) { totals.items[i] += row.count; break; } } else { try names.append(allocator, row.app); try totals.append(allocator, row.count); } } // Largest first; past six apps the rest share one band. const order = try allocator.alloc(usize, names.items.len); for (order, 0..) |*o, i| o.* = i; std.mem.sort(usize, order, totals.items, struct { fn more(t: []const u64, a: usize, b: usize) bool { return t[a] > t[b]; } }.more); const shown = @min(order.len, 6); var grand: u64 = 0; for (totals.items) |t| grand += t; const sign_in = by_kind[@backingInt(Kind.sign_in)]; var password: Agg = .{}; var tokens: Agg = .{}; var authorizations: Agg = .{}; for (history.routes) |total| { if (std.mem.eql(u8, total.route, "create_session")) password.merge(total.agg); if (std.mem.eql(u8, total.route, "oauth_token")) tokens.merge(total.agg); if (std.mem.eql(u8, total.route, "oauth_par")) authorizations.merge(total.agg); } const sign_in_series = try allocator.alloc(f64, history.bars.len); const fail_series = try allocator.alloc(f64, history.bars.len); for (history.bars, 0..) |bar, i| { sign_in_series[i] = @floatFromInt(bar[@backingInt(Kind.sign_in)].count); fail_series[i] = @floatFromInt(bar[@backingInt(Kind.sign_in)].failures); } try w.writeAll("
"); try tile(w, "app sign-ins", try std.fmt.allocPrint(allocator, "{f}", .{grouped(authorizations.count)}), sign_in_series, "a", "OAuth authorization requests"); try tile(w, "token exchanges", try std.fmt.allocPrint(allocator, "{f}", .{grouped(tokens.count)}), sign_in_series, "b", try std.fmt.allocPrint(allocator, "p95 {s}", .{try formatUs(allocator, tokens.quantileUs(0.95))})); try tile(w, "password sign-ins", try std.fmt.allocPrint(allocator, "{f}", .{grouped(password.count)}), sign_in_series, "d", try std.fmt.allocPrint(allocator, "p95 {s}", .{try formatUs(allocator, password.quantileUs(0.95))})); try tile(w, "sign-in errors", try std.fmt.allocPrint(allocator, "{f}", .{grouped(sign_in.failures)}), fail_series, "c", "server errors on sign-in routes"); try w.writeAll("
"); try w.print("

apps authenticated requests{s}{s}

", .{ if (scoped != null) " by @" else " by every resident", if (scoped) |r| r.handle else "" }); try w.writeAll("
"); try w.print("everyone", .{ view.range.label(), if (scoped == null) " aria-current=\"page\"" else "" }); for (residents) |resident| { const current = if (scoped) |r| std.mem.eql(u8, r.did, resident.did) else false; try w.print("{s}", .{ view.range.label(), try escape(allocator, resident.handle), if (current) " aria-current=\"page\"" else "", try escape(allocator, resident.handle) }); } try w.writeAll("
"); if (grand == 0) { try w.writeAll("

no authenticated requests in this range yet.

"); } else { try w.writeAll("
"); var angle: f64 = -std.math.pi / 2.0; var rest: u64 = 0; for (order[shown..]) |i| rest += totals.items[i]; for (0..shown + @intFromBool(order.len > shown)) |slot| { const value: u64 = if (slot < shown) totals.items[order[slot]] else rest; const name = if (slot < shown) names.items[order[slot]] else "other apps"; const fraction = @as(f64, @floatFromInt(value)) / @as(f64, @floatFromInt(grand)); const next = angle + fraction * 2.0 * std.math.pi; const title = try std.fmt.allocPrint(allocator, "{s}: {s} ({f} requests)", .{ try escape(allocator, name), try sharePercent(allocator, value, grand), grouped(value) }); try arc(w, angle, if (fraction >= 0.9999) next - 0.0001 else next, app_tones[slot], title); angle = next; } try w.print("{f}requests
    ", .{grouped(grand)}); for (0..shown) |slot| { const i = order[slot]; const share = try sharePercent(allocator, totals.items[i], grand); try w.print("
  • {s}{s}{f} request{s}
  • ", .{ app_tones[slot], try escape(allocator, names.items[i]), try escape(allocator, share), grouped(totals.items[i]), if (totals.items[i] == 1) "" else "s" }); } if (order.len > shown) try w.print("
  • {d} other apps{s}{f} requests
  • ", .{ app_tones[shown], order.len - shown, try escape(allocator, try sharePercent(allocator, rest, grand)), grouped(rest) }); try w.writeAll("
"); if (app_bars < 3) { try w.writeAll("

Apps are counted by the hour; pick 24h or longer to see them over time. Apps are named by their sign-in client, or for a password session by the app that sent it. Counts are requests to this PDS, not time on screen.

"); } else { // Stacked by app per bar. const stacks = try allocator.alloc([7]u64, app_bars); for (stacks) |*stack| stack.* = @splat(0); for (rows) |row| { const index_i = @divFloor(row.hour * 3600 - app_start, app_step); if (index_i < 0 or index_i >= app_bars) continue; const index: usize = @intCast(index_i); var slot: usize = shown; for (0..shown) |k| if (std.mem.eql(u8, names.items[order[k]], row.app)) { slot = k; }; stacks[index][slot] += row.count; } var peak: u64 = 1; for (stacks) |stack| { var sum: u64 = 0; for (stack) |v| sum += v; peak = @max(peak, sum); } const top = niceCeiling(peak); try w.print("

by {s} stacked

", .{if (app_step >= 12 * 3600) "half day" else if (app_step >= 7200) "two hours" else "hour"}); try w.writeAll("
"); const width = 600.0 / @as(f64, @floatFromInt(app_bars)); for (stacks, 0..) |stack, i| { var y: f64 = 100; for (stack, 0..) |v, slot| { if (v == 0) continue; const h = @as(f64, @floatFromInt(v)) / @as(f64, @floatFromInt(top)) * 100.0; y -= h; try w.print("", .{ app_tones[slot], @as(f64, @floatFromInt(i)) * width + 0.3, y, @max(width - 0.6, 0.4), h }); } } try w.print("{d}
", .{top}); try w.writeAll("

Apps are named by their sign-in client, or for a password session by the app that sent it. Counts are requests to this PDS, not time on screen.

"); } } try w.writeAll("
"); try renderKindBars(w, view, history, .sign_in, "sign-in", "OAuth and session requests"); try w.writeAll("
"); try renderRoutes(allocator, w, history, .sign_in, "sign-in routes", 8); try w.writeAll("
"); } /// App colours avoid the error pink; the last is everything past six apps. const app_tones = [7][]const u8{ "a0", "a1", "a2", "a3", "a4", "a5", "a6" }; fn arc(w: *std.Io.Writer, from: f64, to: f64, tone: []const u8, title: []const u8) !void { const outer = 64.0; const inner = 46.0; const large: u8 = if (to - from > std.math.pi) 1 else 0; try w.print("{s}", .{ tone, 70 + outer * @cos(from), 70 + outer * @sin(from), outer, outer, large, 70 + outer * @cos(to), 70 + outer * @sin(to), 70 + inner * @cos(to), 70 + inner * @sin(to), inner, inner, large, 70 + inner * @cos(from), 70 + inner * @sin(from), title, }); } fn sharePercent(allocator: std.mem.Allocator, part: u64, whole: u64) ![]const u8 { if (whole == 0) return "0%"; const percent = part * 100 / whole; if (percent == 0 and part > 0) return "<1%"; return std.fmt.allocPrint(allocator, "{d}%", .{percent}); } fn formatBytes(allocator: std.mem.Allocator, bytes: u64) ![]const u8 { const value: f64 = @floatFromInt(bytes); if (bytes >= 1 << 30) return std.fmt.allocPrint(allocator, "{d:.1} GB", .{value / (1 << 30)}); if (bytes >= 1 << 20) return std.fmt.allocPrint(allocator, "{d:.0} MB", .{value / (1 << 20)}); return std.fmt.allocPrint(allocator, "{d:.0} KB", .{value / 1024}); } fn barFraction(us: u64) f64 { const v = @log10(@as(f64, @floatFromInt(@max(us, 100)))); return std.math.clamp((v - 2.0) / 5.0, 0.02, 1) * 100.0; } fn renderSummary(allocator: std.mem.Allocator, w: *std.Io.Writer, view: View, history: History, all: Agg) !void { var slow: u64 = 0; var slow_route: ?RouteTotal = null; var failing_route: ?RouteTotal = null; for (history.routes) |total| { const over = total.agg.atLeast(1_000_000); slow += over; if (over > 0 and (slow_route == null or over > slow_route.?.agg.atLeast(1_000_000))) slow_route = total; if (total.agg.failures > 0 and (failing_route == null or total.agg.failures > failing_route.?.agg.failures)) failing_route = total; } const bad = all.failures > 0; try w.print("

", .{if (bad) " bad" else ""}); if (bad) { try w.print("{f} server error{s} in the {s}, most from {s}. ", .{ grouped(all.failures), if (all.failures == 1) "" else "s", view.range.spanLabel(), routeName(failing_route.?.route, failing_route.?.method).title }); } else { try w.print("No server errors in the {s}. ", .{view.range.spanLabel()}); } if (slow == 0) { try w.writeAll("Nothing took over a second."); } else { try w.print("{f} request{s} took over a second, most of them {s}.", .{ grouped(slow), if (slow == 1) "" else "s", routeName(slow_route.?.route, slow_route.?.method).title }); } try w.writeAll("

"); _ = allocator; } /// The last slow or failed requests since the process started, with their /// full paths; history above survives restarts, this list does not. fn renderRecentSlow(allocator: std.mem.Allocator, w: *std.Io.Writer, snap: telemetry.Snapshot, now_s: i64) !void { if (snap.slow_len == 0) return; try w.print("
{d} recent slow or failed requests, since this server started
"); } const RouteName = struct { title: []const u8, detail: []const u8, note: []const u8 = "" }; /// Plain words for the routes people ask about, with the route underneath. fn routeName(route: []const u8, method: []const u8) RouteName { const known = [_]struct { []const u8, []const u8, []const u8 }{ .{ "sync_get_repo", "repo export", "relays and backfill download a whole repo; time grows with its size" }, .{ "sync_get_blob", "blob download", "" }, .{ "sync_get_blocks", "block fetch", "" }, .{ "sync_subscribe_repos", "firehose", "" }, .{ "repo_get_record", "record read", "" }, .{ "repo_list_records", "list records", "" }, .{ "repo_create_record", "record create", "" }, .{ "repo_put_record", "record update", "" }, .{ "repo_delete_record", "record delete", "" }, .{ "repo_apply_writes", "batched writes", "" }, .{ "repo_upload_blob", "blob upload", "" }, .{ "repo_import_repo", "repo import", "" }, .{ "create_session", "password sign-in", "" }, .{ "oauth_token", "token exchange", "" }, .{ "oauth_par", "authorization request", "" }, .{ "oauth_authorize", "sign-in page", "" }, .{ "oauth_client_icon", "app icon", "" }, .{ "root", "homepage", "" }, }; if (std.mem.eql(u8, route, "proxy_xrpc")) { return if (std.mem.eql(u8, method, "POST")) .{ .title = "appview actions", .detail = "proxied POST", .note = "an appview acting on your behalf" } else .{ .title = "appview reads", .detail = "proxied GET", .note = "an appview answering on your behalf" }; } for (known) |entry| if (std.mem.eql(u8, entry[0], route)) { return .{ .title = entry[1], .detail = pathFor(route, method), .note = entry[2] }; }; // An XRPC method without a plain name reads as its last NSID segment, // "describeRepo", with the full method beside it. const path = pathFor(route, method); if (std.mem.startsWith(u8, path, "/xrpc/")) { const nsid = path["/xrpc/".len..]; const last = if (std.mem.lastIndexOfScalar(u8, nsid, '.')) |dot| nsid[dot + 1 ..] else nsid; return .{ .title = last, .detail = nsid }; } const short = if (std.mem.lastIndexOfScalar(u8, path, '/')) |slash| path[slash + 1 ..] else path; return .{ .title = short, .detail = method }; } fn pathFor(route_name: []const u8, method: []const u8) []const u8 { const route = std.meta.stringToEnum(router.Route, route_name) orelse return route_name; if (route == .proxy_xrpc) return "proxied XRPC"; for (router.endpoints) |endpoint| { if (endpoint.route == route and std.mem.eql(u8, endpoint.method, method)) return endpoint.path; } for (router.endpoints) |endpoint| if (endpoint.route == route) return endpoint.path; return route_name; } fn stepLabel(range: Range) []const u8 { return switch (range) { .hour => "minute", .day => "15 minutes", .week => "2 hours", .month => "12 hours", }; } var time_label_buf: [4][32]u8 = undefined; var time_label_next: usize = 0; /// UTC, as "14:05" within a day and "Nov 14" or "Nov 14 06:00" beyond it. fn timeLabel(time_s: i64, range: Range) []const u8 { const buf = &time_label_buf[time_label_next]; time_label_next = (time_label_next + 1) % time_label_buf.len; const day_s: i64 = std.time.s_per_day; const epoch_day = std.time.epoch.EpochDay{ .day = @intCast(@divFloor(time_s, day_s)) }; const year_day = epoch_day.calculateYearDay(); const month_day = year_day.calculateMonthDay(); const seconds = @mod(time_s, day_s); const hour: u32 = @intCast(@divFloor(seconds, 3600)); const minute: u32 = @intCast(@divFloor(@mod(seconds, 3600), 60)); const months = [_][]const u8{ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; const month = months[@backingInt(month_day.month) - 1]; return switch (range) { .hour, .day => std.fmt.bufPrint(buf, "{d:0>2}:{d:0>2}", .{ hour, minute }) catch "", .week => std.fmt.bufPrint(buf, "{s} {d} {d:0>2}:00", .{ month, month_day.day_index + 1, hour }) catch "", .month => std.fmt.bufPrint(buf, "{s} {d}", .{ month, month_day.day_index + 1 }) catch "", }; } fn niceCeiling(value: u64) u64 { var scale: u64 = 1; while (true) : (scale *= 10) { for ([_]u64{ 1, 2, 5 }) |m| if (m * scale >= value) return m * scale; } } fn formatUs(allocator: std.mem.Allocator, us: u64) ![]const u8 { if (us == 0) return allocator.dupe(u8, "—"); if (us >= 1_000_000) return std.fmt.allocPrint(allocator, "{d:.1}s", .{@as(f64, @floatFromInt(us)) / 1_000_000.0}); if (us >= 10_000) return std.fmt.allocPrint(allocator, "{d}ms", .{us / 1000}); return std.fmt.allocPrint(allocator, "{d:.1}ms", .{@as(f64, @floatFromInt(us)) / 1000.0}); } fn formatDuration(allocator: std.mem.Allocator, seconds: u64) ![]const u8 { const days = seconds / 86_400; const hours = (seconds % 86_400) / 3_600; const minutes = (seconds % 3_600) / 60; if (days > 0) return std.fmt.allocPrint(allocator, "{d}d {d}h", .{ days, hours }); if (hours > 0) return std.fmt.allocPrint(allocator, "{d}h {d}m", .{ hours, minutes }); if (minutes > 0) return std.fmt.allocPrint(allocator, "{d}m", .{minutes}); return std.fmt.allocPrint(allocator, "{d}s", .{seconds}); } fn grouped(value: u64) Grouped { return .{ .value = value }; } const Grouped = struct { value: u64, pub fn format(self: Grouped, w: *std.Io.Writer) std.Io.Writer.Error!void { var buf: [24]u8 = undefined; const digits = std.fmt.bufPrint(&buf, "{d}", .{self.value}) catch unreachable; for (digits, 0..) |c, i| { if (i > 0 and (digits.len - i) % 3 == 0) try w.writeByte(','); try w.writeByte(c); } } }; fn escape(allocator: std.mem.Allocator, text: []const u8) ![]const u8 { var out: std.Io.Writer.Allocating = .init(allocator); for (text) |c| switch (c) { '&' => try out.writer.writeAll("&"), '<' => try out.writer.writeAll("<"), '>' => try out.writer.writeAll(">"), '"' => try out.writer.writeAll("""), else => try out.writer.writeByte(c), }; return out.toOwnedSlice(); } fn host() []const u8 { var value = config.publicUrl(); if (std.mem.startsWith(u8, value, "https://")) value = value["https://".len..]; if (std.mem.startsWith(u8, value, "http://")) value = value["http://".len..]; return std.mem.trimEnd(u8, value, "/"); } /// On top of the homepage stylesheet (landing/assets.zig), which gives the /// page the same column, header, palette, theme and background. const style = \\:root{--k0:#7f9ef5;--k1:#d9b13c;--k2:#35b874;--k3:#b083e6;--k4:#ec5f8c;--k5:#e58b54;--k6:#8c867b;--track:color-mix(in srgb,var(--line) 70%,transparent)} \\.defs{position:absolute;width:0;height:0} \\.stats-head{display:flex;align-items:center;flex-wrap:wrap;gap:8px 14px;margin:0 0 14px}.stats-head h1{font-size:22px;line-height:1.2}.stats-head .host{color:var(--muted);font-size:12px}.stats-head .up{margin-left:auto;color:var(--dim);font-size:11px} \\.ranges{display:inline-flex;border:1px solid color-mix(in srgb,var(--line) 80%,white 8%);border-radius:8px;overflow:hidden}.ranges a{padding:5px 10px;color:var(--muted);font-size:11px;text-decoration:none}.ranges a+a{border-left:1px solid color-mix(in srgb,var(--line) 80%,white 8%)}.ranges a:hover{color:var(--text)}.ranges a[aria-current]{color:var(--text);background:color-mix(in srgb,var(--accent-panel) 80%,var(--text) 6%)} \\.tabs{display:flex;gap:2px;margin:0 0 14px;overflow-x:auto;border-bottom:1px solid var(--line);scrollbar-width:none}.tabs a{flex:none;margin-bottom:-1px;padding:8px 12px;border-bottom:2px solid transparent;color:var(--muted);font-size:12px;text-decoration:none}.tabs a:hover{color:var(--text)}.tabs a[aria-current]{color:var(--text);border-color:var(--glass-b)} \\.tiles{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:8px}.tile,.card,.summary,.recent{border:1px solid color-mix(in srgb,var(--line) 70%,white 6%);border-radius:12px;background:color-mix(in srgb,var(--accent-panel) 72%,transparent);box-shadow:inset 0 1px 0 rgba(255,255,255,.08)} \\.tile{display:grid;gap:2px;min-width:0;padding:11px 12px 9px}.tl,.ts{color:var(--dim);font-size:10.5px}.tile b{font-size:20px;font-weight:600}.spark{width:100%;height:26px}.spark polyline{fill:none;stroke-width:1.5;vector-effect:non-scaling-stroke} \\.spark.a polyline{stroke:var(--k0)}.spark.b polyline{stroke:var(--k2)}.spark.c polyline{stroke:var(--k4)}.spark.d polyline{stroke:var(--k1)} \\.split{display:grid;grid-template-columns:minmax(0,1.45fr) minmax(0,1fr);gap:8px;margin-top:8px}.split.even{grid-template-columns:repeat(2,minmax(0,1fr))}.card{min-width:0;padding:12px 13px} \\.card h2{display:flex;justify-content:space-between;align-items:baseline;flex-wrap:wrap;gap:4px 10px;margin:0 0 8px;color:var(--text);font-size:12px;font-weight:700}.card h2 small{color:var(--dim);font-weight:400;font-size:10.5px}.card h2.sub{margin-top:14px}.card h2 i{font-style:normal}i.p50::before,i.p95::before{content:"";display:inline-block;width:9px;height:3px;margin-right:3px;vertical-align:middle;background:var(--k0)}i.p95::before{background:var(--k1)} \\.plot{position:relative;padding-left:40px}.plot+.axis{padding-left:40px}.chart{display:block;width:100%;height:140px}.lat .chart{height:100px}.chart.short{height:90px}.rule{stroke:color-mix(in srgb,var(--line) 75%,transparent);stroke-width:1;vector-effect:non-scaling-stroke}.rule.warn{stroke:color-mix(in srgb,var(--k4) 45%,var(--line));stroke-dasharray:3 3} \\.k0{fill:var(--k0)}.k1{fill:var(--k1)}.k2{fill:var(--k2)}.k3{fill:var(--k3)}.k4{fill:var(--k4)}.k5{fill:var(--k5)}.k6{fill:var(--k6)}.chart rect{opacity:.88}.chart rect.fail{fill:var(--k4);opacity:.18} \\polyline.p50,polyline.p95{fill:none;stroke-width:1.5;vector-effect:non-scaling-stroke}polyline.p50{stroke:var(--k0)}polyline.p95{stroke:var(--k1)} \\.yl{position:absolute;left:0;width:34px;text-align:right;color:var(--dim);font-size:9.5px;line-height:1;transform:translateY(-50%)}.yl.top{top:0;transform:none}.yl.mid{top:50%} \\.lat .l1{top:80%}.lat .l10{top:60%}.lat .l100{top:40%}.lat .l1000{top:20%} \\.axis{display:flex;justify-content:space-between;margin-top:3px;color:var(--dim);font-size:10px}.legend{display:flex;flex-wrap:wrap;gap:4px 12px;margin:6px 0 2px;color:var(--muted);font-size:10.5px}.legend i,.al i{display:inline-block;width:8px;height:8px;margin-right:5px;border-radius:2px;background:currentColor} \\.legend i.k0,.al i.k0{color:var(--k0)}.legend i.k1,.al i.k1{color:var(--k1)}.legend i.k2,.al i.k2{color:var(--k2)}.legend i.k3,.al i.k3{color:var(--k3)}.legend i.k4,.al i.k4{color:var(--k4)}.legend i.k5,.al i.k5{color:var(--k5)}.legend i.k6,.al i.k6{color:var(--k6)} \\.routes{display:grid;gap:9px;margin:0;padding:0;list-style:none}.routes li{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:center;gap:4px 10px}.rname{grid-column:1;grid-row:1;display:flex;align-items:baseline;gap:8px;min-width:0}.rname b{flex:0 1 auto;min-width:0;overflow:hidden;font-weight:500;text-overflow:ellipsis;white-space:nowrap}.rname code{flex:1 1 0;min-width:0;overflow:hidden;color:var(--dim);font-size:10px;text-overflow:ellipsis;white-space:nowrap} \\.rbar{grid-column:1;grid-row:2;width:100%;height:8px}.rbar .track{fill:var(--track)}.rbar .heat{fill:url(#heat)}.rbar .tick{fill:var(--text)}.rnum{grid-column:2;grid-row:1/3;display:grid;text-align:right}.rnum b{font-weight:600}.rnum span{color:var(--dim);font-size:10px;white-space:nowrap}.rnum em{color:var(--k4);font-style:normal}.rnote{grid-column:1/-1;margin:0;color:var(--dim);font-size:10.5px} \\.summary{display:flex;align-items:center;gap:10px;margin:8px 0 0;padding:10px 13px;color:var(--muted);font-size:12px}.summary b{color:var(--text)}.dot{flex:none;width:8px;height:8px;border-radius:50%;background:var(--k2)}.dot.bad{background:var(--k4)} \\.recent{margin-top:8px;padding:10px 13px;color:var(--muted);font-size:11.5px}.recent summary{cursor:pointer}.recent ul{display:grid;gap:4px;margin:8px 0 0;padding:0;list-style:none}.recent li{display:grid;grid-template-columns:64px minmax(0,1fr) auto 34px;gap:10px}.recent code{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--text)}.recent .bad{color:var(--k4)}.recent .ok{color:var(--k2)} \\.gap{height:14px}.people{display:flex;flex-wrap:wrap;gap:6px;margin:0 0 10px}.people a{padding:3px 9px;border:1px solid var(--line);border-radius:999px;color:var(--muted);font-size:11px;text-decoration:none}.people a[aria-current]{color:var(--text);border-color:var(--glass-b)} \\.share{display:grid;grid-template-columns:132px minmax(0,1fr);gap:18px;align-items:center}.donut{width:132px;height:132px}.donut path{stroke:var(--panel);stroke-width:2}.dl{fill:var(--dim);font-size:10px;text-anchor:middle}.dn{fill:var(--text);font-size:19px;font-weight:600;text-anchor:middle}.donut path:hover{opacity:.82} \\.al{display:grid;gap:7px;margin:0;padding:0;list-style:none}.al li{display:grid;grid-template-columns:10px minmax(0,1fr) auto;align-items:center;gap:2px 8px}.al i{width:10px;height:10px;margin:0;border-radius:3px}.al b{overflow:hidden;font-weight:500;text-overflow:ellipsis;white-space:nowrap}.al span{font-weight:600}.al em{grid-column:2/-1;margin-top:-3px;color:var(--dim);font-size:10.5px;font-style:normal} \\.foot{margin:8px 0 0;color:var(--dim);font-size:10.5px} \\:root{--a0:#7f9ef5;--a1:#35b874;--a2:#d9b13c;--a3:#b083e6;--a4:#e58b54;--a5:#4fbfc8;--a6:#8c867b}.a0{fill:var(--a0)}.a1{fill:var(--a1)}.a2{fill:var(--a2)}.a3{fill:var(--a3)}.a4{fill:var(--a4)}.a5{fill:var(--a5)}.a6{fill:var(--a6)} \\.al i.a0{color:var(--a0)}.al i.a1{color:var(--a1)}.al i.a2{color:var(--a2)}.al i.a3{color:var(--a3)}.al i.a4{color:var(--a4)}.al i.a5{color:var(--a5)}.al i.a6{color:var(--a6)}.al span{font-variant-numeric:tabular-nums} \\@media (max-width:700px){.tiles{grid-template-columns:repeat(2,minmax(0,1fr))}.split,.split.even{grid-template-columns:1fr}.stats-head .up{margin-left:0;width:100%}.recent li{grid-template-columns:56px minmax(0,1fr) auto}.recent li span:last-child{display:none}} ; const html_headers = [_]http.Header{ .{ .name = "content-type", .value = "text/html; charset=utf-8" }, .{ .name = "cache-control", .value = "no-store" }, .{ .name = "access-control-allow-origin", .value = "*" }, .{ .name = "access-control-allow-private-network", .value = "true" }, .{ .name = "connection", .value = "close" }, } ++ http_api.htmlSecurityHeaders(.{ .scripts = &([_][]const u8{ appearance_js, swap_js, icons.script } ++ skin.policy_scripts), .styles = &([_][]const u8{ landing_assets.css, style, icons.style } ++ skin.stats_policy_styles), });