145 lines
5.9 KiB
TypeScript
145 lines
5.9 KiB
TypeScript
// PEP-213: how long web pages and server actions take, and how much of it is SQLite.
|
|
// Measured on the server (http "request" event + AsyncLocalStorage probe in @peppa/db);
|
|
// a slow one goes to Bugsink as a warning through the PEP-91 sender, the day's numbers
|
|
// are shown on /observability.
|
|
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
import { Probe, runWithProbe, type Db } from "@peppa/db";
|
|
import { reportPlatformError } from "./error-report.ts";
|
|
|
|
export const DAY_MS = 24 * 3600_000;
|
|
const MAX_SAMPLES = 2000;
|
|
const REPORT_EVERY_MS = 10 * 60_000;
|
|
|
|
export const slowRequestMs = () => Number(process.env.PEPPA_SLOW_REQUEST_MS) || 1500;
|
|
export const slowSqlMs = () => Number(process.env.PEPPA_SLOW_SQL_MS) || 200;
|
|
|
|
/** `/p/PEP/plan/12` → `/p/[key]/plan/[id]`; ids and keys never make a new group. */
|
|
export function routePattern(path: string): string {
|
|
const clean = path.split("?")[0]!.split("#")[0]!;
|
|
const parts = clean.split("/").map((seg) => {
|
|
if (!seg) return seg;
|
|
if (/^[A-Z][A-Z0-9]{1,9}(-\d+)?$/.test(seg)) return "[key]";
|
|
if (/^\d+$/.test(seg) || /^[0-9a-f]{8,}(-[0-9a-f]+)*$/i.test(seg)) return "[id]";
|
|
return seg;
|
|
});
|
|
return parts.join("/") || "/";
|
|
}
|
|
|
|
/** Pages and server actions only; assets, APIs (SSE live feeds, terminals), auth are not measured. */
|
|
export function isMeasuredPath(path: string): boolean {
|
|
return !/^\/(_next|api|mcp|oauth|auth|\.well-known)(\/|$|\?)/.test(path) && !/\.[a-z0-9]{2,5}(\?|$)/i.test(path);
|
|
}
|
|
|
|
interface Sample {
|
|
at: number;
|
|
ms: number;
|
|
sqlMs: number;
|
|
sqlCount: number;
|
|
}
|
|
interface Store {
|
|
samples: Map<string, Sample[]>;
|
|
lastReport: Map<string, number>;
|
|
}
|
|
const g = globalThis as unknown as { __peppaRequestTiming?: Store };
|
|
const store = (): Store => (g.__peppaRequestTiming ??= { samples: new Map(), lastReport: new Map() });
|
|
|
|
export function resetRequestTiming() {
|
|
g.__peppaRequestTiming = undefined;
|
|
}
|
|
|
|
export interface RequestRecord {
|
|
route: string;
|
|
ms: number;
|
|
sqlMs: number;
|
|
sqlCount: number;
|
|
topSql: { sql: string; ms: number }[];
|
|
maxSqlMs: number;
|
|
}
|
|
|
|
/** Store one finished request and report it to Bugsink when it is slow. Never throws. */
|
|
export async function recordRequest(db: Db, r: RequestRecord, now = Date.now()): Promise<boolean> {
|
|
const s = store();
|
|
const list = s.samples.get(r.route) ?? [];
|
|
list.push({ at: now, ms: r.ms, sqlMs: r.sqlMs, sqlCount: r.sqlCount });
|
|
while (list.length > MAX_SAMPLES || (list[0] && now - list[0].at > DAY_MS)) list.shift();
|
|
s.samples.set(r.route, list);
|
|
if (r.ms < slowRequestMs() && r.maxSqlMs < slowSqlMs()) return false;
|
|
const last = s.lastReport.get(r.route);
|
|
if (last !== undefined && now - last < REPORT_EVERY_MS) return false;
|
|
s.lastReport.set(r.route, now);
|
|
const sqlLines = r.topSql.map((q, i) => `${i + 1}. ${Math.round(q.ms)} мс: ${q.sql}`).join("\n");
|
|
const err = new Error(`${Math.round(r.ms)} мс, SQL ${Math.round(r.sqlMs)} мс (${r.sqlCount} шт.)${sqlLines ? `\n${sqlLines}` : ""}`);
|
|
err.name = `Медленно: ${r.route}`;
|
|
err.stack = ""; // a slow request has no failing frame
|
|
return reportPlatformError(db, err, {
|
|
service: "web",
|
|
where: r.route,
|
|
level: "warning",
|
|
fingerprint: ["slow", r.route],
|
|
tags: { route: r.route, ms: String(Math.round(r.ms)), sql_ms: String(Math.round(r.sqlMs)), sql_count: String(r.sqlCount) },
|
|
});
|
|
}
|
|
|
|
export interface RouteStats {
|
|
route: string;
|
|
count: number;
|
|
p50: number;
|
|
p95: number;
|
|
max: number;
|
|
/** Share of the request time spent in SQL, 0..1. */
|
|
sqlShare: number;
|
|
}
|
|
|
|
const quantile = (sorted: number[], q: number) => sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))] ?? 0;
|
|
|
|
/** Last 24 hours per route, slowest p95 first. */
|
|
export function requestSummary(now = Date.now()): RouteStats[] {
|
|
const out: RouteStats[] = [];
|
|
for (const [route, all] of store().samples) {
|
|
const list = all.filter((x) => now - x.at <= DAY_MS);
|
|
if (!list.length) continue;
|
|
const ms = list.map((x) => x.ms).sort((a, b) => a - b);
|
|
const total = list.reduce((n, x) => n + x.ms, 0);
|
|
const sql = list.reduce((n, x) => n + x.sqlMs, 0);
|
|
out.push({ route, count: list.length, p50: quantile(ms, 0.5), p95: quantile(ms, 0.95), max: ms.at(-1)!, sqlShare: total ? Math.min(1, sql / total) : 0 });
|
|
}
|
|
return out.sort((a, b) => b.p95 - a.p95);
|
|
}
|
|
|
|
/** The measured route of a request, or null: server actions are `ACTION <page>`. */
|
|
export function requestRoute(req: Pick<IncomingMessage, "url" | "method" | "headers">): string | null {
|
|
const url = req.url ?? "/";
|
|
if (!isMeasuredPath(url)) return null;
|
|
if (req.method === "POST") return req.headers["next-action"] ? `ACTION ${routePattern(url)}` : null;
|
|
if (req.method !== "GET") return null;
|
|
// Next's client-side navigations fetch the same page (RSC): the same route.
|
|
return routePattern(url);
|
|
}
|
|
|
|
type Emitter = { emit: (...a: unknown[]) => boolean };
|
|
|
|
/** Wrap the HTTP server's "request" event: every measured request gets a probe and a timer. */
|
|
export function installRequestTiming(db: Db, serverProto: Emitter): void {
|
|
const proto = serverProto as Emitter & { __peppaTiming?: boolean };
|
|
if (proto.__peppaTiming) return;
|
|
proto.__peppaTiming = true;
|
|
const emit = proto.emit;
|
|
proto.emit = function (this: unknown, event: unknown, ...args: unknown[]) {
|
|
if (event !== "request") return emit.call(this, event, ...args);
|
|
const req = args[0] as IncomingMessage;
|
|
const res = args[1] as ServerResponse;
|
|
const route = requestRoute(req);
|
|
if (!route) return emit.call(this, event, ...args);
|
|
const probe = new Probe();
|
|
const t0 = performance.now();
|
|
let done = false;
|
|
const finish = () => {
|
|
if (done) return;
|
|
done = true;
|
|
void recordRequest(db, { route, ms: performance.now() - t0, sqlMs: probe.sqlMs, sqlCount: probe.sqlCount, topSql: probe.top, maxSqlMs: probe.maxMs }).catch(() => {});
|
|
};
|
|
res.once("close", finish);
|
|
return runWithProbe(probe, () => emit.call(this, event, ...args));
|
|
};
|
|
}
|