mirror of
https://github.com/bitbaum/heidi.git
synced 2026-12-04 15:37:11 +01:00
Claude-Session: https://claude.ai/code/session_019MDtmvb6xi489TfZMg7n9T Co-authored-by: Claude <noreply@anthropic.com>
141 lines
5.8 KiB
TypeScript
141 lines
5.8 KiB
TypeScript
import { createHash } from "node:crypto";
|
|
import type { Run } from "../../db/run.ts";
|
|
|
|
/**
|
|
* Errors somebody will see.
|
|
*
|
|
* The app logged to the console and nowhere else, so an error on the box was
|
|
* read only by whoever happened to be tailing the journal. This keeps a
|
|
* small table instead of adding a vendor: one row per KIND of error with a
|
|
* count and the last time, shown to the owner beside the numbers
|
|
* (`/api/owner/numbers`).
|
|
*
|
|
* WHAT IS KEPT, AND WHAT CANNOT BE. The route PATTERN (`/api/chat`,
|
|
* `/[locale]/practice`: the path of the file, which holds no visitor's
|
|
* input), the error's name, and its message after `scrub` — which removes
|
|
* addresses, ids, numbers and long tokens, because an error message is
|
|
* written by a library and will happily quote the row it failed on. No
|
|
* request, no body, no header, no query string, no account, no stack.
|
|
*
|
|
* ONE HELPER. `report` is the only writer, and `instrumentation.ts` (Next's
|
|
* hook for errors that reach the server's boundary, from a page or a route
|
|
* handler) is its caller. A handler that catches an error and answers on
|
|
* purpose has handled it; it may call `report` too, and nothing else may
|
|
* write here.
|
|
*
|
|
* CHEAP, AND BOUNDED THREE WAYS. A new kind is added only while the table
|
|
* holds fewer than `MAX_KINDS`; a process writes at most `MAX_WRITES` a
|
|
* minute, so an error storm costs a counter, not a query per failure; rows
|
|
* unseen for `KEEP_DAYS` are removed, at most once an hour. One statement
|
|
* per reported error. A failure to write is swallowed: the sink must never
|
|
* be the reason a request fails.
|
|
*/
|
|
export const MAX_KINDS = 300;
|
|
export const MAX_WRITES = 30;
|
|
export const KEEP_DAYS = 30;
|
|
const MESSAGE_MAX = 200;
|
|
const ROUTE_MAX = 120;
|
|
|
|
/**
|
|
* A message with everything that could be somebody's removed.
|
|
*
|
|
* Order matters: addresses and URLs before the generic token rule, which
|
|
* would otherwise leave half of one behind.
|
|
*/
|
|
export function scrub(message: string): string {
|
|
return message
|
|
.replace(/[^\s@"'<>()]+@[^\s@"'<>()]+\.[^\s@"'<>()]+/g, "<address>")
|
|
.replace(/\b[a-z][a-z0-9+.-]*:\/\/[^\s"'<>)]+/gi, "<url>")
|
|
.replace(/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi, "<id>")
|
|
// What a database quotes back: `Key (email)=(…)`, `value "…"`.
|
|
.replace(/=\s*\([^)]*\)/g, "=(<value>)")
|
|
.replace(/"[^"]*"|'[^']*'|«[^»]*»|`[^`]*`/g, "<quoted>")
|
|
.replace(/\b[A-Za-z0-9_-]{20,}\b/g, "<token>")
|
|
.replace(/\d{3,}/g, "<n>")
|
|
.replace(/\s+/g, " ")
|
|
.trim()
|
|
.slice(0, MESSAGE_MAX);
|
|
}
|
|
|
|
export type Kind = { hash: string; route: string; name: string; message: string };
|
|
|
|
/** A route pattern as it is kept: the path only, never a query string, bounded. */
|
|
function routeOf(route: string): string {
|
|
return (route.split(/[?#]/)[0] ?? "").trim().slice(0, ROUTE_MAX) || "unknown";
|
|
}
|
|
|
|
/** What an error is filed under. Pure. */
|
|
export function kindOf(route: string, error: unknown): Kind {
|
|
const name = (error instanceof Error ? error.name : typeof error).slice(0, 60) || "Error";
|
|
const raw = error instanceof Error ? error.message : typeof error === "string" ? error : "";
|
|
const message = scrub(raw);
|
|
const where = routeOf(route);
|
|
const hash = createHash("sha256").update(`${where}\n${name}\n${message}`).digest("hex").slice(0, 32);
|
|
return { hash, route: where, name, message };
|
|
}
|
|
|
|
/**
|
|
* $1 hash · $2 route · $3 name · $4 message · $5 the cap.
|
|
* A kind already known is counted; a new one is added only under the cap.
|
|
*/
|
|
const WRITE = `
|
|
insert into error_events (hash, route, name, message)
|
|
select $1, $2, $3, $4
|
|
where exists (select 1 from error_events where hash = $1)
|
|
or (select count(*) from error_events) < $5
|
|
on conflict (hash) do update set count = error_events.count + 1, last_seen = now()`;
|
|
|
|
/** How many writes this process made in the current minute, and when it last swept. */
|
|
export type Budget = { minute: number; writes: number; dropped: number; swept: number };
|
|
|
|
export function newBudget(): Budget {
|
|
return { minute: 0, writes: 0, dropped: 0, swept: 0 };
|
|
}
|
|
|
|
/** May this process write one more this minute? Counts it when it may. */
|
|
export function spend(budget: Budget, now: number): boolean {
|
|
const minute = Math.floor(now / 60_000);
|
|
if (minute !== budget.minute) {
|
|
budget.minute = minute;
|
|
budget.writes = 0;
|
|
}
|
|
if (budget.writes >= MAX_WRITES) {
|
|
budget.dropped += 1;
|
|
return false;
|
|
}
|
|
budget.writes += 1;
|
|
return true;
|
|
}
|
|
|
|
/**
|
|
* THE ONE WRITER. Never throws and never rejects.
|
|
*
|
|
* `route` is a route PATTERN. Callers pass the file's path (Next's
|
|
* `routePath`, or a literal like "/api/chat"), never `request.url`.
|
|
*/
|
|
export async function report(run: Run, route: string, error: unknown, budget: Budget, now: number = Date.now()): Promise<void> {
|
|
try {
|
|
if (!spend(budget, now)) return;
|
|
const kind = kindOf(route, error);
|
|
await run(WRITE, [kind.hash, kind.route, kind.name, kind.message, MAX_KINDS]);
|
|
if (now - budget.swept >= 60 * 60_000) {
|
|
budget.swept = now;
|
|
await run(`delete from error_events where last_seen < $1::timestamptz`, [new Date(now - KEEP_DAYS * 86_400_000).toISOString()]);
|
|
}
|
|
} catch {
|
|
// The sink is not allowed to be an error.
|
|
}
|
|
}
|
|
|
|
export type SeenError = { route: string; name: string; message: string; count: number; firstSeen: string; lastSeen: string };
|
|
|
|
/** The most recent kinds, for the owner. */
|
|
export async function recentErrors(run: Run, limit = 50): Promise<SeenError[]> {
|
|
const rows = await run(
|
|
`select route, name, message, count, first_seen, last_seen from error_events order by last_seen desc limit $1`,
|
|
[Math.min(Math.max(1, limit), MAX_KINDS)],
|
|
);
|
|
const iso = (v: unknown) => (v instanceof Date ? v.toISOString() : new Date(String(v)).toISOString());
|
|
return rows.map((r) => ({ route: String(r.route), name: String(r.name), message: String(r.message), count: Number(r.count), firstSeen: iso(r.first_seen), lastSeen: iso(r.last_seen) }));
|
|
}
|