Files
codegraph/telemetry-dashboard/public/app.js
T
49c11fc2e0 Self-hosted telemetry on Cloudflare D1 + password-gated admin dashboard (CG-7) (#1497)
* feat(telemetry): D1 schema + migrations for raw events and daily rollups

First step of replacing PostHog with self-hosted telemetry on Cloudflare D1.
Creates the codegraph-telemetry database binding and the initial migration; no
worker code paths change yet (the ingest write path and the nightly rollup cron
land next).

Schema is raw events plus daily rollups: `events` holds one row per sanitized
event with the envelope broken out into columns and event-specific props as
JSON; `daily_machines`, `daily_event_counts` and `daily_dim_counts` are the
nightly rollups the dashboard reads; `machine_first_seen` and `machine_days`
carry the retention cohorts and are never purged. One generic dimension table
covers every bar and pie, so a new breakdown is a cron change rather than a
migration.

The migration is commented as an audit surface, like the rest of this worker —
every column, and which dashboard chart each rollup table serves.

Three judgment calls worth flagging, all documented in the file:

- `events` gets `(day, event)` instead of the separate `(day)` and `(event, day)`
  indexes. D1 bills a row write per index touched, so a third index on the hot
  table costs ~97k writes/day, and `(day, event)` is a covering index for plain
  day-range scans anyway (verified with EXPLAIN QUERY PLAN).
- `daily_event_counts` and `daily_dim_counts` carry a `machines` column, and
  `machine_days` a `prod` flag. The "users by ..." panels and the production-user
  count are distinct-machine numbers, not event counts, and they are
  unrecoverable once raw events are purged.
- No CHECK constraint on `event`: the worker's allowlist is the source of truth
  and the write path is fail-silent, so a rejected INSERT would lose data
  quietly instead of erroring loudly.

Volume note in the migration footer: ~30M row writes/month against the 50M
included on Workers Paid. Storage is the tighter constraint — raw events grow
~74 MB/day, so retention should start at 90 days (~6.7 GB) rather than 180,
which would exceed D1's 10 GB per-database cap.

* feat(telemetry): admin dashboard worker — scaffold + shared-password auth

New Cloudflare Worker at telemetry-dashboard/, sibling of telemetry-worker/ and
bound read-only to the same D1 database. Serves a static frontend plus a JSON
API behind a shared password, on stats.getcodegraph.com.

Auth is the simplest thing that is actually safe for exactly two users: one
password in a secret, compared in constant time over SHA-256 digests, and an
HMAC-signed cookie (HttpOnly; Secure; SameSite=Lax; Path=/) with a one-year
expiry so you sign in once per browser. The cookie is a signed assertion, not a
lookup key — no session store. Its payload carries a fingerprint of the password
it was minted against, so rotating ADMIN_PASSWORD signs everyone out. Login
attempts are capped at 5/min per IP via a ratelimit binding.

Everything is deny-by-default: assets.run_worker_first routes every request
through the worker before the static-asset server sees it, so the dashboard
HTML, its JS, its CSS and the chart library are all behind the session check.
The login page is rendered inline by the worker rather than served from public/,
which leaves no "is this file public?" judgement calls in the asset directory.
Unauthenticated pages 302 to /login, unauthenticated /api/* gets 401. A missing
secret fails closed rather than opening the dashboard.

scripts/smoke-auth.sh is the regression net — 54 assertions against a throwaway
`wrangler dev` covering the gate, cookie flags and persistence, forged/flipped/
truncated cookies, open-redirect refusal, brute-force capping, and password
rotation invalidating live sessions.

Refs CG-11.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* chore(telemetry-dashboard): simplify the chart-library probe in the shell

Refs CG-11.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(telemetry): nightly rollup cron + raw-event retention purge (CG-10)

Adds a scheduled() handler to the ingest worker that recomputes
daily_event_counts / daily_dim_counts / daily_machines for the just-completed
UTC day plus a 2-day overlap (late-arriving offline buffers), then purges raw
events past the retention window. Rollup writes are idempotent upserts, so a
re-run never double-counts. Also adds an ADMIN_TOKEN-guarded
POST /admin/rollup?day=YYYY-MM-DD for backfill/repair, and drops the PostHog
forwarding path.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(telemetry): dashboard charts — SQL API over D1 + the Chart.js views (CG-12, CG-13)

Replaces the scaffold page with the dashboard proper: 19 panels covering every
view of the PostHog dashboard this retires, driven by one filter row.

src/api.ts is the read API CG-12 specified: /api/{meta,summary,timeseries,
breakdown,activation,retention}, all range-scoped, all parameterized against a
closed set of dims and metrics, all shaped labels[] + datasets[] so the frontend
does no arithmetic. Rollups answer everything except the activation funnel,
which needs raw events and says where they start.

The frontend splits into a DOM-free panel registry (public/panels.js) and the
page that mounts it (public/app.js), so the render check can drive the same
registry the browser rendered from. Panels fail alone, refetch dims rather than
flashing, and every chart carries a table twin.

Two numbers are labelled rather than rounded off: range-wide "users" per
dimension is machine-days (the rollups cannot give distinct machines, and
per-day counts are taken as the largest single-event count so one machine's
install + index + usage is not counted three times), and recent activation and
retention cohorts are marked as still-converting instead of drawn as a cliff.

Both colour scales were run through the data-viz validator against the panel
surface, not picked by eye; the results are recorded in public/theme.js.

Verification, all against the committed fixture (12 machines over 10 days, every
expected number worked out by hand from the events, not recorded from a run):
  scripts/smoke-api.sh      98 assertions
  scripts/render-check.mjs  79 assertions — real Chromium over CDP, no new deps
  scripts/smoke-auth.sh     54 assertions (unchanged, still green)

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* feat(telemetry): cutover runbook + the end-to-end gate that de-risks it (CG-14)

The account-level steps of the PostHog cutover are the maintainer's to run, so
this lands the runbook they follow and the check that has to pass first.

The runbook (telemetry-worker/README.md) walks the six steps in the order that
keeps them reversible: Workers Paid → migrate → deploy → watch 24h → verify the
first rollup and the dashboard → only then delete POSTHOG_KEY and cancel the
subscription. Step 3 records the outgoing version id because `wrangler rollback`
is the escape hatch for the whole verification window, and that window is
precisely why the PostHog key is deleted last rather than first.

The new gate (scripts/smoke-cutover.sh, `npm run smoke:cutover`) covers the one
seam nothing else did. Both workers declare the same D1 database_id, so pointing
them at a single --persist-to directory runs the real chain: a client batch →
the ingest worker → D1 → the nightly rollup → the dashboard API reading the
numbers back. Every other suite stops at one link — smoke-ingest at the events
table, smoke-rollup at hand-checked SQL, smoke-api at a hand-written fixture
that the cron never touched. That left the dimension names the rollup WRITES
versus the ones the dashboard READS agreeing by convention across two branches,
where a mismatch is silent: no error, no failed request, just a panel reading
zero forever. 61 assertions, all 13 dimensions, and three deliberate traps — a
ci machine that is active but not a production user, usage_rollup counts that
must be summed rather than tallied, and an uninstall's `targets` that must not
leak into the install-scoped breakdown.

Writing it caught that the activation funnel's denominator is first-seen
machines, not install events (deliberate — a reinstall must not re-enter the
funnel), so the suite now pins that distinction rather than assuming it.

Also rewords the last PostHog reference in dashboard code: a comment justifying
the 14-day retention curve by pointing at a dashboard step 6 deletes. The
reasoning now stands on its own.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* docs(telemetry): tell the truth about where events are stored (CG-15)

The telemetry docs are a privacy contract, and they still described a
managed analytics store that no longer receives anything. Replace that
with what actually happens now — events land in our own D1 database on
Cloudflare, the endpoint makes no outbound requests, raw events are
purged after 90 days and only anonymous daily rollups outlive them.
This strengthens the guarantee rather than restating it: there is no
second party to share with.

- TELEMETRY.md: new "Where it is stored" section; the never-collected
  IP bullet no longer leans on a vendor-side setting to hold.
- docs/design/telemetry.md: ingest section rewritten around D1 + the
  nightly rollup/retention cron; volume math redone on Workers Paid and
  the D1 quota (storage, not writes, is what sets the 90-day window);
  new section documenting the dashboard worker and cross-linking it.
- Fixed three drifts from the worker allowlist the sweep surfaced:
  schema_version was still 1, client_name/client_version was still
  marked "plumbing to add" though session.ts passes it today, and the
  legacy sqlite_backend field the worker still accepts was undocumented.
- telemetry-worker/README.md: step 6 claimed a repo-wide grep came back
  clean, which this runbook itself falsifies. Added step 7 — deleting
  the runbook is what makes that grep true, and is the completion check.
- smoke-cutover.sh: the vendor guarantee is now asserted by class
  (no analytics-ingest endpoint referenced) rather than by one vendor's
  name, so it keeps working once the name is gone. Verified it still
  catches a planted forwarding URL. 61/61 pass.

Retention is documented as 90 days, not the 180 in the task notes: 180
days of raw events exceeds D1's 10 GB per-database cap, and the code
purges at 90.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* chore: untrack local Kommandr issue DB and ignore its sqlite artifacts

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-01 16:17:10 -05:00

396 lines
13 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* The dashboard page: one filter row, a grid of panels, and a fetch per panel.
*
* Deliberate properties:
* - **One filter row, above everything it scopes.** Changing the range or
* hitting refresh re-queries every panel against the same slice; no panel
* carries its own time control.
* - **Panels fail alone.** Each one fetches, draws, and reports independently,
* so a 503 on one query leaves the other eighteen on screen instead of
* blanking the page.
* - **No client-side cache.** The only reuse is deduplicating identical URLs
* within a single render (four stat tiles read one /api/summary); that map is
* thrown away afterwards, so refresh really does re-ask. Anything longer-lived
* is the API's `Cache-Control` doing its job in the browser's own cache.
* - **No skeleton flash.** A refetch dims the previous render instead of tearing
* it down, so nothing jumps while new numbers land.
* - **Every chart has a table twin.** "Show numbers" reveals the same data as
* text, which is what keeps a value from being reachable only by hovering.
*/
import { PANELS } from './panels.js';
import { applyChartDefaults, shortDay } from './theme.js';
const RANGE_PRESETS = [
{ days: 7, label: 'Last 7 days' },
{ days: 14, label: 'Last 14 days' },
{ days: 30, label: 'Last 30 days' },
{ days: 90, label: 'Last 90 days' },
];
const DEFAULT_PRESET = 30;
const DAY_MS = 86_400_000;
const Chart = window.Chart;
/** Every fetch goes through here so an expired session lands on /login instead
* of failing silently mid-render. */
export async function api(path) {
const response = await fetch(path, { headers: { accept: 'application/json' } });
if (response.status === 401) {
window.location.href = `/login?next=${encodeURIComponent(window.location.pathname)}`;
throw new Error('session expired');
}
if (!response.ok) {
const detail = await response.json().catch(() => null);
throw new Error(detail?.error ?? `responded ${response.status}`);
}
return response.json();
}
// ---------------------------------------------------------------------------
// Days
// ---------------------------------------------------------------------------
const utcDay = (atMs) => new Date(atMs).toISOString().slice(0, 10);
const dayMs = (day) => Date.parse(`${day}T00:00:00Z`);
const addDays = (day, delta) => utcDay(dayMs(day) + delta * DAY_MS);
const isDay = (value) => /^\d{4}-\d{2}-\d{2}$/.test(value) && Number.isFinite(dayMs(value));
// ---------------------------------------------------------------------------
// State
// ---------------------------------------------------------------------------
const state = {
/** Latest day the nightly rollup has written; every preset ends here. */
anchor: utcDay(Date.now()),
earliest: null,
preset: DEFAULT_PRESET,
custom: { from: null, to: null },
/** Panels whose table twin the reader has opened, kept across re-renders. */
openTables: new Set(),
renderToken: 0,
};
const charts = new Map();
function currentRange() {
if (state.preset === 'custom' && state.custom.from && state.custom.to) {
return { from: state.custom.from, to: state.custom.to };
}
const to = state.anchor;
return { from: addDays(to, -(state.preset - 1)), to };
}
// ---------------------------------------------------------------------------
// DOM helpers
// ---------------------------------------------------------------------------
function el(tag, className, text) {
const node = document.createElement(tag);
if (className) node.className = className;
if (text !== undefined) node.textContent = text;
return node;
}
const $ = (root, role) => root.querySelector(`[data-role="${role}"]`);
// ---------------------------------------------------------------------------
// Building the page
// ---------------------------------------------------------------------------
function buildFilters() {
const bar = document.getElementById('filters');
const presets = $(bar, 'presets');
for (const preset of RANGE_PRESETS) {
const button = el('button', 'range', preset.label);
button.type = 'button';
button.dataset.days = String(preset.days);
button.addEventListener('click', () => {
state.preset = preset.days;
syncFilters();
render();
});
presets.append(button);
}
const from = $(bar, 'custom-from');
const to = $(bar, 'custom-to');
const apply = $(bar, 'custom-apply');
apply.addEventListener('click', () => {
if (!isDay(from.value) || !isDay(to.value)) {
setRangeSummary('Enter both dates as YYYY-MM-DD.');
return;
}
if (from.value > to.value) {
setRangeSummary('The start date must come before the end date.');
return;
}
state.preset = 'custom';
state.custom = { from: from.value, to: to.value };
syncFilters();
render();
});
$(bar, 'refresh').addEventListener('click', () => {
refreshMeta().finally(render);
});
}
function syncFilters() {
const bar = document.getElementById('filters');
for (const button of bar.querySelectorAll('button.range')) {
const selected = String(state.preset) === button.dataset.days;
button.classList.toggle('is-selected', selected);
button.setAttribute('aria-pressed', String(selected));
}
const { from, to } = currentRange();
$(bar, 'custom-from').value = from;
$(bar, 'custom-to').value = to;
}
function setRangeSummary(text) {
document.getElementById('range-summary').textContent = text;
}
function buildPanels() {
const grid = document.getElementById('grid');
for (const panel of PANELS) {
const section = el('section', `panel span-${panel.span}`);
section.id = `panel-${panel.id}`;
section.dataset.panel = panel.id;
section.dataset.state = 'loading';
const head = el('div', 'panel-head');
head.append(el('h2', null, panel.title));
const figure = el('p', 'panel-figure');
figure.dataset.role = 'figure';
head.append(figure);
section.append(head);
if (panel.note) section.append(el('p', 'panel-note', panel.note));
const body = el('div', 'panel-body');
body.dataset.role = 'body';
if (panel.kind === 'chart') {
const wrap = el('div', 'chart-wrap');
const canvas = document.createElement('canvas');
canvas.dataset.role = 'canvas';
// Chart.js renders to canvas, so the accessible copy is the table twin
// below — say so rather than leaving a bare graphic.
canvas.setAttribute('role', 'img');
canvas.setAttribute('aria-label', `${panel.title}. The same data is in the table below.`);
wrap.append(canvas);
body.append(wrap);
} else if (panel.kind === 'stat') {
const stat = el('div', 'stat');
stat.dataset.role = 'stat';
stat.append(el('p', 'stat-value'), el('p', 'stat-caption'));
body.append(stat);
} else if (panel.kind === 'funnel') {
const funnel = el('div', 'funnel');
funnel.dataset.role = 'funnel';
body.append(funnel);
}
const status = el('p', 'panel-state');
status.dataset.role = 'state';
body.append(status);
section.append(body);
const toggle = el('button', 'link', 'Show numbers');
toggle.type = 'button';
toggle.dataset.role = 'toggle';
toggle.setAttribute('aria-expanded', 'false');
const table = el('div', 'table-wrap');
table.dataset.role = 'table';
table.hidden = true;
toggle.addEventListener('click', () => {
const open = table.hidden;
table.hidden = !open;
toggle.textContent = open ? 'Hide numbers' : 'Show numbers';
toggle.setAttribute('aria-expanded', String(open));
if (open) state.openTables.add(panel.id);
else state.openTables.delete(panel.id);
});
section.append(toggle, table);
grid.append(section);
}
}
// ---------------------------------------------------------------------------
// Drawing one panel
// ---------------------------------------------------------------------------
function setState(section, name, message) {
section.dataset.state = name;
$(section, 'state').textContent = message ?? '';
}
function drawTable(section, spec) {
const host = $(section, 'table');
host.replaceChildren();
if (!spec) return;
const table = el('table');
const thead = el('thead');
const headRow = el('tr');
for (const column of spec.columns) {
const th = el('th', null, column);
th.scope = 'col';
headRow.append(th);
}
thead.append(headRow);
const tbody = el('tbody');
for (const row of spec.rows) {
const tr = el('tr');
row.forEach((cell, i) => {
const node = el(i === 0 ? 'th' : 'td', null, String(cell));
if (i === 0) node.scope = 'row';
tr.append(node);
});
tbody.append(tr);
}
table.append(thead, tbody);
host.append(table);
}
function drawStat(section, stat) {
const host = $(section, 'stat');
host.querySelector('.stat-value').textContent = stat.value;
host.querySelector('.stat-caption').textContent = stat.caption ?? '';
}
/**
* The two-stage conversion funnel, drawn as proportional bars rather than a
* chart: two bars and a percentage is the whole story, and a two-slice pie or a
* two-bar chart would be more chrome than data.
*/
function drawFunnel(section, funnel) {
const host = $(section, 'funnel');
host.replaceChildren();
for (const stage of funnel.stages) {
const row = el('div', 'funnel-stage');
const head = el('div', 'funnel-label');
head.append(el('span', null, stage.label), el('span', 'funnel-value', stage.value.toLocaleString('en-US')));
const track = el('div', 'funnel-track');
const fill = el('div', 'funnel-fill');
// Width is the datum, so it is set from JS rather than a style attribute —
// the CSP here allows no inline styles at all.
fill.style.width = `${Math.max(0, Math.min(1, stage.share)) * 100}%`;
track.append(fill);
row.append(head, track);
host.append(row);
}
const rate = funnel.rate === null ? '—' : `${(funnel.rate * 100).toFixed(1)}%`;
host.append(
el('p', 'funnel-summary', `${rate} converted · ${funnel.dropped.toLocaleString('en-US')} dropped off`),
);
}
function drawChart(section, panel, config) {
const canvas = $(section, 'canvas');
const existing = charts.get(panel.id);
if (existing) existing.destroy();
charts.set(panel.id, new Chart(canvas, config));
}
async function drawPanel(panel, request, token) {
const section = document.getElementById(`panel-${panel.id}`);
section.dataset.stale = 'true';
try {
const data = await request;
// A slower panel from a superseded render must never overwrite the current one.
if (token !== state.renderToken) return;
if (panel.empty?.(data)) {
setState(section, 'empty', 'Nothing in this range.');
drawTable(section, panel.table?.(data));
return;
}
if (panel.kind === 'stat') drawStat(section, panel.stat(data));
else if (panel.kind === 'funnel') drawFunnel(section, panel.funnel(data));
else drawChart(section, panel, panel.chart(data));
$(section, 'figure').textContent = panel.figure ? panel.figure(data) : '';
drawTable(section, panel.table?.(data));
setState(section, 'ready');
} catch (err) {
if (token !== state.renderToken) return;
// One panel's failure is one panel's problem: the message lands in the
// panel, the rest of the page keeps its data.
setState(section, 'error', `Could not load this panel — ${err.message ?? err}`);
const chart = charts.get(panel.id);
if (chart) {
chart.destroy();
charts.delete(panel.id);
}
} finally {
if (token === state.renderToken) section.dataset.stale = 'false';
}
}
// ---------------------------------------------------------------------------
// Rendering everything
// ---------------------------------------------------------------------------
async function refreshMeta() {
try {
const meta = await api('/api/meta');
if (meta.latest_day) state.anchor = meta.latest_day;
state.earliest = meta.earliest_day ?? null;
syncFilters();
} catch {
// A meta failure is not fatal: the picker falls back to today's date and
// every panel still answers. The banner is what says so.
document.getElementById('data-through').textContent = 'Could not read the data range.';
}
}
async function render() {
const token = ++state.renderToken;
const { from, to } = currentRange();
const query = `from=${from}&to=${to}`;
setRangeSummary(`${shortDay(from)} ${shortDay(to)}, ${to.slice(0, 4)}`);
document.getElementById('data-through').textContent = `Data through ${shortDay(state.anchor)}`;
// Deduplicate identical URLs within THIS render only — the four stat tiles
// share one /api/summary. Discarded when the render ends, so refresh refetches.
const inFlight = new Map();
const request = (path) => {
if (!inFlight.has(path)) inFlight.set(path, api(path));
return inFlight.get(path);
};
await Promise.allSettled(PANELS.map((panel) => drawPanel(panel, request(panel.source(query)), token)));
if (token === state.renderToken) {
document.getElementById('refreshed-at').textContent =
`Last refreshed ${new Date().toLocaleTimeString('en-US')}`;
document.body.dataset.ready = 'true';
}
}
// ---------------------------------------------------------------------------
// Start
// ---------------------------------------------------------------------------
if (!Chart) {
document.getElementById('data-through').textContent =
'The chart library did not load — run `npm run vendor` and reload.';
} else {
applyChartDefaults(Chart);
buildFilters();
buildPanels();
syncFilters();
await refreshMeta();
await render();
}