peppa/packages/testkit/src/mock-bugsink.ts
Асель 498013472f PEP-58: Bugsink — production errors become Peppa incidents and tasks
- infra: Bugsink 2.6.3 in docker (infra/bugsink, scripts/bugsink-up.sh), database
  bugsink in Peppa's Postgres, Traefik route bugsink.telecom.quest
- packages/bugsink: REST API client + custom-webhook payload parsing
- incidents (migration 0011): incident_settings, error_sources, incidents; ingest from
  webhook POST /api/hooks/bugsink/<secret> and a 2-minute poll in the watchdog
- incident policy per project: notify / backlog (default) / start / ask (Telegram
  buttons) / triage (claude -p with the owner's token, falls back to ask)
- daily task cap, environments, ignore pattern; manual "fixed" until PEP-57;
  REGRESSED returns the task to the backlog
- web «Ошибки» section, bot buttons, MCP tools for agents and the PM, help, RULES.md
- testkit: mock-bugsink, mock-triage, incidents.test.ts (one test per scenario,
  plus a live run against the real Bugsink with PEPPA_LIVE_BUGSINK=1)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 14:31:32 +05:00

214 lines
8.5 KiB
TypeScript

// Mock Bugsink (PEP-58) for tests: the subset of /api/canonical/0/ Peppa uses (projects,
// issues, events, resolve) with the same JSON shapes as Bugsink 2.6, Bearer auth, and
// outgoing custom-webhook alerts (NEW / REGRESSED) like Bugsink's `custom` backend.
import { randomUUID } from "node:crypto";
import { createServer, type Server } from "node:http";
import type { AddressInfo } from "node:net";
export interface MockFrame {
filename: string;
function: string;
lineno: number;
in_app?: boolean;
}
export interface MockErrorEvent {
type: string;
value: string;
/** Outermost first, as Sentry SDKs send them. */
frames?: MockFrame[];
environment?: string;
release?: string;
level?: string;
}
interface Project {
id: number;
name: string;
team: string;
key: string;
webhook?: string;
}
interface Issue {
id: string;
friendlyNo: number;
project: number;
type: string;
value: string;
culprit: string;
firstSeen: string;
lastSeen: string;
count: number;
resolved: boolean;
releases: string[];
events: string[];
}
interface Event {
id: string;
issue: string;
timestamp: string;
data: Record<string, unknown>;
}
export class MockBugsink {
readonly token = "mock-bugsink-token";
readonly teamId = randomUUID();
readonly projects = new Map<number, Project>();
readonly issues = new Map<string, Issue>();
readonly events = new Map<string, Event>();
/** Alerts the mock tried to send: url, body, HTTP status (or error). */
readonly alerts: Array<{ url: string; body: Record<string, unknown>; status: number | string }> = [];
private seq = 1;
private server: Server | null = null;
url = "";
async start(): Promise<this> {
this.server = createServer((req, res) => {
let body = "";
req.on("data", (c) => (body += c));
req.on("end", () => {
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 ?? {}));
});
});
await new Promise<void>((r) => this.server!.listen(0, "127.0.0.1", r));
this.url = `http://127.0.0.1:${(this.server.address() as AddressInfo).port}`;
return this;
}
async stop() {
await new Promise<void>((r) => (this.server ? this.server.close(() => r()) : r()));
}
/** What Bugsink's UI/ORM does for alerts (there is no API for it). */
setWebhook(projectId: number, url: string | undefined) {
this.projects.get(projectId)!.webhook = url;
}
dsn(p: Project) {
return `https://${p.key}@bugsink.mock/${p.id}`;
}
issueJson(i: Issue) {
const p = this.projects.get(i.project)!;
return {
id: i.id,
friendly_id: `${p.name.toUpperCase()}-${i.friendlyNo}`,
project: i.project,
digest_order: i.friendlyNo,
last_seen: i.lastSeen,
first_seen: i.firstSeen,
digested_event_count: i.count,
stored_event_count: i.count,
calculated_type: i.type,
calculated_value: i.value,
transaction: "",
is_resolved: i.resolved,
is_resolved_unconditionally: false,
is_resolved_by_next_release: false,
fixed_at: [],
events_at: i.releases,
is_muted: false,
unmute_after: null,
unmute_on_volume_based_conditions: [],
};
}
/**
* An SDK sends an error event: groups it into an issue (type + value + culprit) and, for a
* new or regressed issue, posts the alert to the project's webhook. Resolves with the issue id.
*/
async capture(projectId: number, e: MockErrorEvent, at = new Date()): Promise<string> {
const frames = e.frames ?? [{ filename: "app.js", function: "main", lineno: 1, in_app: true }];
const inner = [...frames].reverse().find((f) => f.in_app !== false) ?? frames.at(-1)!;
const culprit = inner.filename;
let issue = [...this.issues.values()].find((i) => i.project === projectId && i.type === e.type && i.value === e.value && i.culprit === culprit);
let reason: "NEW" | "REGRESSED" | null = null;
const ts = at.toISOString();
if (!issue) {
issue = { id: randomUUID(), friendlyNo: this.seq++, project: projectId, type: e.type, value: e.value, culprit, firstSeen: ts, lastSeen: ts, count: 0, resolved: false, releases: [], events: [] };
this.issues.set(issue.id, issue);
reason = "NEW";
} else if (issue.resolved) {
issue.resolved = false;
reason = "REGRESSED";
}
issue.count++;
issue.lastSeen = ts;
if (e.release && !issue.releases.includes(e.release)) issue.releases.push(e.release);
const ev: Event = {
id: randomUUID(),
issue: issue.id,
timestamp: ts,
data: {
level: e.level ?? "error",
environment: e.environment,
release: e.release,
platform: "javascript",
exception: { values: [{ type: e.type, value: e.value, stacktrace: { frames: frames.map((f) => ({ ...f, in_app: f.in_app ?? true, vars: { secret: "mock-local-value" } })) } }] },
},
};
this.events.set(ev.id, ev);
issue.events.push(ev.id);
if (reason) await this.alert(issue, reason);
return issue.id;
}
private async alert(i: Issue, reason: string) {
const p = this.projects.get(i.project)!;
if (!p.webhook) return;
const body = { ...this.issueJson(i), title: `${i.type}: ${i.value}`, project_name: p.name, url: `${this.url}/issues/issue/${i.id}/event/last/`, alert_reason: reason };
try {
const res = await fetch(p.webhook, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) });
this.alerts.push({ url: p.webhook, body, status: res.status });
} catch (e) {
this.alerts.push({ url: p.webhook, body, status: (e as Error).message });
}
}
private handle(method: string, rawUrl: string, auth: string, body: Record<string, unknown>): { status: number; body?: unknown } {
if (auth !== `Bearer ${this.token}`) return { status: 401, body: { detail: "Authentication credentials were not provided." } };
const url = new URL(rawUrl, "http://x");
const path = url.pathname.replace(/^\/api\/canonical\/0/, "");
let m: RegExpExecArray | null;
if (method === "POST" && path === "/projects/") {
if (body.team !== this.teamId) return { status: 400, body: { team: ["Invalid pk"] } };
const p: Project = { id: this.seq++, name: String(body.name), team: this.teamId, key: randomUUID().replace(/-/g, "") };
this.projects.set(p.id, p);
return { status: 201, body: { id: String(p.id), team: p.team, name: p.name, visibility: "team_members", alert_on_new_issue: true, alert_on_regression: true, alert_on_unmute: true } };
}
if (method === "GET" && (m = /^\/projects\/(\d+)\/$/.exec(path))) {
const p = this.projects.get(Number(m[1]));
return p ? { status: 200, body: { id: p.id, team: p.team, name: p.name, slug: p.name.toLowerCase(), dsn: this.dsn(p) } } : { status: 404, body: { detail: "No Project matches the given query." } };
}
if (method === "GET" && path === "/issues/") {
const project = Number(url.searchParams.get("project"));
const rows = [...this.issues.values()].filter((i) => !project || i.project === project).sort((a, b) => b.lastSeen.localeCompare(a.lastSeen));
return { status: 200, body: { next: null, previous: null, results: rows.map((i) => this.issueJson(i)) } };
}
if ((m = /^\/issues\/([^/]+)\/(resolve\/)?$/.exec(path))) {
const i = this.issues.get(m[1]!);
if (!i) return { status: 404, body: { detail: "No Issue matches the given query." } };
if (m[2] && method === "POST") {
if (i.resolved) return { status: 400, body: { detail: "Issue is already resolved." } };
i.resolved = true;
}
return { status: 200, body: this.issueJson(i) };
}
if (method === "GET" && path === "/events/") {
const i = this.issues.get(url.searchParams.get("issue") ?? "");
if (!i) return { status: 404, body: { detail: "Not found." } };
const ids = url.searchParams.get("order") === "asc" ? i.events : [...i.events].reverse();
return { status: 200, body: { next: null, previous: null, results: ids.map((id) => ({ id, issue: i.id, project: i.project })) } };
}
if (method === "GET" && (m = /^\/events\/([^/]+)\/$/.exec(path))) {
const e = this.events.get(m[1]!);
return e ? { status: 200, body: { ...e, stacktrace_md: "(mock)" } } : { status: 404, body: { detail: "Not found." } };
}
return { status: 404, body: { detail: `mock-bugsink: no route ${method} ${path}` } };
}
}