From 460da8bae2f2352706e822135bceca0d8c4943b6 Mon Sep 17 00:00:00 2001 From: peppa-bot Date: Fri, 27 Nov 2026 00:56:57 +0500 Subject: [PATCH] =?UTF-8?q?PEP-309:=20=C2=AB=D0=9E=D1=88=D0=B8=D0=B1=D0=BA?= =?UTF-8?q?=D0=B8=20=D0=B8=D0=B7=20=D0=BF=D1=80=D0=BE=D0=B4=D0=B0=C2=BB=20?= =?UTF-8?q?=D0=B1=D0=B5=D0=B7=20=D0=BB=D0=BE=D0=B6=D0=BD=D1=8B=D1=85=20?= =?UTF-8?q?=D0=B7=D0=B0=D0=BF=D0=B8=D1=81=D0=B5=D0=B9=20=E2=80=94=20=D0=BE?= =?UTF-8?q?=D1=82=D0=BA=D0=B0=D0=B7=20=D1=87=D0=B5=D0=BB=D0=BE=D0=B2=D0=B5?= =?UTF-8?q?=D0=BA=D1=83,=20=D0=BE=D0=B6=D0=B8=D0=B4=D0=B0=D0=BD=D0=B8?= =?UTF-8?q?=D0=B5=20=D0=B1=D0=B0=D0=B7=D1=8B=20=D0=BF=D1=80=D0=B8=20=D0=B2?= =?UTF-8?q?=D1=8B=D0=BA=D0=B0=D1=82=D0=BA=D0=B5,=20=D0=B4=D0=B5=D0=B9?= =?UTF-8?q?=D1=81=D1=82=D0=B2=D0=B8=D0=B5,=20=D0=BA=D0=BE=D1=82=D0=BE?= =?UTF-8?q?=D1=80=D0=BE=D0=B5=20=D0=B6=D0=B4=D1=91=D1=82=20=D0=B7=D0=B0?= =?UTF-8?q?=D0=BF=D1=83=D1=81=D0=BA=D0=B0=20=D0=B0=D0=B3=D0=B5=D0=BD=D1=82?= =?UTF-8?q?=D0=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit У проекта PEP 17 открытых записей, и часть из них не ошибки: - `PeppaError` («Нет активных подписок…») — понятный отказ на странице, а записан как сбой; - «Медленно: /journal», «/projects» — один запрос по первичному ключу ждал базу 245 и 333 мс, пока выкатка копировала и мигрировала её; - «Медленно: ACTION /», «/dashboard/delays», «/subscriptions» — действие ждёт службу запуска агентов 2,5–6 с по своей природе, порог 1,5 с срабатывал всегда. - core/error-report.ts: `isRefusal`, `reportRequestError` — отказ в ошибки не уходит; apps/web/instrumentation.ts зовёт его из `onRequestError`. - core/request-timing.ts: действиям свой порог `PEPPA_SLOW_ACTION_MS` (10 с); одиночный долгий запрос при быстром ответе — в ошибки только при повторе за час. - Тесты request-timing.test.ts: три новых правила; до исправления падали. Co-Authored-By: Claude Fable 5.2 --- apps/web/instrumentation.ts | 5 ++- packages/core/src/error-report.ts | 13 +++++++ packages/core/src/request-timing.ts | 21 +++++++++- packages/testkit/test/request-timing.test.ts | 41 +++++++++++++++++++- 4 files changed, 74 insertions(+), 6 deletions(-) diff --git a/apps/web/instrumentation.ts b/apps/web/instrumentation.ts index 4113198a..51995c23 100644 --- a/apps/web/instrumentation.ts +++ b/apps/web/instrumentation.ts @@ -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 }, 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 }, diff --git a/packages/core/src/error-report.ts b/packages/core/src/error-report.ts index 6f15b8e3..4f86bf14 100644 --- a/packages/core/src/error-report.ts +++ b/packages/core/src/error-report.ts @@ -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 { + if (isRefusal(e)) return false; + return reportPlatformError(db, e, ctx); +} + export async function reportPlatformError(db: Db, e: unknown, ctx: ErrorContext): Promise { try { if (process.env.PEPPA_ERRORS === "off") return false; diff --git a/packages/core/src/request-timing.ts b/packages/core/src/request-timing.ts index 8ba9f40c..609c6bf1 100644 --- a/packages/core/src/request-timing.ts +++ b/packages/core/src/request-timing.ts @@ -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; lastReport: Map; + /** PEP-309: when a route last answered fast but with one long statement. */ + longSql: Map; } 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); diff --git a/packages/testkit/test/request-timing.test.ts b/packages/testkit/test/request-timing.test.ts index 2ba67901..8baae474 100644 --- a/packages/testkit/test/request-timing.test.ts +++ b/packages/testkit/test/request-timing.test.ts @@ -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[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; + }); }); -- 2.45.2