PEP-309: «Ошибки из прода» без ложных записей — отказ человеку, ожидание базы при выкатке, действие, которое ждёт запуска агента #278

Merged
peppa-bot merged 1 commits from task/pep-309 into main 2026-11-26 20:24:16 +00:00
4 changed files with 74 additions and 6 deletions

View File

@ -24,10 +24,11 @@ export async function register() {
/** PEP-91: an error while rendering or handling a request → Bugsink (PEP-api). */
export async function onRequestError(err: unknown, request: { path: string; method: string; headers: Record<string, string | string[] | undefined> }, context: { routerKind: string; routePath: string; routeType: string }) {
if (process.env.NEXT_RUNTIME !== "nodejs") return;
const { reportPlatformError } = await import("@peppa/core");
const { reportRequestError } = await import("@peppa/core");
const { db } = await import("@/lib/db");
const ua = request.headers["user-agent"];
await reportPlatformError(db, err, {
// PEP-309: a refusal shown to the person (`PeppaError`) is not reported.
await reportRequestError(db, err, {
service: "web",
where: `${request.method} ${context.routePath}`,
request: { url: request.path, method: request.method, userAgent: typeof ua === "string" ? ua : undefined },

View File

@ -183,6 +183,19 @@ export function resetErrorReporting() {
* Report one of Peppa's own errors. Never throws; resolves to whether Bugsink took it
* (false when not connected, throttled, switched off or unreachable).
*/
/**
* PEP-309: a `PeppaError` is a refusal the person reads on the page («Нет активных подписок среди
* подключённых к проекту…»), not a failure of the platform. Checked by name: a web bundle may carry
* its own copy of the class.
*/
export const isRefusal = (e: unknown): boolean => (e as { name?: unknown } | null)?.name === "PeppaError";
/** An error of a web request → Bugsink; a refusal is not an error of the platform and is not sent. */
export async function reportRequestError(db: Db, e: unknown, ctx: ErrorContext): Promise<boolean> {
if (isRefusal(e)) return false;
return reportPlatformError(db, e, ctx);
}
export async function reportPlatformError(db: Db, e: unknown, ctx: ErrorContext): Promise<boolean> {
try {
if (process.env.PEPPA_ERRORS === "off") return false;

View File

@ -7,11 +7,17 @@ import { Probe, runWithProbe, type Db } from "@peppa/db";
import { reportPlatformError } from "./error-report.ts";
export const DAY_MS = 24 * 3600_000;
const HOUR_MS = 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;
/**
* PEP-309: a server action that starts or restarts an agent, merges a result or checks a subscription
* waits for the runner service — seconds by design. Its own limit; a page keeps `slowRequestMs`.
*/
export const slowActionMs = () => Number(process.env.PEPPA_SLOW_ACTION_MS) || 10_000;
/** `/p/PEP/plan/12` → `/p/[key]/plan/[id]`; ids and keys never make a new group. */
export function routePattern(path: string): string {
@ -39,9 +45,11 @@ interface Sample {
interface Store {
samples: Map<string, Sample[]>;
lastReport: Map<string, number>;
/** PEP-309: when a route last answered fast but with one long statement. */
longSql: Map<string, number>;
}
const g = globalThis as unknown as { __peppaRequestTiming?: Store };
const store = (): Store => (g.__peppaRequestTiming ??= { samples: new Map(), lastReport: new Map() });
const store = (): Store => (g.__peppaRequestTiming ??= { samples: new Map(), lastReport: new Map(), longSql: new Map() });
export function resetRequestTiming() {
g.__peppaRequestTiming = undefined;
@ -63,7 +71,16 @@ export async function recordRequest(db: Db, r: RequestRecord, now = Date.now()):
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 slow = r.ms >= (r.route.startsWith("ACTION ") ? slowActionMs() : slowRequestMs());
if (!slow && r.maxSqlMs < slowSqlMs()) return false;
if (!slow) {
// PEP-309: one long statement in a fast answer is usually a wait for the database (a deploy copies
// and migrates it: a lookup by primary key took 245 ms), not a slow query. A slow query repeats —
// the second such answer of the route within an hour is reported.
const seen = s.longSql.get(r.route);
s.longSql.set(r.route, now);
if (seen === undefined || now - seen > HOUR_MS) 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);

View File

@ -79,8 +79,15 @@ describe("PEP-213: slow requests", () => {
// Same route within 10 minutes: not sent again; another route: sent.
assert.equal(await rec("/p/[key]", 3000), false);
assert.equal(await rec("/t/[key]", 3000), true);
// A single slow SQL reports a fast page too.
assert.equal(await rec("/chats", 300, { maxSqlMs: 250 }), true);
// PEP-309: one long statement in a fast page is a wait for the database (a deploy copies and
// migrates it) — reported only when it repeats within an hour.
const T = Date.now();
const recAt = (at: number, route: string, ms: number, extra: Partial<Parameters<typeof core.recordRequest>[1]> = {}) =>
core.recordRequest(db, { route, ms, sqlMs: 10, sqlCount: 3, topSql: [{ sql: "select * from settings where key = ?", ms: 250 }], maxSqlMs: 8, ...extra }, at);
assert.equal(await recAt(T, "/chats", 300, { maxSqlMs: 250 }), false, "once — a lock wait, not a slow query");
assert.equal(await recAt(T + 5 * 60_000, "/chats", 300, { maxSqlMs: 250 }), true, "again within the hour — a slow query");
assert.equal(await recAt(T, "/journal", 267, { maxSqlMs: 245 }), false);
assert.equal(await recAt(T + 2 * 3600_000, "/journal", 267, { maxSqlMs: 245 }), false, "two hours apart — two separate waits");
const stats = core.requestSummary();
const board = stats.find((s) => s.route === "/p/[key]")!;
@ -89,4 +96,34 @@ describe("PEP-213: slow requests", () => {
assert.ok(board.p95 >= board.p50);
assert.ok(board.sqlShare > 0 && board.sqlShare <= 1);
});
test("PEP-309: действие ждёт службу запуска агентов — свой порог, 10 секунд", async () => {
core.resetRequestTiming();
const n = bugsink.ingested.length;
// Starting an agent, restarting it, checking a subscription: 2.5–6 s by design.
assert.equal(await rec("ACTION /", 3736), false);
assert.equal(await rec("ACTION /dashboard/delays", 5402), false);
assert.equal(await rec("ACTION /subscriptions", 5975), false);
assert.equal(bugsink.ingested.length, n);
// «Принять» that kept the person waiting 13.7 s is slow for real; a page keeps its 1.5 s.
assert.equal(await rec("ACTION /p/[key]/accept", 13745), true);
assert.equal(await rec("/gitea", 6553), true);
process.env.PEPPA_SLOW_ACTION_MS = "3000";
assert.equal(await rec("ACTION /team", 3500), true, "the limit is a setting");
delete process.env.PEPPA_SLOW_ACTION_MS;
});
test("PEP-309: отказ, который человек читает на странице (PeppaError), — не ошибка платформы", async () => {
core.resetErrorReporting();
const n = bugsink.ingested.length;
const refusal = new core.PeppaError("Нет активных подписок среди подключённых к проекту — проверьте их в «Подписках»");
assert.equal(core.isRefusal(refusal), true);
assert.equal(await core.reportRequestError(db, refusal, { service: "web", where: "POST /p/[key]" }), false);
assert.equal(bugsink.ingested.length, n, "nothing was sent");
// A copy of the class from another bundle is a refusal too; a real failure is reported as before.
assert.equal(core.isRefusal(Object.assign(new Error("x"), { name: "PeppaError" })), true);
assert.equal(await core.reportRequestError(db, new TypeError("Cannot read properties of undefined (reading 'id')"), { service: "web", where: "GET /p/[key]" }), true);
assert.equal(bugsink.ingested.length, n + 1);
delete process.env.PEPPA_PLATFORM_KEY;
});
});