Skip to content

: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.

feat(pgapi): draw charts with uPlot, hover values and drag to zoom (#102696)

Nick Bestf8c070412a34
diff --git a/rust/pgapi/README.md b/rust/pgapi/README.md
index 2fac645e50dd..a97d73de6afe 100644
--- a/rust/pgapi/README.md
+++ b/rust/pgapi/README.md
@@ -81,4 +81,5 @@ src/queries.rs every question the API can answer, as SQL → JSON (shared by R
src/api.rs REST routes
src/mcp.rs MCP tools
src/db.rs read-only pool, row → JSON
+src/ui/ embedded browser UI (charts use uPlot, loaded from jsDelivr with a pinned version and integrity hash)
```
diff --git a/rust/pgapi/build.rs b/rust/pgapi/build.rs
new file mode 100644
index 000000000000..7b13c649ba48
--- /dev/null
+++ b/rust/pgapi/build.rs
@@ -0,0 +1,35 @@
+//! Emits `PGAPI_BUILD_HASH`, a hash of this crate's sources and the workspace lockfile, so the
+//! binary can tell browsers which build they are talking to. No revision id reaches the image
+//! build, and hashing the executable at runtime trips a security lint, so the sources stand in.
+
+use std::hash::{DefaultHasher, Hash, Hasher};
+use std::path::Path;
+
+fn hash_dir(dir: &Path, h: &mut DefaultHasher) {
+ let mut entries: Vec<_> = std::fs::read_dir(dir)
+ .expect("crate source directory is readable")
+ .map(|e| e.expect("directory entry is readable").path())
+ .collect();
+ entries.sort();
+ for path in entries {
+ if path.is_dir() {
+ hash_dir(&path, h);
+ } else {
+ path.to_string_lossy().hash(h);
+ std::fs::read(&path)
+ .expect("source file is readable")
+ .hash(h);
+ }
+ }
+}
+
+fn main() {
+ let mut h = DefaultHasher::new();
+ hash_dir(Path::new("src"), &mut h);
+ if let Ok(lock) = std::fs::read("../Cargo.lock") {
+ lock.hash(&mut h);
+ }
+ println!("cargo:rustc-env=PGAPI_BUILD_HASH={:016x}", h.finish());
+ println!("cargo:rerun-if-changed=src");
+ println!("cargo:rerun-if-changed=../Cargo.lock");
+}
diff --git a/rust/pgapi/src/api.rs b/rust/pgapi/src/api.rs
index e086053888d9..56dfa40d7428 100644
--- a/rust/pgapi/src/api.rs
+++ b/rust/pgapi/src/api.rs
@@ -7,6 +7,7 @@ use crate::AppState;
use axum::{
extract::{Extension, Path, Query, State},
http::StatusCode,
+ middleware::map_response,
response::{IntoResponse, Json, Response},
routing::get,
Router,
@@ -14,6 +15,14 @@ use axum::{
use serde::Deserialize;
use std::sync::Arc;
+/// A page left open across a deploy sees a new token on its next API call and reloads,
+/// instead of running the old script against the new API.
+async fn stamp_build(mut res: Response) -> Response {
+ res.headers_mut()
+ .insert("x-pgapi-build", crate::ui::BUILD_TOKEN.clone());
+ res
+}
+
type S = State<Arc<AppState>>;
pub struct ApiError(anyhow::Error);
@@ -56,6 +65,7 @@ pub fn router() -> Router<Arc<AppState>> {
.route("/collector/health", get(collector_health))
.route("/sql", get(sql))
.route("/stats-schema", get(stats_schema))
+ .layer(map_response(stamp_build))
}
async fn me(Extension(p): Extension<Principal>) -> R {
diff --git a/rust/pgapi/src/ui.rs b/rust/pgapi/src/ui.rs
index 57a175cb3176..9c607d7ff622 100644
--- a/rust/pgapi/src/ui.rs
+++ b/rust/pgapi/src/ui.rs
@@ -1,14 +1,21 @@
//! Embedded single-page UI, served at `/` behind the same identity middleware as
//! the API. It only ever calls `/api/v1/*`.
-use axum::http::header;
+use axum::http::{header, HeaderValue};
use axum::response::{Html, IntoResponse, Response};
+const INDEX: &str = include_str!("ui/index.html");
+
+/// Identifies the build this process runs, so every replica of one build agrees on it (a
+/// per-process value would make a browser that alternates between pods reload forever) and a
+/// backend-only change still gets a new value. `build.rs` derives it from the crate sources.
+pub static BUILD_TOKEN: HeaderValue = HeaderValue::from_static(concat!(
+ env!("CARGO_PKG_VERSION"),
+ "-",
+ env!("PGAPI_BUILD_HASH")
+));
+
pub async fn index() -> Response {
// The page changes with every deploy; never let a browser keep a stale copy.
- (
- [(header::CACHE_CONTROL, "no-cache")],
- Html(include_str!("ui/index.html")),
- )
- .into_response()
+ ([(header::CACHE_CONTROL, "no-cache")], Html(INDEX)).into_response()
}
diff --git a/rust/pgapi/src/ui/index.html b/rust/pgapi/src/ui/index.html
index f6bbc6a433ba..b6d63ae960f9 100644
--- a/rust/pgapi/src/ui/index.html
+++ b/rust/pgapi/src/ui/index.html
@@ -4,6 +4,8 @@
<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;
@@ -43,9 +45,15 @@
.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; }
- svg.chart { width: 100%; height: 140px; display: block; }
- .legend { display: flex; gap: 12px; font-size: 11px; color: var(--muted); margin-top: 4px; }
- .legend i { display: inline-block; width: 10px; height: 3px; margin-right: 4px; 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; }
.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); }
.tag { display: inline-block; font-family: var(--mono); font-size: 11px; color: var(--accent); background: rgba(122, 162, 247, .1); border: 1px solid rgba(122, 162, 247, .3); border-radius: 4px; padding: 0 5px; margin: 0 4px 2px 0; max-width: 260px; overflow: hidden; text-overflow: ellipsis; vertical-align: middle; white-space: nowrap; }
@@ -63,6 +71,7 @@
<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>
@@ -79,7 +88,7 @@
['tables', 'Tables'], ['indexes', 'Indexes'], ['vacuum', 'Vacuum'], ['events', 'Events'], ['logs', 'Logs'],
['system', 'System'], ['schema', 'Schema'], ['settings', 'Settings'], ['collector', 'Collector health'],
];
- const state = { servers: [], server: null, page: 'overview', params: {}, range: '1h' };
+ 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);
@@ -93,22 +102,46 @@
if (!m) return null;
return { server: decodeURIComponent(m[1]), page: m[2], params: Object.fromEntries(new URLSearchParams(m[3] || '')) };
}
- function go(page, params = {}, server = state.server) {
- const qs = new URLSearchParams(params).toString();
- location.hash = `#/${encodeURIComponent(server)}/${page}${qs ? '?' + qs : ''}`;
+ // 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 >= 1000 ? (v / 1000).toFixed(2) + ' s' : v >= 10 ? v.toFixed(1) + ' ms' : v.toFixed(3) + ' ms'),
+ 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'; },
@@ -149,47 +182,76 @@
const queryLabel = r => el('span', {}, tagPills(r.tags), r.tags && Object.keys(r.tags).length ? el('br') : null, queryCell(r.query));
const tagFilterChip = (tags, onClear) => tags ? el('span', { class: 'chip' }, tags, el('button', { title: 'clear tag filter', onclick: onClear }, '✕')) : null;
- // ---------- simple SVG line chart ----------
+ // ---------- time series chart (uPlot) ----------
// series: [{name, color, points: [[Date, number | null]]}]; a null y breaks the line.
- // stacked: every series is drawn as an area on top of the ones before it; a
- // missing x in a series counts as 0 so the stack stays continuous.
- function chart(series, { yfmt = v => fmt.dec(v, 1), stacked = false } = {}) {
- const W = 800, H = 140, P = { l: 48, r: 8, t: 8, b: 20 };
- if (stacked) {
- const xs = [...new Set(series.flatMap(s => s.points.map(p => +p[0])))].sort((a, b) => a - b);
- let base = new Map(xs.map(x => [x, 0]));
- series = series.map(s => {
- const own = new Map(s.points.map(p => [+p[0], p[1] || 0]));
- const top = new Map(xs.map(x => [x, base.get(x) + (own.get(x) || 0)]));
- const out = { ...s, points: xs.map(x => [new Date(x), top.get(x)]), base: xs.map(x => [new Date(x), base.get(x)]) };
- base = top;
- return out;
- });
- }
- const all = series.flatMap(s => s.points).filter(p => p[1] != null);
- if (!all.length) return el('div', { class: 'empty' }, 'no data points');
- const xs = all.map(p => +p[0]), ys = all.map(p => p[1]);
- const x0 = Math.min(...xs), x1 = Math.max(...xs) || x0 + 1, y1 = Math.max(...ys, 0) || 1;
- const X = x => P.l + (x - x0) / (x1 - x0 || 1) * (W - P.l - P.r), Y = y => H - P.b - (y / y1) * (H - P.t - P.b);
- const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
- svg.setAttribute('viewBox', `0 0 ${W} ${H}`); svg.setAttribute('class', 'chart'); svg.setAttribute('preserveAspectRatio', 'none');
- const n = (tag, a) => { const e = document.createElementNS('http://www.w3.org/2000/svg', tag); for (const [k, v] of Object.entries(a)) e.setAttribute(k, v); return e; };
- for (let i = 0; i <= 3; i++) { const y = Y(y1 * i / 3); svg.append(n('line', { x1: P.l, x2: W - P.r, y1: y, y2: y, stroke: '#2c313a', 'stroke-width': 1 })); const t = n('text', { x: P.l - 4, y: y + 4, 'text-anchor': 'end', fill: '#8b93a1', 'font-size': 10 }); t.textContent = yfmt(y1 * i / 3); svg.append(t); }
- for (const [i, x] of [x0, (x0 + x1) / 2, x1].entries()) { const t = n('text', { x: X(x), y: H - 4, 'text-anchor': i === 0 ? 'start' : i === 1 ? 'middle' : 'end', fill: '#8b93a1', 'font-size': 10 }); t.textContent = fmt.time(new Date(x)); svg.append(t); }
- for (const s of series) {
- const pts = [...s.points].sort((a, b) => a[0] - b[0]);
- let d = '', pen = false;
- for (const p of pts) { if (p[1] == null) { pen = false; continue; } d += (pen ? 'L' : 'M') + X(+p[0]).toFixed(1) + ' ' + Y(p[1]).toFixed(1); pen = true; }
- if (s.base) {
- const back = [...s.base].sort((a, b) => b[0] - a[0]).map(p => 'L' + X(+p[0]).toFixed(1) + ' ' + Y(p[1]).toFixed(1)).join('');
- svg.append(n('path', { d: d + back + 'Z', fill: s.color, 'fill-opacity': 0.35, stroke: 'none' }));
- }
- svg.append(n('path', { d, fill: 'none', stroke: s.color, 'stroke-width': 1.5, 'vector-effect': 'non-scaling-stroke' }));
+ // 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 an area on top of the ones before it, so missing is always 0.
+ // Every chart on a page shares one cursor, and dragging across any of them sets the range.
+ const charts = [];
+ 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 (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(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.
+ const stack = show => {
+ const acc = Array(xs.length).fill(0);
+ const data = raw.map((col, i) => show(i) ? col.map((v, j) => (acc[j] += v)) : col);
+ const vis = raw.map((_, i) => i).filter(show);
+ 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]); };
+ 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 }, 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 => ({ label: s.name, stroke: s.color, width: 1.5, points: { show: false }, fill: stacked ? s.color + '59' : null, spanGaps: false, value: (u, v, si, di) => di == null || raw[si - 1][di] == null ? '–' : yfmt(raw[si - 1][di]) })),
+ ],
+ hooks: { setSeries: stacked ? [restack] : [], 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 el('div', {}, svg, el('div', { class: 'legend' }, series.map(s => el('span', {}, el('i', { style: `background:${s.color}` }), s.name))));
+ 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 = range => range === '15m' ? '10s' : range === '7d' ? '1h' : range === '24h' ? '5m' : '1m';
+ 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 ----------
@@ -198,7 +260,7 @@
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 d = await api(`/servers/${state.server}/overview`, { since: state.range });
+ const d = await api(`/servers/${state.server}/overview`, { ...rangeQuery() });
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);
@@ -212,7 +274,7 @@
),
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: `#/${state.server}/query?queryid=${r.queryid}${r.datname ? `&datname=${encodeURIComponent(r.datname)}` : ''}` }, queryLabel(r)) },
+ { 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, [
@@ -222,7 +284,7 @@
{ 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: `#/${state.server}/events?kind=${encodeURIComponent(r.kind)}` }, r.kind) }, { key: 'n', label: 'count', 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' })),
@@ -238,8 +300,8 @@
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`, { since: state.range, order, limit: 200, datname: state.params.datname, tags: tagFilter }),
- api(`/servers/${state.server}/tags`, { since: state.range, key: group, datname: state.params.datname, limit: 200 }),
+ 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); } },
@@ -281,8 +343,8 @@
pages.query = async () => {
const qid = state.params.queryid;
- const bucket = bucketFor(state.range);
- const d = await api(`/servers/${state.server}/queries/${qid}`, { since: state.range, bucket, datname: state.params.datname });
+ 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; }
@@ -304,7 +366,7 @@
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 : 0]) }, ...qseries], { yfmt: v => fmt.ms(v) }),
+ 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, [
@@ -336,7 +398,7 @@
};
pages.waits = async () => {
- const d = await api(`/servers/${state.server}/waits`, { since: state.range, bucket: bucketFor(state.range) });
+ 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);
@@ -350,7 +412,7 @@
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`, { since: state.range, datname: db, limit: 500 });
+ 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)),
@@ -365,7 +427,7 @@
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`, { since: state.range, datname: db });
+ 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)),
@@ -378,7 +440,7 @@
};
pages.vacuum = async () => {
- const d = await api(`/servers/${state.server}/vacuum`, { since: state.range, datname: state.params.datname });
+ 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' },
@@ -397,7 +459,7 @@
};
pages.events = async () => {
- const rows = await api(`/servers/${state.server}/events`, { since: state.range, kind: state.params.kind, limit: 500 });
+ 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')),
@@ -417,7 +479,7 @@
}
pages.logs = async () => {
- const d = await api(`/servers/${state.server}/logs`, { since: state.range, limit: 300 });
+ 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' },
@@ -432,7 +494,7 @@
};
pages.system = async () => {
- const d = await api(`/servers/${state.server}/system`, { since: state.range });
+ const d = await api(`/servers/${state.server}/system`, { ...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.');
@@ -447,8 +509,8 @@
return [
el('h1', {}, 'System'),
el('div', { class: 'grid two' },
- panel(cpuTitle, d.cpu.length ? chart(byInst(d.cpu, 'cpu_pct'), { yfmt: fmt.pct }) : noProctab()),
- panel('Load average', d.memory.length ? chart(byInst(d.memory, 'load1'), { yfmt: v => fmt.dec(v, 2) }) : el('div', { class: 'empty' }, 'no pg_proctab data')),
+ 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, [
@@ -458,11 +520,11 @@
{ 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: `#/${state.server}/queries?tags=${encodeURIComponent(tagEntries(r.tags).map(([k, v]) => `${k}=${encodeURIComponent(v)}`).join(','))}` }, tagPills(r.tags, 4)) },
+ { 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 (sampled from the active statement each minute)', table(d.cpu_by_query, [
- { key: 'query', label: 'query', render: r => el('a', { href: `#/${state.server}/query?queryid=${r.queryid}${r.datname ? `&datname=${encodeURIComponent(r.datname)}` : ''}` }, queryLabel(r)) },
+ { key: 'query', label: 'query', render: r => el('a', { href: hashFor('query', { queryid: r.queryid, datname: r.datname }) }, queryLabel(r)) },
{ key: 'datname', label: 'db' },
...cpuCols,
], { empty: 'no query ids seen on active backends in this range' }))),
@@ -516,12 +578,13 @@
// ---------- shell ----------
function renderNav() {
- $('#nav').replaceChildren(el('div', { class: 'group' }, 'server'), ...PAGES.map(([p, l]) => el('a', { href: `#/${encodeURIComponent(state.server)}/${p}`, class: state.page === p || (p === 'queries' && state.page === 'query') ? 'active' : '' }, l)));
+ $('#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();
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))); }
@@ -531,16 +594,25 @@
if (!h && state.servers.length) { go('overview', {}, state.servers[0].server_id); 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 => { state.range = e.target.value; render(); };
+ $('#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; }