Public: anyone can read this; the crew can change it.

First-party measurement: visitors, users and real page speed, built into the forge and the app template #2702

Parked opened this in answer to
Closed without merging

scout/forge:scout/2674-first-party-measurement-visitors-users-a → main 3 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
13 files changed +713 −5
README.md +4
@@ -1607,3 +1607,7 @@ operator. (The three guards of migrations 62, 70 and 81 predate the prefix and
16071607 are known by name in `src/http/refusal.ts`.) The terminal's toasts follow the
16081608 same rule. A guard installed by hand without the prefix answers `refused`
16091609 until it is re-created with `forge: ` in front of its message.
1610
1611 ## Measuring the forge (first party)
1612
1613 Every page loads a ~1 KB beacon (`src/web/vitals_client.ts`, served content-addressed and immutable) that sends the route, load, TTFB, LCP, INP and CLS to this forge's own `POST /_vitals` when the page is hidden. Nothing leaves the origin. The store keeps the route *pattern* (never the path) and a visitor hash salted per UTC day (never an address); the day's salt is the only one kept, so visitors cannot be followed across days — "visitors, 7 days" is each day's uniques summed. Do Not Track, Global Privacy Control and a `forge_measure=off` cookie are honoured on both ends. Every response carries `Server-Timing`, and server time per route and hour is a histogram. Admins see users, active, visitors and p75 load/interaction on the home ("Measured here"); boards query the `views` and `timings` sources. New apps made from the template carry the same beacon, a `view` table and `bun run src/measure.ts`.
src/apps/scaffold.ts +209 −1
@@ -14,6 +14,7 @@
1414
1515 import { readFileSync } from "node:fs";
1616 import type { FileWrite } from "../git/write.ts";
17 import { vitalsJs } from "../web/vitals_client.ts";
1718
1819 /**
1920 * The evaluator an app decides with is the forge's own, carried as text:
@@ -55,6 +56,7 @@ export function scaffoldFiles(input: ScaffoldInput): FileWrite[] {
5556 { path: "src/security.ts", content: SECURITY_TS },
5657 { path: "src/audit.ts", content: AUDIT_TS },
5758 { path: "src/db.ts", content: DB_TS },
59 { path: "src/measure.ts", content: MEASURE_TS },
5860 { path: "src/actions.ts", content: ACTIONS_TS },
5961 { path: "src/live.ts", content: LIVE_TS },
6062 { path: "src/http.ts", content: HTTP_TS },
@@ -69,9 +71,11 @@ export function scaffoldFiles(input: ScaffoldInput): FileWrite[] {
6971 { path: "scripts/contract-emit.ts", content: CONTRACT_EMIT_TS },
7072 { path: "static/app.css", content: APP_CSS },
7173 { path: "static/live.js", content: LIVE_JS },
74 { path: "static/vitals.js", content: vitalsJs },
7275 { path: "src/who.test.ts", content: WHO_TEST },
7376 { path: "src/signin.test.ts", content: SIGNIN_TEST },
7477 { path: "src/db.test.ts", content: DB_TEST },
78 { path: "src/measure.test.ts", content: MEASURE_TEST },
7579 { path: "src/actions.test.ts", content: ACTIONS_TEST },
7680 { path: "src/contract.test.ts", content: CONTRACT_TEST },
7781 { path: "src/server.test.ts", content: SERVER_TEST },
@@ -165,6 +169,7 @@ decide nothing themselves. \`AGENTS.md\` says how to add to it.
165169 | \`src/http.ts\` | the floor: headers, body cap, files |
166170 | \`src/server.ts\` | boot: open the database, serve |
167171 | \`src/tty.ts\` | the terminal, over the same actions |
172 | \`src/measure.ts\`, \`static/vitals.js\` | first-party measurement: page views, vitals, visitors; \`bun run src/measure.ts\` |
168173 | \`src/env.ts\` | what the forge told this process |
169174 | \`static/app.css\`, \`static/live.js\` | the look in the tokens' words, and the list that stays current |
170175
@@ -830,6 +835,14 @@ export const migrations: string[] = [
830835 user_name TEXT NOT NULL,
831836 expires_at INTEGER NOT NULL
832837 )\`,
838 // What the browser measured per page view (src/measure.ts): the route
839 // pattern and a visitor hash salted per day, no address, no path.
840 \`CREATE TABLE view (
841 at TEXT NOT NULL, day TEXT NOT NULL, route TEXT NOT NULL, visitor TEXT NOT NULL,
842 load REAL, lcp REAL, inp REAL, cls REAL, ttfb REAL
843 )\`,
844 \`CREATE INDEX view_day ON view (day)\`,
845 \`CREATE TABLE view_salt (day TEXT PRIMARY KEY, salt TEXT NOT NULL)\`,
833846 ];
834847
835848 export function openDb(dir = dataDir): Database {
@@ -1703,6 +1716,7 @@ export function layout(body: string, who: Who, path = "/"): string {
17031716 <link rel="stylesheet" href="\${tokensHref}">
17041717 <link rel="stylesheet" href="\${asset("app.css")}">
17051718 <script type="module" src="\${asset("live.js")}"></script>
1719 <script defer src="\${asset("vitals.js")}"></script>
17061720 <body>
17071721 <div class="page">
17081722 <header class="head">
@@ -1820,6 +1834,7 @@ import {
18201834 text,
18211835 } from "./http.ts";
18221836 import { events } from "./live.ts";
1837 import { optedOut, parseBeacon, recordView } from "./measure.ts";
18231838 import { rpc } from "./mcp.ts";
18241839 import { home } from "./page.ts";
18251840 import {
@@ -2268,6 +2283,22 @@ export const routes: readonly Route[] = [
22682283 }),
22692284 },
22702285
2286 // What the page measured (\`static/vitals.js\`), kept by \`measure.ts\`.
2287 {
2288 method: "POST",
2289 path: "/_vitals",
2290 handle: async (c) => {
2291 const done = new Response(null, { status: 204, headers: SECURITY });
2292 if (optedOut(c.request)) return done;
2293 const beacon = parseBeacon(await c.request.text());
2294 if (beacon === null) return text("bad beacon", 400);
2295 const route = match("GET", beacon.path)?.route.path ?? "(unmatched)";
2296 const seed = \`\${c.request.headers.get("user-agent") ?? ""}|\${c.who.role === "anon" ? "" : c.who.id}\`;
2297 recordView(c.db, beacon, route, seed);
2298 return done;
2299 },
2300 },
2301
22712302 // Files under ./static, cached for a year when linked by content (\`asset\`).
22722303 {
22732304 method: "GET",
@@ -2371,6 +2402,7 @@ export function serve(options: ServeOptions) {
23712402 url.pathname,
23722403 );
23732404 if (found === undefined) return text("not found", 404);
2405 const started = performance.now();
23742406 const response = await found.route.handle({
23752407 request,
23762408 url,
@@ -2379,6 +2411,11 @@ export function serve(options: ServeOptions) {
23792411 params: found.params,
23802412 signin: options.signin,
23812413 });
2414 // What the server took, for the browser's network panel.
2415 response.headers.set(
2416 "server-timing",
2417 \`app;dur=\${(performance.now() - started).toFixed(1)}\`,
2418 );
23822419 return head(request, response);
23832420 },
23842421 // A bug answers with the floor and nothing else: never the runtime's
@@ -2415,6 +2452,158 @@ if (import.meta.main) {
24152452 }
24162453 `;
24172454
2455 // First-party measurement.
2456 const MEASURE_TS = `/**
2457 * What the browser measured about each page, kept here and nowhere else
2458 * (\`static/vitals.js\` sends it to \`POST /_vitals\`). A view is a route
2459 * pattern, the vitals and a visitor hash: sha256 of a salt that lives one
2460 * UTC day, the user agent and who signed in. No address, no path, no cookie.
2461 * Do Not Track, Global Privacy Control and \`forge_measure=off\` are honoured.
2462 * Because the salt changes daily, "visitors, 7 days" is each day's uniques
2463 * summed. \`bun run src/measure.ts\` prints the numbers.
2464 */
2465
2466 import type { Database } from "bun:sqlite";
2467 import { createHash, randomUUID } from "node:crypto";
2468 import { dataDir } from "./env.ts";
2469 import { openDb } from "./db.ts";
2470
2471 export const METRICS = ["load", "lcp", "inp", "cls", "ttfb"] as const;
2472 export type Beacon = { path: string } & Partial<Record<(typeof METRICS)[number], number>>;
2473
2474 /** A beacon body as plain data, or null when anything is off. */
2475 export function parseBeacon(body: string): Beacon | null {
2476 if (body.length > 1024) return null;
2477 let raw: unknown;
2478 try {
2479 raw = JSON.parse(body);
2480 } catch {
2481 return null;
2482 }
2483 if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null;
2484 const o = raw as Record<string, unknown>;
2485 const path = o.p;
2486 if (typeof path !== "string" || !path.startsWith("/") || path.length > 512 || /[\\u0000-\\u001f\\u007f]/.test(path))
2487 return null;
2488 const out: Beacon = { path };
2489 for (const m of METRICS) {
2490 const v = o[m];
2491 if (v === undefined || v === null) continue;
2492 if (typeof v !== "number" || !Number.isFinite(v) || v < 0 || v > (m === "cls" ? 100 : 600_000)) return null;
2493 out[m] = v;
2494 }
2495 return out;
2496 }
2497
2498 export function optedOut(request: Request): boolean {
2499 const h = request.headers;
2500 return (
2501 h.get("dnt") === "1" ||
2502 h.get("sec-gpc") === "1" ||
2503 /(?:^|;\\s*)forge_measure=off(?:;|$)/.test(h.get("cookie") ?? "")
2504 );
2505 }
2506
2507 export function recordView(
2508 db: Database,
2509 beacon: Beacon,
2510 route: string,
2511 seed: string,
2512 now = new Date(),
2513 ): void {
2514 const day = now.toISOString().slice(0, 10);
2515 let salt = db.query<{ salt: string }, [string]>("SELECT salt FROM view_salt WHERE day = ?1").get(day)?.salt;
2516 if (salt === undefined) {
2517 salt = randomUUID();
2518 db.transaction(() => {
2519 db.query("DELETE FROM view_salt WHERE day <> ?1").run(day);
2520 db.query("INSERT OR IGNORE INTO view_salt (day, salt) VALUES (?1, ?2)").run(day, salt!);
2521 db.query("DELETE FROM view WHERE day < date(?1, '-90 days')").run(day);
2522 })();
2523 salt = db.query<{ salt: string }, [string]>("SELECT salt FROM view_salt WHERE day = ?1").get(day)!.salt;
2524 }
2525 const visitor = createHash("sha256").update(\`\${salt}|\${seed}\`).digest("hex").slice(0, 16);
2526 db.query(
2527 "INSERT INTO view (at, day, route, visitor, load, lcp, inp, cls, ttfb) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
2528 ).run(
2529 now.toISOString(), day, route.slice(0, 200), visitor,
2530 beacon.load ?? null, beacon.lcp ?? null, beacon.inp ?? null, beacon.cls ?? null, beacon.ttfb ?? null,
2531 );
2532 }
2533
2534 const p75 = (db: Database, column: "load" | "inp", day: string): number | null => {
2535 const n = db.query<{ n: number }, [string]>(\`SELECT COUNT(\${column}) AS n FROM view WHERE day >= ?1\`).get(day)!.n;
2536 if (n === 0) return null;
2537 return (
2538 db
2539 .query<{ v: number }, [string, number]>(
2540 \`SELECT \${column} AS v FROM view WHERE day >= ?1 AND \${column} IS NOT NULL ORDER BY \${column} LIMIT 1 OFFSET ?2\`,
2541 )
2542 .get(day, Math.ceil(n * 0.75) - 1)?.v ?? null
2543 );
2544 };
2545
2546 export function stats(db: Database, now = new Date()) {
2547 const today = now.toISOString().slice(0, 10);
2548 const week = new Date(now.getTime() - 6 * 86_400_000).toISOString().slice(0, 10);
2549 const n = (sql: string, day: string): number => db.query<{ n: number }, [string]>(sql).get(day)!.n;
2550 return {
2551 viewsToday: n("SELECT COUNT(*) AS n FROM view WHERE day = ?1", today),
2552 visitorsToday: n("SELECT COUNT(DISTINCT visitor) AS n FROM view WHERE day = ?1", today),
2553 visitors7: n("SELECT COUNT(*) AS n FROM (SELECT DISTINCT day, visitor FROM view WHERE day >= ?1)", week),
2554 p75Load: p75(db, "load", week),
2555 p75Inp: p75(db, "inp", week),
2556 };
2557 }
2558
2559 if (import.meta.main) console.log(stats(openDb(dataDir)));
2560 `;
2561
2562 const MEASURE_TEST = `import { expect, test } from "bun:test";
2563 import { Database } from "bun:sqlite";
2564 import { migrate } from "./db.ts";
2565 import { optedOut, parseBeacon, recordView, stats } from "./measure.ts";
2566
2567 const fresh = () => {
2568 const db = new Database(":memory:");
2569 migrate(db);
2570 return db;
2571 };
2572
2573 test("a page view lands with its vitals and counts as a visitor", () => {
2574 const db = fresh();
2575 const beacon = parseBeacon('{"p":"/","load":900,"inp":120,"lcp":800,"cls":0.01,"ttfb":50}')!;
2576 recordView(db, beacon, "/", "agent|anon");
2577 recordView(db, beacon, "/", "agent|anon");
2578 recordView(db, beacon, "/", "other|anon");
2579 const s = stats(db);
2580 expect(s.visitorsToday).toBe(2);
2581 expect(s.viewsToday).toBe(3);
2582 expect(s.p75Load).toBe(900);
2583 expect(s.p75Inp).toBe(120);
2584 });
2585
2586 test("no address, path or seed is stored", () => {
2587 const db = fresh();
2588 recordView(db, parseBeacon('{"p":"/secret-repo"}')!, "/:name", "Mozilla 10.0.0.7|anon");
2589 const dump = JSON.stringify(db.query("SELECT * FROM view").all());
2590 expect(dump).not.toContain("10.0.0.7");
2591 expect(dump).not.toContain("secret-repo");
2592 });
2593
2594 test("a malformed beacon is refused", () => {
2595 for (const bad of ["", "[]", '{"p":"x"}', '{"p":"/","load":-1}', '{"p":"/","load":"1"}', '{"p":"/a\\\\u0000"}', '{"p":"/","cls":1e9}'])
2596 expect(parseBeacon(bad)).toBeNull();
2597 });
2598
2599 test("an opt-out is honoured", () => {
2600 expect(optedOut(new Request("http://x/", { headers: { dnt: "1" } }))).toBe(true);
2601 expect(optedOut(new Request("http://x/", { headers: { "sec-gpc": "1" } }))).toBe(true);
2602 expect(optedOut(new Request("http://x/", { headers: { cookie: "a=b; forge_measure=off" } }))).toBe(true);
2603 expect(optedOut(new Request("http://x/"))).toBe(false);
2604 });
2605 `;
2606
24182607 // The terminal.
24192608 const TTY_TS = `/**
24202609 * The app in a terminal. The forge runs this on a pty when someone
@@ -3248,6 +3437,7 @@ import { tmpdir } from "node:os";
32483437 import { join } from "node:path";
32493438 import { openDb } from "./db.ts";
32503439 import { env } from "./env.ts";
3440 import { stats } from "./measure.ts";
32513441 import { serve } from "./server.ts";
32523442 import { sign } from "./who.ts";
32533443
@@ -3604,6 +3794,19 @@ test("what the web expects: robots.txt, and security.txt from the forge that run
36043794 );
36053795 }
36063796 });
3797
3798 test("the beacon lands over HTTP, honours DNT, and every page carries Server-Timing", async () => {
3799 const send = (headers: Record<string, string> = {}) =>
3800 fetch(base + "/_vitals", { method: "POST", headers, body: '{"p":"/","load":700}' });
3801 expect((await send()).status).toBe(204);
3802 expect((await send({ dnt: "1" })).status).toBe(204);
3803 expect((await send({ origin: "https://evil.example" })).status).toBe(403);
3804 const db = openDb(dataDir);
3805 expect(stats(db).viewsToday).toBe(1);
3806 db.close();
3807 expect((await fetch(base + "/")).headers.get("server-timing")).toMatch(/^app;dur=/);
3808 expect(await (await fetch(base + "/")).text()).toContain("vitals.js");
3809 });
36073810 `;
36083811
36093812 // The look, as data.
@@ -4041,6 +4244,8 @@ export const WRITES: Rate = { burst: 20, perSecond: 2 };
40414244 export const STRANGERS: Rate = { burst: 60, perSecond: 10 };
40424245 /** Each start of a sign-in writes a row; one address may not flush the rest. Behind the forge this is everyone together. */
40434246 export const SIGNINS: Rate = { burst: 20, perSecond: 1 };
4247 /** Page-view beacons: one per page left, so they ration apart from writes. */
4248 export const VIEWS: Rate = { burst: 60, perSecond: 10 };
40444249 const buckets = new Map<string, { tokens: number; at: number }>();
40454250 export function allow(
40464251 key: string,
@@ -4144,8 +4349,11 @@ export function door(
41444349 url.pathname === "/mcp" ||
41454350 url.pathname === "/openapi.json";
41464351 const key = stranger ? \`ip:\${from}\` : \`user:\${who.id}\`;
4352 const beacon = url.pathname === "/_vitals";
41474353
4148 if (writing && !allow(key)) return text("too many requests", 429);
4354 if (beacon && !allow(\`views:\${from}\`, VIEWS))
4355 return text("too many requests", 429);
4356 if (writing && !beacon && !allow(key)) return text("too many requests", 429);
41494357 if (url.pathname === "/signin" && !allow(\`signin:\${from}\`, SIGNINS))
41504358 return text("too many requests", 429);
41514359 if (stranger && api && !allow(\`api:\${from}\`, STRANGERS))
src/boards/sources.ts +33
@@ -139,6 +139,39 @@ export const SOURCES: Readonly<Record<string, Source>> = {
139139 n: "requests in that hour with that pattern, method, status class, role and surface",
140140 },
141141 },
142 // Page views the first-party beacon reported (`core/vitals.ts`, #2674): the
143 // route pattern, never the path, and the browser's own timings. The visitor
144 // hash is not listed, so no query can follow anyone.
145 views: {
146 table: "pageview",
147 owner: "admin",
148 time: "at",
149 columns: {
150 at: "time", day: "text", route: "text",
151 load: "number", lcp: "number", inp: "number", cls: "number", ttfb: "number",
152 },
153 docs: {
154 route: "the route pattern that served the page, or (unmatched)",
155 load: "ms from navigation start to the end of the load event",
156 lcp: "ms to the largest contentful paint",
157 inp: "ms, the slowest interaction seen on the page",
158 cls: "cumulative layout shift, unitless",
159 ttfb: "ms from navigation start to the first byte",
160 },
161 },
162 // Server time per route, as a histogram by the hour: `le` is the bucket's
163 // upper bound in ms and `n` the requests that fell in it.
164 timings: {
165 table: "route_timing",
166 owner: "admin",
167 time: "hour",
168 columns: { hour: "time", pattern: "text", le: "number", n: "number" },
169 docs: {
170 hour: "the hour, UTC, like 2026-10-16T13",
171 le: "the bucket's upper bound in ms (5, 10, 25, 50, 100, 250, 500, 1000, 2500, 1000000)",
172 n: "requests in that hour on that route that took at most le ms and more than the bucket before",
173 },
174 },
142175 // Browser sign-ins: one row per session. The token hash and the session
143176 // id are not listed. Failed sign-ins are not a row anywhere; they are the
144177 // `usage` rows for POST /signin with a 4xx status.
src/core/migrations/20261019130000-vitals.ts added +17
@@ -0,0 +1,17 @@
1 // First-party measurement (#2674). `pageview`: one row per page view the
2 // browser beacon reported, with the route pattern (never the path) and the
3 // visitor as a hash salted per day; no address is kept. `vitals_salt`: the
4 // salt of the current day only. `route_timing`: a histogram of server time
5 // per route and hour, `le` the bucket's upper bound in ms.
6 export default `
7 CREATE TABLE pageview (
8 at TEXT NOT NULL, day TEXT NOT NULL, route TEXT NOT NULL, visitor TEXT NOT NULL,
9 load REAL, lcp REAL, inp REAL, cls REAL, ttfb REAL
10 );
11 CREATE INDEX pageview_at ON pageview (at);
12 CREATE TABLE vitals_salt (day TEXT PRIMARY KEY, salt TEXT NOT NULL);
13 CREATE TABLE route_timing (
14 hour TEXT, pattern TEXT, le INTEGER, n INTEGER NOT NULL DEFAULT 0,
15 PRIMARY KEY (hour, pattern, le)
16 ) WITHOUT ROWID;
17 `;
src/core/vitals.ts added +198
@@ -0,0 +1,198 @@
1 /**
2 * First-party measurement: what the browser beacon reports, kept privately.
3 *
4 * A page view is a route pattern, the vitals the browser measured and a
5 * visitor hash. The hash is sha256 of a random salt that lives for one UTC
6 * day, the address and the user agent; the salt of a past day is deleted, so
7 * yesterday's hashes cannot be recomputed and nobody can be followed across
8 * days. The address itself is an argument and is never written. Because the
9 * hash changes daily, "visitors this week" is the sum of each day's uniques.
10 */
11
12 import type { Database } from "bun:sqlite";
13 import { sha256 } from "../kernel/hash.ts";
14
15 export const METRICS = ["load", "lcp", "inp", "cls", "ttfb"] as const;
16 export type Metric = (typeof METRICS)[number];
17 export type Beacon = { path: string } & Partial<Record<Metric, number>>;
18
19 const MAX_BODY = 1024;
20 const MAX_PATH = 512;
21 const MAX_MS = 600_000;
22 const MAX_CLS = 100;
23 const KEEP_DAYS = 90;
24 const PER_MINUTE = 30;
25 /** Upper bounds, in ms, of the server-time histogram. The last catches the rest. */
26 export const BUCKETS = [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 1_000_000] as const;
27
28 const isCtl = (s: string): boolean => /[\u0000-\u001f\u007f]/.test(s);
29
30 /** A beacon body as plain data, or null when anything is off. */
31 export function parseBeacon(text: string): Beacon | null {
32 if (text.length > MAX_BODY) return null;
33 let raw: unknown;
34 try {
35 raw = JSON.parse(text);
36 } catch {
37 return null;
38 }
39 if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return null;
40 const o = raw as Record<string, unknown>;
41 const path = o.p;
42 if (typeof path !== "string" || !path.startsWith("/") || path.length > MAX_PATH || isCtl(path))
43 return null;
44 const out: Beacon = { path };
45 for (const m of METRICS) {
46 const v = o[m];
47 if (v === undefined || v === null) continue;
48 if (typeof v !== "number" || !Number.isFinite(v) || v < 0 || v > (m === "cls" ? MAX_CLS : MAX_MS))
49 return null;
50 out[m] = v;
51 }
52 return out;
53 }
54
55 /** True when the client asked not to be measured: Do Not Track, Global Privacy Control, or our cookie. */
56 export function optedOut(request: Request): boolean {
57 const h = request.headers;
58 if (h.get("dnt") === "1" || h.get("sec-gpc") === "1") return true;
59 return /(?:^|;\s*)forge_measure=off(?:;|$)/.test(h.get("cookie") ?? "");
60 }
61
62 const day = (at: Date): string => at.toISOString().slice(0, 10);
63
64 function saltOf(db: Database, today: string): string {
65 const row = db.query<{ salt: string }, [string]>("SELECT salt FROM vitals_salt WHERE day = ?1").get(today);
66 if (row) return row.salt;
67 const salt = crypto.randomUUID() + crypto.randomUUID();
68 db.transaction(() => {
69 db.query("DELETE FROM vitals_salt WHERE day <> ?1").run(today);
70 db.query("INSERT OR IGNORE INTO vitals_salt (day, salt) VALUES (?1, ?2)").run(today, salt);
71 const cutoff = new Date(Date.parse(today) - KEEP_DAYS * 86_400_000).toISOString();
72 db.query("DELETE FROM pageview WHERE at < ?1").run(cutoff);
73 })();
74 return db.query<{ salt: string }, [string]>("SELECT salt FROM vitals_salt WHERE day = ?1").get(today)!.salt;
75 }
76
77 const minute = new WeakMap<Database, { at: number; seen: Map<string, number> }>();
78
79 /**
80 * Store one view. `address` and `agent` only feed the hash. Returns false
81 * when this visitor has sent too many this minute (nothing is stored).
82 */
83 export function recordView(
84 db: Database,
85 beacon: Beacon,
86 route: string,
87 who: { address: string; agent: string },
88 now: Date = new Date(),
89 ): boolean {
90 const today = day(now);
91 const visitor = sha256(`${saltOf(db, today)}|${who.address}|${who.agent}`).slice(0, 16);
92 const slot = Math.floor(now.getTime() / 60_000);
93 let bucket = minute.get(db);
94 if (bucket === undefined || bucket.at !== slot) {
95 bucket = { at: slot, seen: new Map() };
96 minute.set(db, bucket);
97 }
98 const n = (bucket.seen.get(visitor) ?? 0) + 1;
99 bucket.seen.set(visitor, n);
100 if (n > PER_MINUTE) return false;
101 db.query(
102 `INSERT INTO pageview (at, day, route, visitor, load, lcp, inp, cls, ttfb)
103 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)`,
104 ).run(
105 now.toISOString(), today, route.slice(0, 200), visitor,
106 beacon.load ?? null, beacon.lcp ?? null, beacon.inp ?? null, beacon.cls ?? null, beacon.ttfb ?? null,
107 );
108 return true;
109 }
110
111 export interface Kpis {
112 users: number;
113 activeToday: number;
114 active7: number;
115 visitorsToday: number;
116 /** The sum of each day's unique visitors: the daily salt cannot join days. */
117 visitors7: number;
118 views7: number;
119 p75Load: number | null;
120 p75Inp: number | null;
121 }
122
123 function p75(db: Database, column: "load" | "inp", since: string): number | null {
124 const n = db
125 .query<{ n: number }, [string]>(`SELECT COUNT(${column}) AS n FROM pageview WHERE at >= ?1`)
126 .get(since)!.n;
127 if (n === 0) return null;
128 const row = db
129 .query<{ v: number }, [string, number]>(
130 `SELECT ${column} AS v FROM pageview WHERE at >= ?1 AND ${column} IS NOT NULL ORDER BY ${column} LIMIT 1 OFFSET ?2`,
131 )
132 .get(since, Math.min(n - 1, Math.ceil(n * 0.75) - 1));
133 return row?.v ?? null;
134 }
135
136 export function kpis(db: Database, now: Date = new Date()): Kpis {
137 const today = day(now);
138 const week = new Date(now.getTime() - 6 * 86_400_000);
139 const weekDay = day(week);
140 const since = `${weekDay}T00:00:00.000Z`;
141 const count = (sql: string, ...p: string[]): number => db.query<{ n: number }, string[]>(sql).get(...p)!.n;
142 return {
143 users: count("SELECT COUNT(*) AS n FROM user WHERE kind = 'user'"),
144 activeToday: count("SELECT COUNT(DISTINCT user_id) AS n FROM session WHERE last_seen_at >= ?1", `${today}T00:00:00.000Z`),
145 active7: count("SELECT COUNT(DISTINCT user_id) AS n FROM session WHERE last_seen_at >= ?1", since),
146 visitorsToday: count("SELECT COUNT(DISTINCT visitor) AS n FROM pageview WHERE day = ?1", today),
147 visitors7: count("SELECT COUNT(*) AS n FROM (SELECT DISTINCT day, visitor FROM pageview WHERE day >= ?1)", weekDay),
148 views7: count("SELECT COUNT(*) AS n FROM pageview WHERE day >= ?1", weekDay),
149 p75Load: p75(db, "load", since),
150 p75Inp: p75(db, "inp", since),
151 };
152 }
153
154 /** The histogram bucket a duration falls in. */
155 export const bucketOf = (ms: number): number => BUCKETS.find((b) => ms <= b) ?? BUCKETS[BUCKETS.length - 1]!;
156
157 export interface RouteTimer {
158 record(pattern: string, ms: number): void;
159 flush(): void;
160 }
161
162 /** Server time per route and hour: counted in memory, written in bulk about a second later. */
163 export function createRouteTimer(db: Database, now: () => Date = () => new Date()): RouteTimer {
164 const pending = new Map<string, number>();
165 let timer: ReturnType<typeof setTimeout> | null = null;
166 const flush = (): void => {
167 if (timer) clearTimeout(timer);
168 timer = null;
169 if (pending.size === 0) return;
170 const batch = [...pending];
171 pending.clear();
172 try {
173 const up = db.query(
174 `INSERT INTO route_timing (hour, pattern, le, n) VALUES (?1, ?2, ?3, ?4)
175 ON CONFLICT (hour, pattern, le) DO UPDATE SET n = n + excluded.n`,
176 );
177 db.transaction(() => {
178 for (const [key, n] of batch) {
179 const [hour, pattern, le] = key.split("\u0000") as [string, string, string];
180 up.run(hour, pattern, Number(le), n);
181 }
182 })();
183 } catch {
184 for (const [k, n] of batch) pending.set(k, (pending.get(k) ?? 0) + n);
185 }
186 };
187 return {
188 record(pattern, ms) {
189 const key = [now().toISOString().slice(0, 13), pattern.slice(0, 200), bucketOf(ms)].join("\u0000");
190 pending.set(key, (pending.get(key) ?? 0) + 1);
191 if (timer === null) {
192 timer = setTimeout(flush, 1000);
193 timer.unref();
194 }
195 },
196 flush,
197 };
198 }
src/http/server.ts +29 −3
@@ -98,6 +98,7 @@ import {
9898 assetResponse,
9999 highlightAsset,
100100 shellAsset,
101 vitalsAsset,
101102 stylesheetAsset,
102103 stylesheetRedirect,
103104 stylesheetResponse,
@@ -444,6 +445,8 @@ import { proposalGate } from "./proposal_gate.ts";
444445 import { feedRoutes } from "./feed.ts";
445446 import type { Database } from "bun:sqlite";
446447 import { mcpRoutes } from "./mcp.ts";
448 import { vitalsSubmit } from "./vitals.ts";
449 import { createRouteTimer, type RouteTimer } from "../core/vitals.ts";
447450 import { createUsageCounter, type UsageCounter } from "../core/usage_count.ts";
448451 import { methodOf, noteUsage, roleOf, surfaceOf, takeUsage } from "./usage_tag.ts";
449452 import { oauthRoutes } from "./oauth.ts";
@@ -633,6 +636,7 @@ export function buildRouter(): Router<Handler> {
633636 router.add("GET", "/assets/:name.js", async (ctx) => {
634637 const shell = shellAsset();
635638 if (ctx.params.name === shell.name) return assetResponse(shell);
639 if (ctx.params.name === vitalsAsset().name) return assetResponse(vitalsAsset());
636640 if (ctx.params.name === TOOLBAR_NAME) return toolbarResponse();
637641 const asset = await highlightAsset();
638642 if (asset === null || ctx.params.name !== asset.name) return notFound();
@@ -641,6 +645,9 @@ export function buildRouter(): Router<Handler> {
641645 // The service worker: root scope needs a root path, and it must never be
642646 // cached by the browser's HTTP cache or an update would wait a day.
643647 router.add("GET", "/sw.js", serviceWorker);
648 router.add("POST", "/_vitals", (ctx) =>
649 vitalsSubmit(ctx, (path) => router.match("GET", path)?.pattern),
650 );
644651 router.add("GET", "/", home);
645652 // A spawned child's claim link: GET shows, POST takes it (spawn/claim.ts).
646653 router.add("GET", "/claim", claimFragmentPage);
@@ -2038,8 +2045,27 @@ export async function serve(app: App): Promise<Servers> {
20382045 // One counter per database: a hosted child counts in its own. `count` is a
20392046 // map increment; a refused event would be a programming error, not worth a 500.
20402047 const counters = new Map<Database, UsageCounter>();
2041 const counted = (owner: App, request: Request, response: Response): void => {
2048 const timers = new Map<Database, RouteTimer>();
2049 const counted = (
2050 owner: App,
2051 request: Request,
2052 response: Response,
2053 ms: number,
2054 ): void => {
20422055 const tag = takeUsage(request);
2056 try {
2057 let timer = timers.get(owner.db);
2058 if (timer === undefined) {
2059 timer = createRouteTimer(owner.db);
2060 timers.set(owner.db, timer);
2061 }
2062 timer.record(tag.pattern, ms);
2063 // The browser shows this in its network panel; the beacon's own
2064 // numbers say what the person felt, this says what the server took.
2065 response.headers.set("server-timing", `app;dur=${ms.toFixed(1)}`);
2066 } catch {
2067 // A response the forge only carries has immutable headers: unmeasured, not broken.
2068 }
20432069 try {
20442070 let counter = counters.get(owner.db);
20452071 if (counter === undefined) {
@@ -2133,7 +2159,7 @@ export async function serve(app: App): Promise<Servers> {
21332159 notePeer(request, server.requestIP(request)?.address, trust);
21342160 armClose(request, () => server.timeout(request, 1));
21352161 const response = await answered(child, request, () => http.handle(request));
2136 counted(child, request, response);
2162 counted(child, request, response, performance.now() - started);
21372163 logged(key, request, response, started);
21382164 await settleBody(request);
21392165 if (!mustClose(request)) return response;
@@ -2152,7 +2178,7 @@ export async function serve(app: App): Promise<Servers> {
21522178 const response = await answered(app, request, () =>
21532179 answer(app, router, apiRouter, limiter, request),
21542180 );
2155 counted(app, request, response);
2181 counted(app, request, response, performance.now() - started);
21562182 logged(app.config.dataDir, request, response, started);
21572183 await settleBody(request);
21582184 if (!mustClose(request)) return response;
src/http/vitals.ts added +37
@@ -0,0 +1,37 @@
1 /**
2 * `POST /_vitals`: the browser beacon's door (#2674). Same-origin only,
3 * silent under an opt-out, bounded in size, and answered 204 whatever it
4 * stored, so the page learns nothing it could not have guessed. The raw path
5 * is turned into a route pattern here and dropped: a private repo's name is
6 * never stored.
7 */
8
9 import { optedOut, parseBeacon, recordView } from "../core/vitals.ts";
10 import { crossOrigin, type Ctx } from "./context.ts";
11 import { UNMATCHED } from "./usage_tag.ts";
12 import { clientAddress } from "./peer.ts";
13
14 const none = (): Response => new Response(null, { status: 204 });
15
16 export async function vitalsSubmit(
17 ctx: Ctx,
18 patternOf: (pathname: string) => string | undefined,
19 ): Promise<Response> {
20 const { request } = ctx;
21 if (crossOrigin(request, ctx.url, ctx.app.log))
22 return new Response("forbidden", { status: 403 });
23 if (optedOut(request)) return none();
24 const declared = Number(request.headers.get("content-length") ?? 0);
25 if (declared > 4096) return new Response("too large", { status: 413 });
26 const beacon = parseBeacon(await request.text());
27 if (beacon === null) return new Response("bad beacon", { status: 400 });
28 try {
29 recordView(ctx.app.db, beacon, patternOf(beacon.path) ?? UNMATCHED, {
30 address: clientAddress(request),
31 agent: request.headers.get("user-agent") ?? "",
32 });
33 } catch (error) {
34 ctx.app.log.warn("could not record a view", { error: String(error) });
35 }
36 return none();
37 }
src/web/asset.ts +12
@@ -19,6 +19,7 @@
1919 import { sha256 } from "../kernel/hash.ts";
2020 import { createLog } from "../kernel/log.ts";
2121 import { shellJs } from "./client.ts";
22 import { vitalsJs } from "./vitals_client.ts";
2223 import { css } from "./style.ts";
2324
2425 const log = createLog("web");
@@ -128,3 +129,14 @@ export function shellAsset(): BuiltAsset {
128129 }
129130 return shell;
130131 }
132
133 let vitals: BuiltAsset | null = null;
134
135 /** The measurement beacon (`vitals_client.ts`), content-addressed like the shell. */
136 export function vitalsAsset(): BuiltAsset {
137 if (vitals === null) {
138 const name = `vitals-${sha256(vitalsJs).slice(0, 16)}`;
139 vitals = { path: `/assets/${name}.js`, name, code: vitalsJs };
140 }
141 return vitals;
142 }
src/web/layout.ts +2 −1
@@ -25,7 +25,7 @@ import {
2525 THEMES,
2626 type ThemeName,
2727 } from "../design/themes.ts";
28 import { shellAsset, stylesheetAsset } from "./asset.ts";
28 import { shellAsset, stylesheetAsset, vitalsAsset } from "./asset.ts";
2929 import { linkHeader, pageLinks } from "./standards.ts";
3030 import {
3131 clearFlashCookie,
@@ -679,6 +679,7 @@ export function page(options: PageOptions, status = 200): Response {
679679 <body>
680680 ${shell}${iconSprite(shell.text)}
681681 <script nonce="${nonce}" src="${shellAsset().path}"></script>
682 <script nonce="${nonce}" src="${vitalsAsset().path}" defer></script>
682683 ${options.scriptJs
683684 ? raw(`<script nonce="${nonce}">${options.scriptJs}</script>`)
684685 : null}
src/web/studio/home.ts +2
@@ -47,6 +47,7 @@ import {
4747 import { writableAppsOf } from "./asks.ts";
4848 import { needsYouSection, type AsksTop } from "./asks_page.ts";
4949 import { flowCards } from "./flow_card.ts";
50 import { measureCard } from "./measure_card.ts";
5051 import { composer, feedJs, feedNote, feedRegion } from "./feed.ts";
5152 import { homeTabs } from "./home_tabs.ts";
5253 import { crewKeyNote } from "./crew.ts";
@@ -262,6 +263,7 @@ export async function studioHome(
262263 <a class="small muted" href="/asked">What you asked for</a>
263264 </div>
264265 ${flowCards(ctx, user)}
266 ${user.isAdmin ? measureCard(ctx) : null}
265267 ${feedNote()}
266268 ${feedRegion(user, ctx)}
267269 </div>
src/web/studio/measure_card.ts added +36
@@ -0,0 +1,36 @@
1 /**
2 * The home's numbers for an admin (#2674): accounts, who was active, visitors
3 * and how fast pages felt (p75 of the browser's own load and interaction
4 * times). Read from `core/vitals.ts`; the same rows are the `views` and
5 * `timings` sources of a board.
6 */
7
8 import { kpis } from "../../core/vitals.ts";
9 import type { Ctx } from "../../http/context.ts";
10 import { html, type Html } from "../html.ts";
11 import { card } from "../ui.ts";
12
13 const ms = (v: number | null): string =>
14 v === null ? "–" : v >= 1000 ? `${(v / 1000).toFixed(1)} s` : `${Math.round(v)} ms`;
15
16 const tile = (label: string, value: string, note = ""): Html =>
17 html`<div class="stat"><div class="small muted">${label}</div><strong>${value}</strong>${
18 note === "" ? null : html` <span class="small muted">${note}</span>`
19 }</div>`;
20
21 export function measureCard(ctx: Ctx): Html {
22 const k = kpis(ctx.app.db);
23 return card(
24 html`<div class="bar">
25 ${tile("Users", String(k.users), `${k.activeToday} today · ${k.active7} in 7 days`)}
26 ${tile("Visitors today", String(k.visitorsToday))}
27 ${tile("Visitors, 7 days", String(k.visitors7), "daily uniques summed")}
28 ${tile("Page load p75", ms(k.p75Load))}
29 ${tile("Interaction p75", ms(k.p75Inp))}
30 </div>`,
31 {
32 id: "measure",
33 head: html`<strong>Measured here</strong> <a class="small muted" href="/boards">Boards</a>`,
34 },
35 );
36 }
src/web/vitals_client.ts added +26
@@ -0,0 +1,26 @@
1 /**
2 * The first-party measurement beacon, as static source (#2674): what the
3 * browser measured about this page, sent to this origin's `/_vitals` when the
4 * page is hidden. No third party, no cookie set, no storage; it stays silent
5 * under Do Not Track, Global Privacy Control or `forge_measure=off`. The app
6 * template carries the same file. INP here is the slowest interaction seen
7 * (the spec takes a high percentile), which is the same or higher.
8 */
9 export const vitalsJs = /* js */ `(function(){
10 var n=navigator;
11 if(!n.sendBeacon||n.doNotTrack==="1"||n.globalPrivacyControl||/(?:^|; )forge_measure=off/.test(document.cookie))return;
12 var v={p:location.pathname,cls:0},sent=0;
13 function ob(t,f,o){try{o=o||{};o.type=t;o.buffered=true;new PerformanceObserver(function(l){l.getEntries().forEach(f)}).observe(o)}catch(e){}}
14 ob("largest-contentful-paint",function(e){v.lcp=e.startTime});
15 ob("layout-shift",function(e){if(!e.hadRecentInput)v.cls+=e.value});
16 ob("event",function(e){if(e.interactionId&&!(e.duration<=v.inp))v.inp=e.duration},{durationThreshold:40});
17 function r(x){return typeof x==="number"?Math.round(x*1e4)/1e4:undefined}
18 function send(){
19 if(sent)return;sent=1;
20 var t=performance.getEntriesByType("navigation")[0];
21 if(t){v.ttfb=t.responseStart;if(t.loadEventEnd>0)v.load=t.loadEventEnd}
22 for(var k in v)v[k]=r(v[k]);
23 n.sendBeacon("/_vitals",JSON.stringify(v))}
24 addEventListener("visibilitychange",function(){if(document.visibilityState==="hidden")send()});
25 addEventListener("pagehide",send)
26 })();`;
test/measurement.test.ts added +108
@@ -0,0 +1,108 @@
1 /** First-party measurement: a page view lands with its vitals, the KPIs count it, no address is kept (#2674). */
2
3 import { afterAll, beforeAll, expect, test } from "bun:test";
4 import { mkdtemp, rm } from "node:fs/promises";
5 import { tmpdir } from "node:os";
6 import { join } from "node:path";
7 import { createApp, type App } from "../src/app.ts";
8 import { runQuery } from "../src/boards/query.ts";
9 import { bucketOf, createRouteTimer, kpis, parseBeacon, recordView } from "../src/core/vitals.ts";
10 import { serve, type Servers } from "../src/http/server.ts";
11 import { vitalsAsset } from "../src/web/asset.ts";
12 import { vitalsJs } from "../src/web/vitals_client.ts";
13
14 let dataDir: string;
15 let app: App;
16 let servers: Servers;
17
18 beforeAll(async () => {
19 dataDir = await mkdtemp(join(tmpdir(), "forge-vitals-"));
20 app = createApp({ dataDir, port: 0 });
21 servers = await serve(app);
22 });
23 afterAll(async () => {
24 servers.stop();
25 app.close();
26 await rm(dataDir, { recursive: true, force: true });
27 });
28
29 const beacon = (body: string, headers: Record<string, string> = {}) =>
30 fetch(`${servers.url}/_vitals`, { method: "POST", headers, body });
31
32 test("a beacon lands with its vitals under the route pattern, and the KPIs count it", async () => {
33 const sent = await beacon('{"p":"/alice/secret-repo","load":1200,"inp":180,"lcp":900,"cls":0.02,"ttfb":40}');
34 expect(sent.status).toBe(204);
35 const rows = app.db.query<Record<string, unknown>, []>("SELECT * FROM pageview").all();
36 expect(rows).toHaveLength(1);
37 expect(rows[0]).toMatchObject({ load: 1200, inp: 180, lcp: 900, cls: 0.02, ttfb: 40 });
38 const k = kpis(app.db);
39 expect(k.visitorsToday).toBe(1);
40 expect(k.visitors7).toBe(1);
41 expect(k.p75Load).toBe(1200);
42 expect(k.p75Inp).toBe(180);
43 // Neither the address nor the private path is anywhere in the store.
44 const dump = JSON.stringify(rows);
45 expect(dump).not.toContain("secret-repo");
46 expect(dump).not.toContain("127.0.0.1");
47 expect(String(rows[0]!.route).startsWith("/")).toBe(true);
48 });
49
50 test("the board source reads the views, admin only", () => {
51 const q = { source: "views", aggregate: "avg", column: "load" };
52 expect(runQuery(app.db, q, { repoIds: "all" })).toEqual({ ok: true, rows: [{ group: null, value: 1200 }] });
53 expect(runQuery(app.db, q, { repoIds: ["x"] })).toEqual({ ok: true, rows: [] });
54 const visitor = runQuery(app.db, { source: "views", aggregate: "count", groupBy: "visitor" }, { repoIds: "all" });
55 expect(visitor.ok).toBe(false);
56 });
57
58 test("an opt-out stores nothing; a cross-site post is refused; junk is a 400", async () => {
59 const before = app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM pageview").get()!.n;
60 expect((await beacon('{"p":"/"}', { dnt: "1" })).status).toBe(204);
61 expect((await beacon('{"p":"/"}', { "sec-gpc": "1" })).status).toBe(204);
62 expect((await beacon('{"p":"/"}', { cookie: "forge_measure=off" })).status).toBe(204);
63 expect((await beacon('{"p":"/"}', { origin: "https://evil.example" })).status).toBe(403);
64 expect((await beacon("not json")).status).toBe(400);
65 expect((await beacon('{"p":"/","load":-5}')).status).toBe(400);
66 expect((await beacon('{"p":"/","pad":"' + "x".repeat(2000) + '"}')).status).toBe(400);
67 const after = app.db.query<{ n: number }, []>("SELECT COUNT(*) AS n FROM pageview").get()!.n;
68 expect(after).toBe(before);
69 });
70
71 test("every page links the beacon, it is small and cached for good, and answers carry Server-Timing", async () => {
72 const res = await fetch(`${servers.url}/signin`, { headers: { accept: "text/html" } });
73 expect(res.headers.get("server-timing")).toMatch(/^app;dur=\d/);
74 expect(await res.text()).toContain(vitalsAsset().path);
75 const asset = await fetch(servers.url + vitalsAsset().path);
76 expect(asset.headers.get("cache-control")).toContain("immutable");
77 expect(vitalsJs.length).toBeLessThan(2048);
78 });
79
80 test("the visitor hash changes with the day, and yesterday's salt is gone", () => {
81 const b = parseBeacon('{"p":"/"}')!;
82 const who = { address: "203.0.113.9", agent: "ua" };
83 recordView(app.db, b, "/x", who, new Date("2030-01-01T10:00:00Z"));
84 recordView(app.db, b, "/x", who, new Date("2030-01-02T10:00:00Z"));
85 const days = app.db
86 .query<{ day: string; visitor: string }, []>("SELECT day, visitor FROM pageview WHERE route = '/x' ORDER BY day")
87 .all();
88 expect(days[0]!.visitor).not.toBe(days[1]!.visitor);
89 expect(app.db.query("SELECT day FROM vitals_salt").all()).toEqual([{ day: "2030-01-02" }]);
90 });
91
92 test("server time is a histogram per route and hour", () => {
93 const timer = createRouteTimer(app.db, () => new Date("2030-01-01T10:30:00Z"));
94 timer.record("/p", 3);
95 timer.record("/p", 4);
96 timer.record("/p", 80);
97 timer.flush();
98 expect(bucketOf(4)).toBe(5);
99 const rows = app.db
100 .query("SELECT hour, pattern, le, n FROM route_timing WHERE pattern = '/p' ORDER BY le")
101 .all();
102 expect(rows).toEqual([
103 { hour: "2030-01-01T10", pattern: "/p", le: 5, n: 2 },
104 { hour: "2030-01-01T10", pattern: "/p", le: 100, n: 1 },
105 ]);
106 const q = runQuery(app.db, { source: "timings", aggregate: "sum", column: "n", groupBy: "le" }, { repoIds: "all" });
107 expect(q.ok).toBe(true);
108 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs