peppa/packages/core/src/incidents.ts
Асель 3a282b8054 PEP-36 stage 2: SQLite (node:sqlite, WAL) instead of Postgres
- packages/db: schema on sqlite-core (timestamps as epoch ms → Date, JSON as text,
  booleans 0/1), one baseline migration; node:sqlite client under drizzle's
  better-sqlite3 session (busy_timeout first, WAL, BEGIN IMMEDIATE, retries on
  SQLITE_BUSY, lazy open, async transaction callbacks refused); PEPPA_DB
  (default ~/.peppa/peppa.db)
- live updates: notify() pokes the bot over a unix socket; the bot also watches
  PRAGMA data_version every second (writes by other processes)
- Postgres specifics ported: createTask transaction is synchronous, no
  `for update skip locked`, `count(*)`, json_extract instead of ->>, json_each
  instead of @>
- `peppa db migrate` and `peppa db migrate-to-sqlite <file>` (read-only
  snapshot of Postgres, FK order from the schema, row count + foreign key
  checks, file appears only when they pass); old Postgres schema kept in
  packages/cli/legacy-pg-migrations for the migration and its test
- daily VACUUM INTO backup from the watchdog (7 copies, admin alert on failure)
- tests: a temp SQLite file per test file; storage.test.ts (20 processes,
  per-project numbering across processes, socket/data_version, migration from
  Postgres incl. a dangling foreign key, backups); two test races fixed
- CI: no per-run Postgres database; PEPPA_TEST_PG only for the migration test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 17:23:24 +05:00

