// Bugsink adapter (PEP-58): REST API client (/api/canonical/0/, Bugsink 2.6) and the // custom-webhook alert payload. No database here — Peppa's incident logic lives in core/runner. import { execFile } from "node:child_process"; import { promisify } from "node:util"; const run = promisify(execFile); /** An issue as Bugsink's API and its custom webhook serialize it (subset we use). */ export interface BugsinkIssueJson { id: string; friendly_id?: string; project: number; first_seen: string; last_seen: string; digested_event_count: number; calculated_type: string; calculated_value: string; transaction?: string; is_resolved: boolean; is_muted?: boolean; events_at?: string[]; // Webhook-only convenience fields. title?: string; project_name?: string; url?: string; alert_reason?: "NEW" | "REGRESSED" | "UNMUTED" | "TEST" | string; } interface Frame { filename?: string; abs_path?: string; module?: string; function?: string; lineno?: number; colno?: number; in_app?: boolean; pre_context?: string[]; context_line?: string; post_context?: string[]; } /** PEP-218: a stack frame for the error card, innermost first. */ export interface StackFrame { file: string; fn: string | null; line: number | null; inApp: boolean; /** Code around the line, when the SDK sent it: [lineNo, text, isTheLine]. */ context: Array<[number | null, string, boolean]>; } /** Frames of the last (innermost) exception, innermost frame first, with code context. */ export function stackFrames(e: BugsinkEventJson | null, max = 40): StackFrame[] { return frames(e) .slice(0, max) .map((f) => { const line = f.lineno ?? null; const pre = f.pre_context ?? []; const ctx: StackFrame["context"] = []; pre.forEach((s, n) => ctx.push([line != null ? line - pre.length + n : null, s, false])); if (f.context_line != null) ctx.push([line, f.context_line, true]); (f.post_context ?? []).forEach((s, n) => ctx.push([line != null ? line + 1 + n : null, s, false])); return { file: f.filename ?? f.abs_path ?? f.module ?? "?", fn: f.function ?? null, line, inApp: f.in_app !== false, context: ctx }; }); } /** Event tags as a flat record (the SDK sends either an object or [key, value] pairs). */ export function eventTags(e: BugsinkEventJson | null): Record { const t = e?.data.tags; if (!t) return {}; return Array.isArray(t) ? Object.fromEntries(t.map(([k, v]) => [k, String(v)])) : Object.fromEntries(Object.entries(t).map(([k, v]) => [k, String(v)])); } /** A Bugsink project as `GET /projects/` lists it. */ export interface BugsinkProjectJson { id: number; name: string; slug?: string; digested_event_count?: number; } export interface BugsinkEventListJson { id: string; event_id?: string; issue: string; timestamp: string; digested_at?: string; } export interface BugsinkTagJson { key: string; value: string; count: number; } export interface BugsinkCountsJson { start: string; end: string; interval_seconds: number; buckets: Array<{ timestamp: string; count: number }>; } export type IssueState = "all" | "open" | "unresolved" | "resolved" | "muted"; export interface IssueSearch { project?: number; state?: IssueState; /** Title text plus `key:value` tag filters (Bugsink's `q`). */ q?: string; sort?: "last_seen" | "digested_event_count"; order?: "asc" | "desc"; cursor?: string; } /** Event detail: `data` is the Sentry event payload. */ export interface BugsinkEventJson { id: string; issue: string; timestamp: string; data: { environment?: string; release?: string; level?: string; platform?: string; exception?: { values?: Array<{ type?: string; value?: string; stacktrace?: { frames?: Frame[] } }> }; tags?: Record | Array<[string, string]>; request?: { url?: string; method?: string }; }; } /** What Peppa needs to know about an issue, whichever way it arrived. */ export interface BugsinkIssue { issueId: string; friendlyId: string | null; bugsinkProjectId: number; title: string; culprit: string | null; level: string | null; environment: string | null; release: string | null; events: number; firstSeen: Date; lastSeen: Date; url: string | null; /** Top of the stack, innermost frame first, without locals. */ stack: string | null; isResolved: boolean; /** Why we got it: webhook alert reason, or POLL. */ reason: "NEW" | "REGRESSED" | "UNMUTED" | "POLL"; } const STACK_LINES = 30; function frameLine(f: Frame): string { const where = f.filename ?? f.abs_path ?? f.module ?? "?"; return `${where}${f.lineno != null ? `:${f.lineno}` : ""} in ${f.function ?? "?"}${f.in_app === false ? "" : " [app]"}`; } function frames(e: BugsinkEventJson | null): Frame[] { const values = e?.data.exception?.values ?? []; // Sentry lists the outermost exception first and frames outermost first. const last = values[values.length - 1]; return [...(last?.stacktrace?.frames ?? [])].reverse(); } /** Where it broke: the innermost in-app frame ("billing/charge.ts"), else the innermost one. */ export function culpritOf(e: BugsinkEventJson | null, transaction?: string): string | null { const fs = frames(e); const f = fs.find((x) => x.in_app) ?? fs[0]; return f?.filename ?? f?.module ?? f?.abs_path ?? (transaction || null); } export function stackOf(e: BugsinkEventJson | null): string | null { const fs = frames(e); return fs.length ? fs.slice(0, STACK_LINES).map(frameLine).join("\n") : null; } /** Normalizes an API/webhook issue plus (optionally) its latest event. */ export function issueFromEvent(i: BugsinkIssueJson, e: BugsinkEventJson | null, reason: BugsinkIssue["reason"]): BugsinkIssue { const title = i.title ?? `${i.calculated_type}: ${i.calculated_value}`; return { issueId: i.id, friendlyId: i.friendly_id ?? null, bugsinkProjectId: Number(i.project), title, culprit: culpritOf(e, i.transaction), level: e?.data.level ?? null, environment: e?.data.environment ?? null, release: e?.data.release ?? i.events_at?.at(-1) ?? null, events: i.digested_event_count, firstSeen: new Date(i.first_seen), lastSeen: new Date(i.last_seen), url: i.url ?? null, stack: stackOf(e), isResolved: i.is_resolved, reason, }; } /** Validates the custom-webhook body; null for anything that isn't an issue alert (e.g. TEST). */ export function parseWebhook(body: unknown): BugsinkIssueJson | null { if (!body || typeof body !== "object") return null; const b = body as Partial; if (typeof b.id !== "string" || b.project == null || typeof b.last_seen !== "string" || typeof b.calculated_type !== "string") return null; if (b.alert_reason === "TEST") return null; return b as BugsinkIssueJson; } export class BugsinkError extends Error { readonly status?: number; constructor(message: string, status?: number) { super(message); this.status = status; } } export interface BugsinkConfig { /** Internal API base, e.g. http://127.0.0.1:3180 */ url: string; token: string; /** Team UUID that new projects go into. */ teamId?: string; /** Public base URL for issue links (defaults to url). */ publicUrl?: string; /** Docker container to configure alert webhooks in (the API has no endpoint for that). */ container?: string; } export type BugsinkClient = ReturnType; export function createBugsinkClient(c: BugsinkConfig) { const base = `${c.url.replace(/\/$/, "")}/api/canonical/0`; const publicUrl = (c.publicUrl ?? c.url).replace(/\/$/, ""); async function call(method: string, path: string, body?: unknown): Promise { let res: Response; try { res = await fetch(`${base}${path}`, { method, headers: { authorization: `Bearer ${c.token}`, ...(body ? { "content-type": "application/json" } : {}) }, body: body ? JSON.stringify(body) : undefined, signal: AbortSignal.timeout(15_000), }); } catch (e) { throw new BugsinkError(`Bugsink недоступен: ${(e as Error).message}`); } if (!res.ok) throw new BugsinkError(`Bugsink ${method} ${path}: HTTP ${res.status} ${(await res.text()).slice(0, 200)}`, res.status); return (await res.json()) as T; } return { publicUrl, issueUrl: (issueId: string) => `${publicUrl}/issues/issue/${issueId}/event/last/`, async createProject(name: string): Promise<{ id: number; dsn: string }> { if (!c.teamId) throw new BugsinkError("BUGSINK_TEAM_ID не задан"); const created = await call<{ id: string | number }>("POST", "/projects/", { team: c.teamId, name }); const p = await call<{ id: number; dsn: string }>("GET", `/projects/${created.id}/`); return { id: Number(p.id), dsn: p.dsn }; }, /** Most recently seen issues of a project (first page). */ async listIssues(projectId: number): Promise { const r = await call<{ results: BugsinkIssueJson[] }>("GET", `/issues/?project=${projectId}&sort=last_seen&order=desc`); return r.results; }, getIssue: (issueId: string) => call("GET", `/issues/${issueId}/`), async latestEvent(issueId: string): Promise { const r = await call<{ results: Array<{ id: string }> }>("GET", `/events/?issue=${issueId}&order=desc`); const first = r.results[0]; return first ? call("GET", `/events/${first.id}/`) : null; }, resolveIssue: (issueId: string) => call("POST", `/issues/${issueId}/resolve/`), // PEP-218: the error browser (endpoints checked against Bugsink 2.6.3, see the change's design.md). async listProjects(): Promise { const out: BugsinkProjectJson[] = []; let path: string | null = "/projects/"; for (let n = 0; path && n < 20; n++) { const r: { next: string | null; results: BugsinkProjectJson[] } = await call("GET", path); out.push(...r.results); path = r.next ? r.next.slice(r.next.indexOf("/projects/")) : null; } return out; }, /** One page of issues; `next` is the cursor of the following page. */ async searchIssues(s: IssueSearch): Promise<{ results: BugsinkIssueJson[]; next: string | null }> { const p = new URLSearchParams(); if (s.project != null) p.set("project", String(s.project)); p.set("state", s.state ?? "all"); if (s.q?.trim()) p.set("q", s.q.trim()); p.set("sort", s.sort ?? "last_seen"); p.set("order", s.order ?? "desc"); if (s.cursor) p.set("cursor", s.cursor); const r = await call<{ results: BugsinkIssueJson[]; next: string | null }>("GET", `/issues/?${p}`); return { results: r.results, next: r.next ? new URL(r.next).searchParams.get("cursor") : null }; }, async listEvents(issueId: string): Promise { const r = await call<{ results: BugsinkEventListJson[] }>("GET", `/events/?issue=${encodeURIComponent(issueId)}&order=desc`); return r.results; }, getEvent: (eventId: string) => call("GET", `/events/${eventId}/`), async issueTags(issueId: string): Promise { const r = await call<{ results: BugsinkTagJson[] }>("GET", `/issues/${encodeURIComponent(issueId)}/tags/`); return r.results; }, /** Hourly event counts of a project (or of one issue) between UTC hour boundaries. */ eventCounts(target: { project: number } | { issue: string }, start?: Date, end?: Date): Promise { const p = new URLSearchParams(); if (start) p.set("start", start.toISOString().replace(/\.\d+Z$/, "Z")); if (end) p.set("end", end.toISOString().replace(/\.\d+Z$/, "Z")); const q = p.size ? `?${p}` : ""; return "project" in target ? call("GET", `/projects/${target.project}/event-counts/${q}`) : call("GET", `/issues/${encodeURIComponent(target.issue)}/event-counts/${q}`); }, muteIssue: (issueId: string) => call("POST", `/issues/${issueId}/mute/`), unmuteIssue: (issueId: string) => call("POST", `/issues/${issueId}/unmute/`), reopenIssue: (issueId: string) => call("POST", `/issues/${issueId}/reopen/`), /** Points the project's alerts (new / regressed / unmuted) at Peppa's webhook URL. */ async setAlertWebhook(projectId: number, webhookUrl: string): Promise { if (!c.container) throw new BugsinkError("API Bugsink не умеет настраивать алерты: добавьте Custom webhook вручную"); const py = [ "import json, sys", "from alerts.models import MessagingServiceConfig", "from projects.models import Project", `p = Project.objects.get(id=${Number(projectId)})`, `cfg = json.dumps({"webhook_url": ${JSON.stringify(webhookUrl)}})`, "m = MessagingServiceConfig.objects.filter(project=p, display_name='Peppa').first()", "m = m or MessagingServiceConfig(project=p, display_name='Peppa', kind='custom')", "m.kind = 'custom'; m.config = cfg; m.save(); print('ok')", ].join("\n"); try { await run("docker", ["exec", c.container, "bugsink-manage", "shell", "-c", py], { timeout: 60_000 }); } catch (e) { throw new BugsinkError(`Не удалось настроить вебхук в Bugsink: ${(e as Error).message.slice(0, 200)}`); } }, }; } /** The client configured in Peppa's env (BUGSINK_URL, BUGSINK_TOKEN…), or null. */ export function bugsinkFromEnv(env: NodeJS.ProcessEnv = process.env): BugsinkClient | null { if (!env.BUGSINK_URL || !env.BUGSINK_TOKEN) return null; return createBugsinkClient({ url: env.BUGSINK_URL, token: env.BUGSINK_TOKEN, teamId: env.BUGSINK_TEAM_ID, publicUrl: env.BUGSINK_PUBLIC_URL, container: env.BUGSINK_CONTAINER, }); }