peppa/apps/web/instrumentation.ts
peppa-bot 460da8bae2
All checks were successful
peppa/lint lint: success за 2с
peppa/typecheck typecheck: success за 55с
peppa/build build: success за 38с
peppa/test test: success за 1698с
peppa-ci / ci (pull_request) Successful in 31m9s
PEP-309: «Ошибки из прода» без ложных записей — отказ человеку, ожидание базы при выкатке, действие, которое ждёт запуска агента
У проекта 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 <noreply@anthropic.com>
2026-11-27 00:56:57 +05:00

38 lines
2.1 KiB
TypeScript

// Runs once when the Next server starts: the web's heartbeat for service monitoring (PEP-20)
// and the runner-client mode (PEP-21): the web enqueues runner commands, the watchdog runs them.
export async function register() {
if (process.env.NEXT_RUNTIME !== "nodejs") return;
const { beat, installCrashReporting } = await import("@peppa/core");
const { db } = await import("@/lib/db");
// PEP-91: a crash of the web goes to Bugsink before launchd restarts it.
installCrashReporting(db, "web");
// PEP-213: page and server action timing, slow ones → Bugsink, the day's numbers → /observability.
const { installRequestTiming } = await import("@peppa/core");
const { Server } = await import("node:http");
installRequestTiming(db, Server.prototype as never);
const { setRunnerClient } = await import("@peppa/runner");
setRunnerClient(true, db);
// PEP-225: the tab's WebSocket (/api/ws) — served by apps/web/server.ts in this process.
const { registerLiveWs } = await import("@/lib/live-server");
registerLiveWs();
const version = process.env.NEXT_PUBLIC_PEPPA_VERSION;
const tick = () => beat(db, "web", { version }).catch((e) => console.error(`heartbeat: ${(e as Error).message}`));
void tick();
setInterval(tick, 60_000).unref();
}
/** 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 { reportRequestError } = await import("@peppa/core");
const { db } = await import("@/lib/db");
const ua = request.headers["user-agent"];
// 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 },
tags: { route_type: context.routeType },
});
}