:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>pgcollector</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/uPlot.min.css" integrity="sha384-IfV0B7MIOYuO95kO9G5ySKPz/85zqFNOAs8iy4tkK5zd9izhJAB8b7lHrwYqqmYE" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/uPlot.iife.min.js" integrity="sha384-Gx3t0zdBAuQOuvvmaLZj7HKEiSgWTAs+VdtNY7wt19QDPTDQjFIwAuXDj0zeN00c" crossorigin="anonymous"></script>
<style>
:root {
--bg: #14161a; --panel: #1c1f25; --panel2: #22262d; --border: #2c313a;
--text: #e6e8eb; --muted: #8b93a1; --accent: #7aa2f7; --ok: #6cc38b; --warn: #e0af68; --error: #f7768e; --tag: #c3a6ff;
--mono: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
* { box-sizing: border-box; }
html, body { margin: 0; height: 100%; }
body { background: var(--bg); color: var(--text); font: 13px/1.45 -apple-system, BlinkMacSystemFont, "Segoe UI", Inter, sans-serif; display: flex; flex-direction: column; }
a { color: var(--accent); text-decoration: none; } a:hover { text-decoration: underline; }
header { display: flex; align-items: center; gap: 14px; padding: 10px 16px; border-bottom: 1px solid var(--border); background: var(--panel); }
header .brand { font-weight: 700; letter-spacing: .3px; }
header .brand span { color: var(--muted); font-weight: 400; margin-left: 6px; }
header .spacer { flex: 1; }
header .me { color: var(--muted); font-size: 12px; }
select, input, button { background: var(--panel2); color: var(--text); border: 1px solid var(--border); border-radius: 6px; padding: 5px 9px; font-size: 12px; font-family: inherit; }
button { cursor: pointer; } button:hover { border-color: var(--accent); }
.layout { display: flex; flex: 1; min-height: 0; }
nav { width: 170px; flex: 0 0 170px; border-right: 1px solid var(--border); padding: 10px 0; background: var(--panel); overflow-y: auto; }
nav a { display: block; padding: 7px 16px; color: var(--muted); } nav a.active { color: var(--text); background: var(--panel2); border-right: 2px solid var(--accent); }
nav .group { padding: 10px 16px 4px; font-size: 10px; text-transform: uppercase; letter-spacing: .08em; color: var(--muted); }
main { flex: 1; overflow: auto; padding: 16px 20px; }
h1 { font-size: 16px; margin: 0 0 12px; } h1 .sub { color: var(--muted); font-weight: 400; font-size: 12px; margin-left: 8px; }
.toolbar { display: flex; gap: 8px; align-items: center; margin: 0 0 12px; flex-wrap: wrap; }
.grid { display: grid; gap: 12px; } .grid.two { grid-template-columns: 1fr 1fr; } .grid.tiles { grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); }
.panel { background: var(--panel); border: 1px solid var(--border); border-radius: 8px; padding: 12px 14px; min-width: 0; }
.panel h2 { margin: 0 0 8px; font-size: 11px; text-transform: uppercase; letter-spacing: .08em; color: var(--muted); }
.tile .v { font-size: 20px; font-weight: 600; font-family: var(--mono); } .tile .l { color: var(--muted); font-size: 11px; }
table { width: 100%; border-collapse: collapse; font-size: 12px; }
th, td { text-align: left; padding: 5px 8px; border-bottom: 1px solid var(--border); vertical-align: top; }
th { color: var(--muted); font-weight: 500; white-space: nowrap; cursor: pointer; user-select: none; } th.sorted { color: var(--text); }
td.num, th.num { text-align: right; font-family: var(--mono); white-space: nowrap; }
td.mono { font-family: var(--mono); } .muted { color: var(--muted); } .ok { color: var(--ok); } .warn { color: var(--warn); } .err { color: var(--error); }
.q { font-family: var(--mono); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 520px; display: block; }
.grid.two .q { max-width: 300px; } .panel.tight { overflow-x: auto; } .panel.tight .q { max-width: 240px; }
.nowrap { white-space: nowrap; } .small { font-size: 11px; }
pre { background: var(--bg); border: 1px solid var(--border); border-radius: 6px; padding: 10px; font-family: var(--mono); font-size: 11.5px; overflow: auto; white-space: pre-wrap; word-break: break-word; margin: 0; max-height: 420px; }
.error-box { padding: 10px 14px; color: var(--error); font-family: var(--mono); font-size: 12px; white-space: pre-wrap; border: 1px solid var(--error); border-radius: 6px; }
.empty { color: var(--muted); padding: 8px 0; }
.bar { display: inline-block; height: 8px; background: var(--accent); border-radius: 2px; vertical-align: middle; }
.chart { min-height: 160px; }
.uplot { font: 11px/1.4 inherit; width: 100%; }
.u-legend { font-size: 11px; color: var(--muted); text-align: left; margin: 2px 0 0; }
.u-legend .u-series > * { padding: 1px 4px; }
.u-legend .u-value { font-family: var(--mono); color: var(--text); min-width: 4ch; }
.u-legend .u-marker { width: 10px; height: 3px; margin-right: 6px; }
.u-select { background: rgba(122, 162, 247, .18); }
.u-hz .u-cursor-x { border-right: 1px dashed var(--muted); }
.u-cursor-pt { border-width: 0 !important; }
.marker { position: absolute; top: 0; bottom: 0; width: 0; border-left: 1px dashed var(--c); pointer-events: none; }
.marker i { position: absolute; top: -1px; left: -4px; width: 8px; height: 8px; background: var(--c); border-radius: 0 0 4px 4px; pointer-events: auto; cursor: help; }
.kv td:first-child { color: var(--muted); width: 180px; }
.pill { display: inline-block; padding: 1px 7px; border-radius: 10px; font-size: 11px; background: var(--panel2); border: 1px solid var(--border); }
.tags { display: flex; flex-wrap: wrap; gap: 2px 14px; margin-top: 3px; font-family: var(--mono); font-size: 11px; }
.tags:first-child { margin-top: 0; }
.tag { display: inline-block; vertical-align: top; color: var(--tag); max-width: 300px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.tag b { color: var(--muted); font-weight: 400; }
.chip { display: inline-flex; align-items: center; gap: 6px; padding: 3px 8px; border: 1px solid var(--accent); border-radius: 6px; font-family: var(--mono); font-size: 11px; }
.chip button { padding: 0 4px; border: 0; background: none; color: var(--muted); }
.clickable { cursor: pointer; } tr.clickable:hover td { background: var(--panel2); }
details summary { cursor: pointer; color: var(--muted); }
</style>
</head>
<body>
<header>
<div class="brand">pgcollector<span>Postgres telemetry</span></div>
<label>server <select id="server"></select></label>
<label>range <select id="range">
<option value="15m">15m</option><option value="1h" selected>1h</option><option value="6h">6h</option><option value="24h">24h</option><option value="7d">7d</option>
</select></label>
<button id="zoomout" title="widen the selected range" hidden>zoom out</button>
<button id="refresh" title="reload">↻</button>
<div class="spacer"></div>
<div class="me" id="me"></div>
</header>
<div class="layout">
<nav id="nav"></nav>
<main id="main"></main>
</div>
<script>
(() => {
// ---------- state & routing ----------
const PAGES = [
['overview', 'Overview'], ['queries', 'Queries'], ['activity', 'Activity'], ['waits', 'Wait events'], ['locks', 'Locks'],
['tables', 'Tables'], ['indexes', 'Indexes'], ['vacuum', 'Vacuum'], ['events', 'Events'], ['logs', 'Logs'],
['cpu', 'CPU'], ['checkpoints', 'Checkpoints'], ['schema', 'Schema'], ['settings', 'Settings'], ['collector', 'Collector health'],
];
const state = { servers: [], server: null, page: 'overview', params: {}, range: '1h', build: null };
const $ = (s, r = document) => r.querySelector(s);
const el = (tag, attrs = {}, ...kids) => {
const e = document.createElement(tag);
for (const [k, v] of Object.entries(attrs)) { if (k === 'class') e.className = v; else if (k.startsWith('on')) e.addEventListener(k.slice(2), v); else if (v != null) e.setAttribute(k, v); }
for (const k of kids.flat()) if (k != null) e.append(k.nodeType ? k : document.createTextNode(String(k)));
return e;
};
function parseHash() {
const m = location.hash.match(/^#\/([^/]+)\/([^?]+)(?:\?(.*))?$/);
if (!m) return null;
return { server: decodeURIComponent(m[1]), page: m[2], params: Object.fromEntries(new URLSearchParams(m[3] || '')) };
}
// A custom range (from/to, set by dragging on a chart) follows the user across pages like the preset does; pass from: null to drop it.
function hashFor(page, params = {}, server = state.server) {
const { from, to } = state.params;
const merged = Object.entries({ from, to, ...params }).filter(([, v]) => v != null && v !== '');
const qs = new URLSearchParams(merged).toString();
return `#/${encodeURIComponent(server)}/${page}${qs ? '?' + qs : ''}`;
}
function go(page, params = {}, server = state.server) { location.hash = hashFor(page, params, server); }
const customRange = () => state.params.from && state.params.to ? { from: state.params.from, to: state.params.to } : null;
const rangeQuery = () => customRange() || { since: state.range };
const PRESET_MS = { '15m': 9e5, '1h': 36e5, '6h': 216e5, '24h': 864e5, '7d': 6048e5 };
const spanMs = () => { const c = customRange(); return c ? new Date(c.to) - new Date(c.from) : PRESET_MS[state.range]; };
function zoomTo(fromMs, toMs) { go(state.page, { ...state.params, from: new Date(fromMs).toISOString(), to: new Date(toMs).toISOString() }); }
// Doubles the custom range around its centre. It returns to the preset only when the preset is at least as
// wide as the doubled span, so zooming out never narrows the view (the preset is whatever the select shows,
// which after a reload with a custom range in the URL is just the default).
function zoomOut() {
const c = customRange();
if (!c) return;
const from = +new Date(c.from), to = +new Date(c.to), span = to - from;
const to2 = Math.min(Date.now(), to + span / 2), from2 = Math.max(to2 - span * 2, to2 - 31 * 864e5);
if (PRESET_MS[state.range] >= to2 - from2) go(state.page, { ...state.params, from: null, to: null });
else zoomTo(from2, to2);
}
// ---------- api & formatting ----------
async function api(path, params = {}) {
const qs = new URLSearchParams(Object.entries(params).filter(([, v]) => v != null && v !== '')).toString();
const r = await fetch(`/api/v1${path}${qs ? '?' + qs : ''}`, { headers: { accept: 'application/json' } });
// The page only ever hash-navigates, so this is the one place it can notice a deploy.
const build = r.headers.get('x-pgapi-build');
if (build && state.build && state.build !== build) location.reload();
state.build = build;
if (!r.ok) { let msg = `${r.status} ${r.statusText}`; try { msg += ': ' + (await r.json()).error; } catch {} throw new Error(msg); }
return r.json();
}
const fmt = {
num: v => v == null ? '–' : Number(v).toLocaleString(undefined, { maximumFractionDigits: 0 }),
dec: (v, d = 2) => v == null ? '–' : Number(v).toLocaleString(undefined, { maximumFractionDigits: d, minimumFractionDigits: 0 }),
ms: v => v == null ? '–' : v === 0 ? '0 ms' : (v >= 1000 ? (v / 1000).toFixed(2) + ' s' : v >= 10 ? v.toFixed(1) + ' ms' : v.toFixed(3) + ' ms'),
bytes: v => { if (v == null) return '–'; const u = ['B', 'KB', 'MB', 'GB', 'TB']; let i = 0; v = Number(v); while (v >= 1024 && i < u.length - 1) { v /= 1024; i++; } return v.toFixed(i ? 1 : 0) + ' ' + u[i]; },
pct: v => v == null ? '–' : Number(v).toFixed(1) + '%',
ago: t => { if (!t) return '–'; const s = (Date.now() - new Date(t)) / 1000; if (s < 90) return Math.round(s) + 's ago'; if (s < 5400) return Math.round(s / 60) + 'm ago'; if (s < 172800) return Math.round(s / 3600) + 'h ago'; return Math.round(s / 86400) + 'd ago'; },
ts: t => t ? new Date(t).toLocaleString(undefined, { hour12: false }) : '–',
time: t => t ? new Date(t).toLocaleTimeString(undefined, { hour12: false }) : '–',
ratio: v => v == null ? '–' : el('span', { class: v >= 1 ? 'err' : v >= 0.7 ? 'warn' : '' }, Number(v).toFixed(2)),
};
// ---------- generic table ----------
// cols: [{key, label, fmt?, num?, sort?(row)->number, render?(row)->node, cls?}]
function table(rows, cols, { sortKey, desc = true, onRow, empty = 'nothing in this range', limit } = {}) {
if (!rows || !rows.length) return el('div', { class: 'empty' }, empty);
let sk = sortKey, sd = desc;
const wrap = el('div');
const render = () => {
const sorted = [...rows];
if (sk) { const c = cols.find(c => c.key === sk); const get = c && c.sort ? c.sort : r => r[sk]; sorted.sort((a, b) => { const x = get(a), y = get(b); if (x == null) return 1; if (y == null) return -1; return (typeof x === 'number' ? x - y : String(x).localeCompare(String(y))) * (sd ? -1 : 1); }); }
const shown = limit ? sorted.slice(0, limit) : sorted;
const t = el('table', {},
el('thead', {}, el('tr', {}, cols.map(c => el('th', { class: (c.num ? 'num ' : '') + (sk === c.key ? 'sorted' : ''), onclick: () => { if (sk === c.key) sd = !sd; else { sk = c.key; sd = true; } render(); } }, c.label, sk === c.key ? (sd ? ' ▾' : ' ▴') : '')))),
el('tbody', {}, shown.map(r => el('tr', { class: onRow ? 'clickable' : '', onclick: onRow ? () => onRow(r) : null }, cols.map(c => {
const v = c.render ? c.render(r) : c.fmt ? c.fmt(r[c.key], r) : r[c.key];
return el('td', { class: (c.num ? 'num ' : '') + (c.cls || '') }, v == null ? el('span', { class: 'muted' }, '–') : v);
})))));
wrap.replaceChildren(...[t, limit && rows.length > limit ? el('div', { class: 'muted', style: 'padding:6px 8px' }, `showing ${limit} of ${rows.length}`) : null].filter(Boolean));
};
render();
return wrap;
}
const panel = (title, ...kids) => el('div', { class: 'panel' }, title ? el('h2', {}, title) : null, ...kids);
const tile = (label, value, cls = '') => el('div', { class: 'panel tile' }, el('div', { class: 'v ' + cls }, value ?? '–'), el('div', { class: 'l' }, label));
const queryCell = q => el('span', { class: 'q', title: q || '' }, q || el('span', { class: 'muted' }, '(text not captured)'));
// Tags label a query by the code that ran it (/* nodejs:PERSONS_WRITE<updatePersonsBatch> */, /* route='/api/x' */).
const TAG_ORDER = ['service', 'db_use', 'operation', 'caller', 'route', 'controller', 'task', 'workflow', 'query_type', 'purpose', 'team_id'];
const tagEntries = tags => tags ? Object.entries(tags).sort(([a], [b]) => (TAG_ORDER.indexOf(a) + 1 || 99) - (TAG_ORDER.indexOf(b) + 1 || 99)) : [];
const tagPills = (tags, max = 5) => { const e = tagEntries(tags); if (!e.length) return null; return el('div', { class: 'tags' }, e.slice(0, max).map(([k, v]) => el('span', { class: 'tag', title: `${k}=${v}` }, el('b', {}, k + '='), v)), e.length > max ? el('span', { class: 'muted' }, `+${e.length - max}`) : null); };
// The row label: SQL first, the tags of the code that ran it on a quieter line underneath.
const queryLabel = r => el('span', {}, queryCell(r.query), tagPills(r.tags));
const tagFilterChip = (tags, onClear) => tags ? el('span', { class: 'chip' }, tags, el('button', { title: 'clear tag filter', onclick: onClear }, '✕')) : null;
// ---------- time series chart (uPlot) ----------
// series: [{name, color, points: [[Date, number | null]]}]; a null y breaks the line.
// missing: what a bucket that a series has no point for counts as. 0 suits counts and
// rates (nothing happened); null suits gauges and latency (nothing was measured) and draws a gap.
// stacked: every series is drawn as a bar on top of the ones before it, one bar per bucket, so missing is always 0.
// Every chart on a page shares one cursor, and dragging across any of them sets the range.
const charts = [];
// Markers for the events in range are fetched once per page and drawn on every chart on it. The
// routine kinds (pg_stat_statements evictions, cancelled statements, lock waits) would smother the rest, so they are left out.
let markerEvents = Promise.resolve([]);
const MARKER_EXCLUDE = 'pgss_dealloc,log_cancel,log_lock%';
const markerColor = k => k.startsWith('settings') ? '#e0af68' : k.startsWith('schema') || k.startsWith('extensions') ? '#7aa2f7' : k.startsWith('log_') ? '#f7768e' : '#8b93a1';
function loadMarkers() {
markerEvents = api(`/servers/${state.server}/events`, { ...rangeQuery(), exclude: MARKER_EXCLUDE, limit: 500 }).catch(() => []);
}
function drawMarkers(u, events) {
for (const m of u.over.querySelectorAll('.marker')) m.remove();
const { min, max } = u.scales.x;
for (const e of events) {
const x = +new Date(e.at) / 1000;
if (x < min || x > max) continue;
const title = `${e.kind}: ${e.subject}${e.datname ? ` (${e.datname})` : ''}\n${fmt.ts(e.at)}`;
u.over.append(el('div', { class: 'marker', style: `left:${u.valToPos(x, 'x')}px; --c:${markerColor(e.kind)}` }, el('i', { title })));
}
}
const BARS = typeof uPlot === 'undefined' ? null : uPlot.paths.bars({ size: [0.85, 40], gap: 1 });
const AXIS = { stroke: '#8b93a1', font: '11px -apple-system, BlinkMacSystemFont, "Segoe UI", Inter, sans-serif', grid: { stroke: '#2c313a', width: 1 }, ticks: { stroke: '#2c313a', width: 1 } };
function chart(series, { yfmt = v => fmt.dec(v, 1), stacked = false, missing = 0, height = 170 } = {}) {
if (stacked) series = [...series.filter(s => !s.line), ...series.filter(s => s.line)];
if (typeof uPlot === 'undefined') return el('div', { class: 'empty' }, 'Charts need cdn.jsdelivr.net, which this browser could not load. The tables below still work.');
if (!series.some(s => s.points.some(p => p[1] != null))) return el('div', { class: 'empty' }, 'no data points');
const sec = t => Math.floor(+t / 1000);
const xs = padGaps([...new Set(series.flatMap(s => s.points.map(p => sec(p[0]))))].sort((a, b) => a - b));
const at = new Map(xs.map((x, i) => [x, i]));
const raw = series.map(s => { const col = Array(xs.length).fill(s.line ? null : stacked ? 0 : missing); for (const [t, v] of s.points) if (v != null) col[at.get(sec(t))] = v; return col; });
// Band [upper, lower] clips the upper series' fill to its own layer; the lowest visible series fills down to zero on its own.
// Hidden series are left out of the running total, so toggling one in the legend restacks the rest. Line series
// stay unstacked and sit after the stacked ones, so the band indexes stay contiguous.
const stack = show => {
const acc = Array(xs.length).fill(0);
const inStack = i => !series[i].line && show(i);
const data = raw.map((col, i) => inStack(i) ? col.map((v, j) => (acc[j] += v)) : col);
const vis = raw.map((_, i) => i).filter(inStack);
return { data, bands: vis.slice(1).map((si, k) => ({ series: [si + 1, vis[k] + 1] })) };
};
let { data, bands } = stacked ? stack(() => true) : { data: raw, bands: [] };
const restack = u => { const { data, bands } = stack(i => u.series[i + 1].show); u.delBand(null); bands.forEach(b => u.addBand(b)); u.setData([xs, ...data]); };
// Bars are centered on their bucket, so the first and last would be cut in half without half a bucket of room at each end.
const half = xs.length > 1 ? xs.slice(1).reduce((min, x, i) => Math.min(min, x - xs[i]), Infinity) / 2 : 0;
const opts = {
width: 600, height, bands,
cursor: { y: false, sync: { key: 'page', setSeries: false }, drag: { x: true, y: false, setScale: false, dist: 4 }, points: { size: 6 }, bind: { dblclick: () => () => zoomOut() } },
legend: { live: true },
scales: { x: { time: true, range: stacked && xs.length > 1 ? (u, min, max) => [min - half, max + half] : undefined }, y: { range: (u, min, max) => [0, max > 0 ? uPlot.rangeNum(0, max, 0.1, true)[1] : 1] } },
axes: [{ ...AXIS }, { ...AXIS, size: 60, values: (u, vals) => vals.map(yfmt) }],
series: [
{ value: (u, v) => v == null ? '' : fmt.ts(new Date(v * 1000)) },
...series.map(s => {
const bar = stacked && !s.line;
return { label: s.name, stroke: s.color, width: bar ? 0 : 1.5, points: { show: false }, dash: s.line ? [4, 4] : null, fill: bar ? s.color + 'cc' : null, paths: bar ? BARS : undefined, spanGaps: !!s.line, value: (u, v, si, di) => di == null || raw[si - 1][di] == null ? '–' : yfmt(raw[si - 1][di]) };
}),
],
hooks: { setSeries: stacked ? [restack] : [], draw: [u => markerEvents.then(ev => drawMarkers(u, ev))], setSelect: [u => {
if (u.select.width < 4) return;
const from = u.posToVal(u.select.left, 'x'), to = u.posToVal(u.select.left + u.select.width, 'x');
u.setSelect({ width: 0, height: 0 }, false);
zoomTo(from * 1000, to * 1000);
}] },
};
const wrap = el('div', { class: 'chart' });
let u = null;
// The panel is not in the document yet, so the width is only known once it is laid out.
const ro = new ResizeObserver(([e]) => {
const width = Math.floor(e.contentRect.width);
if (width <= 0) return;
if (!u) { u = new uPlot({ ...opts, width }, [xs, ...data], wrap); charts.push({ u, ro }); } else u.setSize({ width, height });
});
ro.observe(wrap);
return wrap;
}
// A bucket that no series has a point for is absent from the x values, and the line would bridge it as if
// nothing happened. Gaps wider than 2.5 times the typical spacing get synthetic x values, which take the
// chart's missing value like any other absent bucket.
function padGaps(xs) {
if (xs.length < 3) return xs;
const steps = xs.slice(1).map((x, i) => x - xs[i]).sort((a, b) => a - b), step = steps[steps.length >> 1];
const out = [xs[0]];
for (const x of xs.slice(1)) {
let prev = out[out.length - 1];
if (x - prev > step * 2.5) for (prev += step; prev < x - step / 2 && out.length < 5000; prev += step) out.push(prev);
out.push(x);
}
return out;
}
function destroyCharts() { for (const c of charts.splice(0)) { c.ro.disconnect(); c.u.destroy(); } }
const COLORS = ['#7aa2f7', '#6cc38b', '#e0af68', '#f7768e', '#bb9af7', '#7dcfff', '#ff9e64', '#9ece6a'];
const bucketFor = () => { const s = spanMs(); return s <= 30 * 60e3 ? '10s' : s <= 6 * 3600e3 ? '1m' : s <= 36 * 3600e3 ? '5m' : '1h'; };
const BUCKET_LABEL = { '10s': '10 seconds', '1m': 'minute', '5m': '5 minutes', '1h': 'hour' };
// ---------- pages ----------
const pages = {};
const sv = () => state.servers.find(s => s.server_id === state.server) || {};
const dbSelect = (onchange) => { const dbs = sv().databases || []; const cur = state.params.datname || dbs[0] || ''; const s = el('select', { onchange: e => onchange(e.target.value) }, dbs.map(d => el('option', { value: d, selected: d === cur ? '' : null }, d))); return [s, cur]; };
pages.overview = async () => {
const bucket = bucketFor();
const [d, load] = await Promise.all([api(`/servers/${state.server}/overview`, { ...rangeQuery() }), api(`/servers/${state.server}/load`, { ...rangeQuery(), bucket })]);
const byType = {};
for (const r of load.series) (byType[r.wait_event_type] ||= []).push([new Date(r.bucket), r.avg_active_sessions]);
const loadSeries = Object.entries(byType).sort(([a], [b]) => (a === 'CPU') - (b === 'CPU') || a.localeCompare(b)).reverse()
.map(([k, pts], i) => ({ name: k, color: k === 'CPU' ? COLORS[1] : COLORS[(i + 2) % COLORS.length], points: pts }));
const ncpu = load.host.reduce((a, h) => a + (h.ncpu || 0), 0);
if (ncpu && load.series.length) { const ts = load.series.map(r => new Date(r.bucket)); loadSeries.push({ name: 'vCPUs', color: '#8b93a1', line: true, points: [[new Date(Math.min(...ts)), ncpu], [new Date(Math.max(...ts)), ncpu]] }); }
const conns = d.connections.reduce((a, c) => { a[c.state] = (a[c.state] || 0) + c.backends; return a; }, {});
const dbs = d.databases;
const sum = k => dbs.reduce((a, r) => a + (r[k] || 0), 0);
const hit = (() => { const h = sum('blks_hit'), r = sum('blks_read'); return h + r ? h / (h + r) * 100 : null; })();
return [
el('h1', {}, state.server, el('span', { class: 'sub' }, `${sv().version || ''} · ${fmt.ago(sv().last_collected_at)}`)),
el('div', { class: 'grid tiles' },
tile('connections (active)', conns.active ?? 0), tile('connections (idle)', conns.idle ?? 0), tile('idle in transaction', conns['idle in transaction'] ?? 0),
tile('commits', fmt.num(sum('xact_commit'))), tile('rollbacks', fmt.num(sum('xact_rollback'))), tile('cache hit', hit == null ? '–' : hit.toFixed(2) + '%', hit != null && hit < 95 ? 'warn' : ''),
tile('deadlocks', fmt.num(sum('deadlocks')), sum('deadlocks') ? 'err' : ''), tile('temp bytes', fmt.bytes(sum('temp_bytes'))), tile('max xid age', fmt.num(Math.max(0, ...dbs.map(r => r.xid_age || 0)))),
),
el('div', { style: 'margin-top:12px' }, panel(`Database load (average active sessions per ${BUCKET_LABEL[bucket] || bucket}, by wait type)`, chart(loadSeries, { stacked: true, yfmt: v => fmt.dec(v, 2) }))),
el('div', { class: 'grid two', style: 'margin-top:12px' },
panel('Top queries by total time', table(d.top_queries, [
{ key: 'query', label: 'query', render: r => el('a', { href: hashFor('query', { queryid: r.queryid, datname: r.datname }) }, queryLabel(r)) },
{ key: 'calls', label: 'calls', num: true, fmt: fmt.num }, { key: 'mean_ms', label: 'mean', num: true, fmt: fmt.ms }, { key: 'pct_of_total_time', label: '% time', num: true, fmt: fmt.pct },
])),
panel('Top wait events (active sessions, sampled)', table(d.top_wait_events, [
{ key: 'wait_event_type', label: 'type', fmt: v => v || 'CPU' }, { key: 'wait_event', label: 'event', fmt: v => v || '–' }, { key: 'samples', label: 'samples', num: true, fmt: fmt.num },
])),
panel('Databases', table(dbs, [
{ key: 'datname', label: 'database' }, { key: 'instance', label: 'instance' }, { key: 'xact_commit', label: 'commits', num: true, fmt: fmt.num }, { key: 'cache_hit_pct', label: 'cache hit', num: true, fmt: fmt.pct },
{ key: 'tup_inserted', label: 'ins', num: true, fmt: fmt.num }, { key: 'tup_updated', label: 'upd', num: true, fmt: fmt.num }, { key: 'tup_deleted', label: 'del', num: true, fmt: fmt.num }, { key: 'xid_age', label: 'xid age', num: true, fmt: fmt.num },
])),
panel('Events in range', table(d.events, [{ key: 'kind', label: 'kind', render: r => el('a', { href: hashFor('events', { kind: r.kind }) }, r.kind) }, { key: 'n', label: 'count', num: true, fmt: fmt.num }])),
panel('Vacuum attention', table(d.vacuum_attention, [
{ key: 'datname', label: 'db' }, { key: 'relname', label: 'table' }, { key: 'vacuum_ratio', label: 'dead / threshold', num: true, render: r => fmt.ratio(r.vacuum_ratio) }, { key: 'freeze_ratio', label: 'freeze', num: true, render: r => fmt.ratio(r.freeze_ratio) }, { key: 'autovacuum_enabled', label: 'autovac', fmt: v => v ? 'on' : el('span', { class: 'err' }, 'off') },
], { empty: 'no tables past 100% of their vacuum threshold' })),
),
];
};
pages.queries = async () => {
const order = state.params.order || 'total_exec_time';
const group = state.params.group || '';
const tagFilter = state.params.tags || '';
const orders = [['total_exec_time', 'total time'], ['calls', 'calls'], ['mean_exec_time', 'mean time'], ['rows', 'rows'], ['shared_blks_read', 'blocks read'], ['wal_bytes', 'WAL bytes'], ['storage_blks_read', 'Aurora storage reads']];
const [dbsel] = dbSelect(v => go('queries', { ...state.params, datname: v }));
dbsel.prepend(el('option', { value: '', selected: state.params.datname ? null : '' }, 'all databases'));
const [rows, tagged] = await Promise.all([
group ? null : api(`/servers/${state.server}/queries`, { ...rangeQuery(), order, limit: 200, datname: state.params.datname, tags: tagFilter }),
api(`/servers/${state.server}/tags`, { ...rangeQuery(), key: group, datname: state.params.datname, limit: 200 }),
]);
const keys = (tagged.keys || []).map(k => k.key);
const groupSel = el('select', { onchange: e => { const p = { ...state.params, group: e.target.value }; if (p.group) delete p.tags; go('queries', p); } },
el('option', { value: '', selected: group ? null : '' }, 'query'),
keys.map(k => el('option', { value: k, selected: k === group ? '' : null }, `tag: ${k}`)),
group && !keys.includes(group) ? el('option', { value: group, selected: '' }, `tag: ${group}`) : null);
const toolbar = el('div', { class: 'toolbar' },
el('label', {}, 'group by ', groupSel),
group ? null : el('label', {}, 'order by ', el('select', { onchange: e => go('queries', { ...state.params, order: e.target.value }) }, orders.map(([v, l]) => el('option', { value: v, selected: v === order ? '' : null }, l)))),
el('label', {}, 'database ', dbsel),
tagFilterChip(tagFilter, () => { const p = { ...state.params }; delete p.tags; go('queries', p); }));
if (group) {
const samp = tagged.log_sampling || {};
const sub = samp.enabled ? 'load per code path: active sessions from 10s samples, calls and latency from sampled statement logs' : 'load per code path from 10s activity samples (statement log sampling is off, so no calls or latency)';
return [
el('h1', {}, 'Queries by tag ', el('span', { class: 'mono' }, group), el('span', { class: 'sub' }, sub)),
toolbar,
panel(null, table(tagged.groups, [
{ key: 'value', label: group, render: r => el('span', { class: 'tag', title: r.value }, r.value) },
{ key: 'avg_active_sessions', label: 'avg active sessions', num: true, fmt: v => fmt.dec(v, 2) },
{ key: 'active_over_10s', label: 'samples > 10s', num: true, fmt: fmt.num },
{ key: 'distinct_queries', label: 'queries', num: true, render: r => fmt.num(r.distinct_queries ?? r.distinct_statements) },
{ key: 'est_calls', label: 'est. calls', num: true, fmt: fmt.num }, { key: 'est_total_ms', label: 'est. total', num: true, fmt: fmt.ms },
{ key: 'p50', label: 'p50', num: true, fmt: fmt.ms }, { key: 'p95', label: 'p95', num: true, fmt: fmt.ms }, { key: 'p99', label: 'p99', num: true, fmt: fmt.ms }, { key: 'max_ms', label: 'max', num: true, fmt: fmt.ms },
], { sortKey: 'avg_active_sessions', onRow: r => { const p = { ...state.params, tags: `${group}=${encodeURIComponent(r.value)}` }; delete p.group; go('queries', p); }, empty: 'no tagged activity in this range (queries need a /* key=value */ comment)' })),
];
}
return [
el('h1', {}, 'Queries', el('span', { class: 'sub' }, tagFilter ? 'pg_stat_statements totals for queries seen with this tag; the totals include every caller of each query' : 'pg_stat_statements, per-interval deltas summed over the range')),
toolbar,
panel(null, table(rows, [
{ key: 'query', label: 'query', render: queryLabel },
{ key: 'datname', label: 'db' }, { key: 'rolname', label: 'role' },
{ key: 'calls', label: 'calls', num: true, fmt: fmt.num }, { key: 'total_ms', label: 'total', num: true, fmt: fmt.ms }, { key: 'mean_ms', label: 'mean', num: true, fmt: fmt.ms }, { key: 'stddev_ms', label: 'stddev', num: true, fmt: fmt.ms },
{ key: 'rows', label: 'rows', num: true, fmt: fmt.num }, { key: 'shared_blks_read', label: 'blks read', num: true, fmt: fmt.num }, { key: 'pct_of_total_time', label: '% time', num: true, render: r => el('span', {}, el('span', { class: 'bar', style: `width:${Math.min(100, r.pct_of_total_time || 0)}px` }), ' ', fmt.pct(r.pct_of_total_time)) },
], { onRow: r => go('query', { queryid: r.queryid, ...(r.datname ? { datname: r.datname } : {}) }), empty: tagFilter ? 'no queries seen with this tag in the range' : 'nothing in this range' })),
];
};
pages.query = async () => {
const qid = state.params.queryid;
const bucket = bucketFor();
const d = await api(`/servers/${state.server}/queries/${qid}`, { ...rangeQuery(), bucket, datname: state.params.datname });
const t = d.texts[0] || {};
const byBucket = {};
for (const r of d.series) { const k = r.bucket; (byBucket[k] ||= { calls: 0, total: 0 }); byBucket[k].calls += r.calls || 0; byBucket[k].total += r.total_ms || 0; }
const pts = Object.entries(byBucket).map(([m, v]) => [new Date(m), v]);
const lat = d.latency_from_logs;
const per = BUCKET_LABEL[bucket] || bucket;
// A quantile needs roughly 1/(1-q) samples before it is more than the bucket's max, so each line skips buckets below its own floor.
// Buckets below a line's floor become null points, which chart() draws as gaps rather than bridging.
const QUANTILES = [['p50', COLORS[0], 5], ['p90', COLORS[4], 20], ['p99', COLORS[3], 100]];
const qseries = lat ? QUANTILES.map(([k, color, min]) => ({ name: k, color, points: (d.latency_series || []).map(r => [new Date(r.bucket), r.sampled >= min ? r[k] : null]) })).filter(s => s.points.some(p => p[1] != null)) : [];
const samp = d.log_sampling || {};
const latencyNote = lat
? `${fmt.num(lat.samples)} sampled statements in range (${fmt.dec(samp.rate * 100, 1)}% sample${samp.sample_floor_ms > 0 ? ` of statements over ${fmt.ms(samp.sample_floor_ms)}` : ''}) · range p50 ${fmt.ms(lat.p50)} · p90 ${fmt.ms(lat.p90)} · p99 ${fmt.ms(lat.p99)} · max ${fmt.ms(lat.max_ms)}`
: samp.enabled === false ? 'mean only: statement sampling is off on this server (log_min_duration_sample / log_statement_sample_rate)'
: 'mean only: no sampled durations in this range (needs log_min_duration_sample and the logs collector)';
return [
el('h1', {}, 'Query ', el('span', { class: 'mono' }, qid), el('span', { class: 'sub' }, t.datname || '')),
panel('Text', el('pre', {}, t.query || '(not captured yet)'), t.truncated ? el('div', { class: 'muted' }, 'truncated at 10 KB') : null, tagPills(t.tags, 12) ? el('div', { style: 'margin-top:8px' }, tagPills(t.tags, 12), el('div', { class: 'muted small' }, 'tags on the first call seen')) : null),
el('div', { class: 'grid two', style: 'margin-top:12px' },
panel(`Calls per ${per}`, chart([{ name: 'calls', color: COLORS[0], points: pts.map(([m, v]) => [m, v.calls]) }], { yfmt: fmt.num })),
panel(`Latency per ${per}`,
chart([{ name: 'mean', color: COLORS[2], points: pts.map(([m, v]) => [m, v.calls ? v.total / v.calls : null]) }, ...qseries], { yfmt: v => fmt.ms(v), missing: null }),
el('div', { class: 'muted', style: 'margin-top:6px; font-size:11px' }, latencyNote)),
panel('Wait events while running', table(d.wait_events, [{ key: 'wait_event_type', label: 'type', fmt: v => v || 'CPU' }, { key: 'wait_event', label: 'event', fmt: v => v || '–' }, { key: 'samples', label: 'samples', num: true, fmt: fmt.num }])),
panel('Callers (tags seen while running)', table(d.callers, [
{ key: 'tags', label: 'tags', render: r => tagPills(r.tags, 8) }, { key: 'source', label: 'source', fmt: v => v === 'activity' ? 'activity samples' : 'statement log' },
{ key: 'samples', label: 'samples', num: true, fmt: fmt.num }, { key: 'share_pct', label: 'share', num: true, render: r => el('span', {}, el('span', { class: 'bar', style: `width:${Math.min(100, r.share_pct || 0)}px` }), ' ', fmt.pct(r.share_pct)) },
], { empty: 'no tagged samples in range (queries need a /* key=value */ comment)' })),
),
el('div', { style: 'margin-top:12px' }, panel('Slowest logged samples', table(d.slowest_samples, [{ key: 'log_time', label: 'time', fmt: fmt.ts }, { key: 'log_stream', label: 'instance' }, { key: 'usename', label: 'user' }, { key: 'duration_ms', label: 'duration', num: true, fmt: fmt.ms }, { key: 'tags', label: 'tags', render: r => tagPills(r.tags, 4) }, { key: 'trace_id', label: 'trace', cls: 'mono', render: r => r.trace_id ? el('span', { title: r.trace_id }, r.trace_id.slice(0, 12) + '…') : null }, { key: 'query', label: 'statement', render: r => queryCell(r.query) }]))),
el('div', { style: 'margin-top:12px' }, panel('Execution plans (Aurora plan stats)', d.plans.length ? d.plans.map(p => el('details', { open: '' }, el('summary', {}, `plan ${p.planid} · ${p.plan_type} · calls ${fmt.num(p.calls)} · total ${fmt.ms(p.total_ms)} · captured ${fmt.ago(p.plan_captured_time)}`), el('pre', {}, p.explain_plan || ''))) : el('div', { class: 'empty' }, 'no plans (aurora_stat_plans is Aurora-only)'))),
el('div', { style: 'margin-top:12px' }, panel('auto_explain plans from the log', d.logged_plans.length ? d.logged_plans.map(p => el('details', {}, el('summary', {}, `${fmt.ts(p.log_time)} · ${fmt.ms(p.duration_ms)} · ${p.datname}`), el('pre', {}, JSON.stringify(p.plan, null, 2)))) : el('div', { class: 'empty' }, 'none in range'))),
];
};
pages.activity = async () => {
const d = await api(`/servers/${state.server}/activity`);
return [
el('h1', {}, 'Activity', el('span', { class: 'sub' }, 'latest 10s sample')),
el('div', { class: 'grid two' },
panel('Connections by state', table(d.connections, [{ key: 'instance', label: 'instance' }, { key: 'datname', label: 'db' }, { key: 'state', label: 'state' }, { key: 'backends', label: 'backends', num: true, fmt: fmt.num }])),
panel('Lock waits (blocking graph)', table(d.lock_waits, [{ key: 'waiter_pid', label: 'waiter', num: true }, { key: 'waiting_s', label: 'waiting', num: true, fmt: v => fmt.dec(v, 0) + ' s' }, { key: 'wanted_mode', label: 'mode' }, { key: 'relation', label: 'relation' }, { key: 'blocker_pid', label: 'blocker', num: true }, { key: 'blocker_state', label: 'blocker state' }, { key: 'blocker_query', label: 'blocker query', render: r => queryCell(r.blocker_query) }], { empty: 'nothing blocked' })),
),
el('div', { style: 'margin-top:12px' }, panel('Long-running / waiting / idle-in-transaction sessions', table(d.sessions, [
{ key: 'pid', label: 'pid', num: true }, { key: 'instance', label: 'instance' }, { key: 'datname', label: 'db' }, { key: 'usename', label: 'user' }, { key: 'application_name', label: 'app' }, { key: 'state', label: 'state' },
{ key: 'wait_event_type', label: 'wait', fmt: (v, r) => v ? `${v}:${r.wait_event}` : 'CPU' }, { key: 'query_age_s', label: 'query age', num: true, fmt: v => fmt.dec(v, 0) + ' s' }, { key: 'xact_age_s', label: 'xact age', num: true, fmt: v => fmt.dec(v, 0) + ' s' }, { key: 'blocked_by', label: 'blocked by' },
{ key: 'query', label: 'query', render: queryLabel },
], { empty: 'no interesting sessions right now' }))),
d.memory_hogs.length ? el('div', { style: 'margin-top:12px' }, panel('Backends over 64 MB (Aurora memory contexts)', table(d.memory_hogs, [{ key: 'pid', label: 'pid', num: true }, { key: 'usename', label: 'user' }, { key: 'allocated_bytes', label: 'allocated', num: true, fmt: fmt.bytes }, { key: 'top_context', label: 'largest context' }, { key: 'query', label: 'query', render: r => queryCell(r.query) }]))) : null,
];
};
pages.waits = async () => {
const d = await api(`/servers/${state.server}/waits`, { ...rangeQuery(), bucket: bucketFor() });
const byEv = {};
for (const r of d.sampled) { const k = `${r.wait_event_type}:${r.wait_event}`; (byEv[k] ||= []).push([new Date(r.bucket), r.avg_active_sessions]); }
const top = Object.entries(byEv).map(([k, pts]) => [k, pts.reduce((a, p) => a + p[1], 0), pts]).sort((a, b) => b[1] - a[1]).slice(0, 8);
return [
el('h1', {}, 'Wait events', el('span', { class: 'sub' }, 'average active sessions by wait event (10s samples)')),
panel('Top wait events over time', chart(top.map(([k, , pts], i) => ({ name: k, color: COLORS[i % COLORS.length], points: pts })), { yfmt: v => fmt.dec(v, 1) })),
d.measured_aurora.length ? el('div', { style: 'margin-top:12px' }, panel('Measured wait time (Aurora, exact)', table(d.measured_aurora, [{ key: 'instance', label: 'instance' }, { key: 'type_name', label: 'type' }, { key: 'event_name', label: 'event' }, { key: 'waits', label: 'waits', num: true, fmt: fmt.num }, { key: 'wait_time_us', label: 'time', num: true, fmt: v => fmt.ms(v / 1000) }]))) : null,
];
};
const secs = v => v == null ? '–' : v >= 3600 ? (v / 3600).toFixed(1) + ' h' : v >= 90 ? Math.round(v / 60) + ' min' : Math.round(v) + ' s';
const pidCell = (pid, user, app) => el('span', { class: 'nowrap' }, el('span', { class: 'mono' }, pid), user || app ? [el('br'), el('span', { class: 'muted small' }, [user, app].filter(Boolean).join(' · '))] : null);
const lockCell = r => el('span', { class: 'nowrap' }, r.locktype || '–', el('br'), el('span', { class: 'muted small' }, r.wanted_mode || ''), r.relation ? [el('br'), el('span', { class: 'mono small' }, r.relation)] : null);
// Consecutive 10 s samples with the same state, statement, wait and blocker collapse into one span, so a
// blocker's history reads as "ran X for 8 s, then sat idle in transaction for 15 min". A gap over 30 s or a
// different backend_start (the pid was reused) starts a new span rather than bridging what was not sampled.
function sessionSpans(rows) {
const out = [];
const same = (a, b) => a.state === b.state && a.query === b.query && a.wait_event_type === b.wait_event_type && a.wait_event === b.wait_event && a.blocked_by === b.blocked_by && a.backend_start === b.backend_start && new Date(b.collected_at) - new Date(a.last) <= 30e3;
for (const r of rows) {
const last = out[out.length - 1];
if (last && same(last, r)) { last.last = r.collected_at; last.xact_age_s = r.xact_age_s; last.samples++; last.trace_id = r.trace_id || last.trace_id; }
else out.push({ ...r, first: r.collected_at, last: r.collected_at, samples: 1 });
}
return out;
}
pages.locks = async () => {
const bucket = bucketFor();
const d = await api(`/servers/${state.server}/locks`, { ...rangeQuery(), bucket, limit: 100 });
const byType = {};
for (const r of d.series) (byType[r.locktype] ||= []).push([new Date(r.bucket), r.avg_waiting_sessions]);
const series = Object.entries(byType).sort(([a], [b]) => a.localeCompare(b)).map(([k, pts], i) => ({ name: k, color: COLORS[(i + 3) % COLORS.length], points: pts }));
const per = BUCKET_LABEL[bucket] || bucket;
// A selected episode (instance:pid:from:to:backend_start:at) shows what the blocker was doing across its transaction.
const sel = state.params.session ? state.params.session.split(':').map(decodeURIComponent) : null;
// The history is a drill-down, so a failed fetch shows in its own panel instead of replacing the page.
const history = sel ? await api(`/servers/${state.server}/sessions/${sel[1]}`, { instance: sel[0], from: sel[2], to: sel[3], backend_start: sel[4] || null, at: sel[5] || null }).catch(e => ({ error: String(e.message || e) })) : null;
const clearSel = () => { const p = { ...state.params }; delete p.session; go('locks', p); };
return [
el('h1', {}, 'Locks', el('span', { class: 'sub' }, 'who waited for whom, from 10 s samples of blocked sessions')),
panel(`Sessions waiting on locks per ${per}, by lock type`, chart(series, { stacked: true, yfmt: v => fmt.dec(v, 2) })),
history ? el('div', { style: 'margin-top:12px' }, panel(null,
el('div', { class: 'toolbar' }, el('h2', { style: 'margin:0' }, `Blocker pid ${sel[1]} on ${sel[0]}`), el('span', { class: 'muted' }, `${fmt.ts(sel[2])} to ${fmt.ts(sel[3])}`), el('button', { onclick: clearSel }, '✕ close')),
history.error ? el('div', { class: 'error-box' }, `Couldn't load the session history: ${history.error}. Try again, and if it keeps happening check the API logs.`) : table(sessionSpans(history), [
{ key: 'first', label: 'from', fmt: fmt.time }, { key: 'last', label: 'to', fmt: fmt.time },
{ key: 'state', label: 'state', render: r => el('span', { class: r.state === 'idle in transaction' ? 'warn' : '' }, r.state) },
{ key: 'wait_event_type', label: 'wait', fmt: (v, r) => v ? `${v}:${r.wait_event}` : 'CPU' },
{ key: 'xact_age_s', label: 'txn age at end', num: true, fmt: secs }, { key: 'blocked_by', label: 'blocked by' },
{ key: 'query', label: 'last statement', render: r => r.query_id ? el('a', { href: hashFor('query', { queryid: r.query_id, datname: r.datname }) }, queryLabel(r)) : queryLabel(r) },
{ key: 'trace_id', label: 'trace', cls: 'mono', render: r => r.trace_id ? el('span', { title: r.trace_id }, r.trace_id.slice(0, 12) + '…') : null },
], { empty: 'No samples for this backend in the window. Backends are only sampled once active for 5 s or idle in transaction for 60 s, so a short transaction leaves no history.' }))) : null,
el('div', { style: 'margin-top:12px' }, Object.assign(panel('Who blocked whom', table(d.pairs, [
{ key: 'blocker_query', label: 'blocker was running', render: r => el('span', {}, queryCell(r.blocker_query), el('div', { class: 'muted', style: 'font-size:11px' }, [r.blocker_usename, r.blocker_application_name].filter(Boolean).join(' · '), r.blocker_idle_pct ? el('span', { class: r.blocker_idle_pct >= 50 ? 'warn' : '' }, ` · idle in transaction ${fmt.pct(r.blocker_idle_pct)} of the time`) : null)) },
{ key: 'waiter_query', label: 'waiter', render: r => el('span', {}, queryCell(r.waiter_query), el('div', { class: 'muted', style: 'font-size:11px' }, [r.usename, r.application_name].filter(Boolean).join(' · '))) },
{ key: 'locktype', label: 'lock', render: lockCell },
{ key: 'waited_s', label: 'waited', num: true, fmt: secs }, { key: 'waiters', label: 'waiters', num: true, fmt: fmt.num }, { key: 'blockers', label: 'blockers', num: true, fmt: fmt.num },
{ key: 'max_waiting_s', label: 'longest wait', num: true, fmt: secs }, { key: 'max_blocker_xact_age_s', label: 'blocker txn age', num: true, fmt: secs },
{ key: 'last_seen', label: 'last seen', fmt: fmt.ago },
], { sortKey: 'waited_s', empty: 'no blocked sessions sampled in this range' })), { className: 'panel tight' })),
el('div', { style: 'margin-top:12px' }, Object.assign(panel('Episodes (one waiter blocked by one backend; click for the blocker\'s history)', table(d.episodes, [
{ key: 'first_seen', label: 'start', cls: 'nowrap', fmt: fmt.ts }, { key: 'waited_s', label: 'duration', num: true, fmt: secs },
{ key: 'waiter_pid', label: 'waiter', render: r => pidCell(r.waiter_pid, r.usename, r.application_name) },
{ key: 'waiter_query', label: 'waiting on', render: r => queryCell(r.waiter_query) },
{ key: 'locktype', label: 'lock', render: lockCell },
{ key: 'blocker_pid', label: 'blocker', render: r => el('span', { class: 'nowrap' }, pidCell(r.blocker_pid, r.blocker_usename, r.blocker_application_name), el('br'), el('span', { class: (r.blocker_state === 'idle in transaction' ? 'warn' : '') + ' small' }, r.blocker_state), el('span', { class: 'muted small' }, ` · txn ${secs(r.blocker_xact_age_s)}`)) },
{ key: 'blocker_query', label: 'blocker last ran', render: r => queryCell(r.blocker_query) },
], { onRow: r => { const from = new Date(+new Date(r.first_seen) - (r.blocker_xact_age_at_start_s || 0) * 1000 - 60e3).toISOString(), to = new Date(+new Date(r.last_seen) + 60e3).toISOString(); go('locks', { ...state.params, session: [r.instance, r.blocker_pid, from, to, r.blocker_backend_start || '', r.last_seen].map(encodeURIComponent).join(':') }); }, empty: 'no blocked sessions sampled in this range' })), { className: 'panel tight' })),
el('div', { style: 'margin-top:12px' }, panel('Deadlocks (from the log)', d.deadlocks.length ? d.deadlocks.map(e => el('details', { open: '' }, el('summary', {}, `${fmt.ts(e.at)} · ${e.datname || ''} · ${e.subject || ''}`), el('pre', {}, (e.after && (e.after.detail || e.after.message)) || JSON.stringify(e.after, null, 2)))) : el('div', { class: 'empty' }, 'none in range (needs log_lock_waits or deadlock logging and the logs collector)'))),
];
};
pages.tables = async () => {
const [dbsel, db] = dbSelect(v => go('tables', { datname: v }));
if (!db) return [el('h1', {}, 'Tables'), el('div', { class: 'empty' }, 'no databases discovered yet')];
const rows = await api(`/servers/${state.server}/tables`, { ...rangeQuery(), datname: db, limit: 500 });
return [
el('h1', {}, 'Tables', el('span', { class: 'sub' }, 'counters summed over the range; sizes and tuples latest')),
el('div', { class: 'toolbar' }, el('label', {}, 'database ', dbsel)),
panel(null, table(rows, [
{ key: 'relname', label: 'table', fmt: (v, r) => `${r.schemaname}.${v}`, cls: 'mono' }, { key: 'total_bytes', label: 'size', num: true, fmt: fmt.bytes }, { key: 'index_bytes', label: 'indexes', num: true, fmt: fmt.bytes },
{ key: 'n_live_tup', label: 'live', num: true, fmt: fmt.num }, { key: 'n_dead_tup', label: 'dead', num: true, fmt: fmt.num }, { key: 'seq_scan', label: 'seq scans', num: true, fmt: fmt.num }, { key: 'idx_scan', label: 'idx scans', num: true, fmt: fmt.num },
{ key: 'n_tup_ins', label: 'ins', num: true, fmt: fmt.num }, { key: 'n_tup_upd', label: 'upd', num: true, fmt: fmt.num }, { key: 'n_tup_del', label: 'del', num: true, fmt: fmt.num }, { key: 'xid_age', label: 'xid age', num: true, fmt: fmt.num }, { key: 'last_autovacuum', label: 'last autovac', fmt: fmt.ago },
], { sortKey: 'total_bytes', onRow: r => go('schema', { datname: db, relname: r.relname }) })),
];
};
pages.indexes = async () => {
const [dbsel, db] = dbSelect(v => go('indexes', { datname: v }));
if (!db) return [el('h1', {}, 'Indexes'), el('div', { class: 'empty' }, 'no databases discovered yet')];
const rows = await api(`/servers/${state.server}/indexes`, { ...rangeQuery(), datname: db });
return [
el('h1', {}, 'Indexes', el('span', { class: 'sub' }, 'scans summed over the range; unused = zero scans and not unique/primary')),
el('div', { class: 'toolbar' }, el('label', {}, 'database ', dbsel)),
panel(null, table(rows, [
{ key: 'unused_in_range', label: '', render: r => r.unused_in_range ? el('span', { class: 'pill warn' }, 'unused') : (r.is_valid === false ? el('span', { class: 'pill err' }, 'invalid') : null) },
{ key: 'indexname', label: 'index', fmt: (v, r) => `${r.schemaname}.${r.relname} › ${v}`, cls: 'mono' }, { key: 'idx_scan', label: 'scans', num: true, fmt: fmt.num }, { key: 'idx_tup_read', label: 'tuples read', num: true, fmt: fmt.num },
{ key: 'columns', label: 'columns', cls: 'mono' }, { key: 'access_method', label: 'am' }, { key: 'definition', label: 'definition', render: r => queryCell(r.definition) },
], { sortKey: 'idx_scan', desc: false, empty: 'no index metadata yet (schema collector runs hourly)' })),
];
};
pages.vacuum = async () => {
const d = await api(`/servers/${state.server}/vacuum`, { ...rangeQuery(), datname: state.params.datname });
return [
el('h1', {}, 'Vacuum', el('span', { class: 'sub' }, 'effective autovacuum thresholds per table (reloptions ⊕ GUCs)')),
el('div', { class: 'grid two' },
panel('Database xid age', table(d.database_xid_age, [{ key: 'datname', label: 'db' }, { key: 'xid_age', label: 'xid age', num: true, fmt: fmt.num }])),
panel('In progress', table(d.in_progress, [{ key: 'datname', label: 'db' }, { key: 'phase', label: 'phase' }, { key: 'heap_blks_scanned', label: 'scanned', num: true, fmt: fmt.num }, { key: 'heap_blks_total', label: 'total', num: true, fmt: fmt.num }, { key: 'running_seconds', label: 'running', num: true, fmt: v => fmt.dec(v, 0) + ' s' }], { empty: 'no vacuum running' })),
),
el('div', { style: 'margin-top:12px' }, panel('Tables over 50% of a threshold', table(d.needed, [
{ key: 'datname', label: 'db' }, { key: 'relname', label: 'table', fmt: (v, r) => `${r.schemaname}.${v}`, cls: 'mono' }, { key: 'autovacuum_enabled', label: 'autovac', fmt: v => v ? 'on' : el('span', { class: 'err' }, 'off') },
{ key: 'n_dead_tup', label: 'dead', num: true, fmt: fmt.num }, { key: 'vacuum_ratio', label: 'vacuum', num: true, render: r => fmt.ratio(r.vacuum_ratio) }, { key: 'analyze_ratio', label: 'analyze', num: true, render: r => fmt.ratio(r.analyze_ratio) }, { key: 'insert_ratio', label: 'insert', num: true, render: r => fmt.ratio(r.insert_ratio) },
{ key: 'freeze_ratio', label: 'freeze', num: true, render: r => fmt.ratio(r.freeze_ratio) }, { key: 'xid_age', label: 'xid age', num: true, fmt: fmt.num }, { key: 'last_autovacuum', label: 'last autovac', fmt: fmt.ago }, { key: 'last_autoanalyze', label: 'last analyze', fmt: fmt.ago },
], { sortKey: 'vacuum_ratio', empty: 'nothing near a threshold' }))),
el('div', { style: 'margin-top:12px' }, panel('Recent autovacuum runs (from the log)', table(d.recent_runs, [
{ key: 'log_time', label: 'time', fmt: fmt.ts }, { key: 'kind', label: 'kind' }, { key: 'relation', label: 'relation', cls: 'mono' }, { key: 'aggressive', label: 'aggr', fmt: v => v ? 'yes' : '' }, { key: 'tuples_removed', label: 'removed', num: true, fmt: fmt.num }, { key: 'tuples_remain', label: 'remain', num: true, fmt: fmt.num }, { key: 'tuples_dead_not_removable', label: 'not removable', num: true, fmt: fmt.num }, { key: 'index_scans', label: 'idx scans', num: true }, { key: 'elapsed_s', label: 'elapsed', num: true, fmt: v => fmt.dec(v, 1) + ' s' },
], { empty: 'none in range (needs log_autovacuum_min_duration and the logs collector)' }))),
];
};
pages.events = async () => {
const rows = await api(`/servers/${state.server}/events`, { ...rangeQuery(), kind: state.params.kind, limit: 500 });
const kinds = ['', 'schema_%', 'settings_%', 'log_%', 'stats_reset', 'pgss_dealloc'];
return [
el('h1', {}, 'Events', el('span', { class: 'sub' }, 'schema and settings changes, deadlocks, lock waits, cancellations, stats resets')),
el('div', { class: 'toolbar' }, el('label', {}, 'kind ', el('select', { onchange: e => go('events', { kind: e.target.value }) }, kinds.map(k => el('option', { value: k, selected: k === (state.params.kind || '') ? '' : null }, k || 'all'))))),
panel(null, table(rows, [
{ key: 'at', label: 'time', fmt: fmt.ts }, { key: 'kind', label: 'kind', render: r => el('span', { class: 'pill' }, r.kind) }, { key: 'datname', label: 'db' }, { key: 'subject', label: 'subject', cls: 'mono' },
{ key: 'after', label: 'details', render: r => el('details', {}, el('summary', {}, summarize(r)), el('pre', {}, JSON.stringify({ before: r.before, after: r.after }, null, 2))) },
], { empty: 'no events in range' })),
];
};
function summarize(e) {
const a = e.after || {}, b = e.before || {};
if (e.kind === 'settings_changed') return `${b.setting} → ${a.setting}`;
if (e.kind.startsWith('log_')) return (a.statement || a.reason || a.detail || '').slice(0, 120);
const keys = Object.keys(a).filter(k => k !== 'columns');
return keys.slice(0, 4).map(k => `${k}=${JSON.stringify(a[k])}`).join(' ').slice(0, 140) || 'details';
}
pages.logs = async () => {
const d = await api(`/servers/${state.server}/logs`, { ...rangeQuery(), limit: 300 });
return [
el('h1', {}, 'Logs', el('span', { class: 'sub' }, 'errors, cancellations and temp files from the Postgres log')),
el('div', { class: 'grid two' },
panel('Log lines by class', table(d.counts, [{ key: 'level', label: 'level' }, { key: 'class', label: 'class' }, { key: 'n', label: 'lines', num: true, fmt: fmt.num }])),
panel('Errors grouped', table(d.summary, [{ key: 'class', label: 'class' }, { key: 'sqlstate', label: 'sqlstate', cls: 'mono' }, { key: 'message', label: 'message' }, { key: 'n', label: 'count', num: true, fmt: fmt.num }])),
),
el('div', { style: 'margin-top:12px' }, panel('Recent errors', table(d.recent, [
{ key: 'log_time', label: 'time', fmt: fmt.ts }, { key: 'level', label: 'level', render: r => el('span', { class: r.level === 'ERROR' ? 'warn' : 'err' }, r.level) }, { key: 'datname', label: 'db' }, { key: 'usename', label: 'user' }, { key: 'message', label: 'message' }, { key: 'statement', label: 'statement', render: r => el('span', {}, queryCell(r.statement), tagPills(r.tags, 3)) },
], { empty: 'no errors in range' }))),
el('div', { style: 'margin-top:12px' }, panel('Largest temp-file spills', table(d.temp_files, [{ key: 'log_time', label: 'time', fmt: fmt.ts }, { key: 'datname', label: 'db' }, { key: 'usename', label: 'user' }, { key: 'size_bytes', label: 'size', num: true, fmt: fmt.bytes }, { key: 'statement', label: 'statement', render: r => el('span', {}, queryCell(r.statement), tagPills(r.tags, 3)) }], { empty: 'none (needs log_temp_files)' }))),
];
};
pages.cpu = async () => {
const d = await api(`/servers/${state.server}/cpu`, { ...rangeQuery() });
const byInst = (rows, key) => { const m = {}; for (const r of rows) (m[r.instance] ||= []).push([new Date(r.collected_at), r[key]]); return Object.entries(m).map(([n, pts], i) => ({ name: n, color: COLORS[i], points: pts })); };
const cpuTitle = 'Host CPU %' + (d.host.length ? ` (${d.host.map(h => `${h.instance}: ${h.ncpu} vCPU`).join(', ')})` : '');
const noProctab = () => el('div', { class: 'empty' }, 'No pg_proctab data. Run CREATE EXTENSION pg_proctab in the database the collector connects to; rows start within 10 minutes.');
const userSeries = (() => { const m = Object.create(null); for (const r of d.cpu_by_user_series) (m[`${r.label}${d.host.length > 1 ? ' @' + r.instance : ''}`] ||= []).push([new Date(r.collected_at), r.cores]); const names = Object.keys(m).sort((a, b) => a.startsWith('other') - b.startsWith('other')); return names.map((n, i) => ({ name: n, color: n.startsWith('other') ? '#565f73' : COLORS[i % COLORS.length], points: m[n] })); })();
const cores = v => v == null ? '–' : fmt.dec(v, 3);
const cpuCols = [
{ key: 'cpu_seconds', label: 'CPU time', num: true, fmt: v => fmt.dec(v, 1) + ' s' },
{ key: 'avg_cores', label: 'avg cores', num: true, fmt: cores },
{ key: 'host_pct', label: '% of host', num: true, fmt: v => v == null ? '–' : fmt.dec(v, 2) + '%' },
{ key: 'backends', label: 'backends', num: true, fmt: fmt.num },
];
return [
el('h1', {}, 'CPU'),
el('div', { class: 'grid two' },
panel(cpuTitle, d.cpu.length ? chart(byInst(d.cpu, 'cpu_pct'), { yfmt: fmt.pct, missing: null }) : noProctab()),
panel('Load average', d.memory.length ? chart(byInst(d.memory, 'load1'), { yfmt: v => fmt.dec(v, 2), missing: null }) : el('div', { class: 'empty' }, 'no pg_proctab data')),
),
el('div', { style: 'margin-top:12px' }, panel('CPU by user (cores, stacked)', userSeries.length ? chart(userSeries, { yfmt: cores, stacked: true }) : noProctab())),
el('div', { style: 'margin-top:12px' }, panel('CPU by user', table(d.cpu_by_user, [
{ key: 'usename', label: 'user', render: r => el('span', {}, r.usename || el('span', { class: 'muted' }, r.backend_type), r.application_name ? el('span', { class: 'muted' }, ' · ' + r.application_name) : null, d.host.length > 1 ? el('span', { class: 'muted' }, ' @' + r.instance) : null) },
{ key: 'datname', label: 'db' },
...cpuCols,
{ key: 'hottest_backend_cores', label: 'hottest backend', num: true, fmt: cores },
], { empty: 'no backend CPU rows in this range' }))),
el('div', { style: 'margin-top:12px' }, panel('CPU by code path (query tags)', table(d.cpu_by_code_path, [
{ key: 'tags', label: 'code path', render: r => el('a', { href: hashFor('queries', { tags: tagEntries(r.tags).map(([k, v]) => `${k}=${encodeURIComponent(v)}`).join(',') }) }, tagPills(r.tags, 4)) },
...cpuCols,
], { empty: 'no query tags seen on active backends in this range' }))),
el('div', { style: 'margin-top:12px' }, panel('CPU by query (estimated)',
el('div', { class: 'muted small', style: 'margin-bottom:6px' }, "Each role's measured CPU is split between its queries: execution time minus I/O time first, then the rest (planning, parsing, protocol) by number of calls. Share is of all query CPU on the instance."),
table(d.cpu_by_query, [
{ key: 'query', label: 'query', render: r => el('a', { href: hashFor('query', { queryid: r.queryid, datname: r.datname }) }, queryLabel(r)) },
{ key: 'datname', label: 'db' },
{ key: 'cpu_seconds', label: 'CPU time', num: true, fmt: v => fmt.dec(v, 1) + ' s' },
{ key: 'avg_cores', label: 'avg cores', num: true, fmt: cores },
{ key: 'host_pct', label: '% of host', num: true, fmt: v => v == null ? '–' : fmt.dec(v, 2) + '%' },
{ key: 'share_pct', label: 'share', num: true, fmt: v => v == null ? '–' : fmt.dec(v, 1) + '%' },
{ key: 'calls', label: 'calls', num: true, fmt: fmt.num },
], { empty: 'no pg_stat_statements rows in this range' }))),
];
};
pages.checkpoints = async () => {
const d = await api(`/servers/${state.server}/checkpoints`, { ...rangeQuery() });
return [
el('h1', {}, 'Checkpoints & replicas'),
el('div', { class: 'grid two' },
panel('Checkpoints (from the log)', table(d.checkpoints, [{ key: 'log_time', label: 'time', fmt: fmt.ts }, { key: 'kind', label: 'kind' }, { key: 'buffers_written', label: 'buffers', num: true, fmt: fmt.num }, { key: 'buffers_pct', label: '%', num: true, fmt: fmt.pct }, { key: 'write_s', label: 'write', num: true, fmt: v => fmt.dec(v, 2) + ' s' }, { key: 'sync_s', label: 'sync', num: true, fmt: v => fmt.dec(v, 2) + ' s' }, { key: 'distance_kb', label: 'distance', num: true, fmt: v => fmt.bytes(v * 1024) }], { empty: 'none in range' })),
panel('bgwriter / checkpointer (summed)', table(d.bgwriter, [{ key: 'instance', label: 'instance' }, { key: 'checkpoints_timed', label: 'timed', num: true, fmt: fmt.num }, { key: 'checkpoints_req', label: 'requested', num: true, fmt: fmt.num }, { key: 'buffers_checkpoint', label: 'ckpt buffers', num: true, fmt: fmt.num }, { key: 'buffers_clean', label: 'bgw buffers', num: true, fmt: fmt.num }, { key: 'buffers_alloc', label: 'allocated', num: true, fmt: fmt.num }])),
panel('Aurora replicas', table(d.aurora_replicas, [{ key: 'instance_id', label: 'instance' }, { key: 'role', label: 'role' }, { key: 'replica_lag_ms', label: 'lag', num: true, fmt: v => v == null ? '–' : fmt.ms(v) }, { key: 'replay_latency_us', label: 'replay', num: true, fmt: v => fmt.ms(v / 1000) }, { key: 'active_txns', label: 'txns', num: true }, { key: 'storage_daemon_cpu', label: 'storage cpu', num: true, fmt: fmt.pct }], { empty: 'not Aurora' })),
panel('Aurora per-database latency', table(d.aurora_db_latency, [{ key: 'datname', label: 'db' }, { key: 'commit_latency_us', label: 'commit latency (sum)', num: true, fmt: v => fmt.ms(v / 1000) }, { key: 'selects', label: 'selects', num: true, fmt: fmt.num }, { key: 'updates', label: 'updates', num: true, fmt: fmt.num }, { key: 'avg_update_latency_us', label: 'avg update', num: true, fmt: v => fmt.ms(v / 1000) }], { empty: 'not Aurora' })),
),
];
};
pages.schema = async () => {
const [dbsel, db] = dbSelect(v => go('schema', { datname: v }));
if (!db) return [el('h1', {}, 'Schema'), el('div', { class: 'empty' }, 'no databases discovered yet')];
const d = await api(`/servers/${state.server}/schema`, { datname: db, relname: state.params.relname });
const rel = state.params.relname;
return [
el('h1', {}, 'Schema', el('span', { class: 'sub' }, rel ? `${db} › ${rel}` : db)),
el('div', { class: 'toolbar' }, el('label', {}, 'database ', dbsel), rel ? el('button', { onclick: () => go('schema', { datname: db }) }, '← all relations') : null),
rel ? [
panel('Columns', d.relations.length ? table(d.relations[0].columns || [], [{ key: 'name', label: 'column', cls: 'mono' }, { key: 'type', label: 'type', cls: 'mono' }, { key: 'notnull', label: 'not null', fmt: v => v ? 'yes' : '' }, { key: 'default', label: 'default', cls: 'mono' }]) : el('div', { class: 'empty' }, 'unknown relation')),
el('div', { style: 'margin-top:12px' }, panel('Indexes', table(d.indexes, [{ key: 'indexname', label: 'index', cls: 'mono' }, { key: 'is_valid', label: 'valid', fmt: v => v ? 'yes' : el('span', { class: 'err' }, 'no') }, { key: 'definition', label: 'definition', cls: 'mono' }]))),
el('div', { style: 'margin-top:12px' }, panel('Constraints', table(d.constraints, [{ key: 'conname', label: 'name', cls: 'mono' }, { key: 'contype', label: 'type' }, { key: 'definition', label: 'definition', cls: 'mono' }, { key: 'is_validated', label: 'validated', fmt: v => v ? 'yes' : el('span', { class: 'warn' }, 'no') }]))),
] : panel(null, table(d.relations, [
{ key: 'relname', label: 'relation', fmt: (v, r) => `${r.schemaname}.${v}`, cls: 'mono' }, { key: 'relkind', label: 'kind', fmt: v => ({ r: 'table', p: 'partitioned', v: 'view', m: 'matview' })[v] || v }, { key: 'parent', label: 'parent', cls: 'mono' }, { key: 'n_columns', label: 'cols', num: true }, { key: 'partition_key', label: 'partition key', cls: 'mono' }, { key: 'last_seen', label: 'seen', fmt: fmt.ago },
], { sortKey: 'relname', desc: false, onRow: r => go('schema', { datname: db, relname: r.relname }), empty: 'no schema snapshot yet (runs hourly)' })),
];
};
pages.settings = async () => {
const all = state.params.all === '1';
const rows = await api(`/servers/${state.server}/settings`, { non_default: !all });
return [
el('h1', {}, 'Settings'),
el('div', { class: 'toolbar' }, el('label', {}, el('input', { type: 'checkbox', checked: all ? '' : null, onchange: e => go('settings', { all: e.target.checked ? '1' : '0' }) }), ' show defaults too')),
panel(null, table(rows, [{ key: 'name', label: 'name', cls: 'mono' }, { key: 'setting', label: 'value', cls: 'mono' }, { key: 'unit', label: 'unit' }, { key: 'source', label: 'source' }, { key: 'category', label: 'category' }, { key: 'pending_restart', label: 'pending restart', fmt: v => v ? el('span', { class: 'warn' }, 'yes') : '' }], { sortKey: 'name', desc: false, empty: 'no settings snapshot yet (runs hourly)' })),
];
};
pages.collector = async () => {
const rows = await api('/collector/health');
return [
el('h1', {}, 'Collector health', el('span', { class: 'sub' }, 'last 15 minutes, all servers')),
panel(null, table(rows, [
{ key: 'server_id', label: 'server' }, { key: 'instance', label: 'instance' }, { key: 'collector', label: 'collector', cls: 'mono' }, { key: 'ticks', label: 'ticks', num: true }, { key: 'errors', label: 'errors', num: true, render: r => el('span', { class: r.errors ? 'err' : 'ok' }, r.errors) },
{ key: 'avg_ms', label: 'avg', num: true, fmt: fmt.ms }, { key: 'max_ms', label: 'max', num: true, fmt: fmt.ms }, { key: 'last_tick', label: 'last tick', fmt: fmt.ago }, { key: 'last_error', label: 'last error', render: r => r.last_error ? el('span', { class: 'q err', title: r.last_error }, r.last_error) : null },
], { sortKey: 'errors', empty: 'no collector runs recorded' })),
];
};
// ---------- shell ----------
function renderNav() {
$('#nav').replaceChildren(el('div', { class: 'group' }, 'server'), ...PAGES.map(([p, l]) => el('a', { href: hashFor(p), class: state.page === p || (p === 'queries' && state.page === 'query') ? 'active' : '' }, l)));
}
async function render() {
const main = $('#main');
const fn = pages[state.page];
if (!fn) { main.replaceChildren(el('div', { class: 'error-box' }, `unknown page ${state.page}`)); return; }
destroyCharts();
loadMarkers();
main.replaceChildren(el('div', { class: 'muted' }, 'loading…'));
try { const out = await fn(); main.replaceChildren(...[out].flat(Infinity).filter(Boolean)); }
catch (e) { main.replaceChildren(el('div', { class: 'error-box' }, String(e.message || e))); }
}
async function route() {
const h = parseHash();
if (!h && state.servers.length) { go('overview', {}, state.servers[0].server_id); return; }
// Old bookmarks point at the page before it was renamed.
if (h?.page === 'system') { go('cpu', h.params, h.server); return; }
if (h) { state.server = h.server; state.page = h.page; state.params = h.params; }
$('#server').value = state.server;
syncRangeControl();
renderNav();
render();
}
function syncRangeControl() {
const sel = $('#range'), c = customRange();
sel.querySelector('option[value=custom]')?.remove();
if (c) sel.append(el('option', { value: 'custom', selected: '' }, `${fmt.time(c.from)} to ${fmt.time(c.to)}`));
else sel.value = state.range;
$('#zoomout').hidden = !c;
}
async function boot() {
try { const me = await api('/me'); $('#me').textContent = `${me.email} · ${me.source}`; } catch (e) { $('#me').textContent = 'unauthenticated'; }
try { state.servers = await api('/servers'); } catch (e) { $('#main').replaceChildren(el('div', { class: 'error-box' }, String(e.message))); return; }
const sel = $('#server');
sel.replaceChildren(...state.servers.map(s => el('option', { value: s.server_id }, `${s.server_id}${s.errors_10m ? ' ⚠' : ''}`)));
sel.onchange = () => go(state.page === 'query' ? 'queries' : state.page, {}, sel.value);
$('#range').onchange = e => { if (e.target.value === 'custom') return; state.range = e.target.value; if (customRange()) go(state.page, { ...state.params, from: null, to: null }); else render(); };
$('#zoomout').onclick = zoomOut;
$('#refresh').onclick = render;
window.addEventListener('hashchange', route);
if (!state.servers.length) { $('#main').replaceChildren(el('div', { class: 'empty' }, 'no servers registered yet — is the collector running?')); return; }
route();
}
boot();
})();
</script>
</body>
</html>