// PEP-213: slow pages and server actions are measured on the server; a slow one reaches // Bugsink (PEP-api) as a warning with the longest SQL, once per route per 10 minutes. import assert from "node:assert/strict"; import { after, describe, test } from "node:test"; import { core, db, project, runner, teardown } from "./helpers.ts"; import { MockBugsink } from "../src/mock-bugsink.ts"; import { sql } from "drizzle-orm"; const { createBugsinkClient } = await import("@peppa/bugsink"); const { Probe, runWithProbe } = await import("@peppa/db"); const bugsink = await new MockBugsink().start(); const client = createBugsinkClient({ url: bugsink.url, token: bugsink.token, teamId: bugsink.teamId, publicUrl: bugsink.url }); process.env.BUGSINK_URL = bugsink.url; after(async () => { await bugsink.stop(); await teardown(); }); const rec = (route: string, ms: number, extra: Partial[1]> = {}) => core.recordRequest(db, { route, ms, sqlMs: 10, sqlCount: 3, topSql: [{ sql: "select * from tasks where id = ?", ms: 8 }], maxSqlMs: 8, ...extra }); describe("PEP-213: slow requests", () => { test("routes are grouped without ids and keys", () => { assert.equal(core.routePattern("/p/PEP"), "/p/[key]"); assert.equal(core.routePattern("/t/PEP-42?tab=tasks"), "/t/[key]"); assert.equal(core.routePattern("/p/PEP/plan/12"), "/p/[key]/plan/[id]"); assert.equal(core.routePattern("/subscriptions"), "/subscriptions"); assert.equal(core.routePattern("/"), "/"); }); test("only pages and server actions are measured; live feeds and APIs are not", () => { assert.equal(core.requestRoute({ url: "/p/PEP", method: "GET", headers: {} }), "/p/[key]"); assert.equal(core.requestRoute({ url: "/p/PEP", method: "POST", headers: { "next-action": "x" } }), "ACTION /p/[key]"); assert.equal(core.requestRoute({ url: "/p/PEP", method: "POST", headers: {} }), null); assert.equal(core.requestRoute({ url: "/api/live?scope=home", method: "GET", headers: {} }), null); assert.equal(core.requestRoute({ url: "/api/runners/1/terminal", method: "GET", headers: {} }), null); assert.equal(core.requestRoute({ url: "/_next/static/a.js", method: "GET", headers: {} }), null); }); test("the probe sums statements of the db client inside a request", async () => { const probe = new Probe(); runWithProbe(probe, () => { db.run(sql`select 1`); db.run(sql`select 2`); }); assert.equal(probe.sqlCount, 2); assert.ok(probe.top.length > 0 && !/\d{3,}/.test(probe.top[0]!.sql)); db.run(sql`select 3`); // outside a request: not counted assert.equal(probe.sqlCount, 2); }); test("a slow request → warning in -api with tags and SQL; fast one → only the summary; 10-minute limit", async () => { const p = await project({ turns: [] }); process.env.PEPPA_PLATFORM_KEY = p.key; core.resetErrorReporting(); core.resetRequestTiming(); const r = await runner.connectErrorTracking(db, await core.getProject(db, p.key), client, "http://peppa.test"); const api = r.sources.find((s) => s.kind === "api")!.bugsinkProjectId; const n = bugsink.ingested.length; assert.equal(await rec("/p/[key]", 100), false); assert.equal(bugsink.ingested.length, n); assert.equal(await rec("/p/[key]", 2000, { sqlMs: 1500, sqlCount: 40 }), true); const got = bugsink.ingested.at(-1)!; assert.equal(got.projectId, api); const ev = got.event as ReturnType & { fingerprint?: string[] }; assert.equal(ev.level, "warning"); assert.deepEqual(ev.fingerprint, ["slow", "/p/[key]"]); assert.equal(ev.tags.route, "/p/[key]"); assert.equal(ev.tags.ms, "2000"); assert.equal(ev.tags.sql_ms, "1500"); assert.equal(ev.tags.sql_count, "40"); assert.match(ev.exception.values[0]!.type, /Медленно: \/p\/\[key\]/); assert.match(ev.exception.values[0]!.value, /select \* from tasks where id = \?/); // 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); // 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]")!; assert.equal(board.count, 3); assert.equal(board.max, 3000); 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; }); });