From cd13a334c23afeef89a5e15cce0e9cdc6520937c Mon Sep 17 00:00:00 2001 From: Artur Moreira Date: Sat, 4 Apr 2026 00:19:13 +0000 Subject: [PATCH] feat(bridge): integrate errors.bitreport.pt error reporting (BIT-750) Report 5xx errors from the Fastify error handler to the central ingest API. Enabled when ERROR_REPORTING_TOKEN is set in the environment. Paperclip-Agent: peter-spark Paperclip-Issue: BIT-750 Paperclip-Run: c2c29aef-e79f-4e69-98ed-3353d04b7a6d --- bridge/src/lib/errorReporter.mjs | 136 +++++++++++++++++++++++++++++++ bridge/src/server.ts | 5 ++ 2 files changed, 141 insertions(+) create mode 100644 bridge/src/lib/errorReporter.mjs diff --git a/bridge/src/lib/errorReporter.mjs b/bridge/src/lib/errorReporter.mjs new file mode 100644 index 0000000..3887012 --- /dev/null +++ b/bridge/src/lib/errorReporter.mjs @@ -0,0 +1,136 @@ +/** + * BitReport Error Reporter — lightweight Node.js client for errors.bitreport.pt + * + * Zero dependencies (uses native fetch). Drop this file into any Node.js 18+ project. + * + * Usage: + * import { initReporter, reportError, reportMessage } from './errorReporter.mjs'; + * initReporter({ token: process.env.ERROR_REPORTING_TOKEN, endpoint: 'https://errors.bitreport.pt' }); + * reportError(err, { url: '/api/foo', method: 'POST' }); + * + * Environment variables (alternative to initReporter options): + * ERROR_REPORTING_TOKEN — ingest API key (Bearer token) + * ERROR_REPORTING_ENDPOINT — base URL (default: https://errors.bitreport.pt) + * ERROR_REPORTING_DISABLED — set to "1" to disable + */ + +let _token = ''; +let _endpoint = 'https://errors.bitreport.pt'; +let _disabled = false; +const _queue = []; +let _flushTimer = null; +const BATCH_SIZE = 25; +const FLUSH_MS = 5000; +const TIMEOUT_MS = 8000; + +/** + * Initialise the reporter. Call once at startup. + * @param {{ token?: string, endpoint?: string, disabled?: boolean }} opts + */ +export function initReporter(opts = {}) { + _token = opts.token || process.env.ERROR_REPORTING_TOKEN || ''; + _endpoint = (opts.endpoint || process.env.ERROR_REPORTING_ENDPOINT || 'https://errors.bitreport.pt').replace(/\/$/, ''); + _disabled = opts.disabled ?? process.env.ERROR_REPORTING_DISABLED === '1'; + + if (!_disabled && _token) { + process.on('uncaughtException', (err) => { + reportError(err, { uncaught: true }); + // Re-throw after reporting so the process still crashes + setTimeout(() => { throw err; }, 200); + }); + process.on('unhandledRejection', (reason) => { + const err = reason instanceof Error ? reason : new Error(String(reason)); + reportError(err, { unhandledRejection: true }); + }); + } +} + +/** + * Report an Error object. + * @param {Error} err + * @param {Record} [context] + */ +export function reportError(err, context = {}) { + if (_disabled || !_token) return; + const msg = err?.message || String(err); + const stack = err?.stack || ''; + const fileMatch = stack.match(/at\s+.+?\((.+?):(\d+):\d+\)|at\s+(.+?):(\d+):\d+/); + const filePath = fileMatch?.[1] || fileMatch?.[3] || ''; + const lineNumber = parseInt(fileMatch?.[2] || fileMatch?.[4] || '0', 10); + + _enqueue({ + schema_version: 1, + occurred_at: new Date().toISOString(), + level: 'error', + message: msg, + stacktrace: stack, + context: { + file_path: filePath, + line_number: lineNumber || undefined, + error_type: err?.constructor?.name || 'Error', + error_code: err?.code || undefined, + ...context, + }, + }); +} + +/** + * Report a plain message (warning, info, etc.). + * @param {string} message + * @param {'error'|'warning'|'info'|'critical'} [level] + * @param {Record} [context] + */ +export function reportMessage(message, level = 'error', context = {}) { + if (_disabled || !_token) return; + _enqueue({ + schema_version: 1, + occurred_at: new Date().toISOString(), + level, + message, + context, + }); +} + +/** + * Flush queued events immediately. Call before process exit. + * @returns {Promise} + */ +export async function flush() { + if (_flushTimer) { clearTimeout(_flushTimer); _flushTimer = null; } + while (_queue.length > 0) { + const batch = _queue.splice(0, BATCH_SIZE); + await _send(batch); + } +} + +// --- internals --- + +function _enqueue(event) { + _queue.push(event); + if (_queue.length >= BATCH_SIZE) { + flush().catch(() => {}); + } else if (!_flushTimer) { + _flushTimer = setTimeout(() => { _flushTimer = null; flush().catch(() => {}); }, FLUSH_MS); + if (_flushTimer.unref) _flushTimer.unref(); + } +} + +async function _send(events) { + if (!events.length) return; + try { + const ctrl = new AbortController(); + const timer = setTimeout(() => ctrl.abort(), TIMEOUT_MS); + await fetch(`${_endpoint}/v1/ingest/events`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${_token}`, + }, + body: JSON.stringify({ events }), + signal: ctrl.signal, + }); + clearTimeout(timer); + } catch { + // Fire-and-forget: never crash the host app + } +} diff --git a/bridge/src/server.ts b/bridge/src/server.ts index d7fc089..a547463 100644 --- a/bridge/src/server.ts +++ b/bridge/src/server.ts @@ -1,6 +1,7 @@ import Fastify from 'fastify'; import cors from '@fastify/cors'; import rate_limit from '@fastify/rate-limit'; +import { initReporter, reportError } from './lib/errorReporter.mjs'; import { health_routes } from './routes/health.js'; import { site_config_routes } from './routes/site-config.js'; @@ -9,6 +10,9 @@ import { categories_routes } from './routes/categories.js'; import { homepage_routes } from './routes/homepage.js'; import { writers_routes } from './routes/writers.js'; +// BitReport error reporting (env: ERROR_REPORTING_TOKEN, ERROR_REPORTING_ENDPOINT) +initReporter(); + const PORT = parseInt(process.env['PORT'] ?? '3200', 10); const LOG_LEVEL = process.env['LOG_LEVEL'] ?? 'info'; @@ -51,6 +55,7 @@ app.setErrorHandler((err, req, reply) => { } app.log.error({ url: req.url, err }, 'Unhandled error'); + reportError(err, { url: req.url, method: req.method, route: req.routeOptions?.url }); return reply.code(500).send({ error: 'Internal server error' }); });