peppa/packages/runner/src/incidents.ts

355 lines
18 KiB
TypeScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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.

// Incident flow (PEP-58): Bugsink webhook/poll → ingest → the project's incident policy
// (notify / backlog / start / ask / triage) → bug task, runner, Telegram. Also the PM's
// decisions, manual "fixed" and regressions. See openspec/changes/pep-58-bugsink/design.md.
import { asIs, m } from "@peppa/shared/i18n";
import { bugsinkFromEnv, issueFromEvent, parseWebhook, type BugsinkClient, type BugsinkIssueJson } from "@peppa/bugsink";
import {
addErrorSource,
autoIncidentTasksToday,
logEvent,
proposalRoom,
claimNewIncidents,
closeIncidentAsks,
createBugTask,
enableIncidents,
getIncident,
getIncidentSettings,
INCIDENT_STATUS_RU,
incidentSettingsBySecret,
ingestIssue,
listErrorSources,
PeppaError,
reportProgress,
resolveTask,
sendIncidentMessage,
updateIncident,
updateIncidentSettings,
updateTask,
type ErrorSource,
type Incident,
type IncidentSettings,
type Project,
type TaskRef,
platformFailure,
isProjectPaused,
} from "@peppa/core";
import { errorSources, incidents, projects, tasks, type Db } from "@peppa/db";
import { formatTaskKey } from "@peppa/shared";
import { and, eq, inArray, isNull } from "drizzle-orm";
import { moveTask } from "./flow.ts";
import { runTriage, TRIAGE_MIN_CONFIDENCE, type TriageResult } from "./triage.ts";
export interface IncidentOptions {
now?: Date;
/** Replaces the triage call (tests). */
triage?: (db: Db, project: Project, i: Incident, prompt: string) => Promise<TriageResult>;
log?: (msg: string) => void;
}
type Action = "notify" | "backlog" | "start" | "ignore" | "ask";
const ACTION_RU: Record<Action, string> = { notify: m("только уведомить"), backlog: m("в бэклог"), start: m("в работу"), ignore: m("игнорировать"), ask: m("спросить PM") };
// A closed bug task older than this gets a fresh task when its error comes back.
const REOPEN_WINDOW_MS = 14 * 24 * 3600_000;
async function projectOf(db: Db, id: number): Promise<Project> {
const [p] = await db.select().from(projects).where(eq(projects.id, id));
if (!p) throw new PeppaError(`Project #${id} not found`);
return p;
}
async function taskRefOf(db: Db, taskId: number): Promise<TaskRef | null> {
const [t] = await db.select({ key: projects.key, number: tasks.number }).from(tasks).innerJoin(projects, eq(tasks.projectId, projects.id)).where(eq(tasks.id, taskId));
return t ? resolveTask(db, formatTaskKey(t.key, t.number)) : null;
}
/** Applies the policy to every incident nobody has handled yet (both entry points call this). */
export async function processIncidents(db: Db, o: IncidentOptions = {}): Promise<number> {
const log = o.log ?? (() => {});
const claimed = await claimNewIncidents(db);
for (const i of claimed) {
try {
// PEP-174: on pause the error is recorded, but nobody is told and no agent is started.
if (await isProjectPaused(db, i.projectId)) {
await updateIncident(db, i.id, { status: "open" });
continue;
}
await applyIncidentPolicy(db, i, o);
} catch (e) {
log(`incident #${i.id}: ${(e as Error).message}`);
// Left pending: make sure the PM can still decide.
await sendIncidentMessage(db, i, { kind: "ask", note: m("Не удалось применить политику: {error}", { error: (e as Error).message }) }).catch(() => {});
}
}
return claimed.length;
}
export async function applyIncidentPolicy(db: Db, i: Incident, o: IncidentOptions = {}): Promise<Incident> {
const s = await getIncidentSettings(db, i.projectId);
if (!s) return updateIncident(db, i.id, { status: "open" });
// Unknown environment (no event details) counts as a watched one: better noisy than blind.
if (i.environment && !s.environments.includes(i.environment)) return updateIncident(db, i.id, { status: "open", decision: null, decidedBy: null });
if (s.ignorePattern && new RegExp(s.ignorePattern, "i").test(i.title)) {
return updateIncident(db, i.id, { status: "ignored", decision: "ignore", decidedBy: "policy", decisionReason: m("совпало с шаблоном игнора «{pattern}»", { pattern: s.ignorePattern }) });
}
if (s.policy !== "triage") return execute(db, i, s, s.policy, "policy", null, o);
const project = await projectOf(db, i.projectId);
const r = await (o.triage ?? runTriage)(db, project, i, s.triagePrompt ?? "");
if (!r.ok) return execute(db, i, s, "ask", "triage", null, o, m("Триажёр недоступен ({error}) — реши сам.", { error: r.error }));
const d = r.decision;
if (d.action === "ask" || d.confidence < TRIAGE_MIN_CONFIDENCE) {
return execute(db, i, s, "ask", "triage", d.reason, o, d.action !== "ask" ? m("Триажёр не уверен (склоняется: {action}): {reason}", { action: ACTION_RU[d.action], reason: asIs(d.reason) }) : m("Триажёр не уверен: {reason}", { reason: asIs(d.reason) }));
}
return execute(db, i, s, d.action, "triage", d.reason, o);
}
async function execute(
db: Db,
i: Incident,
s: IncidentSettings,
action: Action,
by: "policy" | "triage",
reason: string | null,
o: IncidentOptions,
note?: string,
): Promise<Incident> {
const base = { decision: action, decidedBy: by, decisionReason: reason } as const;
if (action === "ask") {
const row = await updateIncident(db, i.id, { ...base, status: "pending", decisionReason: note ?? reason });
await sendIncidentMessage(db, row, { kind: "ask", note });
return row;
}
if (action === "ignore") return updateIncident(db, i.id, { ...base, status: "ignored" });
if (action === "notify") {
const row = await updateIncident(db, i.id, { ...base, status: "open" });
await sendIncidentMessage(db, row, { kind: "notify" });
return row;
}
const today = await autoIncidentTasksToday(db, i.projectId, o.now);
if (today >= s.dailyLimit) {
const limitNote =
by === "triage"
? m("Суточный предел задач из ошибок ({n}) исчерпан — задача не создана; триажёр предлагал «{action}»: {reason}.", { n: s.dailyLimit, action: ACTION_RU[action], reason: asIs(reason) })
: m("Суточный предел задач из ошибок ({n}) исчерпан — задача не создана.", { n: s.dailyLimit });
const row = await updateIncident(db, i.id, { decision: "ask", decidedBy: by, status: "pending", decisionReason: limitNote });
await sendIncidentMessage(db, row, { kind: "ask", note: limitNote });
return row;
}
// PEP-295: the daily limit of stories not from a person is shared by every path.
if ((await proposalRoom(db, i.projectId, o.now)).room <= 0) {
const limitNote = m("Предел задач без вашего решения на сегодня исчерпан — задача не создана.");
await logEvent(db, { projectId: i.projectId, type: "proposal_limited", payload: { title: i.title, via: "incident", incident: i.id } });
const row = await updateIncident(db, i.id, { decision: "ask", decidedBy: by, status: "pending", decisionReason: limitNote });
await sendIncidentMessage(db, row, { kind: "ask", note: limitNote });
return row;
}
const ref = await createBugTask(db, i, by, by === "triage" ? reason : null, { decision: base.decision, decisionReason: base.decisionReason });
// PEP-295: a story waiting for «Делать» is never started by the policy.
const proposed = ref.task.proposed;
const started = action === "start" && !proposed ? await startBugTask(db, ref, o) : false;
const row = await getIncident(db, i.id);
await sendIncidentMessage(db, row, { kind: "task", task: ref, started, proposed, reason: by === "triage" ? reason : null });
return row;
}
async function startBugTask(db: Db, ref: TaskRef, o: IncidentOptions): Promise<boolean> {
try {
await moveTask(db, ref, "in_progress");
return true;
} catch (e) {
(o.log ?? (() => {}))(`incident task ${ref.key}: runner not started: ${(e as Error).message}`);
// PEP-154: the text of an exception is for the superadmins and the error tracker, not for the story thread.
const why = await platformFailure(db, e, { service: "runner", where: `incident start ${ref.key}`, log: o.log });
if (why) await reportProgress(db, ref, m("Агент не запустился: {error}", { error: why })).catch(() => {});
return false;
}
}
/** The PM's decision (Telegram button, web, MCP). Not limited by the daily cap. */
export async function decideIncident(db: Db, incidentId: number, action: "backlog" | "start" | "ignore", who: string, o: IncidentOptions = {}): Promise<{ incident: Incident; task: TaskRef | null }> {
const i = await getIncident(db, incidentId);
const already = async () => {
const ref = i.taskId ? await taskRefOf(db, i.taskId) : null;
return new PeppaError(ref ? m("Уже решено: задача {key}", { key: ref.key }) : m("Уже решено: {status}", { status: INCIDENT_STATUS_RU[i.status] }));
};
const open: Incident["status"][] = action === "ignore" ? ["new", "open", "pending", "regressed"] : ["new", "open", "pending", "regressed", "ignored"];
if (i.taskId || !open.includes(i.status)) throw await already();
// Claim it: two people pressing at once get one decision.
const [claimed] = await db
.update(incidents)
.set({ status: action === "ignore" ? "ignored" : "task", decision: action, decidedBy: "pm", decisionReason: m("решение {who}", { who }) })
.where(and(eq(incidents.id, i.id), inArray(incidents.status, open), isNull(incidents.taskId)))
.returning();
if (!claimed) throw new PeppaError(m("Уже решено"));
let task: TaskRef | null = null;
let text = m("Решено ({who}): игнорировать", { who });
if (action !== "ignore") {
task = await createBugTask(db, claimed, "pm");
const started = action === "start" ? await startBugTask(db, task, o) : false;
text = started ? m("Решено ({who}): в работу → {key}", { who, key: task.key }) : m("Решено ({who}): в бэклог → {key}", { who, key: task.key });
}
await closeIncidentAsks(db, i.id, text);
return { incident: await getIncident(db, i.id), task };
}
/** "Fixed" until releases close incidents automatically (PEP-57). */
export async function resolveIncident(db: Db, incidentId: number, o: { who: string; release?: string | null; client?: BugsinkClient | null }): Promise<{ incident: Incident; bugsinkResolved: boolean }> {
const i = await getIncident(db, incidentId);
if (i.status === "resolved") throw new PeppaError(m("Уже отмечено исправленным"));
let bugsinkResolved = false;
const client = o.client === undefined ? bugsinkFromEnv() : o.client;
if (client) {
try {
await client.resolveIssue(i.bugsinkIssueId);
bugsinkResolved = true;
} catch {}
}
const row = await updateIncident(db, i.id, { status: "resolved", resolvedAt: new Date(), resolvedRelease: o.release ?? null });
await closeIncidentAsks(db, i.id, m("Исправлено ({who})", { who: o.who }));
if (i.taskId) {
const ref = await taskRefOf(db, i.taskId);
if (ref) {
await reportProgress(
db,
ref,
(o.release
? bugsinkResolved
? m("Баг #{id} отмечен исправленным вручную ({who}) в версии {release}.", { id: i.id, who: o.who, release: o.release })
: m("Баг #{id} отмечен исправленным вручную ({who}) в версии {release}. Отметить его в учёте ошибок не удалось — он может прийти снова.", { id: i.id, who: o.who, release: o.release })
: bugsinkResolved
? m("Баг #{id} отмечен исправленным вручную ({who}).", { id: i.id, who: o.who })
: m("Баг #{id} отмечен исправленным вручную ({who}). Отметить его в учёте ошибок не удалось — он может прийти снова.", { id: i.id, who: o.who })),
);
}
}
return { incident: row, bugsinkResolved };
}
/** A resolved error came back: incident "regressed", its task back to the backlog. */
export async function handleRegression(db: Db, i: Incident, o: IncidentOptions = {}): Promise<TaskRef | null> {
let ref = i.taskId ? await taskRefOf(db, i.taskId) : null;
const stamp = `${(o.now ?? new Date()).toISOString().slice(0, 16).replace("T", " ")} UTC`;
if (ref && ref.task.status === "done" && (o.now ?? new Date()).getTime() - ref.task.updatedAt.getTime() > REOPEN_WINDOW_MS) {
// PEP-295: a new story is a proposal and spends the shared daily limit; without room the people decide.
if ((await proposalRoom(db, i.projectId, o.now)).room <= 0) {
await logEvent(db, { projectId: i.projectId, type: "proposal_limited", payload: { title: i.title, via: "incident", incident: i.id } });
ref = null;
await updateIncident(db, i.id, { status: "regressed", taskId: null });
} else {
ref = await createBugTask(db, i, "policy", null);
await updateIncident(db, i.id, { status: "regressed" });
}
} else if (ref) {
await moveTask(db, ref, "backlog");
ref = await resolveTask(db, ref.key);
await updateTask(db, ref, { description: `${ref.task.description ?? ""}\n\n⚠️ Ошибка вернулась ${stamp}${i.lastRelease ? ` в релизе ${i.lastRelease}` : ""} (повтор №${i.regressions}).` });
ref = await resolveTask(db, ref.key);
}
await sendIncidentMessage(db, await getIncident(db, i.id), { kind: "regressed", task: ref });
return ref;
}
export interface WebhookResult {
status: 200 | 404;
body: Record<string, unknown>;
}
/**
* POST /api/hooks/bugsink/<secret>: records the issue (enriched with its latest event from
* the API when available). The policy runs afterwards via processIncidents.
*/
export async function receiveBugsinkWebhook(db: Db, secret: string, body: unknown, client: BugsinkClient | null, o: IncidentOptions = {}): Promise<WebhookResult> {
const s = await incidentSettingsBySecret(db, secret);
if (!s) return { status: 404, body: { error: "not found" } };
const issue = parseWebhook(body);
if (!issue) return { status: 200, body: { ok: true, ignored: true } };
const [src] = await db.select().from(errorSources).where(eq(errorSources.bugsinkProjectId, Number(issue.project)));
if (!src || src.projectId !== s.projectId) return { status: 404, body: { error: "not found" } };
const reason = issue.alert_reason === "REGRESSED" || issue.alert_reason === "UNMUTED" ? issue.alert_reason : "NEW";
const event = client ? await client.latestEvent(issue.id).catch(() => null) : null;
const r = await ingestIssue(db, issueFromEvent(issue, event, reason));
if (!r) return { status: 404, body: { error: "not found" } };
if (r.regressed) await handleRegression(db, r.incident, o);
return { status: 200, body: { ok: true, incident: r.incident.id } };
}
/** Fallback entry point: the most recently seen issues of every connected Bugsink project. */
export async function pollBugsink(db: Db, client: BugsinkClient, o: IncidentOptions = {}): Promise<number> {
const log = o.log ?? (() => {});
let changed = 0;
for (const src of await listErrorSources(db)) {
let issues: BugsinkIssueJson[];
try {
issues = await client.listIssues(src.bugsinkProjectId);
} catch (e) {
log(`bugsink poll ${src.bugsinkProjectId}: ${(e as Error).message}`);
continue;
}
for (const j of issues) {
const [old] = await db.select().from(incidents).where(eq(incidents.bugsinkIssueId, j.id));
const seen = new Date(j.last_seen).getTime();
const cameBack = old?.status === "resolved" && !j.is_resolved && old.resolvedAt != null && seen > old.resolvedAt.getTime();
if (old && seen <= old.lastSeen.getTime() && !cameBack) continue;
const event = !old || !old.stack || cameBack ? await client.latestEvent(j.id).catch(() => null) : null;
const r = await ingestIssue(db, issueFromEvent({ ...j, url: j.url ?? client.issueUrl(j.id) }, event, "POLL"));
if (!r) continue;
changed++;
if (r.regressed) await handleRegression(db, r.incident, o);
}
}
return changed;
}
export interface ConnectResult {
settings: IncidentSettings;
sources: ErrorSource[];
webhookUrl: string;
}
/** «Подключить отслеживание ошибок»: Bugsink projects for web and api, webhook, goal, policy. */
export async function connectErrorTracking(db: Db, project: Project, client: BugsinkClient | null, webhookBase: string): Promise<ConnectResult> {
if (!client) throw new PeppaError(m("Отслеживание ошибок ещё не подключено к FORGE. Напишите администратору."));
let settings = await enableIncidents(db, project.id);
const have = await listErrorSources(db, project.id);
const webhookUrl = `${webhookBase.replace(/\/$/, "")}/api/hooks/bugsink/${settings.hookSecret}`;
let auto = true;
for (const kind of ["web", "api"] as const) {
let src = have.find((s) => s.kind === kind);
if (!src) {
const p = await client.createProject(`${project.key}-${kind}`);
src = await addErrorSource(db, { projectId: project.id, kind, bugsinkProjectId: p.id, dsn: p.dsn });
}
try {
await client.setAlertWebhook(src.bugsinkProjectId, webhookUrl);
} catch {
auto = false;
}
}
if (settings.webhookAuto !== auto) settings = await updateIncidentSettings(db, project.id, { webhookAuto: auto });
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";
}
let lastPoll = 0;
const POLL_MS = 2 * 60_000;
/** Watchdog part: poll Bugsink every 2 minutes, apply policies to anything new. */
export async function incidentTick(db: Db, o: IncidentOptions = {}): Promise<void> {
const now = (o.now ?? new Date()).getTime();
const client = bugsinkFromEnv();
if (client && now - lastPoll >= POLL_MS) {
lastPoll = now;
await pollBugsink(db, client, o);
}
await processIncidents(db, o);
}