Merge pull request 'PEP-91: Пеппа ловит свои ошибки — Bugsink для фронта и бэка' (#85) from task/pep-91 into main
This commit is contained in:
commit
c501d4264b
@ -46,6 +46,7 @@
|
||||
- **Перенос репозитория проекта (PEP-4)**: `peppa project transfer <KEY> <owner>` (админ, от имени peppa-bot; `transferProject` в runner/transfer.ts): `POST /repos/{o}/{r}/transfer` → `projects.gitea_owner` → `origin` рабочей копии → `setupCi` (репо вне пространства бота получает свой раннер `repo-<owner>--<repo>`, секрет, вебхук) → событие `repo_transferred` (чат проекта). Повторный запуск доводит до конца (репозиторий уже на месте — чинит только сторону Пеппы); цель — организация, где бот может создавать репозитории, иначе Gitea оставляет перенос ожидающим и команда падает. Откат — та же команда обратно
|
||||
- **Видимость репозиториев (PEP-15/64)**: новые проекты по умолчанию публичные (веб, MCP `create_project`, CLI `project create … --private` — приватный), подключаемый существующий репо не меняется. Сменить — `setProjectVisibility` (runner/share.ts; PATCH repo `private` клиентом владельца, иначе peppa-bot; сбрасывает кэш `describeRepo`): веб «⋯ Настройки проекта» → «Репозиторий» и MCP `set_project_visibility` — только владелец; CLI `peppa project visibility <KEY|--all> public|private` — админ, без проверки владельца
|
||||
- **Ошибки из прода (PEP-58)**: Bugsink 2.6 в docker `peppa-bugsink` (сервис `bugsink` в `infra/docker-compose.yml`, `scripts/bugsink-up.sh`, база — SQLite `/data/db.sqlite3` в томе `peppa-bugsink-data` (PEP-63; перенос из Postgres — `scripts/bugsink-migrate-to-sqlite.sh`: dumpdata → migrate → loaddata → сверка строк; `peppa-postgres` только под профилем `legacy` до недели после переноса, откат — `infra/bugsink-legacy-pg.yml`), `bugsink.telecom.quest`, API на 127.0.0.1:3180, env `BUGSINK_*` в `.env`). Адаптер `packages/bugsink` (API + JSON custom-вебхука). Проект подключается в вебе («Подключить отслеживание ошибок» → два проекта Bugsink `<KEY>-web`/`<KEY>-api`, цель «Стабильность», `incident_settings`, `error_sources`). Входы: `POST /api/hooks/bugsink/<hook_secret>` (`receiveBugsinkWebhook` → `processIncidents` в `after()`) и опрос раз в 2 мин в `tick` вачдога (`pollBugsink`); оба → `ingestIssue` (идемпотентно по issue). Политика проекта (runner/incidents.ts): `notify` / `backlog` (по умолчанию) / `start` / `ask` (кнопки `i:<id>:backlog|start|ignore` в боте) / `triage` (runner/triage.ts: `$PEPPA_TRIAGE_BIN -p --output-format json --model haiku` с токеном владельца, не уверен → `ask`); окружения, игнор-регэксп, предел задач в сутки. «Исправлено» вручную (`resolveIncident`) до PEP-57, `REGRESSED` → задача обратно в бэклог. Моки: `mock-bugsink`, `mock-triage`
|
||||
- **Свои ошибки Пеппы (PEP-91)**: проект `PEP` подключён к Bugsink как любой (`peppa project errors <KEY>` = `connectErrorTrackingFromEnv`), бэк → `PEP-api`, фронт → `PEP-web`. Отправитель без SDK — `core/error-report.ts` (`reportPlatformError`: envelope `POST <BUGSINK_URL|хост DSN>/api/<id>/envelope/`, DSN источников проекта `PEPPA_PLATFORM_KEY` из БД (кэш 5 мин) или `PEPPA_ERRORS_DSN_API`/`_WEB`, `release` = `peppaCommit()`, `environment` = `PEPPA_ENVIRONMENT` (live), теги `service`/`where`; не бросает, 3 с, одна ошибка раз в минуту, ≤30/мин, `PEPPA_ERRORS=off`). Кто шлёт: `onRequestError` в `instrumentation.ts`, вачдог (`failed(db, log, часть)` вместо голого `log`), бот (`handleUpdate`), падения процессов (`installCrashReporting`: отправить и `exit 1`); браузер — `components/ErrorReporter.tsx` → `POST /api/client-errors` (без входа, ≤16 КБ, 20/мин на IP). Мок — envelope в `mock-bugsink` (`ingested`), тест `platform-errors.test.ts`
|
||||
- **Вход через eGov QR (PEP-65)**: relay KazEDS `sign.aitu.uz` (`KAZEDS_RELAY_BASE`, уже доверенный в eGov), `EGOV_ORGANISATION_NAME`/`EGOV_ORGANISATION_BIN` (БИН сгенерирован). `core/egov.ts`: `startEgovFlow` (документ `<auth><challenge/><nonce/></auth>`, поток в `settings` `egov.flow:<hash>`, 5 мин) → `egovFlowStatus` → `completeEgovFlow` (сверка challenge+nonce, ИИН из сертификата — свой разбор DER, `users.egov_iin`). **Подпись XMLDSig не проверяется — доверяем relay (решение PM)**. Веб: `/auth/egov/{start,status,complete}`, handle только в httpOnly cookie `peppa_egov`; `EgovSign` на странице входа и в «Настройках → eGov» (привязать/отвязать). Войти может только пользователь с привязанным ИИН и доступом (PEP-16). CLI `peppa user egov <login> <ИИН|->`. Мок `mock-kazeds-relay` (testkit; подписывает на 3-м опросе поддельным сертификатом). Пример интеграции от PM — `docs/egov-reference/`
|
||||
- **Вход только eGov (PEP-71)**: Gitea-вход и пароль убраны из веба (маршрутов `/auth/start|callback|password` нет). Неизвестный ИИН → `registerEgovUser` (core/egov.ts): учётка `gitea_id < 0` без пароля, логин `egovLoginBase` из имени сертификата («ИВАНОВА АЙГЕРИМ» → `aigerim.ivanova`, дубль `-2`, без имени `user-<4 цифры>`). Самозарегистрированный владелец (без Gitea и пароля, не админ/allowlist) без пула не получает вход машины для агентов — `mayUseMachineLogin` (core/access.ts) в `startSession`. Старым учёткам ИИН — «Настройки» (пока залогинен) или `peppa user egov`; аварийный вход — `peppa web login-link`
|
||||
- **Локальные пользователи (PEP-68)**: `users.gitea_id < 0`, вход по логину и паролю (`POST /auth/password` → `passwordLogin` в `core/local-users.ts`: scrypt `users.password_hash`, одна ошибка «Неверный логин или пароль», 5 неудач на логин / 20 на IP за 15 мин → пауза 15 мин, счётчики в `settings` `auth.fail:*`). Суперадмин = `platform.admins` (`isSuperadmin(db, user)` в core/monitor.ts): раздел `/users` — создать (временный пароль), сбросить пароль, отключить/включить (`users.disabled_at`: `isUserAllowed` → false для любого пользователя, сессии веба и MCP гаснут сразу); смена своего пароля — «Настройки». Вход через Gitea с логином локального пользователя отклоняется (`giteaLoginRefusal`), привязки Gitea к локальному аккаунту нет. Проект локального — в пространстве peppa-bot (`projectNamespace` в runner/provision.ts), участником он добавляется без соавторства в Gitea. CLI `peppa user add <login> [--admin] [--name]`, `peppa user passwd|disable|enable <login>` (пароль из stdin или сгенерированный)
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
// alerts) to the paired chat and turns button presses / replies into answers delivered
|
||||
// back into the agent session. Telegram is an adapter over the DB, not a remote shell:
|
||||
// it can only answer a specific pending question or resume/stop the session it is about.
|
||||
import { reportPlatformError } from "@peppa/core";
|
||||
import {
|
||||
accountUsageForUser,
|
||||
describeUsage,
|
||||
@ -701,6 +702,7 @@ export function createBot(o: BotOptions) {
|
||||
await finishUpdate(db, u.update_id, r, botUserId);
|
||||
} catch (e) {
|
||||
log(`update ${u.update_id}: ${(e as Error).stack ?? e}`);
|
||||
void reportPlatformError(db, e, { service: "bot", where: u.message ? "message" : u.callback_query ? `button ${u.callback_query.data ?? ""}`.slice(0, 60) : "update" });
|
||||
await finishUpdate(db, u.update_id, "failed", botUserId);
|
||||
}
|
||||
}
|
||||
|
||||
@ -2,6 +2,7 @@
|
||||
import { createDb } from "@peppa/db";
|
||||
import { loadEnv } from "@peppa/shared";
|
||||
import { setRunnerClient } from "@peppa/runner";
|
||||
import { installCrashReporting } from "@peppa/core";
|
||||
import { createBot } from "./bot.ts";
|
||||
import { TelegramApi } from "./telegram.ts";
|
||||
|
||||
@ -13,6 +14,8 @@ if (!env.TELEGRAM_BOT_TOKEN) {
|
||||
const db = createDb(env.PEPPA_DB);
|
||||
// PEP-21: the bot only enqueues runner commands; the runner service (watchdog) runs them.
|
||||
setRunnerClient(true, db);
|
||||
// PEP-91: a crash of the bot goes to Bugsink before launchd restarts it.
|
||||
installCrashReporting(db, "bot");
|
||||
const bot = createBot({
|
||||
db,
|
||||
api: new TelegramApi(env.TELEGRAM_BOT_TOKEN, process.env.TELEGRAM_API_URL),
|
||||
|
||||
42
apps/web/app/api/client-errors/route.ts
Normal file
42
apps/web/app/api/client-errors/route.ts
Normal file
@ -0,0 +1,42 @@
|
||||
// PEP-91: errors from the browser (ErrorReporter) → Bugsink, source `web` of the platform project.
|
||||
// No login needed (the login page breaks too): size cap and a per-IP limit instead.
|
||||
import { reportPlatformError } from "@peppa/core";
|
||||
import { db } from "@/lib/db";
|
||||
|
||||
const MAX_BYTES = 16 * 1024;
|
||||
const PER_IP_PER_MIN = 20;
|
||||
const hits = new Map<string, { at: number; n: number }>();
|
||||
|
||||
function limited(ip: string, now = Date.now()): boolean {
|
||||
const h = hits.get(ip);
|
||||
if (!h || now - h.at >= 60_000) {
|
||||
if (hits.size > 5000) hits.clear();
|
||||
hits.set(ip, { at: now, n: 1 });
|
||||
return false;
|
||||
}
|
||||
return ++h.n > PER_IP_PER_MIN;
|
||||
}
|
||||
|
||||
const str = (v: unknown, max: number) => (typeof v === "string" ? v.slice(0, max) : undefined);
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const ip = req.headers.get("cf-connecting-ip") ?? req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ?? "local";
|
||||
if (limited(ip)) return new Response(null, { status: 429 });
|
||||
const raw = await req.text();
|
||||
if (raw.length > MAX_BYTES) return new Response(null, { status: 413 });
|
||||
let b: Record<string, unknown>;
|
||||
try {
|
||||
b = JSON.parse(raw) as Record<string, unknown>;
|
||||
} catch {
|
||||
return new Response(null, { status: 400 });
|
||||
}
|
||||
const message = str(b.message, 2000);
|
||||
if (!message) return new Response(null, { status: 400 });
|
||||
const path = str(b.url, 500);
|
||||
const sent = await reportPlatformError(
|
||||
db,
|
||||
{ name: str(b.type, 100) || "Error", message, stack: str(b.stack, 8000) },
|
||||
{ service: "browser", kind: "web", platform: "javascript", where: path?.split("?")[0], request: { url: path, method: "GET", userAgent: req.headers.get("user-agent") ?? undefined } },
|
||||
);
|
||||
return Response.json({ sent });
|
||||
}
|
||||
@ -4,6 +4,7 @@ import { GeistSans } from "geist/font/sans";
|
||||
import { GeistMono } from "geist/font/mono";
|
||||
import { cn } from "@/lib/utils";
|
||||
import { THEME_COOKIE } from "@/lib/theme";
|
||||
import { ErrorReporter } from "@/components/ErrorReporter";
|
||||
import "./app.css";
|
||||
|
||||
export const metadata = { title: "Peppa", description: "Софтвейр-фабрика: проекты, стори и агенты", icons: { icon: "/icon.svg" } };
|
||||
@ -13,7 +14,10 @@ export default async function RootLayout({ children }: { children: ReactNode })
|
||||
const light = (await cookies()).get(THEME_COOKIE)?.value === "light";
|
||||
return (
|
||||
<html lang="ru" className={cn(GeistSans.variable, GeistMono.variable, !light && "dark")}>
|
||||
<body>{children}</body>
|
||||
<body>
|
||||
<ErrorReporter />
|
||||
{children}
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
|
||||
39
apps/web/components/ErrorReporter.tsx
Normal file
39
apps/web/components/ErrorReporter.tsx
Normal file
@ -0,0 +1,39 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect } from "react";
|
||||
|
||||
const MAX_PER_PAGE = 10;
|
||||
|
||||
/** PEP-91: browser errors of Peppa's own pages → /api/client-errors → Bugsink (PEP-web). */
|
||||
export function ErrorReporter() {
|
||||
useEffect(() => {
|
||||
let sent = 0;
|
||||
const seen = new Set<string>();
|
||||
const send = (type: string, message: string, stack?: string) => {
|
||||
const key = `${type}|${message}`;
|
||||
if (sent >= MAX_PER_PAGE || seen.has(key) || !message) return;
|
||||
seen.add(key);
|
||||
sent++;
|
||||
const body = JSON.stringify({ type, message: message.slice(0, 2000), stack: stack?.slice(0, 8000), url: location.pathname + location.search });
|
||||
void fetch("/api/client-errors", { method: "POST", headers: { "Content-Type": "application/json" }, body, keepalive: true }).catch(() => {});
|
||||
};
|
||||
const onError = (ev: ErrorEvent) => {
|
||||
const e = ev.error as Error | undefined;
|
||||
// "Script error." comes from cross-origin scripts without details: nothing to act on.
|
||||
if (!e && (!ev.message || ev.message === "Script error.")) return;
|
||||
send(e?.name ?? "Error", e?.message ?? ev.message, e?.stack ?? (ev.filename ? ` at ${ev.filename}:${ev.lineno}:${ev.colno}` : undefined));
|
||||
};
|
||||
const onRejection = (ev: PromiseRejectionEvent) => {
|
||||
const r = ev.reason as Error | string | undefined;
|
||||
if (r instanceof Error) send(r.name, r.message, r.stack);
|
||||
else send("UnhandledRejection", typeof r === "string" ? r : JSON.stringify(r) ?? "");
|
||||
};
|
||||
window.addEventListener("error", onError);
|
||||
window.addEventListener("unhandledrejection", onRejection);
|
||||
return () => {
|
||||
window.removeEventListener("error", onError);
|
||||
window.removeEventListener("unhandledrejection", onRejection);
|
||||
};
|
||||
}, []);
|
||||
return null;
|
||||
}
|
||||
@ -2,8 +2,10 @@
|
||||
// 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 } = await import("@peppa/core");
|
||||
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");
|
||||
const { setRunnerClient } = await import("@peppa/runner");
|
||||
setRunnerClient(true, db);
|
||||
const version = process.env.NEXT_PUBLIC_PEPPA_VERSION;
|
||||
@ -11,3 +13,17 @@ export async function register() {
|
||||
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 { reportPlatformError } = await import("@peppa/core");
|
||||
const { db } = await import("@/lib/db");
|
||||
const ua = request.headers["user-agent"];
|
||||
await reportPlatformError(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 },
|
||||
});
|
||||
}
|
||||
|
||||
32
openspec/changes/pep-91-platform-errors/proposal.md
Normal file
32
openspec/changes/pep-91-platform-errors/proposal.md
Normal file
@ -0,0 +1,32 @@
|
||||
# Proposal: PEP-91 — Пеппа ловит свои ошибки
|
||||
|
||||
Задача Пеппы: **PEP-91**.
|
||||
|
||||
## Why
|
||||
|
||||
15.11 живой сайт отдавал 500 всем вошедшим (`no such column: "google_sub"`: схема из рабочей
|
||||
копии опередила миграцию). Узнали об этом от PM. Bugsink (PEP-58) уже ловит ошибки проектов
|
||||
на фабрике, но сама Пеппа к нему не подключена: её ошибки остаются в логах launchd.
|
||||
|
||||
## What Changes
|
||||
|
||||
- Проект `PEP` подключается к Bugsink как любой проект: источники `PEP-web` и `PEP-api`,
|
||||
вебхук, цель «Стабильность», политика `backlog`. Новая команда CLI
|
||||
`peppa project errors <KEY>` делает то же, что кнопка «Подключить отслеживание ошибок».
|
||||
- Свой лёгкий отправитель по протоколу Sentry (`core/error-report.ts`, без внешнего SDK):
|
||||
envelope `POST /api/<id>/envelope/`, `X-Sentry-Auth`, стек V8 → frames, `release` = коммит
|
||||
процесса, `environment` = `PEPPA_ENVIRONMENT` (по умолчанию `live`), теги `service`, `where`.
|
||||
DSN — источники платформенного проекта (`PEPPA_PLATFORM_KEY`) из БД (кэш 5 мин) или
|
||||
`PEPPA_ERRORS_DSN_API`/`_WEB`; адрес приёма — `BUGSINK_URL` (внутренний), иначе хост DSN.
|
||||
Никогда не бросает, тайм-аут 3 с, одна и та же ошибка не чаще раза в минуту на процесс,
|
||||
не больше 30 в минуту. `PEPPA_ERRORS=off` выключает.
|
||||
- Кто отправляет (`api`): сервер веба (`onRequestError` в `instrumentation.ts`), вачдог
|
||||
(ошибки частей тика и сессий), бот (обработка обновлений), падения процессов веб/бот/вачдог
|
||||
(`uncaughtException`/`unhandledRejection`: отправить и упасть, как раньше).
|
||||
- Браузер (`web`): `ErrorReporter` в корневом layout ловит `error`/`unhandledrejection` и шлёт
|
||||
в `POST /api/client-errors` (≤16 КБ, 20 в минуту на IP, не больше 10 со страницы); веб
|
||||
пересылает в `PEP-web`. DSN в браузер не попадает.
|
||||
|
||||
## Вне scope
|
||||
|
||||
Source maps, трейсинг, ошибки агентов в tmux.
|
||||
@ -0,0 +1,22 @@
|
||||
## ADDED Requirements
|
||||
|
||||
### Requirement: Ошибки самой Пеппы уходят в Bugsink
|
||||
Пеппа SHALL отправлять свои ошибки (сервер веба, браузер, бот, вачдог, падения процессов) в
|
||||
источники Bugsink платформенного проекта по протоколу Sentry, без внешнего SDK и не ломая работу
|
||||
при недоступном Bugsink.
|
||||
|
||||
#### Scenario: Ошибка сервера веба
|
||||
- **WHEN** запрос к вебу падает с исключением, а у проекта `PEP` есть источник `api`
|
||||
- **THEN** в Bugsink уходит envelope с типом и текстом ошибки, стеком, `release` = коммит, тегом `service=web` и адресом запроса
|
||||
|
||||
#### Scenario: Ошибка в браузере
|
||||
- **WHEN** на странице Пеппы случается необработанная ошибка JS
|
||||
- **THEN** браузер шлёт её в `/api/client-errors`, веб пересылает в источник `web`; DSN браузеру не выдаётся
|
||||
|
||||
#### Scenario: Шум и недоступность
|
||||
- **WHEN** одна и та же ошибка повторяется много раз в минуту или Bugsink не отвечает
|
||||
- **THEN** отправляется не больше одной такой ошибки в минуту, а вызывающий код не получает исключения и не ждёт дольше 3 секунд
|
||||
|
||||
#### Scenario: Не подключено
|
||||
- **WHEN** у платформенного проекта нет источников и env DSN не задан, или `PEPPA_ERRORS=off`
|
||||
- **THEN** ничего не отправляется
|
||||
15
openspec/changes/pep-91-platform-errors/tasks.md
Normal file
15
openspec/changes/pep-91-platform-errors/tasks.md
Normal file
@ -0,0 +1,15 @@
|
||||
## 1. Отправитель
|
||||
- [x] 1.1 `core/error-report.ts`: `parseDsn`, `errorEvent` (стек V8 → frames), `bugsinkEnvelope`, `reportPlatformError` (DSN из env/БД, троттлинг, тайм-аут, выключатель)
|
||||
- [x] 1.2 `installCrashReporting(db, service)` — падение процесса: отправить и выйти с кодом 1
|
||||
|
||||
## 2. Кто отправляет
|
||||
- [x] 2.1 Веб: `onRequestError` в `instrumentation.ts`, `installCrashReporting` в `register`
|
||||
- [x] 2.2 Браузер: `components/ErrorReporter.tsx` + `POST /api/client-errors` (лимиты)
|
||||
- [x] 2.3 Вачдог: ошибки частей тика и сессий; `installCrashReporting` в `peppa watchdog`
|
||||
- [x] 2.4 Бот: ошибки обработки обновлений; `installCrashReporting`
|
||||
|
||||
## 3. Подключение
|
||||
- [x] 3.1 CLI `peppa project errors <KEY>` (= `connectErrorTracking`)
|
||||
- [x] 3.2 `mock-bugsink`: приём envelope (`events`), e2e `platform-errors.test.ts`
|
||||
- [x] 3.3 AGENTS.md
|
||||
- [ ] 3.4 На живой системе: `peppa project errors PEP` (координатор после мержа)
|
||||
@ -74,6 +74,8 @@ import { promoteRunner, queueTaskOnRunner, renameRunner, startFreeRunner, runner
|
||||
import { checkPlatformChannel, describeChannel, getPlatformChannel, parseChatId, platformDigestTick, setPlatformChannel, PLATFORM_CHANNEL_EVENTS, type PlatformChannelPatch } from "@peppa/core";
|
||||
import { setSharedPool, sharedPool, createHost, deleteHost, findHost, HOST_STATUS_RU, listHosts, setHostDisabled, updateHost } from "@peppa/core";
|
||||
import { getProjectRunnerSettings, getSystemRunnerSettings, getTaskRunnerSettings, resolveRunnerSettings, runnerStories, setProjectRunnerSettings, setSystemRunnerSettings, setTaskRunnerSettings, type RunnerSettingsPatch } from "@peppa/core";
|
||||
import { connectErrorTrackingFromEnv } from "@peppa/runner";
|
||||
import { installCrashReporting } from "@peppa/core";
|
||||
import { answerAndDeliver, connectCi, importIssues, deployProd, listReleases, platformReleaseOffers, setPlatformReleaseOffers, recordRelease, type ReleaseStatus, provisionProject, setProjectVisibility, transferProject, PROVIDERS, type Provider, resumeSession, runWatchdog, sendToSession, startSession, stopSession, tick } from "@peppa/runner";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { readFileSync } from "node:fs";
|
||||
@ -88,6 +90,7 @@ const USAGE = `peppa — Peppa software factory CLI
|
||||
peppa project agent <KEY|KEY-N|--platform> [key=value…] (PEP-41: provider model effort escalateModel escalateEffort escalateAfter fallbackProvider fallbackModel; value - = inherit)
|
||||
peppa project visibility <KEY|--all> public|private (repo visibility in Gitea: owner's client, then peppa-bot)
|
||||
peppa project transfer <KEY> <owner> (PEP-4: move the repo to another Gitea namespace as peppa-bot; fixes origin, CI runner, secret, webhook)
|
||||
peppa project errors <KEY> (PEP-58/91: connect to Bugsink — <KEY>-web and <KEY>-api, webhook, goal «Стабильность»)
|
||||
peppa project import-issues <KEY> (PEP-46: open Gitea issues of the repo → backlog stories, linked back)
|
||||
peppa project list
|
||||
peppa deploy prod [KEY] (healthy staging release → prod, as the PM's button)
|
||||
@ -293,6 +296,14 @@ async function main(): Promise<void> {
|
||||
console.log(`${p.key} owner → ${u?.login ?? "none"}`);
|
||||
break;
|
||||
}
|
||||
case "project errors": {
|
||||
if (!args[0]) throw new PeppaError("usage: peppa project errors <KEY>");
|
||||
const p = await getProject(db, args[0]);
|
||||
const r = await connectErrorTrackingFromEnv(db, p);
|
||||
for (const s of r.sources) console.log(`${s.kind}: Bugsink project #${s.bugsinkProjectId}`);
|
||||
console.log(`webhook: ${r.settings.webhookAuto ? "set automatically" : `add a Custom webhook in Bugsink → ${r.webhookUrl}`}`);
|
||||
break;
|
||||
}
|
||||
case "project import-issues": {
|
||||
if (!args[0]) throw new PeppaError("usage: peppa project import-issues <KEY>");
|
||||
const p = await getProject(db, args[0]);
|
||||
@ -832,7 +843,11 @@ async function main(): Promise<void> {
|
||||
log: (m: string) => console.log(`${new Date().toISOString()} ${m}`),
|
||||
};
|
||||
if (opts.once) await tick(db, wopts);
|
||||
else await runWatchdog(db, wopts);
|
||||
else {
|
||||
// PEP-91: a crash of the watchdog goes to Bugsink before launchd restarts it.
|
||||
installCrashReporting(db, "watchdog");
|
||||
await runWatchdog(db, wopts);
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
|
||||
211
packages/core/src/error-report.ts
Normal file
211
packages/core/src/error-report.ts
Normal file
@ -0,0 +1,211 @@
|
||||
// PEP-91: Peppa reports its own errors to Bugsink — the Sentry envelope protocol without an SDK.
|
||||
// DSNs are the error sources of the platform project (PEPPA_PLATFORM_KEY, connected like any
|
||||
// project, PEP-58) or PEPPA_ERRORS_DSN_API / _WEB. Never throws, never waits longer than 3 s.
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { hostname } from "node:os";
|
||||
import { and, eq } from "drizzle-orm";
|
||||
import { errorSources, projects, type Db } from "@peppa/db";
|
||||
import { peppaCommit, peppaVersion } from "./monitor.ts";
|
||||
|
||||
export type ErrorSourceKind = "api" | "web";
|
||||
|
||||
export interface ParsedDsn {
|
||||
key: string;
|
||||
origin: string;
|
||||
projectId: string;
|
||||
}
|
||||
|
||||
/** `https://<key>@host/<id>` → parts; null for anything else. */
|
||||
export function parseDsn(dsn: string): ParsedDsn | null {
|
||||
try {
|
||||
const u = new URL(dsn);
|
||||
const projectId = u.pathname.replace(/^\/+|\/+$/g, "");
|
||||
if (!u.username || !/^\d+$/.test(projectId)) return null;
|
||||
return { key: decodeURIComponent(u.username), origin: u.origin, projectId };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export interface StackFrame {
|
||||
function?: string;
|
||||
filename: string;
|
||||
lineno?: number;
|
||||
colno?: number;
|
||||
in_app: boolean;
|
||||
}
|
||||
|
||||
const FRAME_RE = /^\s*at (?:(.+?) \()?(.+?):(\d+):(\d+)\)?\s*$/;
|
||||
|
||||
/** V8 stack (`at fn (file:1:2)`) → Sentry frames, outermost first. */
|
||||
export function stackFrames(stack: string | undefined): StackFrame[] {
|
||||
const frames: StackFrame[] = [];
|
||||
for (const line of (stack ?? "").split("\n")) {
|
||||
const m = FRAME_RE.exec(line);
|
||||
if (!m) continue;
|
||||
const filename = m[2]!.replace(/^file:\/\//, "");
|
||||
frames.push({
|
||||
function: m[1] || undefined,
|
||||
filename,
|
||||
lineno: Number(m[3]),
|
||||
colno: Number(m[4]),
|
||||
in_app: !/node_modules|^node:|^internal\//.test(filename),
|
||||
});
|
||||
}
|
||||
return frames.reverse().slice(-50);
|
||||
}
|
||||
|
||||
export interface ErrorContext {
|
||||
service: string;
|
||||
/** Which part failed: "tick: autonomy", "session #12", "GET /p/PEP"… */
|
||||
where?: string;
|
||||
kind?: ErrorSourceKind;
|
||||
platform?: "node" | "javascript";
|
||||
request?: { url?: string; method?: string; userAgent?: string };
|
||||
tags?: Record<string, string>;
|
||||
/** Overrides for tests. */
|
||||
release?: string | null;
|
||||
environment?: string;
|
||||
}
|
||||
|
||||
export interface ErrorLike {
|
||||
name?: string;
|
||||
message?: string;
|
||||
stack?: string;
|
||||
}
|
||||
|
||||
function asError(e: unknown): ErrorLike {
|
||||
if (e instanceof Error) return e;
|
||||
if (e && typeof e === "object" && "message" in e) return e as ErrorLike;
|
||||
return { name: "Error", message: typeof e === "string" ? e : JSON.stringify(e) ?? String(e) };
|
||||
}
|
||||
|
||||
/** A Sentry event for an error. */
|
||||
export function errorEvent(e: unknown, ctx: ErrorContext, at = new Date()) {
|
||||
const err = asError(e);
|
||||
const frames = stackFrames(err.stack);
|
||||
const tags: Record<string, string> = { service: ctx.service, ...(ctx.where ? { where: ctx.where.slice(0, 200) } : {}), ...ctx.tags };
|
||||
return {
|
||||
event_id: randomBytes(16).toString("hex"),
|
||||
timestamp: at.getTime() / 1000,
|
||||
platform: ctx.platform ?? "node",
|
||||
level: "error",
|
||||
logger: ctx.service,
|
||||
server_name: hostname(),
|
||||
release: (ctx.release !== undefined ? ctx.release : peppaCommit()) ?? `peppa@${peppaVersion()}`,
|
||||
environment: ctx.environment ?? process.env.PEPPA_ENVIRONMENT ?? "live",
|
||||
tags,
|
||||
...(ctx.request ? { request: { url: ctx.request.url, method: ctx.request.method, headers: ctx.request.userAgent ? { "User-Agent": ctx.request.userAgent } : undefined } } : {}),
|
||||
exception: {
|
||||
values: [{ type: err.name || "Error", value: (err.message ?? "").slice(0, 2000), ...(frames.length ? { stacktrace: { frames } } : {}) }],
|
||||
},
|
||||
};
|
||||
}
|
||||
export type ErrorEvent = ReturnType<typeof errorEvent>;
|
||||
|
||||
/** The envelope body for one event. */
|
||||
export function bugsinkEnvelope(dsn: string, event: ErrorEvent): string {
|
||||
return [JSON.stringify({ event_id: event.event_id, dsn, sent_at: new Date().toISOString() }), JSON.stringify({ type: "event" }), JSON.stringify(event)].join("\n") + "\n";
|
||||
}
|
||||
|
||||
/** POST one event; `ingestBase` (BUGSINK_URL on the same host) beats the DSN's public host. */
|
||||
export async function sendEvent(dsn: string, event: ErrorEvent, o: { ingestBase?: string; timeoutMs?: number } = {}): Promise<boolean> {
|
||||
const d = parseDsn(dsn);
|
||||
if (!d) return false;
|
||||
const base = (o.ingestBase || d.origin).replace(/\/$/, "");
|
||||
try {
|
||||
const res = await fetch(`${base}/api/${d.projectId}/envelope/`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-sentry-envelope", "X-Sentry-Auth": `Sentry sentry_version=7, sentry_key=${d.key}, sentry_client=peppa/${peppaVersion()}` },
|
||||
body: bugsinkEnvelope(dsn, event),
|
||||
signal: AbortSignal.timeout(o.timeoutMs ?? 3000),
|
||||
});
|
||||
return res.ok;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const DSN_TTL = 5 * 60_000;
|
||||
const dsnCache = new Map<ErrorSourceKind, { dsn: string | null; at: number }>();
|
||||
|
||||
/** DSN of the platform project's source: env first, then the DB (cached 5 min). */
|
||||
export async function platformDsn(db: Db, kind: ErrorSourceKind, now = Date.now()): Promise<string | null> {
|
||||
const env = process.env[kind === "web" ? "PEPPA_ERRORS_DSN_WEB" : "PEPPA_ERRORS_DSN_API"];
|
||||
if (env) return env;
|
||||
const hit = dsnCache.get(kind);
|
||||
if (hit && now - hit.at < DSN_TTL) return hit.dsn;
|
||||
const key = process.env.PEPPA_PLATFORM_KEY || "PEP";
|
||||
const [row] = await db
|
||||
.select({ dsn: errorSources.dsn })
|
||||
.from(errorSources)
|
||||
.innerJoin(projects, eq(projects.id, errorSources.projectId))
|
||||
.where(and(eq(projects.key, key), eq(errorSources.kind, kind)));
|
||||
const dsn = row?.dsn ?? null;
|
||||
dsnCache.set(kind, { dsn, at: now });
|
||||
return dsn;
|
||||
}
|
||||
|
||||
const SAME_ERROR_MS = 60_000;
|
||||
const MAX_PER_MINUTE = 30;
|
||||
const seen = new Map<string, number>();
|
||||
let windowStart = 0;
|
||||
let windowCount = 0;
|
||||
|
||||
/** Throttle: one per fingerprint per minute, 30 a minute overall. Exported for tests. */
|
||||
export function shouldSend(fingerprint: string, now = Date.now()): boolean {
|
||||
if (now - windowStart >= 60_000) {
|
||||
windowStart = now;
|
||||
windowCount = 0;
|
||||
for (const [k, t] of seen) if (now - t >= SAME_ERROR_MS) seen.delete(k);
|
||||
}
|
||||
const last = seen.get(fingerprint);
|
||||
if (last !== undefined && now - last < SAME_ERROR_MS) return false;
|
||||
if (windowCount >= MAX_PER_MINUTE) return false;
|
||||
seen.set(fingerprint, now);
|
||||
windowCount++;
|
||||
return true;
|
||||
}
|
||||
|
||||
export function resetErrorReporting() {
|
||||
seen.clear();
|
||||
dsnCache.clear();
|
||||
windowStart = 0;
|
||||
windowCount = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Report one of Peppa's own errors. Never throws; resolves to whether Bugsink took it
|
||||
* (false when not connected, throttled, switched off or unreachable).
|
||||
*/
|
||||
export async function reportPlatformError(db: Db, e: unknown, ctx: ErrorContext): Promise<boolean> {
|
||||
try {
|
||||
if (process.env.PEPPA_ERRORS === "off") return false;
|
||||
const kind = ctx.kind ?? "api";
|
||||
const event = errorEvent(e, ctx);
|
||||
const ex = event.exception.values[0]!;
|
||||
const top = ex.stacktrace?.frames.at(-1);
|
||||
if (!shouldSend(`${kind}|${ctx.service}|${ex.type}|${ex.value.slice(0, 200)}|${top?.filename ?? ""}:${top?.lineno ?? ""}`)) return false;
|
||||
const dsn = await platformDsn(db, kind);
|
||||
if (!dsn) return false;
|
||||
return await sendEvent(dsn, event, { ingestBase: process.env.BUGSINK_URL });
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
let crashInstalled = false;
|
||||
|
||||
/** A process crash (uncaught exception / unhandled rejection) goes to Bugsink, then exit 1 as before. */
|
||||
export function installCrashReporting(db: Db, service: string, log: (m: string) => void = (m) => console.error(m)): void {
|
||||
if (crashInstalled) return;
|
||||
crashInstalled = true;
|
||||
const crash = (kind: string) => (e: unknown) => {
|
||||
log(`${service} ${kind}: ${(e as Error)?.stack ?? String(e)}`);
|
||||
const done = () => process.exit(1);
|
||||
setTimeout(done, 3500).unref();
|
||||
void reportPlatformError(db, e, { service, where: kind }).finally(done);
|
||||
};
|
||||
process.on("uncaughtException", crash("uncaughtException"));
|
||||
process.on("unhandledRejection", crash("unhandledRejection"));
|
||||
}
|
||||
@ -15,6 +15,7 @@ export * from "./users.ts";
|
||||
export * from "./oauth.ts";
|
||||
export * from "./access.ts";
|
||||
export * from "./monitor.ts";
|
||||
export * from "./error-report.ts";
|
||||
export * from "./backup.ts";
|
||||
export * from "./repo-info.ts";
|
||||
export * from "./incidents.ts";
|
||||
|
||||
@ -292,6 +292,11 @@ export async function connectErrorTracking(db: Db, project: Project, client: Bug
|
||||
return { settings, sources: await listErrorSources(db, project.id), webhookUrl };
|
||||
}
|
||||
|
||||
/** `peppa project errors <KEY>` (PEP-91): connect with the Bugsink configured in env. */
|
||||
export function connectErrorTrackingFromEnv(db: Db, project: Project): Promise<ConnectResult> {
|
||||
return connectErrorTracking(db, project, bugsinkFromEnv(), bugsinkWebhookBase());
|
||||
}
|
||||
|
||||
/** Where Bugsink (in docker) reaches Peppa's web; PEPPA_WEB_URL by default. */
|
||||
export function bugsinkWebhookBase(): string {
|
||||
return process.env.BUGSINK_WEBHOOK_BASE ?? process.env.PEPPA_WEB_URL ?? "http://localhost:3100";
|
||||
|
||||
@ -24,7 +24,7 @@ import * as tmux from "./tmux.ts";
|
||||
import { recordLimit } from "./limits.ts";
|
||||
import { killRunner, resumeSession } from "./sessions.ts";
|
||||
import { hostTick } from "./hosts.ts";
|
||||
import { getSubscription, isUsable } from "@peppa/core";
|
||||
import { getSubscription, isUsable, reportPlatformError } from "@peppa/core";
|
||||
import { planRotation, rotationEnabled, tryRotate, usageWarning } from "./rotation.ts";
|
||||
import { monitorTick } from "./monitor.ts";
|
||||
import { platformBuildTick } from "./platform-build.ts";
|
||||
@ -70,42 +70,50 @@ async function tickInner(db: Db, opts: WatchdogOptions): Promise<void> {
|
||||
try {
|
||||
await checkSession(db, s, opts, cfg, log);
|
||||
} catch (e) {
|
||||
log(`session #${s.id}: ${(e as Error).message}`);
|
||||
failed(db, log, `session #${s.id}`)(e);
|
||||
}
|
||||
}
|
||||
// PEP-28: planned automatic restarts, reminders/escalation, runners waiting for nobody.
|
||||
await restartTick(db, { now, cfg, log }).catch((e) => log(`restarts: ${(e as Error).message}`));
|
||||
await remindTick(db, { now, cfg, log }).catch((e) => log(`reminders: ${(e as Error).message}`));
|
||||
await idleStopTick(db, { now, cfg, log }).catch((e) => log(`idle: ${(e as Error).message}`));
|
||||
await restartTick(db, { now, cfg, log }).catch(failed(db, log, "restarts"));
|
||||
await remindTick(db, { now, cfg, log }).catch(failed(db, log, "reminders"));
|
||||
await idleStopTick(db, { now, cfg, log }).catch(failed(db, log, "idle"));
|
||||
// Runner queues and worktrees (PEP-10/27): next story, orphaned queue items, cleanup.
|
||||
await runnerTick(db, { log }).catch((e) => log(`runners: ${(e as Error).message}`));
|
||||
await runnerTick(db, { log }).catch(failed(db, log, "runners"));
|
||||
// PEP-40: runner hosts — online/offline, load, versions (once a minute each).
|
||||
await hostTick(db, { now: opts.now, log }).catch((e) => log(`hosts: ${(e as Error).message}`));
|
||||
await hostTick(db, { now: opts.now, log }).catch(failed(db, log, "hosts"));
|
||||
// Story budgets (PEP-43): over the limit → pause and ask the PM.
|
||||
await budgetTick(db, { now: opts.now, log }).catch((e) => log(`budgets: ${(e as Error).message}`));
|
||||
await budgetTick(db, { now: opts.now, log }).catch(failed(db, log, "budgets"));
|
||||
// Autonomous factory (PEP-23/24/25): auto-merge, auto-close, backlog dispatcher.
|
||||
// PEP-84: «продакт» and «аналитик» refine new stories before the dispatcher sees them.
|
||||
await intakeTick(db, { now: opts.now, log }).catch((e) => log(`intake: ${(e as Error).message}`));
|
||||
await autonomyTick(db, { now: opts.now, log }).catch((e) => log(`autonomy: ${(e as Error).message}`));
|
||||
await intakeTick(db, { now: opts.now, log }).catch(failed(db, log, "intake"));
|
||||
await autonomyTick(db, { now: opts.now, log }).catch(failed(db, log, "autonomy"));
|
||||
// Errors of running products (PEP-58): Bugsink poll + incident policies.
|
||||
await incidentTick(db, { now: opts.now, log }).catch((e) => log(`incidents: ${(e as Error).message}`));
|
||||
await incidentTick(db, { now: opts.now, log }).catch(failed(db, log, "incidents"));
|
||||
// Daily digest at each user's time (PEP-29); a no-op outside their window.
|
||||
await digestTick(db, { now: opts.now, log }).catch((e) => log(`digest: ${(e as Error).message}`));
|
||||
await digestTick(db, { now: opts.now, log }).catch(failed(db, log, "digest"));
|
||||
// PEP-60: platform channel — re-check a channel that isn't working yet, new builds, the
|
||||
// platform digest at its time.
|
||||
await recheckPlatformChannel(db, { now: opts.now, log }).catch((e) => log(`platform channel: ${(e as Error).message}`));
|
||||
await platformBuildTick(db, { now: opts.now, log }).catch((e) => log(`platform build: ${(e as Error).message}`));
|
||||
await platformDigestTick(db, { now: opts.now, log }).catch((e) => log(`platform digest: ${(e as Error).message}`));
|
||||
await recheckPlatformChannel(db, { now: opts.now, log }).catch(failed(db, log, "platform channel"));
|
||||
await platformBuildTick(db, { now: opts.now, log }).catch(failed(db, log, "platform build"));
|
||||
await platformDigestTick(db, { now: opts.now, log }).catch(failed(db, log, "platform digest"));
|
||||
// PEP-62: events → chats (the bot does it too; idempotent) and the chats' TTL, once an hour.
|
||||
await syncChats(db, { now: opts.now }).catch((e) => log(`chats: ${(e as Error).message}`));
|
||||
await syncChats(db, { now: opts.now }).catch(failed(db, log, "chats"));
|
||||
const nowMs = (opts.now ?? new Date()).getTime();
|
||||
if (nowMs - lastChatPrune >= 3600_000) {
|
||||
lastChatPrune = nowMs;
|
||||
await pruneChats(db, { now: opts.now }).then((n) => n && log(`chats: pruned ${n}`)).catch((e) => log(`chats prune: ${(e as Error).message}`));
|
||||
await pruneChats(db, { now: opts.now }).then((n) => n && log(`chats: pruned ${n}`)).catch(failed(db, log, "chats prune"));
|
||||
}
|
||||
}
|
||||
let lastChatPrune = 0;
|
||||
|
||||
/** A part of the watchdog failed: log it and send it to Bugsink (PEP-91). */
|
||||
function failed(db: Db, log: (m: string) => void, where: string) {
|
||||
return (e: unknown) => {
|
||||
log(`${where}: ${(e as Error)?.message ?? e}`);
|
||||
void reportPlatformError(db, e, { service: "watchdog", where });
|
||||
};
|
||||
}
|
||||
|
||||
async function checkSession(db: Db, s: SessionView, opts: WatchdogOptions, cfg: WatchdogSettings, log: (m: string) => void) {
|
||||
if (s.tmuxName.startsWith("pending-")) return;
|
||||
const nowDate = opts.now ?? new Date();
|
||||
@ -219,18 +227,18 @@ export async function runWatchdog(db: Db, opts: WatchdogOptions, signal?: AbortS
|
||||
});
|
||||
}
|
||||
while (!signal?.aborted) {
|
||||
await tick(db, opts).catch((e) => log(`tick failed: ${(e as Error).message}`));
|
||||
await tick(db, opts).catch(failed(db, log, "tick failed"));
|
||||
// Heartbeat and the check on the bot and the web (PEP-20).
|
||||
await monitorTick(db, { log }).catch((e) => log(`monitor failed: ${(e as Error).message}`));
|
||||
await monitorTick(db, { log }).catch(failed(db, log, "monitor failed"));
|
||||
// CI results lost on the way (PEP-57): poll commit statuses about once a minute.
|
||||
if (Date.now() - lastCiPoll >= 60_000) {
|
||||
lastCiPoll = Date.now();
|
||||
await pollChecks(db).catch((e) => log(`ci poll failed: ${(e as Error).message}`));
|
||||
await pollChecks(db).catch(failed(db, log, "ci poll failed"));
|
||||
// Reviews whose MCP process died before running them (PEP-26).
|
||||
await reviewTick(db, log).catch((e) => log(`review tick failed: ${(e as Error).message}`));
|
||||
await reviewTick(db, log).catch(failed(db, log, "review tick failed"));
|
||||
}
|
||||
// Daily copy of the SQLite database (PEP-36); a no-op until a day has passed.
|
||||
await backupDb(db, { log }).catch((e) => log(`backup failed: ${(e as Error).message}`));
|
||||
await backupDb(db, { log }).catch(failed(db, log, "backup failed"));
|
||||
await new Promise((r) => setTimeout(r, opts.intervalMs));
|
||||
}
|
||||
await service?.stop();
|
||||
|
||||
@ -69,6 +69,14 @@ export class MockBugsink {
|
||||
let body = "";
|
||||
req.on("data", (c) => (body += c));
|
||||
req.on("end", () => {
|
||||
const ingest = /^\/api\/(\d+)\/envelope\/$/.exec(req.url!.split("?")[0]!);
|
||||
if (req.method === "POST" && ingest) {
|
||||
void this.ingestEnvelope(Number(ingest[1]), String(req.headers["x-sentry-auth"] ?? ""), body).then((r) => {
|
||||
res.writeHead(r.status, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify(r.body));
|
||||
});
|
||||
return;
|
||||
}
|
||||
const r = this.handle(req.method!, req.url!, req.headers.authorization ?? "", body ? JSON.parse(body) : {});
|
||||
res.writeHead(r.status, { "Content-Type": "application/json" });
|
||||
res.end(JSON.stringify(r.body ?? {}));
|
||||
@ -157,6 +165,24 @@ export class MockBugsink {
|
||||
return issue.id;
|
||||
}
|
||||
|
||||
/** Envelopes taken by the ingest endpoint (PEP-91): the raw event as the SDK sent it. */
|
||||
readonly ingested: Array<{ projectId: number; event: Record<string, unknown> }> = [];
|
||||
|
||||
/** `POST /api/<id>/envelope/` like Bugsink's ingest: sentry_key must match the project's DSN. */
|
||||
async ingestEnvelope(projectId: number, auth: string, body: string): Promise<{ status: number; body: unknown }> {
|
||||
const p = this.projects.get(projectId);
|
||||
const key = /sentry_key=([^,\s]+)/.exec(auth)?.[1];
|
||||
if (!p || key !== p.key) return { status: 403, body: { error: "invalid sentry_key" } };
|
||||
const lines = body.split("\n").filter(Boolean);
|
||||
const item = lines.findIndex((l, n) => n > 0 && (JSON.parse(l) as { type?: string }).type === "event");
|
||||
if (item < 0 || !lines[item + 1]) return { status: 400, body: { error: "no event item" } };
|
||||
const event = JSON.parse(lines[item + 1]!) as Record<string, any>;
|
||||
this.ingested.push({ projectId, event });
|
||||
const ex = event.exception?.values?.[0] ?? { type: "Error", value: String(event.message ?? "") };
|
||||
await this.capture(projectId, { type: ex.type, value: ex.value, frames: ex.stacktrace?.frames, environment: event.environment, release: event.release, level: event.level });
|
||||
return { status: 200, body: { id: event.event_id } };
|
||||
}
|
||||
|
||||
private async alert(i: Issue, reason: string) {
|
||||
const p = this.projects.get(i.project)!;
|
||||
if (!p.webhook) return;
|
||||
|
||||
108
packages/testkit/test/platform-errors.test.ts
Normal file
108
packages/testkit/test/platform-errors.test.ts
Normal file
@ -0,0 +1,108 @@
|
||||
// PEP-91: Peppa's own errors → Bugsink (envelope protocol, no SDK): the platform project is
|
||||
// connected like any project; server errors go to <KEY>-api, browser errors to <KEY>-web,
|
||||
// the watchdog's failing parts too; throttled, never throwing, silent when not connected.
|
||||
import assert from "node:assert/strict";
|
||||
import { after, describe, test } from "node:test";
|
||||
// helpers must load first: it sets the isolated test env that runner modules read on load.
|
||||
import { core, db, project, runner, teardown, waitFor } from "./helpers.ts";
|
||||
import { MockBugsink } from "../src/mock-bugsink.ts";
|
||||
import { sql } from "drizzle-orm";
|
||||
|
||||
const { createBugsinkClient } = await import("@peppa/bugsink");
|
||||
|
||||
const bugsink = await new MockBugsink().start();
|
||||
const client = createBugsinkClient({ url: bugsink.url, token: bugsink.token, teamId: bugsink.teamId, publicUrl: bugsink.url });
|
||||
// Ingest goes to BUGSINK_URL (same host), not to the DSN's public host.
|
||||
process.env.BUGSINK_URL = bugsink.url;
|
||||
|
||||
after(async () => {
|
||||
await bugsink.stop();
|
||||
await teardown();
|
||||
});
|
||||
|
||||
describe("PEP-91: Peppa reports its own errors to Bugsink", () => {
|
||||
test("not connected → nothing is sent and nothing throws", async () => {
|
||||
process.env.PEPPA_PLATFORM_KEY = "NOPE";
|
||||
core.resetErrorReporting();
|
||||
assert.equal(await core.reportPlatformError(db, new Error("boom"), { service: "web" }), false);
|
||||
assert.equal(bugsink.ingested.length, 0);
|
||||
});
|
||||
|
||||
test("parseDsn and V8 stack → frames (outermost first)", () => {
|
||||
assert.deepEqual(core.parseDsn("https://abc123@bugsink.telecom.quest/4"), { key: "abc123", origin: "https://bugsink.telecom.quest", projectId: "4" });
|
||||
assert.equal(core.parseDsn("not a dsn"), null);
|
||||
const frames = core.stackFrames("Error: x\n at inner (/app/packages/core/src/users.ts:43:17)\n at async outer (/app/node_modules/next/x.js:1:2)\n at node:internal/process:3:4");
|
||||
assert.equal(frames.length, 3);
|
||||
assert.equal(frames.at(-1)!.function, "inner");
|
||||
assert.equal(frames.at(-1)!.in_app, true);
|
||||
assert.equal(frames[1]!.in_app, false);
|
||||
});
|
||||
|
||||
test("connected platform project: server error → <KEY>-api with release, service and request", async () => {
|
||||
const p = await project({ turns: [] });
|
||||
process.env.PEPPA_PLATFORM_KEY = p.key;
|
||||
core.resetErrorReporting();
|
||||
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 web = r.sources.find((s) => s.kind === "web")!.bugsinkProjectId;
|
||||
|
||||
const err = new Error('no such column: "google_sub"');
|
||||
const ok = await core.reportPlatformError(db, err, { service: "web", where: "GET /", request: { url: "/", method: "GET" }, release: "abc1234", environment: "live" });
|
||||
assert.equal(ok, true);
|
||||
const got = bugsink.ingested.at(-1)!;
|
||||
assert.equal(got.projectId, api);
|
||||
const ev = got.event as ReturnType<typeof core.errorEvent>;
|
||||
assert.equal(ev.release, "abc1234");
|
||||
assert.equal(ev.environment, "live");
|
||||
assert.equal(ev.tags.service, "web");
|
||||
assert.equal(ev.tags.where, "GET /");
|
||||
assert.equal(ev.request?.url, "/");
|
||||
assert.equal(ev.exception.values[0]!.value, 'no such column: "google_sub"');
|
||||
assert.ok(ev.exception.values[0]!.stacktrace!.frames.length > 0);
|
||||
// Bugsink grouped it into an issue — Peppa's own poll turns it into an incident of the project.
|
||||
const issues = await client.listIssues(api);
|
||||
assert.equal(issues.length, 1);
|
||||
assert.equal(await runner.pollBugsink(db, client), 1);
|
||||
const incidents = await core.listIncidents(db, (await core.getProject(db, p.key)).id);
|
||||
assert.equal(incidents.length, 1);
|
||||
|
||||
// Same error again within a minute: throttled, not sent.
|
||||
assert.equal(await core.reportPlatformError(db, err, { service: "web", where: "GET /", release: "abc1234" }), false);
|
||||
assert.equal(bugsink.ingested.filter((i) => i.projectId === api).length, 1);
|
||||
|
||||
// Browser errors go to <KEY>-web.
|
||||
assert.equal(await core.reportPlatformError(db, { name: "TypeError", message: "x is undefined", stack: "TypeError: x\n at f (https://peppa.test/_next/static/a.js:1:2)" }, { service: "browser", kind: "web", platform: "javascript" }), true);
|
||||
assert.equal(bugsink.ingested.at(-1)!.projectId, web);
|
||||
});
|
||||
|
||||
test("a failing watchdog part is reported (service=watchdog, where=<part>)", async () => {
|
||||
core.resetErrorReporting();
|
||||
const before = bugsink.ingested.length;
|
||||
// A part of the tick blows up: hide the incidents table for one tick.
|
||||
db.run(sql`ALTER TABLE incidents RENAME TO incidents_x`);
|
||||
try {
|
||||
await runner.tick(db, { intervalMs: 1000, stallMs: 60_000 });
|
||||
} finally {
|
||||
db.run(sql`ALTER TABLE incidents_x RENAME TO incidents`);
|
||||
}
|
||||
// Sent in the background: the tick doesn't wait for Bugsink.
|
||||
const tags = () => bugsink.ingested.slice(before).map((i) => (i.event as ReturnType<typeof core.errorEvent>).tags);
|
||||
await waitFor("watchdog error in Bugsink", async () => tags().some((t) => t.service === "watchdog" && t.where === "incidents"), 5000);
|
||||
});
|
||||
|
||||
test("Bugsink down → false within the timeout, no exception", async () => {
|
||||
core.resetErrorReporting();
|
||||
process.env.BUGSINK_URL = "http://127.0.0.1:9";
|
||||
const t0 = Date.now();
|
||||
assert.equal(await core.reportPlatformError(db, new Error("unreachable"), { service: "bot" }), false);
|
||||
assert.ok(Date.now() - t0 < 3500);
|
||||
process.env.BUGSINK_URL = bugsink.url;
|
||||
});
|
||||
|
||||
test("PEPPA_ERRORS=off switches it off", async () => {
|
||||
core.resetErrorReporting();
|
||||
process.env.PEPPA_ERRORS = "off";
|
||||
assert.equal(await core.reportPlatformError(db, new Error("quiet"), { service: "web" }), false);
|
||||
delete process.env.PEPPA_ERRORS;
|
||||
});
|
||||
});
|
||||
Loading…
Reference in New Issue
Block a user