From 0d2bd5eb95e855f01add06371b401d79adbe86d5 Mon Sep 17 00:00:00 2001 From: Peter Spark Date: Sat, 4 Apr 2026 00:18:52 +0000 Subject: [PATCH] feat: add Node.js and PHP error reporter client libraries (BIT-750) Lightweight drop-in clients for sending errors to the ingest API: - clients/node/errorReporter.mjs (ESM) and .cjs (CommonJS) - clients/php/ErrorReporter.php (PHP 8+) Both use Bearer auth against /v1/ingest/events, fire-and-forget, zero external dependencies. Paperclip-Agent: peter-spark Paperclip-Issue: BIT-750 Paperclip-Run: c2c29aef-e79f-4e69-98ed-3353d04b7a6d --- clients/node/errorReporter.cjs | 102 +++++++++++++++++ clients/node/errorReporter.mjs | 136 +++++++++++++++++++++++ clients/php/ErrorReporter.php | 196 +++++++++++++++++++++++++++++++++ 3 files changed, 434 insertions(+) create mode 100644 clients/node/errorReporter.cjs create mode 100644 clients/node/errorReporter.mjs create mode 100644 clients/php/ErrorReporter.php diff --git a/clients/node/errorReporter.cjs b/clients/node/errorReporter.cjs new file mode 100644 index 0000000..a745812 --- /dev/null +++ b/clients/node/errorReporter.cjs @@ -0,0 +1,102 @@ +/** + * BitReport Error Reporter — lightweight Node.js client (CommonJS). + * See errorReporter.mjs for full docs. + */ +'use strict'; + +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; + +function initReporter(opts) { + opts = 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 != null ? opts.disabled : process.env.ERROR_REPORTING_DISABLED === '1'; + + if (!_disabled && _token) { + process.on('uncaughtException', function (err) { + reportError(err, { uncaught: true }); + setTimeout(function () { throw err; }, 200); + }); + process.on('unhandledRejection', function (reason) { + var e = reason instanceof Error ? reason : new Error(String(reason)); + reportError(e, { unhandledRejection: true }); + }); + } +} + +function reportError(err, context) { + if (_disabled || !_token) return; + context = context || {}; + var msg = (err && err.message) || String(err); + var stack = (err && err.stack) || ''; + var fileMatch = stack.match(/at\s+.+?\((.+?):(\d+):\d+\)|at\s+(.+?):(\d+):\d+/); + var filePath = (fileMatch && (fileMatch[1] || fileMatch[3])) || ''; + var lineNumber = parseInt((fileMatch && (fileMatch[2] || fileMatch[4])) || '0', 10); + + _enqueue({ + schema_version: 1, + occurred_at: new Date().toISOString(), + level: 'error', + message: msg, + stacktrace: stack, + context: Object.assign({ + file_path: filePath, + line_number: lineNumber || undefined, + error_type: (err && err.constructor && err.constructor.name) || 'Error', + error_code: (err && err.code) || undefined, + }, context), + }); +} + +function reportMessage(message, level, context) { + if (_disabled || !_token) return; + _enqueue({ + schema_version: 1, + occurred_at: new Date().toISOString(), + level: level || 'error', + message: message, + context: context || {}, + }); +} + +async function flush() { + if (_flushTimer) { clearTimeout(_flushTimer); _flushTimer = null; } + while (_queue.length > 0) { + var batch = _queue.splice(0, BATCH_SIZE); + await _send(batch); + } +} + +function _enqueue(event) { + _queue.push(event); + if (_queue.length >= BATCH_SIZE) { + flush().catch(function () {}); + } else if (!_flushTimer) { + _flushTimer = setTimeout(function () { _flushTimer = null; flush().catch(function () {}); }, FLUSH_MS); + if (_flushTimer.unref) _flushTimer.unref(); + } +} + +async function _send(events) { + if (!events.length) return; + try { + var ctrl = new AbortController(); + var timer = setTimeout(function () { ctrl.abort(); }, TIMEOUT_MS); + await fetch(_endpoint + '/v1/ingest/events', { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + _token }, + body: JSON.stringify({ events: events }), + signal: ctrl.signal, + }); + clearTimeout(timer); + } catch (_) { /* fire-and-forget */ } +} + +module.exports = { initReporter, reportError, reportMessage, flush }; diff --git a/clients/node/errorReporter.mjs b/clients/node/errorReporter.mjs new file mode 100644 index 0000000..3887012 --- /dev/null +++ b/clients/node/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/clients/php/ErrorReporter.php b/clients/php/ErrorReporter.php new file mode 100644 index 0000000..ee78077 --- /dev/null +++ b/clients/php/ErrorReporter.php @@ -0,0 +1,196 @@ + true, 'errno' => $err['type']] + ); + }); + + set_exception_handler(static function (\Throwable $e): void { + self::reportThrowable($e, ['uncaught' => true]); + error_log('Uncaught ' . $e::class . ': ' . $e->getMessage() . ' @ ' . $e->getFile() . ':' . $e->getLine()); + if (!headers_sent()) { + header('HTTP/1.1 500 Internal Server Error'); + } + echo 'Internal Server Error'; + exit(1); + }); + } + + public static function reportThrowable(\Throwable $e, array $context = []): void + { + $severity = ($e instanceof \Error) ? 'critical' : 'error'; + self::reportMessage( + $e->getMessage(), + $severity, + $e->getFile(), + $e->getLine(), + $e->getTraceAsString(), + array_merge(['error_type' => $e::class], $context) + ); + } + + /** + * @param array $context + */ + public static function reportMessage( + string $message, + string $level = 'error', + string $filePath = '', + int $lineNumber = 0, + string $stackTrace = '', + array $context = [] + ): void { + if (!self::isConfigured()) { + return; + } + + $ctx = array_merge([ + 'file_path' => $filePath, + 'line_number' => $lineNumber ?: null, + 'php_sapi' => PHP_SAPI, + 'request_uri' => $_SERVER['REQUEST_URI'] ?? null, + 'http_method' => $_SERVER['REQUEST_METHOD'] ?? null, + 'ip_address' => $_SERVER['REMOTE_ADDR'] ?? null, + ], $context); + + // Remove null values + $ctx = array_filter($ctx, static fn($v) => $v !== null && $v !== ''); + + $event = [ + 'schema_version' => 1, + 'occurred_at' => gmdate('Y-m-d\TH:i:s.v\Z'), + 'level' => $level, + 'message' => $message, + ]; + if ($stackTrace !== '') { + $event['stacktrace'] = $stackTrace; + } + if (!empty($ctx)) { + $event['context'] = $ctx; + } + + $payload = json_encode(['events' => [$event]], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); + if ($payload === false) { + return; + } + + self::post($payload); + } + + private static function post(string $json): void + { + $url = self::endpoint(); + $token = self::token(); + $headers = [ + 'Content-Type: application/json', + 'Authorization: Bearer ' . $token, + ]; + + try { + if (function_exists('curl_init')) { + $ch = curl_init($url); + if ($ch === false) return; + curl_setopt_array($ch, [ + CURLOPT_POST => true, + CURLOPT_POSTFIELDS => $json, + CURLOPT_HTTPHEADER => $headers, + CURLOPT_RETURNTRANSFER => true, + CURLOPT_TIMEOUT => 4, + CURLOPT_CONNECTTIMEOUT => 2, + CURLOPT_PROTOCOLS => CURLPROTO_HTTP | CURLPROTO_HTTPS, + ]); + @curl_exec($ch); + curl_close($ch); + return; + } + + $headerStr = implode("\r\n", $headers); + $ctx = stream_context_create([ + 'http' => [ + 'method' => 'POST', + 'header' => $headerStr . "\r\n", + 'content' => $json, + 'timeout' => 4, + 'ignore_errors' => true, + ], + ]); + @file_get_contents($url, false, $ctx); + } catch (\Throwable $e) { + error_log('BitReport\\ErrorReporter: send failed: ' . $e->getMessage()); + } + } +}