363 lines
17 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Incidents (PEP-58): Bugsink issues seen in Peppa, the project's incident policy settings,
// bug tasks made from incidents and their Telegram messages. The policy itself (which may
// start a runner) is applied in runner/incidents.ts.
import { randomBytes } from "node:crypto";
import type { BugsinkIssue } from "@peppa/bugsink";
import { errorSources, incidentPolicies, incidents, incidentSettings, incidentStatuses, projects, telegramOutbox, type Db, type IncidentPolicy } from "@peppa/db";
import { loadEnv } from "@peppa/shared";
import { and, asc, desc, eq, gte, inArray, isNotNull, isNull, like, sql } from "drizzle-orm";
import { PeppaError } from "./errors.ts";
import { notify } from "./notify.ts";
import { createGoal, listGoals, type Project } from "./projects.ts";
import { createTask, type TaskRef } from "./tasks.ts";
import { enqueueTelegram, questionRecipients } from "./telegram.ts";
export type Incident = typeof incidents.$inferSelect;
export type IncidentStatus = Incident["status"];
export type IncidentSettings = typeof incidentSettings.$inferSelect;
export type ErrorSource = typeof errorSources.$inferSelect;
export type IncidentAction = "notify" | "backlog" | "start" | "ignore";
export { incidentPolicies, incidentStatuses, type IncidentPolicy };
export const INCIDENT_STATUS_RU: Record<IncidentStatus, string> = {
new: "новая",
open: "без задачи",
pending: "ждёт разбора",
task: "задача",
ignored: "игнорируется",
resolved: "исправлена",
regressed: "вернулась",
};
export const POLICY_RU: Record<IncidentPolicy, string> = {
notify: "только уведомить",
backlog: "задача в бэклог",
start: "задача сразу в работу",
ask: "спросить в Telegram",
triage: "решает агент-триажёр",
};
export const STABILITY_GOAL = "Стабильность";
// ── settings ─────────────────────────────────────────────────────────────────────
export async function getIncidentSettings(db: Db, projectId: number): Promise<IncidentSettings | null> {
const [row] = await db.select().from(incidentSettings).where(eq(incidentSettings.projectId, projectId));
return row ?? null;
}
export async function incidentSettingsBySecret(db: Db, secret: string): Promise<IncidentSettings | null> {
if (!secret || secret.length < 16) return null;
const [row] = await db.select().from(incidentSettings).where(eq(incidentSettings.hookSecret, secret));
return row ?? null;
}
/** Turns error tracking on: webhook secret, default policy and the «Стабильность» goal. */
export async function enableIncidents(db: Db, projectId: number, o: { webhookAuto?: boolean } = {}): Promise<IncidentSettings> {
const existing = await getIncidentSettings(db, projectId);
if (existing) return existing;
const goal = (await listGoals(db, projectId)).find((g) => g.title === STABILITY_GOAL) ?? (await createGoal(db, projectId, STABILITY_GOAL, "Ошибки из работающего продукта (Bugsink): задачи-баги создаются здесь."));
const [row] = await db
.insert(incidentSettings)
.values({ projectId, hookSecret: randomBytes(24).toString("base64url"), goalId: goal.id, webhookAuto: o.webhookAuto ?? false })
.returning();
return row!;
}
export interface IncidentSettingsPatch {
policy?: IncidentPolicy;
triagePrompt?: string | null;
environments?: string[];
dailyLimit?: number;
ignorePattern?: string | null;
webhookAuto?: boolean;
}
export async function updateIncidentSettings(db: Db, projectId: number, patch: IncidentSettingsPatch): Promise<IncidentSettings> {
if (!(await getIncidentSettings(db, projectId))) throw new PeppaError("Отслеживание ошибок в проекте не подключено");
if (patch.policy && !incidentPolicies.includes(patch.policy)) throw new PeppaError(`Неизвестная политика «${patch.policy}»: ${incidentPolicies.join(", ")}`);
if (patch.ignorePattern) {
try {
new RegExp(patch.ignorePattern, "i");
} catch {
throw new PeppaError("Шаблон игнора — неверное регулярное выражение");
}
}
if (patch.dailyLimit != null && (!Number.isInteger(patch.dailyLimit) || patch.dailyLimit < 0)) throw new PeppaError("Предел в сутки — целое число ≥ 0");
if (patch.environments) patch.environments = [...new Set(patch.environments.map((e) => e.trim()).filter(Boolean))];
const [row] = await db.update(incidentSettings).set(patch).where(eq(incidentSettings.projectId, projectId)).returning();
return row!;
}
export async function addErrorSource(db: Db, s: { projectId: number; kind: ErrorSource["kind"]; bugsinkProjectId: number; dsn: string }): Promise<ErrorSource> {
const [row] = await db
.insert(errorSources)
.values(s)
.onConflictDoUpdate({ target: [errorSources.projectId, errorSources.kind], set: { bugsinkProjectId: s.bugsinkProjectId, dsn: s.dsn } })
.returning();
return row!;
}
export async function listErrorSources(db: Db, projectId?: number): Promise<ErrorSource[]> {
return db
.select()
.from(errorSources)
.where(projectId != null ? eq(errorSources.projectId, projectId) : undefined)
.orderBy(asc(errorSources.projectId), asc(errorSources.kind));
}
// ── incidents ────────────────────────────────────────────────────────────────────
export interface IngestResult {
incident: Incident;
created: boolean;
/** A resolved incident came back. */
regressed: boolean;
}
/**
* Records a Bugsink issue (webhook or poll). Idempotent per issue: a repeat updates the
* counters of the same incident. Null when the issue's Bugsink project isn't connected.
*/
export async function ingestIssue(db: Db, i: BugsinkIssue): Promise<IngestResult | null> {
const [src] = await db.select().from(errorSources).where(eq(errorSources.bugsinkProjectId, i.bugsinkProjectId));
if (!src) return null;
const [old] = await db.select().from(incidents).where(eq(incidents.bugsinkIssueId, i.issueId));
if (!old) {
const [row] = await db
.insert(incidents)
.values({
projectId: src.projectId,
source: src.kind,
bugsinkIssueId: i.issueId,
friendlyId: i.friendlyId,
title: i.title,
culprit: i.culprit,
level: i.level,
environment: i.environment,
firstRelease: i.release,
lastRelease: i.release,
events: Math.max(1, i.events),
firstSeen: i.firstSeen,
lastSeen: i.lastSeen,
url: i.url,
stack: i.stack,
})
.onConflictDoNothing()
.returning();
// Lost a race with the other entry point: treat it as a repeat.
if (row) {
await notify(db, { type: "incident", incidentId: row.id });
return { incident: row, created: true, regressed: false };
}
return ingestIssue(db, i);
}
const newer = i.lastSeen.getTime() > old.lastSeen.getTime();
const regressed =
old.status === "resolved" &&
(i.reason === "REGRESSED" || (!i.isResolved && old.resolvedAt != null && i.lastSeen.getTime() > old.resolvedAt.getTime()));
const [row] = await db
.update(incidents)
.set({
events: Math.max(old.events, i.events),
lastSeen: newer ? i.lastSeen : old.lastSeen,
lastRelease: newer && i.release ? i.release : old.lastRelease,
culprit: old.culprit ?? i.culprit,
stack: old.stack ?? i.stack,
environment: old.environment ?? i.environment,
level: old.level ?? i.level,
url: old.url ?? i.url,
...(regressed ? { status: "regressed" as const, regressions: old.regressions + 1 } : {}),
})
.where(eq(incidents.id, old.id))
.returning();
if (newer || regressed) await notify(db, { type: "incident", incidentId: old.id });
return { incident: row!, created: false, regressed };
}
export async function getIncident(db: Db, id: number): Promise<Incident> {
const [row] = await db.select().from(incidents).where(eq(incidents.id, id));
if (!row) throw new PeppaError(`Инцидент #${id} не найден`);
return row;
}
export async function incidentForTask(db: Db, taskId: number): Promise<Incident | null> {
const [row] = await db.select().from(incidents).where(eq(incidents.taskId, taskId)).orderBy(desc(incidents.id)).limit(1);
return row ?? null;
}
export async function listIncidents(db: Db, projectId: number, statuses?: IncidentStatus[]): Promise<Incident[]> {
return db
.select()
.from(incidents)
.where(and(eq(incidents.projectId, projectId), statuses?.length ? inArray(incidents.status, statuses) : undefined))
.orderBy(desc(incidents.lastSeen))
.limit(200);
}
export async function updateIncident(db: Db, id: number, patch: Partial<Omit<Incident, "id" | "projectId" | "bugsinkIssueId">>): Promise<Incident> {
const [row] = await db.update(incidents).set(patch).where(eq(incidents.id, id)).returning();
if (!row) throw new PeppaError(`Инцидент #${id} не найден`);
await notify(db, { type: "incident", incidentId: id });
return row;
}
/** Takes incidents nobody has applied the policy to yet; each one is returned once (one statement: SQLite runs writers one at a time). */
export async function claimNewIncidents(db: Db, limit = 20): Promise<Incident[]> {
return db
.update(incidents)
.set({ status: "pending" })
.where(inArray(incidents.id, sql`(select id from ${incidents} where ${incidents.status} = 'new' order by id limit ${limit})`))
.returning();
}
/** Bug tasks created automatically (policy / triage) since local midnight. */
export async function autoIncidentTasksToday(db: Db, projectId: number, now = new Date()): Promise<number> {
const midnight = new Date(now);
midnight.setHours(0, 0, 0, 0);
const [r] = await db
.select({ n: sql<number>`count(*)` })
.from(incidents)
.where(and(eq(incidents.projectId, projectId), gte(incidents.taskCreatedAt, midnight), inArray(incidents.decidedBy, ["policy", "triage"])));
return r?.n ?? 0;
}
// ── bug tasks ────────────────────────────────────────────────────────────────────
const clip = (s: string, n: number) => (s.length > n ? `${s.slice(0, n - 1)}…` : s);
export function bugTaskTitle(i: Pick<Incident, "title" | "culprit">): string {
return clip(`Ошибка: ${i.title}${i.culprit ? ` (${i.culprit})` : ""}`, 200);
}
export function bugTaskDescription(i: Incident, reason?: string | null): string {
const fmt = (d: Date) => d.toISOString().slice(0, 16).replace("T", " ");
const lines = [
`Ошибка из работающего продукта (Bugsink, инцидент #${i.id}).`,
"",
`- Ошибка: ${i.title}`,
`- Место: ${i.culprit ?? "—"}`,
`- Источник: ${i.source === "web" ? "фронт (web)" : "бэк (api)"}, окружение: ${i.environment ?? "—"}`,
`- Релиз: ${i.lastRelease ?? "—"}${i.firstRelease && i.firstRelease !== i.lastRelease ? ` (впервые в ${i.firstRelease})` : ""}`,
`- Событий: ${i.events}, впервые ${fmt(i.firstSeen)}, последний раз ${fmt(i.lastSeen)} UTC`,
];
if (i.url) lines.push(`- Bugsink: ${i.url}`);
if (reason) lines.push("", `Решение триажёра: ${reason}`);
lines.push("", "Верх стека:", "", "```", i.stack ?? "(стек недоступен — смотри Bugsink)", "```");
lines.push(
"",
"Условия готовности:",
"- воспроизводящий тест (падает на текущем коде с этой ошибкой);",
"- исправление, тест зелёный;",
"- ошибка не повторяется в новом релизе.",
"",
"Подробности ошибки: MCP get_incident.",
);
return lines.join("\n");
}
/** Creates the bug task under «Стабильность» and links it to the incident. */
export async function createBugTask(db: Db, i: Incident, by: NonNullable<Incident["decidedBy"]>, reason?: string | null): Promise<TaskRef> {
const settings = await getIncidentSettings(db, i.projectId);
const ref = await createTask(db, {
projectId: i.projectId,
goalId: settings?.goalId ?? undefined,
title: bugTaskTitle(i),
description: bugTaskDescription(i, reason),
});
await updateIncident(db, i.id, { taskId: ref.task.id, taskCreatedAt: new Date(), status: "task", decidedBy: by });
return ref;
}
// ── Telegram ─────────────────────────────────────────────────────────────────────
const esc = (s: string) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
export type IncidentMessage =
| { kind: "notify" }
| { kind: "task"; task: TaskRef; started?: boolean; reason?: string | null }
| { kind: "ask"; note?: string | null }
| { kind: "regressed"; task?: TaskRef | null };
/** Callback data of the decision buttons: "i:<incidentId>:<backlog|start|ignore>". */
export function incidentButtons(id: number) {
return [
[
{ text: "📥 В бэклог", callback_data: `i:${id}:backlog` },
{ text: "▶️ В работу", callback_data: `i:${id}:start` },
],
[{ text: "🙈 Игнорировать", callback_data: `i:${id}:ignore` }],
];
}
export function renderIncidentMessage(project: Pick<Project, "key" | "name">, i: Incident, m: IncidentMessage, webUrl: string): string {
const head = m.kind === "regressed" ? "🔁 Ошибка вернулась" : "🐞 Новая ошибка";
const lines = [
`<b>${esc(project.key)}</b> · ${head} (${i.source}, ${esc(i.environment ?? "—")})`,
`<b>${esc(clip(i.title, 300))}</b>`,
[i.culprit && `📍 ${esc(i.culprit)}`, i.lastRelease && `релиз ${esc(i.lastRelease)}`, `событий: ${i.events}`].filter(Boolean).join(" · "),
];
if (i.url) lines.push(`<a href="${esc(i.url)}">Открыть в Bugsink</a>`);
const taskLink = (t: TaskRef) => `<a href="${esc(`${webUrl}/t/${t.key}`)}">${esc(t.key)}</a>`;
if (m.kind === "task") {
lines.push("", m.started ? `▶️ Агент взялся: ${taskLink(m.task)}` : `📥 Задача в бэклоге: ${taskLink(m.task)}`);
if (m.reason) lines.push(`🤖 Триажёр: ${esc(clip(m.reason, 500))}`);
} else if (m.kind === "ask") {
if (m.note) lines.push("", `<i>${esc(clip(m.note, 500))}</i>`);
lines.push("", "Что делаем?");
} else if (m.kind === "regressed") {
lines.push("", m.task ? `Задача ${taskLink(m.task)} снова в бэклоге.` : "Задачи нет — реши, что делать.");
} else {
lines.push("", `<a href="${esc(`${webUrl}/p/${project.key}`)}">Ошибки проекта</a>`);
}
return lines.join("\n");
}
/** Sends an incident message to everyone who gets the project's questions in Telegram. */
export async function sendIncidentMessage(db: Db, i: Incident, m: IncidentMessage): Promise<number> {
const recipients = await questionRecipients(db, i.projectId);
if (!recipients.length) return 0;
const [project] = await db.select().from(projects).where(eq(projects.id, i.projectId));
if (!project) return 0;
const text = renderIncidentMessage(project, i, m, loadEnv().PEPPA_WEB_URL);
const markup = m.kind === "ask" || (m.kind === "regressed" && !m.task) ? { inline_keyboard: incidentButtons(i.id) } : undefined;
const kind = m.kind === "ask" || markup ? "ask" : m.kind;
for (const u of recipients) {
await enqueueTelegram(db, {
dedupeKey: `inc:${i.id}:${kind}:r${i.regressions}:${u.telegramChatId}`,
method: "sendMessage",
params: { chat_id: u.telegramChatId, text, parse_mode: "HTML", link_preview_options: { is_disabled: true }, ...(markup ? { reply_markup: markup } : {}) },
});
}
await notify(db, { type: "incident", incidentId: i.id });
return recipients.length;
}
/** Closes delivered decision messages: original text + the decision, buttons removed. */
export async function closeIncidentAsks(db: Db, incidentId: number, decision: string): Promise<void> {
const sent = await db
.select()
.from(telegramOutbox)
.where(and(like(telegramOutbox.dedupeKey, `inc:${incidentId}:ask:%`), eq(telegramOutbox.status, "sent"), isNotNull(telegramOutbox.telegramMessageId)));
for (const row of sent) {
await enqueueTelegram(db, {
dedupeKey: `${row.dedupeKey}:done`,
method: "editMessageText",
params: {
chat_id: row.params.chat_id,
message_id: row.telegramMessageId,
text: `${String(row.params.text).replace(/\n\nЧто делаем\?$/, "")}\n\n✅ ${esc(decision)}`,
parse_mode: "HTML",
link_preview_options: { is_disabled: true },
reply_markup: { inline_keyboard: [] },
},
});
}
// Not delivered yet: no point in asking any more.
await db
.update(telegramOutbox)
.set({ status: "sent", error: "decided before delivery" })
.where(and(like(telegramOutbox.dedupeKey, `inc:${incidentId}:ask:%`), eq(telegramOutbox.status, "pending"), eq(telegramOutbox.method, "sendMessage"), isNull(telegramOutbox.telegramMessageId)));
await notify(db, { type: "incident", incidentId });
}