Files
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

466 lines
19 KiB
JavaScript
Raw Permalink 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.
#!/usr/bin/env node
/**
* Renders the dashboard in a real browser against the fixture and checks that
* every panel drew, and drew the numbers the API returned.
*
* smoke-api.sh proves the SQL; this proves the other half — that each panel is
* wired to the right endpoint and plots it without mangling it. It reads the
* Chart.js instance off each canvas and compares its dataset arrays against the
* same endpoint fetched straight from Node, so a panel pointed at the wrong dim
* fails here even though both halves are individually fine.
*
* node scripts/render-check.mjs (or: npm run smoke:render)
*
* Zero new dependencies: it drives whatever Chromium is already on the machine
* over the DevTools protocol (Node 22 has WebSocket built in). With no browser
* installed it SKIPS rather than fails — the shell smoke suites stay the
* portable floor, and this is the deeper check where a browser exists.
*/
import { spawn } from 'node:child_process';
import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
const root = dirname(dirname(fileURLToPath(import.meta.url)));
const PORT = Number(process.env.DASH_PORT ?? 8790);
const BASE = `http://127.0.0.1:${PORT}`;
/** The fixture's own window — see scripts/fixture.sql. */
const FROM = '2026-07-01';
const TO = '2026-07-10';
let pass = 0;
let fail = 0;
const ok = (what) => {
console.log(` ok ${what}`);
pass++;
};
const bad = (what, detail) => {
console.log(` FAIL ${what}${detail ? ` (${detail})` : ''}`);
fail++;
};
const check = (what, condition, detail) => (condition ? ok(what) : bad(what, detail));
const same = (what, expected, actual) =>
check(
what,
JSON.stringify(expected) === JSON.stringify(actual),
`expected ${JSON.stringify(expected)}, got ${JSON.stringify(actual)}`,
);
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// ---------------------------------------------------------------------------
// Finding a browser
// ---------------------------------------------------------------------------
/** Expands one `*` in a path segment, newest match first. */
function glob(pattern) {
const [head, ...rest] = pattern.split('*');
const base = dirname(head);
const prefix = head.slice(base.length + 1);
if (!existsSync(base)) return [];
return readdirSync(base)
.filter((name) => name.startsWith(prefix))
.sort()
.reverse()
.map((name) => join(base, name) + rest.join('*'));
}
function findBrowser() {
const home = process.env.HOME ?? '';
const candidates = [
process.env.CHROME_BIN,
...glob(`${home}/Library/Caches/ms-playwright/chromium_headless_shell-*/chrome-headless-shell-mac-arm64/chrome-headless-shell`),
...glob(`${home}/Library/Caches/ms-playwright/chromium_headless_shell-*/chrome-headless-shell-mac-x64/chrome-headless-shell`),
...glob(`${home}/.cache/ms-playwright/chromium_headless_shell-*/chrome-headless-shell-linux/chrome-headless-shell`),
...glob(`${home}/.cache/ms-playwright/chromium-*/chrome-linux/chrome`),
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
'/Applications/Chromium.app/Contents/MacOS/Chromium',
'/usr/bin/chromium',
'/usr/bin/chromium-browser',
'/usr/bin/google-chrome',
];
return candidates.find((path) => path && existsSync(path)) ?? null;
}
// ---------------------------------------------------------------------------
// A minimal DevTools-protocol client
// ---------------------------------------------------------------------------
class CDP {
constructor(socket) {
this.socket = socket;
this.nextId = 1;
this.pending = new Map();
this.events = [];
socket.addEventListener('message', (event) => {
const message = JSON.parse(event.data);
if (message.id !== undefined) {
const waiter = this.pending.get(message.id);
if (!waiter) return;
this.pending.delete(message.id);
if (message.error) waiter.reject(new Error(message.error.message));
else waiter.resolve(message.result);
} else {
this.events.push(message);
}
});
}
static async connect(url) {
const socket = new WebSocket(url);
await new Promise((resolve, reject) => {
socket.addEventListener('open', resolve, { once: true });
socket.addEventListener('error', () => reject(new Error(`cannot reach ${url}`)), { once: true });
});
return new CDP(socket);
}
send(method, params = {}, sessionId) {
const id = this.nextId++;
return new Promise((resolve, reject) => {
this.pending.set(id, { resolve, reject });
this.socket.send(JSON.stringify(sessionId ? { id, method, params, sessionId } : { id, method, params }));
});
}
/** Runs an expression in the page and returns its value, awaiting promises. */
async evaluate(sessionId, expression) {
const result = await this.send(
'Runtime.evaluate',
{ expression, returnByValue: true, awaitPromise: true },
sessionId,
);
if (result.exceptionDetails) {
throw new Error(result.exceptionDetails.exception?.description ?? 'page threw');
}
return result.result.value;
}
}
// ---------------------------------------------------------------------------
// The page probe
// ---------------------------------------------------------------------------
/**
* Runs inside the page. Reads what each panel actually rendered — including the
* live Chart.js instance behind each canvas — rather than trusting that a
* fetch resolved.
*/
const PROBE = `(() => {
const panels = [...document.querySelectorAll('[data-panel]')].map((section) => {
const canvas = section.querySelector('canvas');
const chart = canvas && window.Chart ? window.Chart.getChart(canvas) : null;
return {
id: section.dataset.panel,
state: section.dataset.state,
stale: section.dataset.stale,
title: section.querySelector('h2').textContent,
figure: section.querySelector('[data-role="figure"]').textContent,
note: section.querySelector('.panel-note')?.textContent ?? '',
message: section.querySelector('[data-role="state"]').textContent,
stat: section.querySelector('.stat-value')?.textContent ?? null,
funnelValues: [...section.querySelectorAll('.funnel-value')].map((n) => n.textContent),
funnelWidths: [...section.querySelectorAll('.funnel-fill')].map((n) => n.style.width),
chart: chart && {
type: chart.config.type,
labels: chart.data.labels,
datasets: chart.data.datasets.map((d) => ({ label: d.label, data: d.data })),
legend: chart.options.plugins?.legend?.display !== false,
},
tableRows: section.querySelectorAll('[data-role="table"] tbody tr').length,
tableCols: section.querySelectorAll('[data-role="table"] thead th').length,
tableHidden: section.querySelector('[data-role="table"]').hidden,
};
});
return {
ready: document.body.dataset.ready === 'true',
range: document.getElementById('range-summary').textContent,
dataThrough: document.getElementById('data-through').textContent,
refreshed: document.getElementById('refreshed-at').textContent,
selectedPreset: document.querySelector('button.range.is-selected')?.textContent ?? null,
panels,
};
})()`;
// ---------------------------------------------------------------------------
// Run
// ---------------------------------------------------------------------------
const children = [];
let profileDir = null;
function cleanup() {
for (const child of children) {
try {
child.kill('SIGTERM');
} catch {
/* already gone */
}
}
if (profileDir) rmSync(profileDir, { recursive: true, force: true });
}
process.on('exit', cleanup);
process.on('SIGINT', () => process.exit(130));
function run(command, args, options = {}) {
const child = spawn(command, args, { cwd: root, stdio: 'ignore', ...options });
children.push(child);
return child;
}
async function waitFor(what, probe, attempts = 90) {
for (let i = 0; i < attempts; i++) {
try {
if (await probe()) return true;
} catch {
/* not up yet */
}
await sleep(1000);
}
throw new Error(`timed out waiting for ${what}`);
}
async function main() {
const browserPath = findBrowser();
if (!browserPath) {
console.log('render-check: no Chromium found — skipping.');
console.log(' Set CHROME_BIN, or install Chrome; the shell smoke suites cover the rest.');
return 0;
}
console.log(`Browser: ${browserPath}`);
console.log('Seeding the local D1 fixture…');
const seed = run('./scripts/seed-fixture.sh', [], { stdio: 'inherit' });
const seeded = await new Promise((resolve) => seed.on('exit', resolve));
if (seeded !== 0) throw new Error('seeding failed');
console.log(`Starting wrangler dev on :${PORT}…`);
run('npx', ['wrangler', 'dev', '--port', String(PORT), '--ip', '127.0.0.1']);
await waitFor('wrangler dev', async () => (await fetch(`${BASE}/robots.txt`)).ok);
const password = readFileSync(join(root, '.dev.vars'), 'utf8').match(/^ADMIN_PASSWORD="(.*)"$/m)?.[1];
if (!password) throw new Error('no ADMIN_PASSWORD in .dev.vars');
const login = await fetch(`${BASE}/login`, {
method: 'POST',
body: new URLSearchParams({ password }),
redirect: 'manual',
});
const cookie = login.headers.getSetCookie().find((c) => c.startsWith('cg_admin_session='));
if (!cookie) throw new Error('login did not set a session cookie');
const [name, value] = cookie.split(';')[0].split('=');
profileDir = mkdtempSync(join(tmpdir(), 'cg-dash-profile-'));
// chrome-headless-shell is headless by construction and rejects the flag;
// a full Chrome needs it.
const headlessFlag = browserPath.includes('headless') ? [] : ['--headless=new'];
run(browserPath, [
...headlessFlag,
'--disable-gpu',
'--no-first-run',
'--no-default-browser-check',
'--remote-debugging-port=0',
`--user-data-dir=${profileDir}`,
'about:blank',
]);
let devtoolsPort = null;
await waitFor('the browser', () => {
const portFile = join(profileDir, 'DevToolsActivePort');
if (!existsSync(portFile)) return false;
devtoolsPort = Number(readFileSync(portFile, 'utf8').split('\n')[0]);
return Number.isFinite(devtoolsPort) && devtoolsPort > 0;
}, 30);
const version = await (await fetch(`http://127.0.0.1:${devtoolsPort}/json/version`)).json();
const cdp = await CDP.connect(version.webSocketDebuggerUrl);
const { targetId } = await cdp.send('Target.createTarget', { url: 'about:blank' });
const { sessionId } = await cdp.send('Target.attachToTarget', { targetId, flatten: true });
await cdp.send('Page.enable', {}, sessionId);
await cdp.send('Runtime.enable', {}, sessionId);
await cdp.send('Log.enable', {}, sessionId);
await cdp.send('Network.enable', {}, sessionId);
await cdp.send('Network.setCookie', { url: BASE, name, value, path: '/', httpOnly: true }, sessionId);
await cdp.send('Page.navigate', { url: `${BASE}/` }, sessionId);
await waitFor('the dashboard to finish rendering', async () => {
const view = await cdp.evaluate(sessionId, 'document.body.dataset.ready === "true"');
return view === true;
}, 60);
let view = await cdp.evaluate(sessionId, PROBE);
// -- what loaded ---------------------------------------------------------
console.log('\nThe page renders');
// The very same registry the page just rendered from, imported here so the
// expectations cannot drift from the panels under test.
const { PANELS } = await import(pathToFileURL(join(root, 'public', 'panels.js')).href);
check(`all ${PANELS.length} panels are on the page`, view.panels.length === PANELS.length, `got ${view.panels.length}`);
const broken = view.panels.filter((p) => p.state !== 'ready');
check(
'every panel reached its ready state',
broken.length === 0,
broken.map((p) => `${p.id}: ${p.state} ${p.message}`).join(' | '),
);
check('the default range is the 30-day preset', view.selectedPreset === 'Last 30 days', view.selectedPreset);
check('the range is stated in the filter row', /Jun|Jul/.test(view.range), view.range);
check('the data horizon is stated', view.dataThrough.includes('Jul 10'), view.dataThrough);
check('the refresh time is stated', view.refreshed.startsWith('Last refreshed'), view.refreshed);
// A CSP violation surfaces here as a `security` log entry, which is the point
// of the check: the page must work under `script-src 'self'` with no inline
// styles at all. The favicon 404 is expected — there isn't one — and is the
// only network noise allowed through.
const errors = cdp.events.filter(
(e) =>
(e.method === 'Log.entryAdded' &&
e.params.entry.level === 'error' &&
!/favicon/.test(e.params.entry.url ?? '')) ||
e.method === 'Runtime.exceptionThrown',
);
check(
'no console errors — the strict CSP allows everything the page needs',
errors.length === 0,
errors.map((e) => e.params.entry?.text ?? e.params.exceptionDetails?.text).join(' | '),
);
// -- the range picker really re-queries ----------------------------------
console.log('\nChanging the range re-queries every panel');
await cdp.evaluate(
sessionId,
`document.body.dataset.ready = "";
[...document.querySelectorAll('button.range')].find((b) => b.textContent === 'Last 7 days').click();`,
);
await waitFor('the 7-day render', async () =>
(await cdp.evaluate(sessionId, 'document.body.dataset.ready === "true"')) === true,
);
view = await cdp.evaluate(sessionId, PROBE);
const weekly = view.panels.find((p) => p.id === 'daily-production-users');
check('a daily line now holds 7 points', weekly.chart?.labels.length === 7, `${weekly.chart?.labels.length}`);
check('the 7-day preset is marked selected', view.selectedPreset === 'Last 7 days', view.selectedPreset);
check('every panel re-rendered cleanly', view.panels.every((p) => p.state === 'ready'));
console.log('\nA custom range works the same way');
await cdp.evaluate(
sessionId,
`document.body.dataset.ready = "";
document.querySelector('[data-role="custom-from"]').value = "${FROM}";
document.querySelector('[data-role="custom-to"]').value = "${TO}";
document.querySelector('[data-role="custom-apply"]').click();`,
);
await waitFor('the custom-range render', async () =>
(await cdp.evaluate(sessionId, 'document.body.dataset.ready === "true"')) === true,
);
view = await cdp.evaluate(sessionId, PROBE);
check('the fixture window is 10 days', view.panels.find((p) => p.id === 'daily-production-users').chart?.labels.length === 10);
check('no preset stays highlighted', view.selectedPreset === null, view.selectedPreset);
// -- every panel plots what the API returned ------------------------------
console.log('\nEvery panel plots the APIs own numbers');
const query = `from=${FROM}&to=${TO}`;
const fetched = new Map();
const apiGet = async (path) => {
if (!fetched.has(path)) {
fetched.set(
path,
fetch(`${BASE}${path}`, { headers: { cookie: `${name}=${value}` } }).then((r) => r.json()),
);
}
return fetched.get(path);
};
for (const panel of PANELS) {
const rendered = view.panels.find((p) => p.id === panel.id);
const data = await apiGet(panel.source(query));
if (panel.kind === 'chart') {
const plotted = rendered.chart?.datasets.map((d) => d.data);
same(`${panel.id}: plots the endpoint's series`, data.datasets.map((d) => d.data), plotted);
// A legend is owed wherever colour carries identity: any multi-series
// chart, and every pie (whose slices are identities inside one dataset).
// A single line needs none — the panel title already names it.
const owed = rendered.chart.type === 'pie' || data.datasets.length > 1;
check(
`${panel.id}: a legend exactly where colour carries identity`,
rendered.chart.legend === owed,
`legend ${rendered.chart.legend}, expected ${owed}`,
);
} else if (panel.kind === 'stat') {
same(`${panel.id}: shows the endpoint's number`, panel.stat(data).value, rendered.stat);
} else if (panel.kind === 'funnel') {
same(
`${panel.id}: shows both funnel stages`,
panel.funnel(data).stages.map((s) => s.value.toLocaleString('en-US')),
rendered.funnelValues,
);
}
const table = panel.table(data);
check(
`${panel.id}: the table twin carries every row`,
rendered.tableRows === table.rows.length && rendered.tableCols === table.columns.length,
`${rendered.tableRows}×${rendered.tableCols} vs ${table.rows.length}×${table.columns.length}`,
);
}
// -- a few numbers checked against the fixture by hand --------------------
console.log('\nSpot checks against the fixture, worked out by hand');
const byId = Object.fromEntries(view.panels.map((p) => [p.id, p]));
same('production users is 11 (m12 is the CI machine)', '11', byId['production-users'].stat);
same('installs is 12', '12', byId['installs'].stat);
same('uninstalls is 2', '2', byId['uninstalls'].stat);
same('indexing runs is 13', '13', byId['indexing-runs'].stat);
same('the funnel loses m04 and m06', ['12', '10'], byId['activation-funnel'].funnelValues);
const widths = byId['activation-funnel'].funnelWidths;
check(
'…and draws the drop as a shorter bar',
widths[0] === '100%' && widths[1].startsWith('83.3'),
widths.join(' / '),
);
same('the OS pie is machine-days', ['linux', 'darwin', 'win32'], byId.os.chart.labels);
same('…and its slices are 9 / 8 / 4', [[9, 8, 4]], byId.os.chart.datasets.map((d) => d.data));
check('…with the honest metric named under the title', byId.os.figure === '21 machine-days', byId.os.figure);
same('run length keeps its bucket order', ['<10s', '10-60s', '1-5m', '5m+'], byId['run-length'].chart.labels);
same('languages lead with typescript', 'typescript', byId.languages.chart.labels[0]);
check('retention starts at 100%', byId.retention.chart.datasets[0].data[0] === 100);
// Colour, spacing and label collisions are not things an assertion catches.
// RENDER_SHOT=/tmp/dash.png npm run smoke:render → look at it.
if (process.env.RENDER_SHOT) {
await cdp.send(
'Emulation.setDeviceMetricsOverride',
{ width: 1440, height: 900, deviceScaleFactor: 2, mobile: false },
sessionId,
);
await sleep(500);
const shot = await cdp.send(
'Page.captureScreenshot',
{ format: 'png', captureBeyondViewport: true },
sessionId,
);
writeFileSync(process.env.RENDER_SHOT, Buffer.from(shot.data, 'base64'));
console.log(`\nScreenshot written to ${process.env.RENDER_SHOT}`);
}
console.log('\nPanel copy follows the house rules');
const capsy = view.panels.filter((p) => /^[A-Z0-9 ]{4,}$/.test(p.title));
check('no shouty panel titles', capsy.length === 0, capsy.map((p) => p.title).join(', '));
check('every panel says what it is counting', view.panels.every((p) => p.note.length > 20));
check('tables start closed', view.panels.every((p) => p.tableHidden));
return fail;
}
try {
const failures = await main();
console.log(`\n${pass} passed, ${fail} failed`);
process.exit(failures === 0 ? 0 : 1);
} catch (err) {
console.error(`\nrender-check: ${err.message}`);
process.exit(1);
}