From 64d52fc69104c712247d8d15e37dac8a2bc62ab4 Mon Sep 17 00:00:00 2001 From: spark Date: Wed, 14 Oct 2026 19:32:54 +0100 Subject: [PATCH] Errors to errors.bitreport.pt from API, worker, app, desktop, sites and print agent API and worker report error log lines, unhandled 5xx and crashes to the hub with the photoreport ingest key (ERROR_REPORTING_TOKEN); browsers (app, desktop webview, sites), Next server renders and the print agent send through POST /v1/client-errors so the key stays on the server. Repeats folded, rate-limited. docs/errors.md. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW --- apps/api/.env.example | 7 + apps/api/src/app.ts | 15 +- apps/api/src/config.ts | 7 + apps/api/src/lib/clientErrors.ts | 42 +++++ apps/api/src/lib/errors.ts | 2 +- apps/api/src/lib/reporter.ts | 193 +++++++++++++++++++++ apps/api/src/server.ts | 6 +- apps/api/src/worker.ts | 7 +- apps/api/test/reporter.test.ts | 105 +++++++++++ apps/app/src/errorReporting.ts | 58 +++++++ apps/app/src/main.tsx | 12 +- apps/print-agent/src/cli.ts | 26 ++- apps/site/src/app/layout.tsx | 7 +- apps/site/src/components/ErrorReporter.tsx | 45 +++++ apps/site/src/instrumentation.ts | 32 ++++ docs/errors.md | 27 +++ 16 files changed, 582 insertions(+), 9 deletions(-) create mode 100644 apps/api/src/lib/clientErrors.ts create mode 100644 apps/api/src/lib/reporter.ts create mode 100644 apps/api/test/reporter.test.ts create mode 100644 apps/app/src/errorReporting.ts create mode 100644 apps/site/src/components/ErrorReporter.tsx create mode 100644 apps/site/src/instrumentation.ts create mode 100644 docs/errors.md diff --git a/apps/api/.env.example b/apps/api/.env.example index 208d771..e857872 100644 --- a/apps/api/.env.example +++ b/apps/api/.env.example @@ -48,3 +48,10 @@ MAIL_FROM=PhotoReport # DESKTOP_RELEASES_TOKEN= # Public address of this API (installer links for the desktop updater). # API_PUBLIC_URL=https://api.next.photoreport.pt + +# Errors to errors.bitreport.pt (BitReport's error hub; Paperclip picks them up and fixes them). The ingest key of +# the "photoreport" project there; without it nothing is sent. API, worker and the browsers (through the API's +# /v1/client-errors) all report with it. +# ERROR_REPORTING_TOKEN= +# ERROR_REPORTING_ENDPOINT=https://errors.bitreport.pt +# ERROR_REPORTING_DISABLED=0 diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index e3256aa..afcd64d 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -53,6 +53,10 @@ import { registerSportsRoutes } from "./sports/routes.js"; import { SportsService } from "./sports/service.js"; import { attachRealtime, type Broadcaster, silentBroadcaster } from "./realtime.js"; import { LocalStorage, UrlSigner } from "./storage/storage.js"; +import { registerClientErrors } from "./lib/clientErrors.js"; +import { type ErrorReporter, reporterFor } from "./lib/reporter.js"; + +export { reporterFor }; export interface AppDeps { config: Config; @@ -61,15 +65,19 @@ export interface AppDeps { realtime?: "socket" | Broadcaster; /** Outgoing HTTP for deliveries (tests point it at a fake Nextcloud). */ fetchImpl?: typeof fetch; + /** Errors to errors.bitreport.pt (made from the config when not given). */ + reporter?: ErrorReporter; } /** * Builds the API. Modules (ingest, library, oplog, galleries, sales, events, print, delivery) register here as * they are built. */ -export async function buildApp({ config, db, realtime, fetchImpl }: AppDeps): Promise { +export async function buildApp({ config, db, realtime, fetchImpl, reporter: given }: AppDeps): Promise { + const reporter = given ?? reporterFor(config); const app = Fastify({ - logger: config.NODE_ENV === "test" ? false : { level: config.LOG_LEVEL }, + // Error lines (and warnings carrying an error) also go to errors.bitreport.pt. + logger: config.NODE_ENV === "test" ? false : { level: config.LOG_LEVEL, hooks: reporter.logHooks("api") }, trustProxy: true, }); const sessions = new SessionService(db, config); @@ -93,6 +101,7 @@ export async function buildApp({ config, db, realtime, fetchImpl }: AppDeps): Pr const delivery = new DeliveryService({ db, storage, secrets, broadcaster, log: app.log, originals: archive, ...(fetchImpl && { fetchImpl }) }); registerErrorHandler(app); + app.addHook("onClose", async () => reporter.flush()); await app.register(cookie); await app.register(cors, { delegator: (req, cb) => @@ -104,6 +113,8 @@ export async function buildApp({ config, db, realtime, fetchImpl }: AppDeps): Pr }); await app.register(rateLimit, { global: false }); + registerClientErrors(app, reporter); + app.get("/health", async () => { await db.$queryRaw`SELECT 1`; return { status: "ok", version: config.APP_VERSION }; diff --git a/apps/api/src/config.ts b/apps/api/src/config.ts index 787a535..e6182c4 100644 --- a/apps/api/src/config.ts +++ b/apps/api/src/config.ts @@ -5,6 +5,13 @@ const Env = z.object({ PORT: z.coerce.number().int().positive().default(3000), LOG_LEVEL: z.string().default("info"), APP_VERSION: z.string().default("dev"), + /** The project's ingest key on errors.bitreport.pt (errors go there for Paperclip to work on). Unset: nothing sent. */ + ERROR_REPORTING_TOKEN: z.string().optional(), + ERROR_REPORTING_ENDPOINT: z.string().url().default("https://errors.bitreport.pt"), + ERROR_REPORTING_DISABLED: z + .enum(["0", "1", "true", "false"]) + .default("0") + .transform((v) => v === "1" || v === "true"), DATABASE_URL: z.string().url(), JWT_SECRET: z.string().min(32, "JWT_SECRET must have at least 32 characters"), ACCESS_TOKEN_TTL_SEC: z.coerce.number().int().positive().default(900), diff --git a/apps/api/src/lib/clientErrors.ts b/apps/api/src/lib/clientErrors.ts new file mode 100644 index 0000000..ca70004 --- /dev/null +++ b/apps/api/src/lib/clientErrors.ts @@ -0,0 +1,42 @@ +import type { FastifyInstance } from "fastify"; +import { z } from "zod"; +import type { ErrorReporter } from "./reporter.js"; + +const ClientEvent = z.object({ + message: z.string().min(1).max(2000), + stack: z.string().max(20_000).optional(), + level: z.enum(["error", "warning", "info"]).default("error"), + /** The web app, the public sites, the desktop shell's webview. */ + component: z.enum(["app", "site", "site-server", "desktop", "print-agent"]), + url: z.string().max(500).optional(), + release: z.string().max(64).optional(), + userAgent: z.string().max(300).optional(), + extra: z.record(z.string(), z.union([z.string().max(500), z.number(), z.boolean(), z.null()])).optional(), +}); + +const Body = z.object({ events: z.array(ClientEvent).min(1).max(10) }); + +/** + * Errors from the browsers (app, sites, desktop webview), passed on to errors.bitreport.pt with the server's key: + * the key never reaches a browser. Rate-limited per address; the reporter folds repeats together. + */ +export function registerClientErrors(app: FastifyInstance, reporter: ErrorReporter): void { + app.post("/v1/client-errors", { config: { rateLimit: { max: 30, timeWindow: "1 minute" } }, bodyLimit: 256 * 1024 }, async (req, reply) => { + const { events } = Body.parse(req.body); + for (const e of events) { + reporter.report({ + level: e.level, + message: e.message, + stack: e.stack, + component: e.component, + context: { + ...(e.url && { client_url: e.url }), + ...(e.release && { client_release: e.release }), + ...(e.userAgent && { user_agent: e.userAgent }), + ...e.extra, + }, + }); + } + return reply.code(202).send({ accepted: events.length }); + }); +} diff --git a/apps/api/src/lib/errors.ts b/apps/api/src/lib/errors.ts index 74b953f..de3918d 100644 --- a/apps/api/src/lib/errors.ts +++ b/apps/api/src/lib/errors.ts @@ -32,7 +32,7 @@ export function registerErrorHandler(app: FastifyInstance): void { if ("statusCode" in err && typeof err.statusCode === "number" && err.statusCode < 500) { return reply.code(err.statusCode).send({ error: err.code ?? "request_error", message: err.message }); } - req.log.error({ err }, "unhandled error"); + req.log.error({ err, method: req.method, route: req.routeOptions?.url ?? req.url.split("?")[0] }, "unhandled error"); return reply.code(500).send({ error: "internal_error" }); }); } diff --git a/apps/api/src/lib/reporter.ts b/apps/api/src/lib/reporter.ts new file mode 100644 index 0000000..4eb54f1 --- /dev/null +++ b/apps/api/src/lib/reporter.ts @@ -0,0 +1,193 @@ +import { createHash } from "node:crypto"; + +/** + * Errors to errors.bitreport.pt (BitReport's error hub; Paperclip picks them up from there and works on them). + * Port of the hub's Node client (clients/node/errorReporter.mjs): batched, fire-and-forget, never throws into the + * app. Same error again within a while is sent once (with how many times it happened), so a failing loop does not + * flood the hub. + * + * Off without ERROR_REPORTING_TOKEN (the project's ingest key on the hub), or with ERROR_REPORTING_DISABLED=1. + */ +export type ReportLevel = "critical" | "error" | "warning" | "info"; + +export interface ReportEvent { + level: ReportLevel; + message: string; + stack?: string | undefined; + /** Where it happened: api, worker, app, site, desktop, print-agent. */ + component: string; + context?: Record; +} + +export interface ReporterOptions { + token?: string | undefined; + endpoint?: string | undefined; + disabled?: boolean; + environment: string; + release: string; + fetchImpl?: typeof fetch; +} + +const PROJECT = { project_name: "PhotoReport", project_slug: "photoreport", gitea_repo: "BitReport.pt/photoreport" }; +const BATCH = 25; +const FLUSH_MS = 5_000; +const TIMEOUT_MS = 8_000; +/** The same error is sent at most once in this time. */ +const QUIET_MS = 10 * 60_000; + +export class ErrorReporter { + private readonly queue: Record[] = []; + private timer: NodeJS.Timeout | null = null; + private readonly seen = new Map(); + private readonly endpoint: string; + private readonly fetchImpl: typeof fetch; + + constructor(private readonly opts: ReporterOptions) { + this.endpoint = (opts.endpoint || "https://errors.bitreport.pt").replace(/\/+$/, ""); + this.fetchImpl = opts.fetchImpl ?? fetch; + } + + get enabled(): boolean { + return !this.opts.disabled && !!this.opts.token; + } + + report(e: ReportEvent): void { + if (!this.enabled) return; + const message = e.message.slice(0, 2000) || "(no message)"; + const fingerprint = fingerprintOf(e.component, message, e.stack); + const now = Date.now(); + const last = this.seen.get(fingerprint); + if (last && now - last.at < QUIET_MS) { + last.repeats++; + return; + } + const repeats = last?.repeats ?? 0; + this.seen.set(fingerprint, { at: now, repeats: 0 }); + if (this.seen.size > 5000) this.seen.delete(this.seen.keys().next().value!); + const where = frameOf(e.stack); + this.queue.push({ + schema_version: 1, + occurred_at: new Date(now).toISOString(), + level: e.level, + message, + fingerprint, + ...(e.stack && { stacktrace: e.stack.slice(0, 20_000) }), + context: { + ...PROJECT, + component: e.component, + environment: this.opts.environment, + release: this.opts.release, + ...(where && { file_path: where.file, line_number: where.line }), + ...(repeats && { repeated_since_last_report: repeats }), + ...e.context, + }, + }); + if (this.queue.length >= BATCH) void this.flush(); + else if (!this.timer) { + this.timer = setTimeout(() => { + this.timer = null; + void this.flush(); + }, FLUSH_MS); + this.timer.unref?.(); + } + } + + reportError(err: unknown, component: string, context: Record = {}, level: ReportLevel = "error"): void { + const e = err instanceof Error ? err : new Error(typeof err === "string" ? err : JSON.stringify(err)); + const code = (e as { code?: unknown }).code; + this.report({ level, message: `${e.name}: ${e.message}`, stack: e.stack, component, context: { error_type: e.constructor?.name ?? "Error", ...(code !== undefined && { error_code: String(code) }), ...context } }); + } + + /** Sends what is queued (call before the process exits). */ + async flush(): Promise { + if (this.timer) { + clearTimeout(this.timer); + this.timer = null; + } + while (this.queue.length) { + const events = this.queue.splice(0, BATCH); + try { + const ctrl = new AbortController(); + const t = setTimeout(() => ctrl.abort(), TIMEOUT_MS); + await this.fetchImpl(`${this.endpoint}/v1/ingest/events`, { + method: "POST", + headers: { "Content-Type": "application/json", Authorization: `Bearer ${this.opts.token}` }, + body: JSON.stringify({ events }), + signal: ctrl.signal, + }).finally(() => clearTimeout(t)); + } catch { + // Never let reporting break the app. + } + } + } + + /** Uncaught exceptions and unhandled rejections of this process. */ + watchProcess(component: string): void { + if (!this.enabled) return; + process.on("uncaughtException", (err) => { + this.reportError(err, component, { uncaught: true }, "critical"); + void this.flush().finally(() => process.exit(1)); + }); + process.on("unhandledRejection", (reason) => this.reportError(reason, component, { unhandled_rejection: true })); + } + + /** + * pino hooks: error and fatal log lines are reported; warnings too when they carry an error (a job that failed + * and will be retried), as "warning". + */ + logHooks(component: string) { + const reporter = this; + return { + logMethod(this: unknown, args: unknown[], method: (...a: unknown[]) => void, level: number) { + if (level >= 40) { + try { + const [first, second] = args; + const obj = first && typeof first === "object" && !(first instanceof Error) ? (first as Record) : null; + const err = first instanceof Error ? first : obj?.err instanceof Error ? obj.err : null; + const msg = typeof first === "string" ? first : typeof second === "string" ? second : ""; + if (level >= 50 || err) { + const lvl: ReportLevel = level >= 60 ? "critical" : level >= 50 ? "error" : "warning"; + const extra = obj ? Object.fromEntries(Object.entries(obj).filter(([k, v]) => k !== "err" && (typeof v !== "object" || v === null)).slice(0, 20)) : {}; + if (err) reporter.reportError(err, component, { log_message: msg, ...extra }, lvl); + else reporter.report({ level: lvl, message: msg || "(log without message)", component, context: extra }); + } + } catch { + // ignore + } + } + method.apply(this, args); + }, + }; + } +} + +/** What makes two reports the same error: where, and the message without its numbers and ids. */ +function fingerprintOf(component: string, message: string, stack?: string): string { + const shape = message.replace(/[0-9a-f]{8}-[0-9a-f-]{27,}/gi, "").replace(/\d+/g, "").slice(0, 300); + const frame = frameOf(stack); + return createHash("sha1").update(`${component}|${shape}|${frame ? `${frame.file}:${frame.line}` : ""}`).digest("hex").slice(0, 32); +} + +/** The first frame of the stack in our own code (not node_modules). */ +function frameOf(stack?: string): { file: string; line: number } | null { + if (!stack) return null; + for (const m of stack.matchAll(/at (?:.+? \()?(.+?):(\d+):\d+\)?$/gm)) { + if (!/node_modules|node:internal|^node:/.test(m[1]!)) return { file: m[1]!, line: Number(m[2]) }; + } + return null; +} + +/** The reporter of this deployment (off without ERROR_REPORTING_TOKEN, and in tests). */ +export function reporterFor( + config: { ERROR_REPORTING_TOKEN?: string | undefined; ERROR_REPORTING_ENDPOINT: string; ERROR_REPORTING_DISABLED: boolean; NODE_ENV: string; APP_VERSION: string }, + fetchImpl?: typeof fetch, +): ErrorReporter { + return new ErrorReporter({ + token: config.ERROR_REPORTING_TOKEN, + endpoint: config.ERROR_REPORTING_ENDPOINT, + disabled: config.ERROR_REPORTING_DISABLED || config.NODE_ENV === "test", + environment: config.NODE_ENV, + release: config.APP_VERSION, + ...(fetchImpl && { fetchImpl }), + }); +} diff --git a/apps/api/src/server.ts b/apps/api/src/server.ts index 48d4dc6..41fb38f 100644 --- a/apps/api/src/server.ts +++ b/apps/api/src/server.ts @@ -1,10 +1,12 @@ -import { buildApp } from "./app.js"; +import { buildApp, reporterFor } from "./app.js"; import { loadConfig } from "./config.js"; import { createDb } from "./db.js"; const config = loadConfig(); const db = createDb(config.DATABASE_URL); -const app = await buildApp({ config, db, realtime: "socket" }); +const reporter = reporterFor(config); +reporter.watchProcess("api"); +const app = await buildApp({ config, db, realtime: "socket", reporter }); const shutdown = async (signal: string) => { app.log.info({ signal }, "shutting down"); diff --git a/apps/api/src/worker.ts b/apps/api/src/worker.ts index 0311205..58669a3 100644 --- a/apps/api/src/worker.ts +++ b/apps/api/src/worker.ts @@ -1,6 +1,7 @@ import { existsSync } from "node:fs"; import { dirname, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; +import { reporterFor } from "./lib/reporter.js"; import pino from "pino"; import { loadConfig } from "./config.js"; import { planCapacity, Pressure } from "./lib/capacity.js"; @@ -32,7 +33,10 @@ import { InvoicingService, InvoicingWorker } from "./invoicing/service.js"; * and the storage (PM2 app `photoreport-worker`, never clustered: it owns the drop folder). */ const config = loadConfig(); -const log = pino({ level: config.LOG_LEVEL, name: "worker" }); +// Error lines (and warnings carrying an error) also go to errors.bitreport.pt, as do crashes. +const reporter = reporterFor(config); +reporter.watchProcess("worker"); +const log = pino({ level: config.LOG_LEVEL, name: "worker", hooks: reporter.logHooks("worker") }); /** * The engines the deploy builds (target/release) and the models it downloads (next to the storage) are used when @@ -148,6 +152,7 @@ const shutdown = async (signal: string) => { await closeRenderer(); await broadcaster.close(); await db.$disconnect(); + await reporter.flush(); process.exit(0); }; process.on("SIGTERM", () => void shutdown("SIGTERM")); diff --git a/apps/api/test/reporter.test.ts b/apps/api/test/reporter.test.ts new file mode 100644 index 0000000..a182228 --- /dev/null +++ b/apps/api/test/reporter.test.ts @@ -0,0 +1,105 @@ +import pino from "pino"; +import { Writable } from "node:stream"; +import { afterAll, describe, expect, it } from "vitest"; +import { buildApp } from "../src/app.js"; +import { loadConfig } from "../src/config.js"; +import { createDb } from "../src/db.js"; +import { ErrorReporter } from "../src/lib/reporter.js"; + +type Sent = { url: string; auth: string | null; events: { level: string; message: string; fingerprint: string; stacktrace?: string; context: Record }[] }; + +function fakeHub() { + const sent: Sent[] = []; + const fetchImpl = (async (url: string | URL | Request, init?: RequestInit) => { + sent.push({ url: String(url), auth: new Headers(init?.headers).get("authorization"), events: JSON.parse(String(init?.body)).events }); + return new Response("{}", { status: 200 }); + }) as typeof fetch; + return { sent, fetchImpl }; +} + +const reporterWith = (fetchImpl: typeof fetch, token: string | undefined = "ingest-key") => + new ErrorReporter({ token, endpoint: "https://errors.test/", environment: "production", release: "abc1234", fetchImpl }); + +describe("errors to errors.bitreport.pt", () => { + it("sends errors to the hub's ingest with the project's key, once per error for a while", async () => { + const hub = fakeHub(); + const reporter = reporterWith(hub.fetchImpl); + const boom = () => new Error("archive scan failed for 7d1e9c1a-4c4f-4a55-9d2f-0f1c2b3a4d5e"); + reporter.reportError(boom(), "worker", { sourceId: "x" }); + reporter.reportError(boom(), "worker"); + reporter.reportError(new Error("something else"), "worker"); + await reporter.flush(); + expect(hub.sent).toHaveLength(1); + expect(hub.sent[0]).toMatchObject({ url: "https://errors.test/v1/ingest/events", auth: "Bearer ingest-key" }); + const [first, other] = hub.sent[0]!.events; + expect(first).toMatchObject({ + level: "error", + message: expect.stringContaining("archive scan failed"), + context: { project_slug: "photoreport", gitea_repo: "BitReport.pt/photoreport", component: "worker", environment: "production", release: "abc1234", sourceId: "x" }, + }); + expect(first!.stacktrace).toContain("reporter.test.ts"); + expect(first!.context.file_path).toContain("reporter.test.ts"); + expect(other!.fingerprint).not.toBe(first!.fingerprint); + }); + + it("does nothing without a key", async () => { + const hub = fakeHub(); + const reporter = reporterWith(hub.fetchImpl, ""); + reporter.reportError(new Error("x"), "api"); + await reporter.flush(); + expect(hub.sent).toHaveLength(0); + }); + + it("reports the log's errors, and warnings that carry an error, not the rest", async () => { + const hub = fakeHub(); + const reporter = reporterWith(hub.fetchImpl); + const sink = new Writable({ write: (_c, _e, cb) => cb() }); + const log = pino({ level: "info", hooks: reporter.logHooks("worker") }, sink); + log.info("worker started"); + log.warn({ fileId: "f1" }, "slow"); + log.warn({ err: new Error("cloud timeout"), fileId: "f2" }, "archive: image not indexed"); + log.error({ err: new Error("render crashed") }, "render failed"); + log.error("no error object here"); + await reporter.flush(); + const events = hub.sent.flatMap((s) => s.events); + expect(events.map((e) => [e.level, e.message])).toEqual([ + ["warning", "Error: cloud timeout"], + ["error", "Error: render crashed"], + ["error", "no error object here"], + ]); + expect(events[0]!.context).toMatchObject({ log_message: "archive: image not indexed", fileId: "f2" }); + }); +}); + +describe("browser errors through the API", () => { + const hub = fakeHub(); + const config = loadConfig({ + NODE_ENV: "test", + DATABASE_URL: process.env.DATABASE_URL_TEST ?? "postgresql://x@127.0.0.1:5432/photoreport_test", + JWT_SECRET: "test-secret-test-secret-test-secret-123", + }); + const db = createDb(config.DATABASE_URL); + const reporter = reporterWith(hub.fetchImpl); + const appP = buildApp({ config, db, reporter }); + afterAll(async () => { + await (await appP).close(); + await db.$disconnect(); + }); + + it("passes the app's and the sites' errors on with the server's key", async () => { + const app = await appP; + let res = await app.inject({ + method: "POST", + url: "/v1/client-errors", + payload: { events: [{ message: "TypeError: x is undefined", stack: "TypeError: x is undefined\n at Gallery (https://app.test/assets/index.js:1:200)", component: "app", url: "https://app.test/library", release: "abc1234" }] }, + }); + expect(res.statusCode).toBe(202); + res = await app.inject({ method: "POST", url: "/v1/client-errors", payload: { events: [{ message: "x", component: "evil" }] } }); + expect(res.statusCode).toBe(400); + await reporter.flush(); + const events = hub.sent.flatMap((s) => s.events); + expect(events).toHaveLength(1); + expect(events[0]).toMatchObject({ message: "TypeError: x is undefined", context: { component: "app", client_url: "https://app.test/library", project_slug: "photoreport" } }); + expect(hub.sent[0]!.auth).toBe("Bearer ingest-key"); + }); +}); diff --git a/apps/app/src/errorReporting.ts b/apps/app/src/errorReporting.ts new file mode 100644 index 0000000..751ad25 --- /dev/null +++ b/apps/app/src/errorReporting.ts @@ -0,0 +1,58 @@ +/** + * The app's errors (uncaught, unhandled promise rejections, React render errors) to errors.bitreport.pt, through + * the API's /v1/client-errors (the hub's key stays on the server). Same error sent once per page load; at most a + * few per minute; never in development or tests. + */ +type ClientEvent = { message: string; stack?: string; component: "app" | "desktop"; url: string; release?: string; userAgent: string; extra?: Record }; + +const seen = new Set(); +let queue: ClientEvent[] = []; +let timer: ReturnType | null = null; +let sentThisMinute = 0; +let endpoint = ""; +let component: ClientEvent["component"] = "app"; +let release: string | undefined; + +/** Noise from outside our code: extensions, cancelled loads, a closed tab. */ +const IGNORED = /ResizeObserver loop|Script error\.?$|AbortError|The user aborted a request|Load failed$|NetworkError when attempting|Failed to fetch$|chrome-extension:|moz-extension:/; + +export function installErrorReporting(opts: { apiUrl: string; desktop: boolean; release?: string | undefined; enabled?: boolean }): void { + if (opts.enabled === false || typeof window === "undefined") return; + endpoint = `${opts.apiUrl.replace(/\/+$/, "")}/v1/client-errors`; + component = opts.desktop ? "desktop" : "app"; + release = opts.release; + setInterval(() => { + sentThisMinute = 0; + }, 60_000); + window.addEventListener("error", (e) => reportClientError(e.error ?? e.message, { source: "window.onerror" })); + window.addEventListener("unhandledrejection", (e) => reportClientError(e.reason, { source: "unhandledrejection" })); +} + +export function reportClientError(err: unknown, extra: Record = {}): void { + if (!endpoint) return; + const e = err instanceof Error ? err : new Error(typeof err === "string" ? err : safeString(err)); + const message = `${e.name}: ${e.message}`.slice(0, 2000); + if (IGNORED.test(message) || IGNORED.test(e.stack ?? "")) return; + const key = `${message}|${(e.stack ?? "").split("\n")[1] ?? ""}`; + if (seen.has(key) || sentThisMinute >= 10) return; + seen.add(key); + sentThisMinute++; + queue.push({ message, ...(e.stack && { stack: e.stack.slice(0, 20_000) }), component, url: location.href.split("?")[0]!.slice(0, 500), ...(release && { release }), userAgent: navigator.userAgent.slice(0, 300), extra }); + if (!timer) timer = setTimeout(send, 2000); +} + +function send(): void { + timer = null; + const events = queue.splice(0, 10); + queue = []; + if (!events.length) return; + void fetch(endpoint, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ events }), keepalive: true }).catch(() => undefined); +} + +function safeString(v: unknown): string { + try { + return JSON.stringify(v) ?? String(v); + } catch { + return String(v); + } +} diff --git a/apps/app/src/main.tsx b/apps/app/src/main.tsx index 515b069..78c229a 100644 --- a/apps/app/src/main.tsx +++ b/apps/app/src/main.tsx @@ -1,11 +1,21 @@ import { StrictMode } from "react"; import { createRoot } from "react-dom/client"; import { App } from "./App.js"; +import { API_URL } from "./api.js"; +import { installErrorReporting, reportClientError } from "./errorReporting.js"; +import { isDesktop } from "./platform.js"; import "./styles.css"; +// Errors go to errors.bitreport.pt (through the API) for Paperclip to work on; not from a developer's machine. +installErrorReporting({ apiUrl: API_URL, desktop: isDesktop(), release: import.meta.env.VITE_APP_VERSION as string | undefined, enabled: import.meta.env.PROD }); + const root = document.getElementById("root"); if (root) { - createRoot(root).render( + createRoot(root, { + // A component that failed to render (React 19 tells the root). + onUncaughtError: (err, info) => reportClientError(err, { source: "react", componentStack: (info.componentStack ?? "").slice(0, 480) }), + onCaughtError: (err, info) => reportClientError(err, { source: "react-boundary", componentStack: (info.componentStack ?? "").slice(0, 480) }), + }).render( , diff --git a/apps/print-agent/src/cli.ts b/apps/print-agent/src/cli.ts index cb2bb9d..42d7aa7 100644 --- a/apps/print-agent/src/cli.ts +++ b/apps/print-agent/src/cli.ts @@ -68,6 +68,7 @@ async function main() { } if (cmd === "run") { const c = await load(); + reportCrashes(c.api); const agent = new PrintAgent({ api: c.api, token: c.token, provider: provider(c), version: VERSION, log: (m) => console.log(new Date().toISOString(), m) }); process.on("SIGINT", () => agent.stop()); process.on("SIGTERM", () => agent.stop()); @@ -78,7 +79,30 @@ async function main() { console.log(usage); } -main().catch((err: Error) => { +/** + * Crashes of the agent go to errors.bitreport.pt through the PhotoReport API it is paired with (the hub's key + * stays on the server). Failed print jobs are not crashes: the server already has those. + */ +let reportTo: string | null = null; +function reportCrashes(api: string): void { + reportTo = api; + process.on("uncaughtException", (err) => void sendCrash(err).finally(() => process.exit(1))); + process.on("unhandledRejection", (reason) => void sendCrash(reason)); +} +async function sendCrash(err: unknown): Promise { + if (!reportTo) return; + const e = err instanceof Error ? err : new Error(String(err)); + console.error(new Date().toISOString(), e.stack ?? e.message); + await fetch(`${reportTo}/v1/client-errors`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ events: [{ message: `${e.name}: ${e.message}`.slice(0, 2000), ...(e.stack && { stack: e.stack.slice(0, 20_000) }), component: "print-agent", release: VERSION, extra: { platform: `${process.platform} ${hostname()}` } }] }), + signal: AbortSignal.timeout(5000), + }).catch(() => undefined); +} + +main().catch(async (err: Error) => { + await sendCrash(err); console.error(err.message); process.exit(1); }); diff --git a/apps/site/src/app/layout.tsx b/apps/site/src/app/layout.tsx index 75c674c..cb1788c 100644 --- a/apps/site/src/app/layout.tsx +++ b/apps/site/src/app/layout.tsx @@ -10,6 +10,7 @@ import { headers } from "next/headers"; import Link from "next/link"; import type { ReactNode } from "react"; import { CartLink } from "../components/CartLink"; +import { ErrorReporter } from "../components/ErrorReporter"; import { Logo } from "../components/Logo"; import { getSite, NotFound } from "../lib/api"; @@ -34,7 +35,10 @@ export default async function RootLayout({ children }: { children: ReactNode }) if (path.startsWith("/e/") || path.startsWith("/arquivo/")) { return ( - {children} + + + {children} + ); } @@ -49,6 +53,7 @@ export default async function RootLayout({ children }: { children: ReactNode }) return ( +
diff --git a/apps/site/src/components/ErrorReporter.tsx b/apps/site/src/components/ErrorReporter.tsx new file mode 100644 index 0000000..86e5cf7 --- /dev/null +++ b/apps/site/src/components/ErrorReporter.tsx @@ -0,0 +1,45 @@ +"use client"; + +import { useEffect } from "react"; + +/** + * The sites' browser errors to errors.bitreport.pt, through the API (`/v1` on the site's own origin): uncaught + * errors and unhandled rejections, once per page load each, a few per minute at most. Not in development. + */ +const IGNORED = /ResizeObserver loop|Script error\.?$|AbortError|The user aborted a request|Load failed$|NetworkError when attempting|Failed to fetch$|chrome-extension:|moz-extension:/; + +export function ErrorReporter() { + useEffect(() => { + if (process.env.NODE_ENV !== "production") return; + const seen = new Set(); + let count = 0; + const reset = setInterval(() => (count = 0), 60_000); + const report = (err: unknown, source: string) => { + const e = err instanceof Error ? err : new Error(typeof err === "string" ? err : String(err)); + const message = `${e.name}: ${e.message}`.slice(0, 2000); + if (IGNORED.test(message) || IGNORED.test(e.stack ?? "")) return; + const key = `${message}|${(e.stack ?? "").split("\n")[1] ?? ""}`; + if (seen.has(key) || count >= 10) return; + seen.add(key); + count++; + void fetch("/v1/client-errors", { + method: "POST", + headers: { "Content-Type": "application/json" }, + keepalive: true, + body: JSON.stringify({ + events: [{ message, ...(e.stack && { stack: e.stack.slice(0, 20_000) }), component: "site", url: location.href.split("?")[0]!.slice(0, 500), userAgent: navigator.userAgent.slice(0, 300), extra: { source } }], + }), + }).catch(() => undefined); + }; + const onError = (e: ErrorEvent) => report(e.error ?? e.message, "window.onerror"); + const onRejection = (e: PromiseRejectionEvent) => report(e.reason, "unhandledrejection"); + window.addEventListener("error", onError); + window.addEventListener("unhandledrejection", onRejection); + return () => { + clearInterval(reset); + window.removeEventListener("error", onError); + window.removeEventListener("unhandledrejection", onRejection); + }; + }, []); + return null; +} diff --git a/apps/site/src/instrumentation.ts b/apps/site/src/instrumentation.ts new file mode 100644 index 0000000..3a3c1a9 --- /dev/null +++ b/apps/site/src/instrumentation.ts @@ -0,0 +1,32 @@ +import type { Instrumentation } from "next"; + +/** + * Errors while rendering a page on the server go to errors.bitreport.pt, through the API (the hub's key stays + * there). Pages the API says do not exist are not errors. + */ +export const onRequestError: Instrumentation.onRequestError = async (err, request, context) => { + if (process.env.NODE_ENV !== "production") return; + const e = err instanceof Error ? err : new Error(String(err)); + if (e.name === "NotFound" || /NEXT_NOT_FOUND|NEXT_REDIRECT/.test(e.message)) return; + const api = process.env.API_URL ?? "http://localhost:3000"; + try { + await fetch(`${api}/v1/client-errors`, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + events: [ + { + message: `${e.name}: ${e.message}`.slice(0, 2000), + ...(e.stack && { stack: e.stack.slice(0, 20_000) }), + component: "site-server", + url: `${request.headers.host ?? ""}${request.path}`.split("?")[0]!.slice(0, 500), + extra: { method: request.method, route: context.routePath, routeType: context.routeType, digest: (err as { digest?: string }).digest ?? null }, + }, + ], + }), + signal: AbortSignal.timeout(5000), + }); + } catch { + // never break the page over a report + } +}; diff --git a/docs/errors.md b/docs/errors.md new file mode 100644 index 0000000..c9e69b8 --- /dev/null +++ b/docs/errors.md @@ -0,0 +1,27 @@ +# Errors → errors.bitreport.pt + +Every part of PhotoReport reports its errors to BitReport's error hub (errors.bitreport.pt, repo +`BitReport.pt/errors.bitreport.pt`), project slug `photoreport`, Gitea repo `BitReport.pt/photoreport`. Paperclip +reads the hub (`/v1/paperclip/recent-errors?project_slug=photoreport`) and works on them. + +| Part | How | `component` | +|------|-----|-------------| +| API (pr-api) | error log lines, unhandled 5xx (method, route), crashes | `api` | +| Worker (pr-api, PM2) | error log lines, warnings that carry an error (a job that failed and is retried), crashes | `worker` | +| Web app | uncaught errors, unhandled rejections, React render errors → `POST /v1/client-errors` | `app` | +| Desktop (Tauri webview) | same as the web app | `desktop` | +| Public sites (browser) | uncaught errors, unhandled rejections → `/v1/client-errors` on the site's origin | `site` | +| Public sites (server render) | Next `onRequestError` → the API's `/v1/client-errors` | `site-server` | +| Print agent | crashes → its API's `/v1/client-errors` | `print-agent` | + +Only the API holds the hub's key (`ERROR_REPORTING_TOKEN` in pr-api's `.env`, the ingest key of the +`photoreport` project on the hub); browsers and agents send to the API, which passes events on. Without the key +nothing is sent (development, tests). `ERROR_REPORTING_DISABLED=1` turns it off. + +Each event carries `component`, `environment`, `release` (the deployed commit, `APP_VERSION`), file and line of the +first frame in our code, and the context logged with it. The same error (same component, message shape and place) +is sent once per 10 minutes, with how many times it happened since (`repeated_since_last_report`); browsers send +each error once per page load, at most ten a minute. `/v1/client-errors` is rate-limited (30 a minute per address). + +Code: `apps/api/src/lib/reporter.ts` (a port of the hub's Node client), `apps/api/src/lib/clientErrors.ts`, +`apps/app/src/errorReporting.ts`, `apps/site/src/components/ErrorReporter.tsx`, `apps/site/src/instrumentation.ts`.