PEP-213: медленные запросы видны — замер на сервере и warning в Bugsink #204
@ -45,8 +45,8 @@
|
||||
- Формат сообщения агента (PEP-152): сообщение агента человеку — через `admitAgentMessage` + `renderMain` (core/agent-message.ts): в тексте — основная часть (слова агента в `asIs`), техника — `details` (`messageDetails`), экран режет `splitForDisplay`. Суть с файлом, веткой, командой, «PR #N», статусом из кода, словом «Нельзя» — отказ.
|
||||
- Чужой текст в сообщениях (PEP-139/140): слова человека/модели, название задачи/проекта, логин, варианты агента, причину извне подставляй в `m()` как `asIs(…)` (shared/i18n) — перевод их не трогает; фразы самой фабрики (`PeppaError`, причина гейта) не помечай. Вопрос агента = `questionIsFreeText`, текст переводящему читателю — `questionText(q)`; MCP, CLI, агенту и сравнение текста в тестах — `stripAsIs`.
|
||||
- Один голос (PEP-198): человеку пишет только Аналитик — вопрос агента через `relayAgentQuestion` (runner/question-relay.ts; `runner/agent-relay.ts` — это релей песочницы, не путать), задачи из чата — только оффер `stories` и кнопка; новая строка сообщения роли — в `ROLE_MESSAGE_KEYS` выше «Агент {name}», иначе он её съест.
|
||||
- Тесты: места подписки занимай `core.createSession` с `subscriptionId`; задачу из очереди ёмкости убирай `moveTask(backlog)`, иначе её подхватит тик соседнего теста. Конец хода агента вопроса не создаёт — жди статус сессии `idle`. Сообщения суперадмина — `superadmin()` из helpers.ts. Текст из `chat_messages` сравнивай через `stripAsIs`.
|
||||
- Узкие места: подписка — `pickSubscription`/`rotationCandidate`; агент — `startRunner`/`resumeSession`, модель — `claudePrint`, сообщение — `deliverToUser`; проекты — `listProjects`/`userProjectIds` (`from(projects)` — с `isNull(deletedAt)`); веб с агентами — runnerCall.
|
||||
- Тесты: места подписки занимай `core.createSession` с `subscriptionId`; очередь ёмкости чисти `moveTask(backlog)`. Конец хода вопроса не создаёт — жди `idle`. Суперадмин — `superadmin()`. Текст чатов — через `stripAsIs`.
|
||||
- Узкие места: подписка — `pickSubscription`/`rotationCandidate`; агент — `startRunner`/`resumeSession`, модель — `claudePrint`, сообщение — `deliverToUser`; проекты — `listProjects`/`userProjectIds` (`from(projects)` — с `isNull(deletedAt)`); веб → runnerCall.
|
||||
- Вопрос ≠ задача (PEP-153): текст человека, который может стать задачей, — через `classifyMessage` (runner/message-intent.ts; в тестах mock-intake роль `intent`); молча задачу не заводить — кнопки (`chat.offer:<messageId>`, `INTENT_TEXT`).
|
||||
- Задачу агента заводи через createTask с origin (acceptance|incident|analyst) и fileStories/checkDuplicate (PEP-197); «Предложено» = backlog + tasks.proposed, readyBacklog их не отдаёт; автомерж задач агента — по autonomy.acceptOwn (mayAutoAcceptTask).
|
||||
- Неудачная версия (PEP-158): `rolled_back`/`failed` → агенту задачи, `returnFailedRelease` (runner/deploy-feedback.ts); счётчик — `attempts` задержки `deploy` (3 — суперадмину, 6 — стоп).
|
||||
@ -55,6 +55,7 @@
|
||||
|
||||
## Решения
|
||||
- Docker (PEP-222): раннеры по умолчанию `container` (тесты — `PEPPA_DEFAULT_ISOLATION=none`).
|
||||
- Медленные запросы (PEP-213): `core/request-timing.ts` (`http.Server` в instrumentation.ts, probe в db) → warning Bugsink; порог `PEPPA_SLOW_REQUEST_MS`.
|
||||
- Застрявшая задача (PEP-209): лечит `stuckTaskTick` — платформа сама на ревью/в «Готово», агенту — новый процесс (`restartAgent`: старый не вернёт MCP), не `sendToSession`. Новая причина задержки с повторами — `platformDelay` с `retryMin`/`retryAt`, суперадмину кнопки — `buttons: true`.
|
||||
- Сообщения людям — только через `telegram_outbox`/`push_outbox`: ночная тишина 23–08 (PEP-208) стоит на их выборке; тестам и стенду `PEPPA_NIGHT_QUIET=off`.
|
||||
- `template/` уходит в Gitea сам с выкаткой (PEP-242); старым проектам — `peppa ci connect <KEY> [--secrets-only]`.
|
||||
|
||||
@ -2,7 +2,7 @@
|
||||
import Link from "next/link";
|
||||
import { notFound } from "next/navigation";
|
||||
import { Activity, Pause, Play, Plus } from "lucide-react";
|
||||
import { describeTarget, observeRemindMin, egovLoginSummary, errorScope, errorsOverview, getLastRetention, isSuperadmin, listErrors, listMonitorViews } from "@peppa/core";
|
||||
import { describeTarget, observeRemindMin, egovLoginSummary, errorScope, errorsOverview, getLastRetention, isSuperadmin, listErrors, listMonitorViews, requestSummary } from "@peppa/core";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
import { LiveRefresh } from "@/components/LiveRefresh";
|
||||
import { Hidden } from "@/components/cards";
|
||||
@ -90,6 +90,8 @@ export default async function Observability({ searchParams }: { searchParams: Pr
|
||||
const monitors = listMonitorViews();
|
||||
const egov = await egovLoginSummary(db);
|
||||
const retention = await getLastRetention(db);
|
||||
const speed = requestSummary();
|
||||
const ms = (n: number) => (n >= 1000 ? t("{n} с", { n: (n / 1000).toFixed(1) }) : t("{n} мс", { n: Math.round(n) }));
|
||||
const web = loadEnv().PEPPA_WEB_URL;
|
||||
const down = monitors.filter((m) => !m.paused && m.state === "down").length;
|
||||
const degraded = monitors.filter((m) => !m.paused && m.state === "degraded").length;
|
||||
@ -155,6 +157,40 @@ export default async function Observability({ searchParams }: { searchParams: Pr
|
||||
</form>
|
||||
</Disclosure>
|
||||
</Section>
|
||||
|
||||
<Section title={t("Скорость страниц")} count={speed.length}>
|
||||
<p className="mb-2 text-sm text-muted-foreground">{t("Страницы и действия за последние 24 часа: сколько раз открывали, как долго отвечали и какая часть времени ушла на базу данных. Медленные запросы приходят в Bugsink сами. Числа считаются с последнего перезапуска сайта.")}</p>
|
||||
{speed.length === 0 ? (
|
||||
<Empty>{t("Пока нет данных: сайт открывали недавно.")}</Empty>
|
||||
) : (
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="text-left text-xs text-muted-foreground">
|
||||
<th className="py-1 pr-3 font-medium">{t("Страница")}</th>
|
||||
<th className="px-2 text-right font-medium">{t("Запросов")}</th>
|
||||
<th className="px-2 text-right font-medium">{t("Типичный (p50)")}</th>
|
||||
<th className="px-2 text-right font-medium">{t("Медленные (p95)")}</th>
|
||||
<th className="px-2 text-right font-medium">{t("Дольше всех")}</th>
|
||||
<th className="pl-2 text-right font-medium">{t("Доля базы")}</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{speed.map((r) => (
|
||||
<tr key={r.route} className="border-t border-border">
|
||||
<td className="py-1 pr-3 font-mono text-xs">{r.route}</td>
|
||||
<td className="px-2 text-right tabular-nums">{r.count}</td>
|
||||
<td className="px-2 text-right tabular-nums">{ms(r.p50)}</td>
|
||||
<td className={`px-2 text-right tabular-nums ${r.p95 >= 1500 ? "text-warn" : ""}`}>{ms(r.p95)}</td>
|
||||
<td className="px-2 text-right tabular-nums">{ms(r.max)}</td>
|
||||
<td className="pl-2 text-right tabular-nums">{Math.round(r.sqlShare * 100)}%</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)}
|
||||
</Section>
|
||||
</div>
|
||||
</Workspace>
|
||||
);
|
||||
|
||||
@ -6,6 +6,10 @@ export async function register() {
|
||||
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.
|
||||
|
||||
@ -0,0 +1,8 @@
|
||||
## Решения
|
||||
- Контекст запроса — AsyncLocalStorage в `packages/db/src/probe.ts`; `Statement` в client.ts добавляет время и текст SQL (плейсхолдеры `?`, значений нет).
|
||||
- Начало/конец запроса: `instrumentation.ts` вызывает `installRequestTiming`, он оборачивает `http.Server.prototype.emit("request")`. Так видны и страницы, и server actions (POST с `next-action`), без правки каждой страницы.
|
||||
- Считаются только маршруты страниц и actions; `/_next`, `/api/*`, `/mcp`, `/oauth`, `/auth` — нет (SSE `/api/live` и терминал внутри `/api`).
|
||||
- Маршрут нормализуется: ключи `PEP`, `PEP-42` → `[key]`, числа/хэши → `[id]`.
|
||||
- Bugsink: тот же отправитель `reportPlatformError` (PEP-91), `level: warning`, `fingerprint: ["slow", route]`; предел — одно событие на маршрут в 10 минут.
|
||||
- Сводка — в памяти веб-процесса за 24 ч (до 2000 замеров на маршрут); после перезапуска веба копится заново.
|
||||
- MCP `platform.status()` (PEP-212) в репозитории нет — не делаем.
|
||||
@ -0,0 +1,10 @@
|
||||
## Why
|
||||
Страницы тормозят, а цифры видны только в web.log. Нужен замер на сервере и сообщение в Bugsink.
|
||||
|
||||
## What Changes
|
||||
- Замер длительности страницы и server action, суммы и числа SQL внутри запроса.
|
||||
- Медленный запрос (`PEPPA_SLOW_REQUEST_MS`, 1500) или SQL > `PEPPA_SLOW_SQL_MS` (200) — warning «Медленно: <маршрут>» в Bugsink (PEP-api).
|
||||
- Сводка за сутки на `/observability` (суперадмин).
|
||||
|
||||
## Impact
|
||||
packages/db (probe), packages/core (request-timing, error-report), apps/web (instrumentation, observability).
|
||||
@ -0,0 +1,18 @@
|
||||
## ADDED Requirements
|
||||
### Requirement: Медленные запросы видны
|
||||
Система SHALL измерять длительность запросов страниц и server actions и время SQL внутри них, показывать сводку за сутки суперадмину и отправлять медленные запросы в Bugsink.
|
||||
|
||||
#### Scenario: Медленная страница попала в Bugsink
|
||||
- **GIVEN** порог `PEPPA_SLOW_REQUEST_MS` равен 1500 и Bugsink подключён
|
||||
- **WHEN** страница `/p/PEP` отвечает 2000 мс с тремя SQL-запросами
|
||||
- **THEN** в Bugsink приходит warning «Медленно: /p/[key]» с тегами `route`, `ms`, `sql_ms`, `sql_count` и самыми долгими SQL
|
||||
|
||||
#### Scenario: Быстрый запрос не шлётся
|
||||
- **GIVEN** порог 1500 мс
|
||||
- **WHEN** страница отвечает за 100 мс
|
||||
- **THEN** в Bugsink ничего не уходит, но запрос учтён в сводке
|
||||
|
||||
#### Scenario: Предел на маршрут
|
||||
- **GIVEN** по маршруту `/t/[key]` уже ушло событие
|
||||
- **WHEN** в течение 10 минут снова медленный запрос по нему
|
||||
- **THEN** новое событие не отправляется
|
||||
@ -0,0 +1,9 @@
|
||||
## 1. Замер
|
||||
- [x] 1.1 probe в packages/db и обёртка Statement
|
||||
- [x] 1.2 core/request-timing.ts: маршрут, сводка, отправка в Bugsink
|
||||
- [x] 1.3 level/fingerprint в error-report.ts
|
||||
- [x] 1.4 instrumentation.ts
|
||||
|
||||
## 2. Показ и тест
|
||||
- [x] 2.1 сводка на /observability
|
||||
- [x] 2.2 тест на моке Bugsink
|
||||
24
openspec/specs/slow-requests/spec.md
Normal file
24
openspec/specs/slow-requests/spec.md
Normal file
@ -0,0 +1,24 @@
|
||||
# slow-requests Specification
|
||||
|
||||
## Purpose
|
||||
TBD - created by archiving change pep-213-slow-requests. Update Purpose after archive.
|
||||
|
||||
## Requirements
|
||||
|
||||
### Requirement: Медленные запросы видны
|
||||
Система SHALL измерять длительность запросов страниц и server actions и время SQL внутри них, показывать сводку за сутки суперадмину и отправлять медленные запросы в Bugsink.
|
||||
|
||||
#### Scenario: Медленная страница попала в Bugsink
|
||||
- **GIVEN** порог `PEPPA_SLOW_REQUEST_MS` равен 1500 и Bugsink подключён
|
||||
- **WHEN** страница `/p/PEP` отвечает 2000 мс с тремя SQL-запросами
|
||||
- **THEN** в Bugsink приходит warning «Медленно: /p/[key]» с тегами `route`, `ms`, `sql_ms`, `sql_count` и самыми долгими SQL
|
||||
|
||||
#### Scenario: Быстрый запрос не шлётся
|
||||
- **GIVEN** порог 1500 мс
|
||||
- **WHEN** страница отвечает за 100 мс
|
||||
- **THEN** в Bugsink ничего не уходит, но запрос учтён в сводке
|
||||
|
||||
#### Scenario: Предел на маршрут
|
||||
- **GIVEN** по маршруту `/t/[key]` уже ушло событие
|
||||
- **WHEN** в течение 10 минут снова медленный запрос по нему
|
||||
- **THEN** новое событие не отправляется
|
||||
@ -63,6 +63,10 @@ export interface ErrorContext {
|
||||
platform?: "node" | "javascript";
|
||||
request?: { url?: string; method?: string; userAgent?: string };
|
||||
tags?: Record<string, string>;
|
||||
/** PEP-213: "warning" for things that are not errors (slow requests). */
|
||||
level?: "error" | "warning";
|
||||
/** PEP-213: Bugsink grouping, e.g. ["slow", route]. */
|
||||
fingerprint?: string[];
|
||||
/** Overrides for tests. */
|
||||
release?: string | null;
|
||||
environment?: string;
|
||||
@ -89,7 +93,8 @@ export function errorEvent(e: unknown, ctx: ErrorContext, at = new Date()) {
|
||||
event_id: randomBytes(16).toString("hex"),
|
||||
timestamp: at.getTime() / 1000,
|
||||
platform: ctx.platform ?? "node",
|
||||
level: "error",
|
||||
level: ctx.level ?? "error",
|
||||
...(ctx.fingerprint ? { fingerprint: ctx.fingerprint } : {}),
|
||||
logger: ctx.service,
|
||||
server_name: hostname(),
|
||||
release: (ctx.release !== undefined ? ctx.release : peppaCommit()) ?? `peppa@${peppaVersion()}`,
|
||||
|
||||
@ -28,6 +28,7 @@ export * from "./monitor.ts";
|
||||
export * from "./superadmins.ts";
|
||||
export * from "./domain-guard.ts";
|
||||
export * from "./error-report.ts";
|
||||
export * from "./request-timing.ts";
|
||||
export * from "./backup.ts";
|
||||
export * from "./repo-info.ts";
|
||||
export * from "./incidents.ts";
|
||||
|
||||
144
packages/core/src/request-timing.ts
Normal file
144
packages/core/src/request-timing.ts
Normal file
@ -0,0 +1,144 @@
|
||||
// PEP-213: how long web pages and server actions take, and how much of it is SQLite.
|
||||
// Measured on the server (http "request" event + AsyncLocalStorage probe in @peppa/db);
|
||||
// a slow one goes to Bugsink as a warning through the PEP-91 sender, the day's numbers
|
||||
// are shown on /observability.
|
||||
import type { IncomingMessage, ServerResponse } from "node:http";
|
||||
import { Probe, runWithProbe, type Db } from "@peppa/db";
|
||||
import { reportPlatformError } from "./error-report.ts";
|
||||
|
||||
export const DAY_MS = 24 * 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;
|
||||
|
||||
/** `/p/PEP/plan/12` → `/p/[key]/plan/[id]`; ids and keys never make a new group. */
|
||||
export function routePattern(path: string): string {
|
||||
const clean = path.split("?")[0]!.split("#")[0]!;
|
||||
const parts = clean.split("/").map((seg) => {
|
||||
if (!seg) return seg;
|
||||
if (/^[A-Z][A-Z0-9]{1,9}(-\d+)?$/.test(seg)) return "[key]";
|
||||
if (/^\d+$/.test(seg) || /^[0-9a-f]{8,}(-[0-9a-f]+)*$/i.test(seg)) return "[id]";
|
||||
return seg;
|
||||
});
|
||||
return parts.join("/") || "/";
|
||||
}
|
||||
|
||||
/** Pages and server actions only; assets, APIs (SSE live feeds, terminals), auth are not measured. */
|
||||
export function isMeasuredPath(path: string): boolean {
|
||||
return !/^\/(_next|api|mcp|oauth|auth|\.well-known)(\/|$|\?)/.test(path) && !/\.[a-z0-9]{2,5}(\?|$)/i.test(path);
|
||||
}
|
||||
|
||||
interface Sample {
|
||||
at: number;
|
||||
ms: number;
|
||||
sqlMs: number;
|
||||
sqlCount: number;
|
||||
}
|
||||
interface Store {
|
||||
samples: Map<string, Sample[]>;
|
||||
lastReport: Map<string, number>;
|
||||
}
|
||||
const g = globalThis as unknown as { __peppaRequestTiming?: Store };
|
||||
const store = (): Store => (g.__peppaRequestTiming ??= { samples: new Map(), lastReport: new Map() });
|
||||
|
||||
export function resetRequestTiming() {
|
||||
g.__peppaRequestTiming = undefined;
|
||||
}
|
||||
|
||||
export interface RequestRecord {
|
||||
route: string;
|
||||
ms: number;
|
||||
sqlMs: number;
|
||||
sqlCount: number;
|
||||
topSql: { sql: string; ms: number }[];
|
||||
maxSqlMs: number;
|
||||
}
|
||||
|
||||
/** Store one finished request and report it to Bugsink when it is slow. Never throws. */
|
||||
export async function recordRequest(db: Db, r: RequestRecord, now = Date.now()): Promise<boolean> {
|
||||
const s = store();
|
||||
const list = s.samples.get(r.route) ?? [];
|
||||
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 last = s.lastReport.get(r.route);
|
||||
if (last !== undefined && now - last < REPORT_EVERY_MS) return false;
|
||||
s.lastReport.set(r.route, now);
|
||||
const sqlLines = r.topSql.map((q, i) => `${i + 1}. ${Math.round(q.ms)} мс: ${q.sql}`).join("\n");
|
||||
const err = new Error(`${Math.round(r.ms)} мс, SQL ${Math.round(r.sqlMs)} мс (${r.sqlCount} шт.)${sqlLines ? `\n${sqlLines}` : ""}`);
|
||||
err.name = `Медленно: ${r.route}`;
|
||||
err.stack = ""; // a slow request has no failing frame
|
||||
return reportPlatformError(db, err, {
|
||||
service: "web",
|
||||
where: r.route,
|
||||
level: "warning",
|
||||
fingerprint: ["slow", r.route],
|
||||
tags: { route: r.route, ms: String(Math.round(r.ms)), sql_ms: String(Math.round(r.sqlMs)), sql_count: String(r.sqlCount) },
|
||||
});
|
||||
}
|
||||
|
||||
export interface RouteStats {
|
||||
route: string;
|
||||
count: number;
|
||||
p50: number;
|
||||
p95: number;
|
||||
max: number;
|
||||
/** Share of the request time spent in SQL, 0..1. */
|
||||
sqlShare: number;
|
||||
}
|
||||
|
||||
const quantile = (sorted: number[], q: number) => sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))] ?? 0;
|
||||
|
||||
/** Last 24 hours per route, slowest p95 first. */
|
||||
export function requestSummary(now = Date.now()): RouteStats[] {
|
||||
const out: RouteStats[] = [];
|
||||
for (const [route, all] of store().samples) {
|
||||
const list = all.filter((x) => now - x.at <= DAY_MS);
|
||||
if (!list.length) continue;
|
||||
const ms = list.map((x) => x.ms).sort((a, b) => a - b);
|
||||
const total = list.reduce((n, x) => n + x.ms, 0);
|
||||
const sql = list.reduce((n, x) => n + x.sqlMs, 0);
|
||||
out.push({ route, count: list.length, p50: quantile(ms, 0.5), p95: quantile(ms, 0.95), max: ms.at(-1)!, sqlShare: total ? Math.min(1, sql / total) : 0 });
|
||||
}
|
||||
return out.sort((a, b) => b.p95 - a.p95);
|
||||
}
|
||||
|
||||
/** The measured route of a request, or null: server actions are `ACTION <page>`. */
|
||||
export function requestRoute(req: Pick<IncomingMessage, "url" | "method" | "headers">): string | null {
|
||||
const url = req.url ?? "/";
|
||||
if (!isMeasuredPath(url)) return null;
|
||||
if (req.method === "POST") return req.headers["next-action"] ? `ACTION ${routePattern(url)}` : null;
|
||||
if (req.method !== "GET") return null;
|
||||
// Next's client-side navigations fetch the same page (RSC): the same route.
|
||||
return routePattern(url);
|
||||
}
|
||||
|
||||
type Emitter = { emit: (...a: unknown[]) => boolean };
|
||||
|
||||
/** Wrap the HTTP server's "request" event: every measured request gets a probe and a timer. */
|
||||
export function installRequestTiming(db: Db, serverProto: Emitter): void {
|
||||
const proto = serverProto as Emitter & { __peppaTiming?: boolean };
|
||||
if (proto.__peppaTiming) return;
|
||||
proto.__peppaTiming = true;
|
||||
const emit = proto.emit;
|
||||
proto.emit = function (this: unknown, event: unknown, ...args: unknown[]) {
|
||||
if (event !== "request") return emit.call(this, event, ...args);
|
||||
const req = args[0] as IncomingMessage;
|
||||
const res = args[1] as ServerResponse;
|
||||
const route = requestRoute(req);
|
||||
if (!route) return emit.call(this, event, ...args);
|
||||
const probe = new Probe();
|
||||
const t0 = performance.now();
|
||||
let done = false;
|
||||
const finish = () => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
void recordRequest(db, { route, ms: performance.now() - t0, sqlMs: probe.sqlMs, sqlCount: probe.sqlCount, topSql: probe.top, maxSqlMs: probe.maxMs }).catch(() => {});
|
||||
};
|
||||
res.once("close", finish);
|
||||
return runWithProbe(probe, () => emit.call(this, event, ...args));
|
||||
};
|
||||
}
|
||||
@ -7,6 +7,7 @@
|
||||
import { DatabaseSync, type StatementSync } from "node:sqlite";
|
||||
import { mkdirSync } from "node:fs";
|
||||
import { dirname } from "node:path";
|
||||
import { probed } from "./probe.ts";
|
||||
|
||||
export const BUSY_TIMEOUT_MS = 5000;
|
||||
const BUSY_RETRIES = 3;
|
||||
@ -37,13 +38,13 @@ class Statement {
|
||||
this.stmt = db.prepare(sql);
|
||||
}
|
||||
run(...p: Params) {
|
||||
return retryBusy(() => this.stmt.run(...(p as never[])));
|
||||
return probed(this.sql, () => retryBusy(() => this.stmt.run(...(p as never[]))));
|
||||
}
|
||||
all(...p: Params) {
|
||||
return retryBusy(() => this.stmt.all(...(p as never[])));
|
||||
return probed(this.sql, () => retryBusy(() => this.stmt.all(...(p as never[]))));
|
||||
}
|
||||
get(...p: Params) {
|
||||
return retryBusy(() => this.stmt.get(...(p as never[])));
|
||||
return probed(this.sql, () => retryBusy(() => this.stmt.get(...(p as never[]))));
|
||||
}
|
||||
/** The same statement returning rows as arrays (drizzle maps columns by position). */
|
||||
raw() {
|
||||
@ -52,7 +53,11 @@ class Statement {
|
||||
this.rawStmt.setReturnArrays(true);
|
||||
}
|
||||
const s = this.rawStmt;
|
||||
return { all: (...p: Params) => retryBusy(() => s.all(...(p as never[]))), get: (...p: Params) => retryBusy(() => s.get(...(p as never[]))) };
|
||||
const sql = this.sql;
|
||||
return {
|
||||
all: (...p: Params) => probed(sql, () => retryBusy(() => s.all(...(p as never[])))),
|
||||
get: (...p: Params) => probed(sql, () => retryBusy(() => s.get(...(p as never[])))),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@ -14,6 +14,7 @@ import * as schema from "./schema.ts";
|
||||
|
||||
export * from "./schema.ts";
|
||||
export { schema, SqliteClient };
|
||||
export { Probe, runWithProbe, currentProbe } from "./probe.ts";
|
||||
|
||||
/**
|
||||
* PEP-214: «ключ начинается с префикса» диапазоном по первичному ключу. `LIKE 'x:%'` в SQLite
|
||||
|
||||
49
packages/db/src/probe.ts
Normal file
49
packages/db/src/probe.ts
Normal file
@ -0,0 +1,49 @@
|
||||
// PEP-213: per-request SQL probe. A request (web) runs inside runWithProbe; every statement
|
||||
// of SqliteClient adds its time and text (placeholders, no values) to the current probe.
|
||||
import { AsyncLocalStorage } from "node:async_hooks";
|
||||
|
||||
export interface SqlSample {
|
||||
sql: string;
|
||||
ms: number;
|
||||
}
|
||||
|
||||
export class Probe {
|
||||
sqlMs = 0;
|
||||
sqlCount = 0;
|
||||
/** The longest statements, longest first (at most 3). */
|
||||
top: SqlSample[] = [];
|
||||
/** Longest single statement. */
|
||||
maxMs = 0;
|
||||
add(sql: string, ms: number) {
|
||||
this.sqlMs += ms;
|
||||
this.sqlCount++;
|
||||
if (ms > this.maxMs) this.maxMs = ms;
|
||||
if (this.top.length < 3 || ms > this.top[2]!.ms) {
|
||||
this.top.push({ sql: sql.replace(/\s+/g, " ").trim().slice(0, 300), ms });
|
||||
this.top.sort((a, b) => b.ms - a.ms);
|
||||
this.top.length = Math.min(this.top.length, 3);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const als = new AsyncLocalStorage<Probe>();
|
||||
|
||||
export function runWithProbe<T>(probe: Probe, fn: () => T): T {
|
||||
return als.run(probe, fn);
|
||||
}
|
||||
|
||||
export function currentProbe(): Probe | undefined {
|
||||
return als.getStore();
|
||||
}
|
||||
|
||||
/** Time `fn` into the current probe, if any. */
|
||||
export function probed<T>(sql: string, fn: () => T): T {
|
||||
const p = als.getStore();
|
||||
if (!p) return fn();
|
||||
const t = performance.now();
|
||||
try {
|
||||
return fn();
|
||||
} finally {
|
||||
p.add(sql, performance.now() - t);
|
||||
}
|
||||
}
|
||||
@ -25,6 +25,15 @@ export const observe: Dict = {
|
||||
"Аптайм за 24 часа": "Uptime for 24 hours",
|
||||
"Аптайм за 7 дней": "Uptime for 7 days",
|
||||
"ещё не проверялся": "not checked yet",
|
||||
"Скорость страниц": "Page speed",
|
||||
"Страницы и действия за последние 24 часа: сколько раз открывали, как долго отвечали и какая часть времени ушла на базу данных. Медленные запросы приходят в Bugsink сами. Числа считаются с последнего перезапуска сайта.": "Pages and actions over the last 24 hours: how often they were opened, how long they took and how much of that time went to the database. Slow requests reach Bugsink by themselves. Numbers are counted since the site was last restarted.",
|
||||
"Пока нет данных: сайт открывали недавно.": "No data yet: the site was restarted recently.",
|
||||
"Страница": "Page",
|
||||
"Запросов": "Requests",
|
||||
"Дольше всех": "Slowest",
|
||||
"Доля базы": "Database share",
|
||||
"Типичный (p50)": "Typical (p50)",
|
||||
"Медленные (p95)": "Slow (p95)",
|
||||
"Новый мониторинг": "New monitor",
|
||||
"на паузе": "paused",
|
||||
"Последние проверки": "Last checks",
|
||||
|
||||
@ -25,6 +25,15 @@ export const observe: Dict = {
|
||||
"Аптайм за 24 часа": "24 сағаттағы аптайм",
|
||||
"Аптайм за 7 дней": "7 күндегі аптайм",
|
||||
"ещё не проверялся": "әлі тексерілмеген",
|
||||
"Скорость страниц": "Беттер жылдамдығы",
|
||||
"Страницы и действия за последние 24 часа: сколько раз открывали, как долго отвечали и какая часть времени ушла на базу данных. Медленные запросы приходят в Bugsink сами. Числа считаются с последнего перезапуска сайта.": "Соңғы 24 сағаттағы беттер мен әрекеттер: қанша рет ашылды, қанша уақытта жауап берді және уақыттың қандай бөлігі дерекқорға кетті. Баяу сұраулар Bugsink-ке өздігінен түседі. Сандар сайт соңғы рет қайта іске қосылғаннан бері есептеледі.",
|
||||
"Пока нет данных: сайт открывали недавно.": "Әзірге дерек жоқ: сайт жақында қайта іске қосылды.",
|
||||
"Страница": "Бет",
|
||||
"Запросов": "Сұраулар",
|
||||
"Дольше всех": "Ең ұзағы",
|
||||
"Доля базы": "Дерекқор үлесі",
|
||||
"Типичный (p50)": "Әдеттегі (p50)",
|
||||
"Медленные (p95)": "Баяу (p95)",
|
||||
"Новый мониторинг": "Жаңа мониторинг",
|
||||
"на паузе": "кідірісте",
|
||||
"Последние проверки": "Соңғы тексерулер",
|
||||
|
||||
92
packages/testkit/test/request-timing.test.ts
Normal file
92
packages/testkit/test/request-timing.test.ts
Normal file
@ -0,0 +1,92 @@
|
||||
// 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<Parameters<typeof core.recordRequest>[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 <KEY>-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<typeof core.errorEvent> & { 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);
|
||||
// A single slow SQL reports a fast page too.
|
||||
assert.equal(await rec("/chats", 300, { maxSqlMs: 250 }), true);
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user