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 <[email protected]> Claude-Session: https://claude.ai/code/session_01HT6iXLYUUp9pJz5Kza9xCW
This commit is contained in:
1 parent
beb7a249a9
commit
64d52fc691
16 files changed
+582
-9
No files matched your search
@@ -48,3 +48,10 @@ MAIL_FROM=PhotoReport <[email protected]>
|
||||
# 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
|
||||
+13
-2
@@ -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<FastifyInstance> {
|
||||
export async function buildApp({ config, db, realtime, fetchImpl, reporter: given }: AppDeps): Promise<FastifyInstance> {
|
||||
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 };
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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 });
|
||||
});
|
||||
}
|
||||
@@ -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" });
|
||||
});
|
||||
}
|
||||
@@ -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<string, unknown>;
|
||||
}
|
||||
|
||||
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<string, unknown>[] = [];
|
||||
private timer: NodeJS.Timeout | null = null;
|
||||
private readonly seen = new Map<string, { at: number; repeats: number }>();
|
||||
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<string, unknown> = {}, 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<void> {
|
||||
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<string, unknown>) : 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, "<id>").replace(/\d+/g, "<n>").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 }),
|
||||
});
|
||||
}
|
||||
@@ -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");
|
||||
|
||||
@@ -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"));
|
||||
|
||||
@@ -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<string, unknown> }[] };
|
||||
|
||||
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://[email protected]: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");
|
||||
});
|
||||
});
|
||||
@@ -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<string, string | number | boolean | null> };
|
||||
|
||||
const seen = new Set<string>();
|
||||
let queue: ClientEvent[] = [];
|
||||
let timer: ReturnType<typeof setTimeout> | 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<string, string | number | boolean | null> = {}): 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);
|
||||
}
|
||||
}
|
||||
+11
-1
@@ -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(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
|
||||
@@ -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<void> {
|
||||
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);
|
||||
});
|
||||
@@ -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 (
|
||||
<html lang="pt">
|
||||
<body>{children}</body>
|
||||
<body>
|
||||
<ErrorReporter />
|
||||
{children}
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -49,6 +53,7 @@ export default async function RootLayout({ children }: { children: ReactNode })
|
||||
return (
|
||||
<html lang="pt" data-skin={site.skin} style={site.settings.accent ? ({ "--accent": site.settings.accent } as React.CSSProperties) : undefined}>
|
||||
<body>
|
||||
<ErrorReporter />
|
||||
<header className="bar">
|
||||
<div className="wrap">
|
||||
<Link href="/">
|
||||
|
||||
@@ -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<string>();
|
||||
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;
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
};
|
||||
@@ -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`.
|
||||
Reference in new issue
Block a user