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 #2688
scout/forge:scout/2674-first-party-measurement-visitors-users-a → main 2 commits fork
13 files
changed +721
−5
README.md +4
| @@ -1607,3 +1607,7 @@ operator. (The three guards of migrations 62, 70 and 81 predate the prefix and | ||
| 1607 | 1607 | are known by name in `src/http/refusal.ts`.) The terminal's toasts follow the |
| 1608 | 1608 | same rule. A guard installed by hand without the prefix answers `refused` |
| 1609 | 1609 | 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 +217 −1
| @@ -14,6 +14,7 @@ | ||
| 14 | 14 | |
| 15 | 15 | import { readFileSync } from "node:fs"; |
| 16 | 16 | import type { FileWrite } from "../git/write.ts"; |
| 17 | import { vitalsJs } from "../web/vitals_client.ts"; | |
| 17 | 18 | |
| 18 | 19 | /** |
| 19 | 20 | * The evaluator an app decides with is the forge's own, carried as text: |
| @@ -55,6 +56,7 @@ export function scaffoldFiles(input: ScaffoldInput): FileWrite[] { | ||
| 55 | 56 | { path: "src/security.ts", content: SECURITY_TS }, |
| 56 | 57 | { path: "src/audit.ts", content: AUDIT_TS }, |
| 57 | 58 | { path: "src/db.ts", content: DB_TS }, |
| 59 | { path: "src/measure.ts", content: MEASURE_TS }, | |
| 58 | 60 | { path: "src/actions.ts", content: ACTIONS_TS }, |
| 59 | 61 | { path: "src/live.ts", content: LIVE_TS }, |
| 60 | 62 | { path: "src/http.ts", content: HTTP_TS }, |
| @@ -69,9 +71,11 @@ export function scaffoldFiles(input: ScaffoldInput): FileWrite[] { | ||
| 69 | 71 | { path: "scripts/contract-emit.ts", content: CONTRACT_EMIT_TS }, |
| 70 | 72 | { path: "static/app.css", content: APP_CSS }, |
| 71 | 73 | { path: "static/live.js", content: LIVE_JS }, |
| 74 | { path: "static/vitals.js", content: vitalsJs }, | |
| 72 | 75 | { path: "src/who.test.ts", content: WHO_TEST }, |
| 73 | 76 | { path: "src/signin.test.ts", content: SIGNIN_TEST }, |
| 74 | 77 | { path: "src/db.test.ts", content: DB_TEST }, |
| 78 | { path: "src/measure.test.ts", content: MEASURE_TEST }, | |
| 75 | 79 | { path: "src/actions.test.ts", content: ACTIONS_TEST }, |
| 76 | 80 | { path: "src/contract.test.ts", content: CONTRACT_TEST }, |
| 77 | 81 | { path: "src/server.test.ts", content: SERVER_TEST }, |
| @@ -165,6 +169,7 @@ decide nothing themselves. \`AGENTS.md\` says how to add to it. | ||
| 165 | 169 | | \`src/http.ts\` | the floor: headers, body cap, files | |
| 166 | 170 | | \`src/server.ts\` | boot: open the database, serve | |
| 167 | 171 | | \`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\` | | |
| 168 | 173 | | \`src/env.ts\` | what the forge told this process | |
| 169 | 174 | | \`static/app.css\`, \`static/live.js\` | the look in the tokens' words, and the list that stays current | |
| 170 | 175 | |
| @@ -830,6 +835,14 @@ export const migrations: string[] = [ | ||
| 830 | 835 | user_name TEXT NOT NULL, |
| 831 | 836 | expires_at INTEGER NOT NULL |
| 832 | 837 | )\`, |
| 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)\`, | |
| 833 | 846 | ]; |
| 834 | 847 | |
| 835 | 848 | export function openDb(dir = dataDir): Database { |
| @@ -1703,6 +1716,7 @@ export function layout(body: string, who: Who, path = "/"): string { | ||
| 1703 | 1716 | <link rel="stylesheet" href="\${tokensHref}"> |
| 1704 | 1717 | <link rel="stylesheet" href="\${asset("app.css")}"> |
| 1705 | 1718 | <script type="module" src="\${asset("live.js")}"></script> |
| 1719 | <script defer src="\${asset("vitals.js")}"></script> | |
| 1706 | 1720 | <body> |
| 1707 | 1721 | <div class="page"> |
| 1708 | 1722 | <header class="head"> |
| @@ -1820,6 +1834,7 @@ import { | ||
| 1820 | 1834 | text, |
| 1821 | 1835 | } from "./http.ts"; |
| 1822 | 1836 | import { events } from "./live.ts"; |
| 1837 | import { optedOut, parseBeacon, recordView } from "./measure.ts"; | |
| 1823 | 1838 | import { rpc } from "./mcp.ts"; |
| 1824 | 1839 | import { home } from "./page.ts"; |
| 1825 | 1840 | import { |
| @@ -2268,6 +2283,22 @@ export const routes: readonly Route[] = [ | ||
| 2268 | 2283 | }), |
| 2269 | 2284 | }, |
| 2270 | 2285 | |
| 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 | ||
| 2271 | 2302 | // Files under ./static, cached for a year when linked by content (\`asset\`). |
| 2272 | 2303 | { |
| 2273 | 2304 | method: "GET", |
| @@ -2371,6 +2402,7 @@ export function serve(options: ServeOptions) { | ||
| 2371 | 2402 | url.pathname, |
| 2372 | 2403 | ); |
| 2373 | 2404 | if (found === undefined) return text("not found", 404); |
| 2405 | const started = performance.now(); | |
| 2374 | 2406 | const response = await found.route.handle({ |
| 2375 | 2407 | request, |
| 2376 | 2408 | url, |
| @@ -2379,6 +2411,11 @@ export function serve(options: ServeOptions) { | ||
| 2379 | 2411 | params: found.params, |
| 2380 | 2412 | signin: options.signin, |
| 2381 | 2413 | }); |
| 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 | ); | |
| 2382 | 2419 | return head(request, response); |
| 2383 | 2420 | }, |
| 2384 | 2421 | // A bug answers with the floor and nothing else: never the runtime's |
| @@ -2415,6 +2452,180 @@ if (import.meta.main) { | ||
| 2415 | 2452 | } |
| 2416 | 2453 | `; |
| 2417 | 2454 | |
| 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 { afterAll, expect, test } from "bun:test"; | |
| 2563 | import { Database } from "bun:sqlite"; | |
| 2564 | import { mkdtempSync } from "node:fs"; | |
| 2565 | import { tmpdir } from "node:os"; | |
| 2566 | import { join } from "node:path"; | |
| 2567 | import { migrate, openDb } from "./db.ts"; | |
| 2568 | import { optedOut, parseBeacon, recordView, stats } from "./measure.ts"; | |
| 2569 | import { serve } from "./server.ts"; | |
| 2570 | ||
| 2571 | const dir = mkdtempSync(join(tmpdir(), "app-")); | |
| 2572 | const server = serve({ port: 0, dataDir: dir, identityKey: "k" }); | |
| 2573 | const base = \`http://\${server.hostname}:\${server.port}\`; | |
| 2574 | afterAll(() => server.stop(true)); | |
| 2575 | ||
| 2576 | test("the beacon lands over HTTP, honours DNT, and every page carries Server-Timing", async () => { | |
| 2577 | const send = (headers: Record<string, string> = {}) => | |
| 2578 | fetch(base + "/_vitals", { method: "POST", headers, body: '{"p":"/","load":700}' }); | |
| 2579 | expect((await send()).status).toBe(204); | |
| 2580 | expect((await send({ dnt: "1" })).status).toBe(204); | |
| 2581 | expect((await send({ origin: "https://evil.example" })).status).toBe(403); | |
| 2582 | const db = openDb(dir); | |
| 2583 | expect(stats(db).viewsToday).toBe(1); | |
| 2584 | db.close(); | |
| 2585 | expect((await fetch(base + "/")).headers.get("server-timing")).toMatch(/^app;dur=/); | |
| 2586 | expect(await (await fetch(base + "/")).text()).toContain("vitals.js"); | |
| 2587 | }); | |
| 2588 | ||
| 2589 | const fresh = () => { | |
| 2590 | const db = new Database(":memory:"); | |
| 2591 | migrate(db); | |
| 2592 | return db; | |
| 2593 | }; | |
| 2594 | ||
| 2595 | test("a page view lands with its vitals and counts as a visitor", () => { | |
| 2596 | const db = fresh(); | |
| 2597 | const beacon = parseBeacon('{"p":"/","load":900,"inp":120,"lcp":800,"cls":0.01,"ttfb":50}')!; | |
| 2598 | recordView(db, beacon, "/", "agent|anon"); | |
| 2599 | recordView(db, beacon, "/", "agent|anon"); | |
| 2600 | recordView(db, beacon, "/", "other|anon"); | |
| 2601 | const s = stats(db); | |
| 2602 | expect(s.visitorsToday).toBe(2); | |
| 2603 | expect(s.viewsToday).toBe(3); | |
| 2604 | expect(s.p75Load).toBe(900); | |
| 2605 | expect(s.p75Inp).toBe(120); | |
| 2606 | }); | |
| 2607 | ||
| 2608 | test("no address, path or seed is stored", () => { | |
| 2609 | const db = fresh(); | |
| 2610 | recordView(db, parseBeacon('{"p":"/secret-repo"}')!, "/:name", "Mozilla 10.0.0.7|anon"); | |
| 2611 | const dump = JSON.stringify(db.query("SELECT * FROM view").all()); | |
| 2612 | expect(dump).not.toContain("10.0.0.7"); | |
| 2613 | expect(dump).not.toContain("secret-repo"); | |
| 2614 | }); | |
| 2615 | ||
| 2616 | test("a malformed beacon is refused", () => { | |
| 2617 | for (const bad of ["", "[]", '{"p":"x"}', '{"p":"/","load":-1}', '{"p":"/","load":"1"}', '{"p":"/a\\\\u0000"}', '{"p":"/","cls":1e9}']) | |
| 2618 | expect(parseBeacon(bad)).toBeNull(); | |
| 2619 | }); | |
| 2620 | ||
| 2621 | test("an opt-out is honoured", () => { | |
| 2622 | expect(optedOut(new Request("http://x/", { headers: { dnt: "1" } }))).toBe(true); | |
| 2623 | expect(optedOut(new Request("http://x/", { headers: { "sec-gpc": "1" } }))).toBe(true); | |
| 2624 | expect(optedOut(new Request("http://x/", { headers: { cookie: "a=b; forge_measure=off" } }))).toBe(true); | |
| 2625 | expect(optedOut(new Request("http://x/"))).toBe(false); | |
| 2626 | }); | |
| 2627 | `; | |
| 2628 | ||
| 2418 | 2629 | // The terminal. |
| 2419 | 2630 | const TTY_TS = `/** |
| 2420 | 2631 | * The app in a terminal. The forge runs this on a pty when someone |
| @@ -4041,6 +4252,8 @@ export const WRITES: Rate = { burst: 20, perSecond: 2 }; | ||
| 4041 | 4252 | export const STRANGERS: Rate = { burst: 60, perSecond: 10 }; |
| 4042 | 4253 | /** Each start of a sign-in writes a row; one address may not flush the rest. Behind the forge this is everyone together. */ |
| 4043 | 4254 | export const SIGNINS: Rate = { burst: 20, perSecond: 1 }; |
| 4255 | /** Page-view beacons: one per page left, so they ration apart from writes. */ | |
| 4256 | export const VIEWS: Rate = { burst: 60, perSecond: 10 }; | |
| 4044 | 4257 | const buckets = new Map<string, { tokens: number; at: number }>(); |
| 4045 | 4258 | export function allow( |
| 4046 | 4259 | key: string, |
| @@ -4144,8 +4357,11 @@ export function door( | ||
| 4144 | 4357 | url.pathname === "/mcp" || |
| 4145 | 4358 | url.pathname === "/openapi.json"; |
| 4146 | 4359 | const key = stranger ? \`ip:\${from}\` : \`user:\${who.id}\`; |
| 4360 | const beacon = url.pathname === "/_vitals"; | |
| 4147 | 4361 | |
| 4148 | if (writing && !allow(key)) return text("too many requests", 429); | |
| 4362 | if (beacon && !allow(\`views:\${from}\`, VIEWS)) | |
| 4363 | return text("too many requests", 429); | |
| 4364 | if (writing && !beacon && !allow(key)) return text("too many requests", 429); | |
| 4149 | 4365 | if (url.pathname === "/signin" && !allow(\`signin:\${from}\`, SIGNINS)) |
| 4150 | 4366 | return text("too many requests", 429); |
| 4151 | 4367 | if (stranger && api && !allow(\`api:\${from}\`, STRANGERS)) |
src/boards/sources.ts +33
| @@ -139,6 +139,39 @@ export const SOURCES: Readonly<Record<string, Source>> = { | ||
| 139 | 139 | n: "requests in that hour with that pattern, method, status class, role and surface", |
| 140 | 140 | }, |
| 141 | 141 | }, |
| 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 | }, | |
| 142 | 175 | // Browser sign-ins: one row per session. The token hash and the session |
| 143 | 176 | // id are not listed. Failed sign-ins are not a row anywhere; they are the |
| 144 | 177 | // `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 { | ||
| 98 | 98 | assetResponse, |
| 99 | 99 | highlightAsset, |
| 100 | 100 | shellAsset, |
| 101 | vitalsAsset, | |
| 101 | 102 | stylesheetAsset, |
| 102 | 103 | stylesheetRedirect, |
| 103 | 104 | stylesheetResponse, |
| @@ -444,6 +445,8 @@ import { proposalGate } from "./proposal_gate.ts"; | ||
| 444 | 445 | import { feedRoutes } from "./feed.ts"; |
| 445 | 446 | import type { Database } from "bun:sqlite"; |
| 446 | 447 | import { mcpRoutes } from "./mcp.ts"; |
| 448 | import { vitalsSubmit } from "./vitals.ts"; | |
| 449 | import { createRouteTimer, type RouteTimer } from "../core/vitals.ts"; | |
| 447 | 450 | import { createUsageCounter, type UsageCounter } from "../core/usage_count.ts"; |
| 448 | 451 | import { methodOf, noteUsage, roleOf, surfaceOf, takeUsage } from "./usage_tag.ts"; |
| 449 | 452 | import { oauthRoutes } from "./oauth.ts"; |
| @@ -633,6 +636,7 @@ export function buildRouter(): Router<Handler> { | ||
| 633 | 636 | router.add("GET", "/assets/:name.js", async (ctx) => { |
| 634 | 637 | const shell = shellAsset(); |
| 635 | 638 | if (ctx.params.name === shell.name) return assetResponse(shell); |
| 639 | if (ctx.params.name === vitalsAsset().name) return assetResponse(vitalsAsset()); | |
| 636 | 640 | if (ctx.params.name === TOOLBAR_NAME) return toolbarResponse(); |
| 637 | 641 | const asset = await highlightAsset(); |
| 638 | 642 | if (asset === null || ctx.params.name !== asset.name) return notFound(); |
| @@ -641,6 +645,9 @@ export function buildRouter(): Router<Handler> { | ||
| 641 | 645 | // The service worker: root scope needs a root path, and it must never be |
| 642 | 646 | // cached by the browser's HTTP cache or an update would wait a day. |
| 643 | 647 | router.add("GET", "/sw.js", serviceWorker); |
| 648 | router.add("POST", "/_vitals", (ctx) => | |
| 649 | vitalsSubmit(ctx, (path) => router.match("GET", path)?.pattern), | |
| 650 | ); | |
| 644 | 651 | router.add("GET", "/", home); |
| 645 | 652 | // A spawned child's claim link: GET shows, POST takes it (spawn/claim.ts). |
| 646 | 653 | router.add("GET", "/claim", claimFragmentPage); |
| @@ -2038,8 +2045,27 @@ export async function serve(app: App): Promise<Servers> { | ||
| 2038 | 2045 | // One counter per database: a hosted child counts in its own. `count` is a |
| 2039 | 2046 | // map increment; a refused event would be a programming error, not worth a 500. |
| 2040 | 2047 | 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 => { | |
| 2042 | 2055 | 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 | } | |
| 2043 | 2069 | try { |
| 2044 | 2070 | let counter = counters.get(owner.db); |
| 2045 | 2071 | if (counter === undefined) { |
| @@ -2133,7 +2159,7 @@ export async function serve(app: App): Promise<Servers> { | ||
| 2133 | 2159 | notePeer(request, server.requestIP(request)?.address, trust); |
| 2134 | 2160 | armClose(request, () => server.timeout(request, 1)); |
| 2135 | 2161 | const response = await answered(child, request, () => http.handle(request)); |
| 2136 | counted(child, request, response); | |
| 2162 | counted(child, request, response, performance.now() - started); | |
| 2137 | 2163 | logged(key, request, response, started); |
| 2138 | 2164 | await settleBody(request); |
| 2139 | 2165 | if (!mustClose(request)) return response; |
| @@ -2152,7 +2178,7 @@ export async function serve(app: App): Promise<Servers> { | ||
| 2152 | 2178 | const response = await answered(app, request, () => |
| 2153 | 2179 | answer(app, router, apiRouter, limiter, request), |
| 2154 | 2180 | ); |
| 2155 | counted(app, request, response); | |
| 2181 | counted(app, request, response, performance.now() - started); | |
| 2156 | 2182 | logged(app.config.dataDir, request, response, started); |
| 2157 | 2183 | await settleBody(request); |
| 2158 | 2184 | 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 @@ | ||
| 19 | 19 | import { sha256 } from "../kernel/hash.ts"; |
| 20 | 20 | import { createLog } from "../kernel/log.ts"; |
| 21 | 21 | import { shellJs } from "./client.ts"; |
| 22 | import { vitalsJs } from "./vitals_client.ts"; | |
| 22 | 23 | import { css } from "./style.ts"; |
| 23 | 24 | |
| 24 | 25 | const log = createLog("web"); |
| @@ -128,3 +129,14 @@ export function shellAsset(): BuiltAsset { | ||
| 128 | 129 | } |
| 129 | 130 | return shell; |
| 130 | 131 | } |
| 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 { | ||
| 25 | 25 | THEMES, |
| 26 | 26 | type ThemeName, |
| 27 | 27 | } from "../design/themes.ts"; |
| 28 | import { shellAsset, stylesheetAsset } from "./asset.ts"; | |
| 28 | import { shellAsset, stylesheetAsset, vitalsAsset } from "./asset.ts"; | |
| 29 | 29 | import { linkHeader, pageLinks } from "./standards.ts"; |
| 30 | 30 | import { |
| 31 | 31 | clearFlashCookie, |
| @@ -679,6 +679,7 @@ export function page(options: PageOptions, status = 200): Response { | ||
| 679 | 679 | <body> |
| 680 | 680 | ${shell}${iconSprite(shell.text)} |
| 681 | 681 | <script nonce="${nonce}" src="${shellAsset().path}"></script> |
| 682 | <script nonce="${nonce}" src="${vitalsAsset().path}" defer></script> | |
| 682 | 683 | ${options.scriptJs |
| 683 | 684 | ? raw(`<script nonce="${nonce}">${options.scriptJs}</script>`) |
| 684 | 685 | : null} |
src/web/studio/home.ts +2
| @@ -47,6 +47,7 @@ import { | ||
| 47 | 47 | import { writableAppsOf } from "./asks.ts"; |
| 48 | 48 | import { needsYouSection, type AsksTop } from "./asks_page.ts"; |
| 49 | 49 | import { flowCards } from "./flow_card.ts"; |
| 50 | import { measureCard } from "./measure_card.ts"; | |
| 50 | 51 | import { composer, feedJs, feedNote, feedRegion } from "./feed.ts"; |
| 51 | 52 | import { homeTabs } from "./home_tabs.ts"; |
| 52 | 53 | import { crewKeyNote } from "./crew.ts"; |
| @@ -262,6 +263,7 @@ export async function studioHome( | ||
| 262 | 263 | <a class="small muted" href="/asked">What you asked for</a> |
| 263 | 264 | </div> |
| 264 | 265 | ${flowCards(ctx, user)} |
| 266 | ${user.isAdmin ? measureCard(ctx) : null} | |
| 265 | 267 | ${feedNote()} |
| 266 | 268 | ${feedRegion(user, ctx)} |
| 267 | 269 | </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 | }); |
new above
offline