diff --git a/deploy/systemd/writer-andebol.env.example b/deploy/systemd/writer-andebol.env.example index 0c6fd5a..778e0da 100644 --- a/deploy/systemd/writer-andebol.env.example +++ b/deploy/systemd/writer-andebol.env.example @@ -18,3 +18,11 @@ ANDEBOL_WP_APP_PASSWORD=xxxx xxxx xxxx xxxx xxxx xxxx # WRITER_WEBDAV_USER= # WRITER_WEBDAV_PASSWORD= # WRITER_WEBDAV_DEFAULT_CREDIT=Foto: … (line used as WP media caption when filename has no Credit___pattern) + +# Error hub ingest (errors.bitreport.pt) — token from vault only; never commit real values (BIT-25125) +# ERROR_REPORTING_ENDPOINT=https://errors.bitreport.pt +# ERROR_REPORTING_TOKEN= +ERROR_REPORTING_PROJECT_NAME=news-platform-writer-pipeline +ERROR_REPORTING_PROJECT_SLUG=news-platform +ERROR_REPORTING_GITEA_REPO=BitReport.pt/news-platform +# ERROR_REPORTING_DISABLED=1 diff --git a/writer-pipeline/.env.example b/writer-pipeline/.env.example index 840b6fc..580ef07 100644 --- a/writer-pipeline/.env.example +++ b/writer-pipeline/.env.example @@ -6,3 +6,11 @@ # Optional: aggregator HTTP service (default 127.0.0.1:3310) # AGGREGATOR_PORT=3310 # AGGREGATOR_STORE_PATH=/opt/bitreport/news-platform/writer-pipeline/var/aggregated-items.json + +# Error hub (errors.bitreport.pt) — see deploy/systemd/writer-andebol.env.example (BIT-25125) +# ERROR_REPORTING_ENDPOINT=https://errors.bitreport.pt +# ERROR_REPORTING_TOKEN= +# ERROR_REPORTING_PROJECT_NAME=news-platform-writer-pipeline +# ERROR_REPORTING_PROJECT_SLUG=news-platform +# ERROR_REPORTING_GITEA_REPO=BitReport.pt/news-platform +# ERROR_REPORTING_DISABLED=1 diff --git a/writer-pipeline/src/cycle-error-report.test.ts b/writer-pipeline/src/cycle-error-report.test.ts new file mode 100644 index 0000000..f15b22f --- /dev/null +++ b/writer-pipeline/src/cycle-error-report.test.ts @@ -0,0 +1,25 @@ +import { describe, it } from 'node:test'; +import assert from 'node:assert/strict'; +import { initReporter, reportMessage, flush } from './lib/errorReporter.js'; +import { reportCycleErrors } from './lib/cycle-error-report.js'; + +describe('errorReporter', () => { + it('no-ops when disabled without token', async () => { + initReporter({ disabled: true, token: '' }); + reportMessage('test ingest failure', 'error', { site: 'andebol.net' }); + await flush(); + assert.ok(true); + }); +}); + +describe('reportCycleErrors', () => { + it('maps ingest error strings without throwing when reporter disabled', async () => { + initReporter({ disabled: true, token: '' }); + reportCycleErrors('andebol.net', [ + 'rss fpa (https://example.com/feed): timeout', + 'sitemap fpa: no pathIncludes and 500 URLs — truncating to 200 before maxItems', + ]); + await flush(); + assert.ok(true); + }); +}); diff --git a/writer-pipeline/src/lib/cycle-error-report.ts b/writer-pipeline/src/lib/cycle-error-report.ts new file mode 100644 index 0000000..db47def --- /dev/null +++ b/writer-pipeline/src/lib/cycle-error-report.ts @@ -0,0 +1,26 @@ +import { reportError, reportMessage } from './errorReporter.js'; + +/** Report writer-pipeline cycle failures to errors.bitreport.pt (ingest, publish, config). */ +export function reportCycleErrors( + site: string, + errors: string[], + context: Record = {}, +): void { + for (const message of errors) { + const level = message.startsWith('sitemap') && message.includes('truncating') ? 'warning' : 'error'; + reportMessage(message, level, { + site, + component: 'writer-pipeline', + ...context, + }); + } +} + +export function reportCycleFailure(site: string, err: unknown, context: Record = {}): void { + const error = err instanceof Error ? err : new Error(String(err)); + reportError(error, { + site, + component: 'writer-pipeline', + ...context, + }); +} diff --git a/writer-pipeline/src/lib/errorReporter.ts b/writer-pipeline/src/lib/errorReporter.ts new file mode 100644 index 0000000..bd0214a --- /dev/null +++ b/writer-pipeline/src/lib/errorReporter.ts @@ -0,0 +1,138 @@ +/** + * BitReport Error Reporter — lightweight Node.js client for errors.bitreport.pt + * + * Shared implementation with bridge/src/lib/errorReporter.ts (keep in sync). + * Zero dependencies (uses native fetch). + */ + +let _token = ''; +let _endpoint = 'https://errors.bitreport.pt'; +let _disabled = false; +let _projectName = process.env['ERROR_REPORTING_PROJECT_NAME'] || 'news-platform-writer-pipeline'; +let _projectSlug = process.env['ERROR_REPORTING_PROJECT_SLUG'] || 'news-platform'; +let _giteaRepo = process.env['ERROR_REPORTING_GITEA_REPO'] || 'BitReport.pt/news-platform'; +const _queue: Record[] = []; +let _flushTimer: ReturnType | null = null; +const BATCH_SIZE = 25; +const FLUSH_MS = 5000; +const TIMEOUT_MS = 8000; + +type ReporterOpts = { + token?: string; + endpoint?: string; + disabled?: boolean; + projectName?: string; + projectSlug?: string; + giteaRepo?: string; +}; + +export function initReporter(opts: ReporterOpts = {}): void { + _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'; + _projectName = opts.projectName || process.env['ERROR_REPORTING_PROJECT_NAME'] || _projectName; + _projectSlug = opts.projectSlug || process.env['ERROR_REPORTING_PROJECT_SLUG'] || _projectSlug; + _giteaRepo = opts.giteaRepo || process.env['ERROR_REPORTING_GITEA_REPO'] || _giteaRepo; + + if (!_disabled && _token) { + process.on('uncaughtException', (err: Error) => { + reportError(err, { uncaught: true }); + setTimeout(() => { + throw err; + }, 200); + }); + process.on('unhandledRejection', (reason: unknown) => { + const err = reason instanceof Error ? reason : new Error(String(reason)); + reportError(err, { unhandledRejection: true }); + }); + } +} + +export function reportError(err: Error, context: Record = {}): void { + 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 as NodeJS.ErrnoException)?.code || undefined, + project_name: _projectName, + project_slug: _projectSlug, + gitea_repo: _giteaRepo, + ...context, + }, + }); +} + +export function reportMessage( + message: string, + level: 'error' | 'warning' | 'info' | 'critical' = 'error', + context: Record = {}, +): void { + if (_disabled || !_token) return; + _enqueue({ + schema_version: 1, + occurred_at: new Date().toISOString(), + level, + message, + context: { project_name: _projectName, project_slug: _projectSlug, gitea_repo: _giteaRepo, ...context }, + }); +} + +export async function flush(): Promise { + if (_flushTimer) { + clearTimeout(_flushTimer); + _flushTimer = null; + } + while (_queue.length > 0) { + const batch = _queue.splice(0, BATCH_SIZE); + await _send(batch); + } +} + +function _enqueue(event: Record): void { + _queue.push(event); + if (_queue.length >= BATCH_SIZE) { + void flush().catch(() => {}); + } else if (!_flushTimer) { + _flushTimer = setTimeout(() => { + _flushTimer = null; + void flush().catch(() => {}); + }, FLUSH_MS); + if (_flushTimer.unref) _flushTimer.unref(); + } +} + +async function _send(events: Record[]): Promise { + 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/writer-pipeline/src/run-cycle.ts b/writer-pipeline/src/run-cycle.ts index e619871..908800b 100644 --- a/writer-pipeline/src/run-cycle.ts +++ b/writer-pipeline/src/run-cycle.ts @@ -21,6 +21,10 @@ import { import type { AggregatedItem, CycleMetrics } from './types.js'; import { createDraftFromAggregatedItem } from './wp-publish.js'; import { wpCredentialsForSite } from './wp-site-env.js'; +import { initReporter, flush } from './lib/errorReporter.js'; +import { reportCycleErrors, reportCycleFailure } from './lib/cycle-error-report.js'; + +initReporter(); const __dirname = path.dirname(fileURLToPath(import.meta.url)); const PKG_ROOT = path.resolve(__dirname, '..'); @@ -132,10 +136,19 @@ async function main(): Promise { await appendMetrics(metricsPath, metrics); console.log(JSON.stringify(metrics, null, 2)); - if (errors.length) process.exitCode = 1; + + if (errors.length) { + reportCycleErrors(site, errors, { cycleId, dryRun }); + await flush(); + process.exitCode = 1; + } } -main().catch((e) => { +main().catch(async (e) => { console.error(e); + reportCycleFailure(argValue('--site', process.argv.slice(2)) ?? 'andebol.net', e, { + phase: 'run-cycle', + }); + await flush(); process.exit(1); });