peppa/packages/db/src/probe.ts
2026-11-23 14:56:43 +00:00

50 lines
1.3 KiB
TypeScript

// PEP-213: per-request SQL probe. A request (web) runs inside runWithProbe; every statement
// of SqliteClient adds its time and text (placeholders, no values) to the current probe.
import { AsyncLocalStorage } from "node:async_hooks";
export interface SqlSample {
sql: string;
ms: number;
}
export class Probe {
sqlMs = 0;
sqlCount = 0;
/** The longest statements, longest first (at most 3). */
top: SqlSample[] = [];
/** Longest single statement. */
maxMs = 0;
add(sql: string, ms: number) {
this.sqlMs += ms;
this.sqlCount++;
if (ms > this.maxMs) this.maxMs = ms;
if (this.top.length < 3 || ms > this.top[2]!.ms) {
this.top.push({ sql: sql.replace(/\s+/g, " ").trim().slice(0, 300), ms });
this.top.sort((a, b) => b.ms - a.ms);
this.top.length = Math.min(this.top.length, 3);
}
}
}
const als = new AsyncLocalStorage<Probe>();
export function runWithProbe<T>(probe: Probe, fn: () => T): T {
return als.run(probe, fn);
}
export function currentProbe(): Probe | undefined {
return als.getStore();
}
/** Time `fn` into the current probe, if any. */
export function probed<T>(sql: string, fn: () => T): T {
const p = als.getStore();
if (!p) return fn();
const t = performance.now();
try {
return fn();
} finally {
p.add(sql, performance.now() - t);
}
}