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

11 KiB
Raw Permalink Blame History

codegraph telemetry dashboard

The private admin view behind stats.getcodegraph.com. Its sibling telemetry-worker/ writes anonymous usage events into a D1 database; this worker reads them back and draws the charts. Two people use it, so the auth is deliberately the simplest thing that is actually safe: one shared password in a secret, and a long-lived signed cookie.

This directory is in the public repo for the same reason the ingest worker is — the code that touches telemetry should be readable by the people it collects from. Nothing secret lives here: the password and the cookie-signing key are deployment secrets, and the D1 database ID is an identifier, not a credential.

What is gated

Everything except the login page and robots.txt. assets.run_worker_first is true in wrangler.jsonc, so Cloudflare hands every request to src/index.ts before the static asset server sees it — the dashboard HTML, its JS, its CSS and the chart library are all behind the session check, and a request without a valid cookie gets a redirect (pages) or a 401 (/api/*). The login page is rendered inline by the worker rather than served from public/, so the asset directory needs no "is this file public?" judgement calls.

Route Auth Notes
GET /login public Password form. Redirects to / if already signed in.
POST /login public Rate-limited per IP; sets the session cookie on success.
POST /logout public Clears the cookie.
GET /robots.txt public Disallow: /.
GET /api/* required JSON. 401 without a session. See the API below.
everything else required Static assets from public/. 302 /login without a session.

The API

Every endpoint is GET, session-gated, and scoped by ?from=YYYY-MM-DD&to=YYYY-MM-DD (inclusive, UTC days). Ranges wider than 366 days are clamped and say so in range.clamped. Responses come back Chart.js-shaped — labels[] + datasets[] — plus a rows[] in the data's natural shape, which is what each panel's "Show numbers" table renders. Bad input is a 400 with a message, never a guess. Chart data carries Cache-Control: private, max-age=300.

Endpoint Answers
/api/meta The days data actually exists for. The picker anchors its presets on latest_day so no chart ends on a day the nightly rollup has not written yet.
/api/summary Big numbers: production users, active machines, new machines, installs, uninstalls, indexing runs, tool calls.
/api/timeseries?metric= installs_uninstalls, new_installs, production_users, indexing_activity, tool_calls, duration_buckets. One dense point per day — a day with nothing is a zero, not a gap.
/api/breakdown?dim= os, arch, codegraph_version, node_major, language, file_count_bucket, duration_bucket, target, scope, kind, name, client_name, name_error. Optional &event=, &metric=count|machines, &limit=.
/api/activation?window=7 Install → first index funnel, plus the daily rate.
/api/retention Day 014 cohort curve for machines first seen in the range.
/api/health Liveness plus the latest event/rollup day. Uncached.

Everything reads the daily_* rollups and machine_days, which are kept forever, so a chart stays correct for days whose raw events have been purged. /api/activation is the one exception — "did this machine ever run an index" is not a daily aggregate — so it reads raw events and is bounded by the ingest worker's retention window. It reports raw_events_from for that reason.

Two numbers that are easy to misread

Both are labelled honestly in the UI rather than rounded off into something friendlier:

  • Machine-days, not users. daily_dim_counts.machines is per day, so summing it over a range counts a machine once per day it was active. A range-wide distinct count per dimension value is not recoverable from the rollups at all, so the panels that use it say "machine-days" and are share-of-total panels where the distinction does not move the shape. Where a dimension rides several event types, the per-day figure is the largest single-event count rather than their sum, so one machine's install + index + usage on one day is not counted three times.
  • Recent cohorts have not finished converting. A machine that installed yesterday has not had seven days to run an index, so the tail of the activation curve is a floor, not a result. The API marks those days (complete: false, incomplete_from) and the panel says so instead of drawing a cliff and calling it a drop in conversion. Retention does the same thing with a per-day denominator: day k is measured only over the machines that have actually had k days to come back.

How the session works

  • The password is compared in constant time, over SHA-256 digests so the operands are always the same length and nothing about the secret leaks through timing.
  • The cookie is a signed assertion — base64url(payload).base64url(HMAC-SHA256) — not a lookup key. There is no session store; a tampered payload fails the signature check.
  • HttpOnly; Secure; SameSite=Lax; Path=/, Max-Age one year. You sign in once per browser and it survives restarts.
  • The payload carries a fingerprint of the password it was minted against, so rotating ADMIN_PASSWORD signs everyone out — that is the revocation story.
  • Login attempts are capped at 5/min per IP. Unlike the ingest worker, which never reads the client IP at all, this one does — solely as a rate-limit key, never stored or logged.

Deploy

Prereqs: the getcodegraph.com zone on the deploying Cloudflare account (the custom domain auto-provisions DNS + cert), and the D1 database from telemetry-worker/ already created.

cd telemetry-dashboard
npm install
npx wrangler login                      # once

npx wrangler secret put ADMIN_PASSWORD  # the shared password
npx wrangler secret put SESSION_SECRET  # cookie-signing key, e.g. `openssl rand -base64 48`

npm run deploy

Both secrets are required — the worker refuses every request if either is missing, so a half-configured deployment fails closed rather than becoming an open dashboard.

Rotating either one is a wrangler secret put away. Rotating SESSION_SECRET invalidates outstanding cookies too, and is the right move if you think one leaked.

Migrations belong to the writer, not to this worker: apply schema changes from telemetry-worker/ (npm run db:migrate). D1 is read-only here.

Local dev & checks

cp .dev.vars.example .dev.vars   # placeholder secrets; also feeds `wrangler types`
npm run check                    # vendor + wrangler types + tsc --noEmit + deploy --dry-run
npm run seed                     # load scripts/fixture.sql into the LOCAL D1
npm run dev                      # http://localhost:8787

npm run smoke:auth               # the auth gate            (54 assertions)
npm run smoke:api                # the SQL and its numbers  (98 assertions)
npm run smoke:render             # the panels, in a browser (79 assertions)

Each suite starts its own throwaway wrangler dev on its own port and cleans up after itself, so they can be run in any order (DASH_PORT overrides the port).

smoke-auth.sh is the regression net for the gate: unauthenticated requests reach nothing (pages, API and static assets), the cookie is persistent and correctly flagged, flipped/truncated/forged cookies are all rejected, brute force is capped, and rotating the password invalidates existing sessions. Run it after touching src/auth.ts or the route table in src/index.ts.

smoke-api.sh checks every endpoint against scripts/fixture.sql — twelve machines over ten days, listed machine by machine in that file's header, small enough that every expected number was worked out by hand rather than recorded from a passing run. It also covers the boring half: bad dims, malformed dates, backwards ranges and over-wide ranges.

render-check.mjs loads the real page in whatever Chromium is already on the machine (over the DevTools protocol — no new dependency; it skips if there is no browser) and reads the live Chart.js instance behind each canvas, comparing what every panel plotted against the same endpoint fetched from Node. That is what catches a panel wired to the wrong dimension, which neither of the other two suites can see. It also drives the range picker and asserts a clean console, so a CSP regression fails the build. RENDER_SHOT=/tmp/dash.png npm run smoke:render writes a full-page screenshot — the only way to check the things assertions cannot, like label collisions.

Frontend

Plain static files in public/ — one HTML page, ES modules, no framework, no build step.

File Holds
index.html The shell: masthead, the one filter row, an empty grid.
panels.js The panel registry — data in, chart config out, no DOM. Adding a panel is one entry.
theme.js Palette, formatters, and the Chart.js defaults every panel inherits.
app.js The page: range picker, one fetch per panel, loading/empty/error states.

The split is what lets render-check.mjs import the same registry the browser just rendered from, so its expectations cannot drift from the panels under test.

Panels fail alone: each fetches, draws and reports independently, so a failed query leaves the other eighteen on screen. There is no client-side cache — the only reuse is deduplicating identical URLs within a single render (four stat tiles share one /api/summary), and that map is discarded afterwards, so refresh really does re-ask. A refetch dims the previous render rather than tearing it down, so nothing jumps. Every chart has a "Show numbers" table twin, which is what keeps a value from being reachable only by hovering.

Colours

Two scales, both run through the data-viz validator against this dashboard's actual chart surface (#ffffff, the panel fill) rather than picked by eye — the exact results are recorded at the top of theme.js:

  • Categorical #a8342a #2a6f9e #17916a #c98500 — identity (which series). Slot 1 is the brand oxblood stepped up into the legible lightness band. Clears every gate including all-pairs colour-vision separation, with no contrast relief needed.
  • Ordinal #d99a90 #c26a5c #a3423a #7a201a — one hue, light to dark, for scales whose order is their meaning (run length, codebase size), so the ordering is visible in the colour instead of needing the legend.

Nominal bars all take slot 1: colouring them by value would spend the identity channel re-encoding what bar length already shows. If you change a hex, re-run the validator — the red/green pair that "looks fine" is the one that collapses under deuteranopia. Workers Static Assets serves them verbatim, so third-party libraries are copied out of node_modules into public/vendor/ by npm run vendor (wired into dev and deploy). That keeps the version pinned by the lockfile, avoids a third-party origin at runtime, and lets the CSP stay script-src 'self'. public/vendor/ is gitignored — it is build output.

Visual conventions follow the rest of codegraph: flat and editorial, square corners, hairline rules, sentence-case headings, one oxblood accent, no tiny all-caps tracked labels.