// 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://@host/` → 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; /** 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 = { 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; /** 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 { 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(); /** 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 { 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(); 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 { 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")); }