// PEP-217: Web Vitals of real users (LCP, INP, CLS, TTFB) — what the browser measured on Peppa's // own pages. Stored in observe.db (7 days), p75 per route for the last day on /observability, // one warning in Bugsink (PEP-web) per route and metric per day when p75 is bad. // glossary-ignore-file: the section is for the superadmin only. import type { Db } from "@peppa/db"; import { observeDb } from "./observe.ts"; import { reportPlatformError } from "./error-report.ts"; export const VITAL_METRICS = ["LCP", "INP", "CLS", "TTFB"] as const; export type VitalMetric = (typeof VITAL_METRICS)[number]; export type VitalDevice = "narrow" | "wide"; export type VitalMode = "product" | "engineer"; /** Bad p75 of a route: LCP > 4 s, INP > 500 ms (CLS > 0.25 is shown, not reported). */ export const VITAL_BAD: Record = { LCP: 4000, INP: 500, CLS: 0.25, TTFB: 1800 }; export const VITAL_WARN_METRICS: VitalMetric[] = ["LCP", "INP"]; /** Fewer samples than this do not make a verdict. */ export const VITAL_MIN_SAMPLES = 5; const MAX_VALUE: Record = { LCP: 600_000, INP: 600_000, TTFB: 600_000, CLS: 100 }; const ID_SEGMENT = /^(\d+|[0-9a-f]{8,}|[A-Za-z]{2,10}-\d+)$/i; const KEY_PARENTS = new Set(["p", "t", "chats"]); /** A path without ids and keys: /t/PEP-12 → /t/:key, /runners/7 → /runners/:id. */ export function normalizeRoute(path: unknown): string | null { if (typeof path !== "string") return null; const clean = path.split(/[?#]/)[0]!.slice(0, 300); if (!clean.startsWith("/")) return null; const parts = clean.split("/").filter(Boolean).slice(0, 6); const out = parts.map((seg, i) => { if (i > 0 && KEY_PARENTS.has(parts[i - 1]!)) return ":key"; if (ID_SEGMENT.test(seg)) return ":id"; return seg.slice(0, 40).replace(/[^\w.\-~%]/g, "_"); }); return `/${out.join("/")}`; } export interface VitalInput { route: unknown; metric: unknown; value: unknown; device: unknown; mode: unknown; } /** Stores one sample; false when the input is not a valid sample. */ export function recordVital(i: VitalInput, now = new Date()): boolean { const route = normalizeRoute(i.route); const metric = VITAL_METRICS.find((m) => m === i.metric); const value = typeof i.value === "number" ? i.value : NaN; if (!route || !metric || !Number.isFinite(value) || value < 0 || value > MAX_VALUE[metric]) return false; const device: VitalDevice = i.device === "narrow" ? "narrow" : "wide"; const mode: VitalMode = i.mode === "engineer" ? "engineer" : "product"; observeDb() .prepare("INSERT INTO web_vitals (at, route, metric, value, device, mode) VALUES (?, ?, ?, ?, ?, ?)") .run(now.toISOString(), route, metric, value, device, mode); return true; } /** Nearest-rank 75th percentile. */ export function p75(values: number[]): number | null { if (!values.length) return null; const s = [...values].sort((a, b) => a - b); return s[Math.ceil(s.length * 0.75) - 1]!; } export interface RouteVitals { route: string; samples: number; /** p75 per metric; null — no samples. */ p75: Record; /** How many samples per metric. */ n: Record; } /** p75 per route over the last `hours` (default a day); the most visited routes first. */ export function vitalsSummary(o: { hours?: number; device?: VitalDevice; now?: Date } = {}): RouteVitals[] { const now = o.now ?? new Date(); const since = new Date(now.getTime() - (o.hours ?? 24) * 3_600_000).toISOString(); const rows = (o.device ? observeDb().prepare("SELECT route, metric, value FROM web_vitals WHERE at >= ? AND device = ?").all(since, o.device) : observeDb().prepare("SELECT route, metric, value FROM web_vitals WHERE at >= ?").all(since)) as { route: string; metric: VitalMetric; value: number }[]; const by = new Map>(); for (const r of rows) { const e = by.get(r.route) ?? { LCP: [], INP: [], CLS: [], TTFB: [] }; e[r.metric]?.push(r.value); by.set(r.route, e); } const out: RouteVitals[] = [...by].map(([route, e]) => ({ route, samples: Math.max(...VITAL_METRICS.map((m) => e[m].length)), p75: { LCP: p75(e.LCP), INP: p75(e.INP), CLS: p75(e.CLS), TTFB: p75(e.TTFB) }, n: { LCP: e.LCP.length, INP: e.INP.length, CLS: e.CLS.length, TTFB: e.TTFB.length }, })); return out.sort((a, b) => b.samples - a.samples || a.route.localeCompare(b.route)); } export const isBadVital = (metric: VitalMetric, value: number | null, n: number) => value != null && n >= VITAL_MIN_SAMPLES && value > VITAL_BAD[metric]; /** * Bad p75 → one warning to Bugsink per route and metric per day (observe_meta remembers it). * Returns what was reported. */ export async function vitalsAlertTick(db: Db, now = new Date()): Promise { const meta = observeDb(); const day = now.toISOString().slice(0, 10); const sent: string[] = []; for (const r of vitalsSummary({ now })) { for (const m of VITAL_WARN_METRICS) { const v = r.p75[m]; if (!isBadVital(m, v, r.n[m])) continue; const key = `vitals.warned:${r.route}:${m}:${day}`; if (meta.prepare("SELECT 1 FROM observe_meta WHERE key = ?").get(key)) continue; meta.prepare("INSERT OR IGNORE INTO observe_meta (key, value) VALUES (?, ?)").run(key, String(now.getTime())); const text = `${m} p75 ${Math.round(v!)} ms (> ${VITAL_BAD[m]}) on ${r.route}, ${r.n[m]} samples in 24 h`; await reportPlatformError(db, { name: `SlowPage ${m}`, message: text }, { service: "browser", kind: "web", platform: "javascript", where: r.route, level: "warning", tags: { vital: m } }); sent.push(`${r.route}:${m}`); } } meta.prepare("DELETE FROM observe_meta WHERE key LIKE 'vitals.warned:%' AND key NOT LIKE ?").run(`%:${day}`); return sent; }