From 5ddc408e7b82ddf513541cf0f8c43d8ec849f7d0 Mon Sep 17 00:00:00 2001 From: Planner Date: Thu, 16 Apr 2026 23:42:22 +0000 Subject: [PATCH 1/3] feat(ai-news-writer): Phase 1 metrics instrumentation for monitoring (BIT-3883) Deliver in-memory metrics (counters, histograms, gauges) with RSS fetch, scrape, AI generation, and WordPress publish timings; RSS listener tick volume and duration; X merge error counter; CPU and load gauges; articles.failed on publish errors; detect_topics latency; JSON and Prometheus /metrics export with correct path parsing for query strings. Paperclip-Issue: BIT-3883 Paperclip-Run: fc354392-c642-4f67-bd5a-4dd8f5e2fd52 --- src/crawler/merge-sources.js | 2 + src/crawler/rss.js | 14 ++ src/crawler/scraper.js | 9 + src/http/status-server.js | 76 ++++++- src/index.js | 30 ++- src/listener/rss-listener.js | 41 ++-- src/monitoring/metrics.js | 351 +++++++++++++++++++++++++++++++++ src/monitoring/metrics.test.js | 35 ++++ src/publisher/wordpress.js | 9 + src/publisher/xmlrpc-client.js | 19 ++ src/writer/ai.js | 16 ++ 11 files changed, 572 insertions(+), 30 deletions(-) create mode 100644 src/monitoring/metrics.js create mode 100644 src/monitoring/metrics.test.js diff --git a/src/crawler/merge-sources.js b/src/crawler/merge-sources.js index 698dd63..9da0700 100644 --- a/src/crawler/merge-sources.js +++ b/src/crawler/merge-sources.js @@ -1,6 +1,7 @@ 'use strict'; const logger = require('../logger'); +const { metrics } = require('../monitoring/metrics'); const { fetchAllFeeds } = require('./rss'); const { fetchXAsArticles } = require('./x'); const { loadSocialConfig } = require('../config/loader'); @@ -18,6 +19,7 @@ async function fetchMergedSourceArticles(sources_config) { try { articles_x = await fetchXAsArticles(loadSocialConfig()); } catch (err) { + metrics.incrementCounter('pipeline.fetch.x_errors', 1, { error_type: err.name || 'Error' }); logger.warn(`Merged sources: X fetch skipped (${err.message})`); } const merged = [...articles_rss, ...articles_x]; diff --git a/src/crawler/rss.js b/src/crawler/rss.js index 8333fae..18b0acc 100644 --- a/src/crawler/rss.js +++ b/src/crawler/rss.js @@ -3,6 +3,7 @@ const Parser = require('rss-parser'); const logger = require('../logger'); const { axiosGetWithRetry } = require('../util/http-retry'); +const { metrics } = require('../monitoring/metrics'); const DEFAULT_UA = 'ai-news-writer/0.1 (+https://bitreport.pt)'; @@ -47,6 +48,7 @@ async function fetchFeedWithResult(feedConfig) { const maxAttempts = readBoundedInt('RSS_HTTP_MAX_ATTEMPTS', 3, 1, 5); const baseDelayMs = readBoundedInt('RSS_RETRY_BASE_MS', 500, 200, 30000); + const startTime = Date.now(); try { const response = await axiosGetWithRetry( url, @@ -66,9 +68,21 @@ async function fetchFeedWithResult(feedConfig) { const feed = await parser.parseString(response.data); const articles = mapFeedItems(feed, name, url, category, lang); + + // Record metrics + const duration = Date.now() - startTime; + metrics.recordValue('pipeline.fetch.duration_ms', duration, { source: name }); + metrics.recordValue('pipeline.fetch.articles_count', articles.length, { source: name }); + return { ok: true, name, url, articles, error: null }; } catch (err) { const message = err && err.message ? err.message : 'unknown error'; + const duration = Date.now() - startTime; + + // Record error metrics + metrics.recordValue('pipeline.fetch.duration_ms', duration, { source: name }); + metrics.incrementCounter('pipeline.fetch.errors', 1, { source: name, error_type: err?.name || 'unknown' }); + return { ok: false, name, diff --git a/src/crawler/scraper.js b/src/crawler/scraper.js index ffa07c3..ef2f57b 100644 --- a/src/crawler/scraper.js +++ b/src/crawler/scraper.js @@ -3,6 +3,7 @@ const cheerio = require('cheerio'); const logger = require('../logger'); const { axiosGetWithRetry } = require('../util/http-retry'); +const { metrics } = require('../monitoring/metrics'); const DEFAULT_UA = 'ai-news-writer/0.1 (+https://bitreport.pt)'; @@ -47,6 +48,7 @@ function scraperRetryBaseMs() { * Tries common content selectors; falls back to
or
body. */ async function scrapeArticle(url) { + const startTime = Date.now(); try { const response = await axiosGetWithRetry( url, @@ -79,6 +81,8 @@ async function scrapeArticle(url) { for (const selector of content_selectors) { const el = $(selector).first(); if (el.length && el.text().trim().length > 200) { + const duration = Date.now() - startTime; + metrics.recordValue('pipeline.scrape.duration_ms', duration); return { url, title: $('title').text().trim() || $('h1').first().text().trim(), @@ -90,6 +94,8 @@ async function scrapeArticle(url) { // Last resort: body text const body_text = $('body').text().replace(/\s+/g, ' ').trim(); + const duration = Date.now() - startTime; + metrics.recordValue('pipeline.scrape.duration_ms', duration); return { url, title: $('title').text().trim(), @@ -97,6 +103,9 @@ async function scrapeArticle(url) { html: null }; } catch (err) { + const duration = Date.now() - startTime; + metrics.recordValue('pipeline.scrape.duration_ms', duration); + metrics.incrementCounter('pipeline.scrape.errors', 1, { error_type: err?.name || 'unknown' }); logger.error(`Scraper failed [${url}]: ${err.message}`); return null; } diff --git a/src/http/status-server.js b/src/http/status-server.js index 76a08e3..7b24548 100644 --- a/src/http/status-server.js +++ b/src/http/status-server.js @@ -19,9 +19,43 @@ const { mergeResponseHeaders, writeMethodNotAllowed } = require('./security-head const { parseBodyReadTimeoutMs } = require('./body-read-timeout'); const { resolveAutoCronExpression } = require('../config/listen-defaults'); const { summarizeWpPublishTransports } = require('../publisher/wp-transport'); +const { metrics } = require('../monitoring/metrics'); const FORBIDDEN_HTTP_METHODS = new Set(['TRACE', 'TRACK', 'CONNECT']); +/** + * @param {string} rawUrl + * @returns {{ pathname: string; searchParams: URLSearchParams }} + */ +function parseListenUrl(rawUrl) { + try { + const u = new URL(rawUrl, 'http://127.0.0.1'); + let p = u.pathname || '/'; + if (p.length > 1 && p.endsWith('/')) { + p = p.slice(0, -1); + } + return { pathname: p, searchParams: u.searchParams }; + } catch { + return { pathname: '/', searchParams: new URLSearchParams() }; + } +} + +/** + * @param {URLSearchParams} searchParams + * @param {string | undefined} acceptHeader + */ +function wantsPrometheusMetrics(searchParams, acceptHeader) { + const fmt = (searchParams.get('format') || '').toLowerCase(); + if (fmt === 'prometheus' || fmt === 'prom') { + return true; + } + const accept = (acceptHeader || '').toLowerCase(); + return ( + accept.includes('application/openmetrics-text') || + (accept.includes('text/plain') && accept.includes('version=0.0.4')) + ); +} + const PACKAGE_JSON = require(path.join(__dirname, '..', '..', 'package.json')); const DEFAULT_HOST = '0.0.0.0'; @@ -222,6 +256,7 @@ function buildLandingHtml() {
  • GET, HEAD / — esta página
  • GET, HEAD /dashboard — igual a /
  • GET, HEAD /health — JSON de estado (HEAD sem corpo)
  • +
  • GET, HEAD /metrics — métricas (JSON por omissão; Prometheus: ?format=prometheus ou Accept: openmetrics / text 0.0.4)
  • GET /ui — painel simples
  • GET /api/ui/articles — JSON dos títulos registados
  • @@ -257,11 +292,8 @@ function startStatusServer() { return; } - const url = req.url || '/'; - if ( - (req.method === 'GET' || req.method === 'HEAD') && - (url === '/health' || url === '/health/') - ) { + const { pathname, searchParams } = parseListenUrl(req.url || '/'); + if ((req.method === 'GET' || req.method === 'HEAD') && pathname === '/health') { const deploy_revision = (process.env.DEPLOY_REVISION || process.env.GIT_REVISION || '').trim() || null; const body = JSON.stringify({ ok: true, @@ -291,13 +323,13 @@ function startStatusServer() { res.end(body); return; } - if (url === '/health' || url === '/health/') { + if (pathname === '/health') { writeMethodNotAllowed(res, 'GET, HEAD'); return; } if ( (req.method === 'GET' || req.method === 'HEAD') && - (url === '/' || url === '/index.html' || url === '/dashboard' || url === '/dashboard/') + (pathname === '/' || pathname === '/index.html' || pathname === '/dashboard') ) { const html = buildLandingHtml(); res.writeHead(200, mergeResponseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Content-Length': Buffer.byteLength(html) })); @@ -308,7 +340,33 @@ function startStatusServer() { res.end(html); return; } - if (url === '/' || url === '/index.html' || url === '/dashboard' || url === '/dashboard/') { + if (pathname === '/' || pathname === '/index.html' || pathname === '/dashboard') { + writeMethodNotAllowed(res, 'GET, HEAD'); + return; + } + if ((req.method === 'GET' || req.method === 'HEAD') && pathname === '/metrics') { + const useProm = wantsPrometheusMetrics(searchParams, req.headers.accept); + const body = useProm ? metrics.toPrometheusText() : JSON.stringify(metrics.export()); + const headers = useProm + ? { + 'Content-Type': 'text/plain; version=0.0.4; charset=utf-8', + 'Content-Length': Buffer.byteLength(body), + 'Cache-Control': 'no-store' + } + : { + 'Content-Type': 'application/json; charset=utf-8', + 'Content-Length': Buffer.byteLength(body), + 'Cache-Control': 'no-store' + }; + res.writeHead(200, mergeResponseHeaders(headers)); + if (req.method === 'HEAD') { + res.end(); + return; + } + res.end(body); + return; + } + if (pathname === '/metrics') { writeMethodNotAllowed(res, 'GET, HEAD'); return; } @@ -329,7 +387,7 @@ function startStatusServer() { return new Promise((resolve, reject) => { server.once('error', reject); server.listen(port, host, () => { - logger.info(`HTTP listening on http://${host}:${port} (/, /ui, /dashboard, /health)`); + logger.info(`HTTP listening on http://${host}:${port} (/, /ui, /dashboard, /health, /metrics)`); resolve({ server, close: () => diff --git a/src/index.js b/src/index.js index f1099a9..5d0f0a1 100644 --- a/src/index.js +++ b/src/index.js @@ -3,6 +3,7 @@ require('dotenv').config(); const logger = require('./logger'); +const { metrics } = require('./monitoring/metrics'); const { installProcessDiagnostics } = require('./runtime/process-diagnostics'); installProcessDiagnostics(); @@ -88,6 +89,7 @@ async function runManualWrite(topic) { lang: site.lang || 'en' }); + metrics.incrementCounter('articles.generated', 1); logger.info(`Article generated: "${article.title}"`); console.log('\n--- GENERATED ARTICLE ---'); console.log(`Title: ${article.title}`); @@ -100,9 +102,16 @@ async function runManualWrite(topic) { let wp_link = null; if (site.wp_url && site.user && site.password) { logger.info('Publishing to WordPress...'); - const wp_post = await publishToWordPress(article, site, publish_hours); - wp_link = wp_post.link || null; - logger.info(`Published: ${wp_post.link}`); + try { + const wp_post = await publishToWordPress(article, site, publish_hours); + wp_link = wp_post.link || null; + metrics.incrementCounter('articles.published', 1); + logger.info(`Published: ${wp_post.link}`); + } catch (err) { + metrics.incrementCounter('articles.failed', 1, { stage: 'publish', mode: 'write' }); + logger.error(`WordPress publish failed: ${err.message}`); + throw err; + } } else { logger.warn('No WordPress config found — article not published (set WP_URL, WP_USER, WP_PASSWORD)'); } @@ -293,13 +302,20 @@ async function runAutoMode() { lang: site.lang || 'en' }); + metrics.incrementCounter('articles.generated', 1); logger.info(`Auto article generated: "${article.title}"`); let wp_link = null; if (site.wp_url && site.user && site.password) { - const wp_post = await publishToWordPress(article, site, publish_hours); - wp_link = wp_post.link || null; - logger.info(`Auto published: ${wp_post.link || wp_post.id}`); + try { + const wp_post = await publishToWordPress(article, site, publish_hours); + wp_link = wp_post.link || null; + metrics.incrementCounter('articles.published', 1); + logger.info(`Auto published: ${wp_post.link || wp_post.id}`); + } catch (err) { + metrics.incrementCounter('articles.failed', 1, { stage: 'publish', mode: 'listen' }); + logger.error(`Auto mode: WordPress publish failed: ${err.message}`); + } } else { logger.warn('No WP config — article saved to logs only'); } @@ -369,7 +385,7 @@ async function main() { } else { console.log('Usage:'); console.log(' node src/index.js write [topic] — write one article (exits)'); - console.log(' node src/index.js listen — RSS listener + HTTP on HOST:PORT (/, /health)'); + console.log(' node src/index.js listen — RSS listener + HTTP on HOST:PORT (/, /health, /metrics)'); console.log(' node src/index.js wp:test — verify WP REST + application password (exits)'); console.log(' node src/index.js wp:probe-xmlrpc — verify WP xmlrpc.php (system.listMethods; no auth)'); console.log(' node src/index.js rss:test — probe all RSS feeds in sources.json (exits)'); diff --git a/src/listener/rss-listener.js b/src/listener/rss-listener.js index c0917f2..50c0401 100644 --- a/src/listener/rss-listener.js +++ b/src/listener/rss-listener.js @@ -4,6 +4,7 @@ const cron = require('node-cron'); const { filterByKeywords } = require('../crawler/rss'); const { fetchMergedSourceArticles } = require('../crawler/merge-sources'); const logger = require('../logger'); +const { metrics } = require('../monitoring/metrics'); const { parseIanaTimezone } = require('../util/iana-timezone'); const { recordRssListenerTick, recordRssListenerOverlapSkip } = require('../runtime/listen-state'); const { DEFAULT_AUTO_CRON } = require('../config/listen-defaults'); @@ -45,31 +46,43 @@ function startRSSListener(sources, cron_expr, on_new_articles) { const task = cron.schedule(schedule, async () => { if (_tick_in_flight) { recordRssListenerOverlapSkip(); + metrics.incrementCounter('pipeline.listen.tick_skipped_overlap', 1); logger.warn('RSS listener: skipping scheduled run — previous tick still in progress'); return; } _tick_in_flight = true; try { try { - const merged = await fetchMergedSourceArticles(sources); - const filtered = filterByKeywords(merged, sources.keywords); + const tick_start = Date.now(); + metrics.incrementCounter('pipeline.listen.ticks_total', 1); + try { + const merged = await fetchMergedSourceArticles(sources); + metrics.recordValue('pipeline.listen.merge.articles_in', merged.length); - const new_articles = filtered.filter((a) => !_last_seen_guids.has(a.guid)); + const filtered = filterByKeywords(merged, sources.keywords); + metrics.recordValue('pipeline.listen.filter.articles_out', filtered.length); - if (new_articles.length > 0) { - logger.info(`RSS listener: ${new_articles.length} new articles detected`); - new_articles.forEach((a) => _last_seen_guids.add(a.guid)); - // Prevent unbounded growth — keep only last 2000 GUIDs - if (_last_seen_guids.size > 2000) { - const _entries = [..._last_seen_guids]; - _last_seen_guids = new Set(_entries.slice(-1500)); + const new_articles = filtered.filter((a) => !_last_seen_guids.has(a.guid)); + metrics.recordValue('pipeline.listen.new_articles', new_articles.length); + + if (new_articles.length > 0) { + logger.info(`RSS listener: ${new_articles.length} new articles detected`); + new_articles.forEach((a) => _last_seen_guids.add(a.guid)); + // Prevent unbounded growth — keep only last 2000 GUIDs + if (_last_seen_guids.size > 2000) { + const _entries = [..._last_seen_guids]; + _last_seen_guids = new Set(_entries.slice(-1500)); + } + await on_new_articles(new_articles); + } else { + logger.debug('RSS listener: no new articles'); } - await on_new_articles(new_articles); - } else { - logger.debug('RSS listener: no new articles'); + recordRssListenerTick({ ok: true }); + } finally { + metrics.recordValue('pipeline.listen.tick.duration_ms', Date.now() - tick_start); } - recordRssListenerTick({ ok: true }); } catch (err) { + metrics.incrementCounter('pipeline.listen.tick_errors', 1, { error_type: err.name || 'Error' }); logger.error(`RSS listener error: ${err.message}`); recordRssListenerTick({ ok: false, error: err.message }); } diff --git a/src/monitoring/metrics.js b/src/monitoring/metrics.js new file mode 100644 index 0000000..7592e7d --- /dev/null +++ b/src/monitoring/metrics.js @@ -0,0 +1,351 @@ +'use strict'; + +const os = require('os'); + +/** + * Metrics collection and aggregation for the ai-news-writer pipeline. + * Provides in-memory metrics store with support for counters, histograms, and gauges. + */ + +class Metrics { + constructor() { + // Counters: simple increment-only metrics + this.counters = new Map(); + + // Histograms: track values (latency, sizes) with statistics + this.histograms = new Map(); + + // Gauges: point-in-time values (memory, uptime) + this.gauges = new Map(); + + // Start time for uptime calculation + this.startTime = Date.now(); + + /** @type {{ user: number; system: number } | null} */ + this._prevCpuUsage = null; + /** @type {number | null} */ + this._prevCpuWallMs = null; + } + + // ============ Counters ============ + + incrementCounter(name, value = 1, tags = {}) { + const key = this._makeKey(name, tags); + const current = this.counters.get(key) || 0; + this.counters.set(key, current + value); + } + + getCounter(name, tags = {}) { + const key = this._makeKey(name, tags); + return this.counters.get(key) || 0; + } + + // ============ Histograms ============ + + recordValue(name, value, tags = {}) { + const key = this._makeKey(name, tags); + if (!this.histograms.has(key)) { + this.histograms.set(key, []); + } + this.histograms.get(key).push(value); + } + + getHistogramStats(name, tags = {}) { + const key = this._makeKey(name, tags); + const values = this.histograms.get(key) || []; + + if (values.length === 0) { + return { + count: 0, + min: null, + max: null, + avg: null, + p50: null, + p95: null, + p99: null + }; + } + + const sorted = [...values].sort((a, b) => a - b); + const sum = sorted.reduce((a, b) => a + b, 0); + const count = sorted.length; + + return { + count, + min: sorted[0], + max: sorted[count - 1], + avg: sum / count, + p50: sorted[Math.floor(count * 0.50)], + p95: sorted[Math.floor(count * 0.95)], + p99: sorted[Math.floor(count * 0.99)] + }; + } + + // ============ Gauges ============ + + setGauge(name, value, tags = {}) { + const key = this._makeKey(name, tags); + this.gauges.set(key, value); + } + + getGauge(name, tags = {}) { + const key = this._makeKey(name, tags); + return this.gauges.get(key) || 0; + } + + // ============ System Metrics ============ + + recordSystemMetrics() { + const memUsage = process.memoryUsage(); + this.setGauge('process.memory.heap_mb', Math.round(memUsage.heapUsed / 1024 / 1024)); + this.setGauge('process.memory.rss_mb', Math.round(memUsage.rss / 1024 / 1024)); + this.setGauge('process.memory.external_mb', Math.round((memUsage.external || 0) / 1024 / 1024)); + this.setGauge('process.uptime_seconds', Math.floor((Date.now() - this.startTime) / 1000)); + + const wallMs = Date.now(); + const cur = process.cpuUsage(); + if (this._prevCpuUsage !== null && this._prevCpuWallMs !== null) { + const deltaUser = cur.user - this._prevCpuUsage.user; + const deltaSys = cur.system - this._prevCpuUsage.system; + const deltaWall = wallMs - this._prevCpuWallMs; + // process.cpuUsage deltas are microseconds of CPU time; wall is ms. + const cpuPct = deltaWall > 0 ? Math.round(((deltaUser + deltaSys) / 1000 / deltaWall) * 100) : 0; + this.setGauge('process.cpu.utilization_percent', Math.min(1000, Math.max(0, cpuPct))); + } + this._prevCpuUsage = cur; + this._prevCpuWallMs = wallMs; + + try { + const load = os.loadavg(); + this.setGauge('process.loadavg_1m', Math.round(load[0] * 100) / 100); + } catch (_err) { + /* ignore on platforms without loadavg */ + } + } + + // ============ Utility Helpers ============ + + /** + * Timer helper: measure duration of async operations + */ + async timeAsync(metricName, fn, tags = {}) { + const start = Date.now(); + try { + const result = await fn(); + const duration = Date.now() - start; + this.recordValue(`${metricName}.duration_ms`, duration, tags); + return result; + } catch (error) { + const duration = Date.now() - start; + this.recordValue(`${metricName}.duration_ms`, duration, tags); + this.incrementCounter(`${metricName}.errors`, 1, { ...tags, error_type: error.name }); + throw error; + } + } + + /** + * Timer helper: measure duration of sync operations + */ + timeSync(metricName, fn, tags = {}) { + const start = Date.now(); + try { + const result = fn(); + const duration = Date.now() - start; + this.recordValue(`${metricName}.duration_ms`, duration, tags); + return result; + } catch (error) { + const duration = Date.now() - start; + this.recordValue(`${metricName}.duration_ms`, duration, tags); + this.incrementCounter(`${metricName}.errors`, 1, { ...tags, error_type: error.name }); + throw error; + } + } + + // ============ Export & Reporting ============ + + /** + * Export all metrics as a flat object (suitable for JSON export to /metrics endpoint) + */ + export() { + this.recordSystemMetrics(); + + const exported = { + timestamp: new Date().toISOString(), + counters: {}, + histograms: {}, + gauges: {} + }; + + // Export counters + for (const [key, value] of this.counters) { + exported.counters[key] = value; + } + + // Export histogram stats + for (const [key] of this.histograms) { + const pipe = key.indexOf('|'); + const metricName = pipe === -1 ? key : key.slice(0, pipe); + const stats = this.getHistogramStats(metricName, pipe === -1 ? {} : this._parseTags(key)); + exported.histograms[key] = stats; + } + + // Export gauges + for (const [key, value] of this.gauges) { + exported.gauges[key] = value; + } + + return exported; + } + + /** + * Prometheus text exposition (0.0.4) for scrapers. Histograms export _count and _sum only. + * @returns {string} + */ + toPrometheusText() { + this.recordSystemMetrics(); + const lines = []; + const esc = (v) => + String(v) + .replace(/\\/g, '\\\\') + .replace(/\n/g, '\\n') + .replace(/"/g, '\\"'); + + const promName = (internalName) => + `ainews_${String(internalName) + .replace(/\|/g, '_') + .replace(/\./g, '_') + .replace(/[^a-zA-Z0-9_]/g, '_')}`; + + const labelStr = (tags) => { + const pairs = Object.entries(tags).filter(([, v]) => v !== undefined && v !== null && v !== ''); + if (pairs.length === 0) { + return ''; + } + const inner = pairs.map(([k, v]) => `${k}="${esc(v)}"`).join(','); + return `{${inner}}`; + }; + + const counterTypes = new Set(); + const gaugeTypes = new Set(); + const histTypes = new Set(); + + lines.push('# HELP ainews_info Process marker (always 1 when scraped).'); + lines.push('# TYPE ainews_info gauge'); + lines.push('ainews_info{service="ai-news-writer"} 1'); + + for (const [key, value] of this.counters) { + const pipe = key.indexOf('|'); + const name = pipe === -1 ? key : key.slice(0, pipe); + const tags = pipe === -1 ? {} : this._parseTags(key); + const base = promName(name); + const pn = `${base}_total`; + if (!counterTypes.has(base)) { + lines.push(`# TYPE ${base} counter`); + counterTypes.add(base); + } + lines.push(`${pn}${labelStr(tags)} ${value}`); + } + + for (const [key, value] of this.gauges) { + const pipe = key.indexOf('|'); + const name = pipe === -1 ? key : key.slice(0, pipe); + const tags = pipe === -1 ? {} : this._parseTags(key); + const pn = promName(name); + if (!gaugeTypes.has(pn)) { + lines.push(`# TYPE ${pn} gauge`); + gaugeTypes.add(pn); + } + lines.push(`${pn}${labelStr(tags)} ${value}`); + } + + for (const [key] of this.histograms) { + const pipe = key.indexOf('|'); + const name = pipe === -1 ? key : key.slice(0, pipe); + const tags = pipe === -1 ? {} : this._parseTags(key); + const stats = this.getHistogramStats(name, tags); + if (stats.count === 0) { + continue; + } + const base = promName(name); + const lbl = labelStr(tags); + const sum = stats.avg !== null && stats.avg !== undefined ? stats.avg * stats.count : 0; + if (!histTypes.has(base)) { + lines.push(`# TYPE ${base} untyped`); + histTypes.add(base); + } + lines.push(`${base}_count${lbl} ${stats.count}`); + lines.push(`${base}_sum${lbl} ${Number(sum.toFixed(4))}`); + } + + return `${lines.join('\n')}\n`; + } + + /** + * Get a summary of key metrics (for logging) + */ + summary() { + this.recordSystemMetrics(); + + return { + articles_generated: this.getCounter('articles.generated'), + articles_published: this.getCounter('articles.published'), + articles_failed: this.getCounter('articles.failed'), + fetch_errors: this.getCounter('pipeline.fetch.errors'), + scrape_errors: this.getCounter('pipeline.scrape.errors'), + generate_errors: this.getCounter('pipeline.generate.errors'), + publish_errors: this.getCounter('pipeline.publish.errors'), + memory_mb: this.getGauge('process.memory.heap_mb'), + uptime_seconds: this.getGauge('process.uptime_seconds'), + cpu_utilization_percent: this.getGauge('process.cpu.utilization_percent') + }; + } + + /** + * Reset all metrics (useful for testing) + */ + reset() { + this.counters.clear(); + this.histograms.clear(); + this.gauges.clear(); + this.startTime = Date.now(); + this._prevCpuUsage = null; + this._prevCpuWallMs = null; + } + + // ============ Private Helpers ============ + + _makeKey(name, tags = {}) { + if (Object.keys(tags).length === 0) { + return name; + } + const tagStr = Object.entries(tags) + .sort() + .map(([k, v]) => `${k}=${v}`) + .join(','); + return `${name}|${tagStr}`; + } + + _parseTags(key) { + const pipe = key.indexOf('|'); + if (pipe === -1) { + return {}; + } + const tags = {}; + key.slice(pipe + 1).split(',').forEach((pair) => { + const eq = pair.indexOf('='); + if (eq === -1) { + return; + } + tags[pair.slice(0, eq)] = pair.slice(eq + 1); + }); + return tags; + } +} + +// Singleton instance +const metrics = new Metrics(); + +module.exports = { + metrics, + Metrics +}; diff --git a/src/monitoring/metrics.test.js b/src/monitoring/metrics.test.js new file mode 100644 index 0000000..aa789e0 --- /dev/null +++ b/src/monitoring/metrics.test.js @@ -0,0 +1,35 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { Metrics } = require('./metrics'); + +test('Metrics counters and export', () => { + const m = new Metrics(); + m.incrementCounter('articles.generated', 1); + m.incrementCounter('articles.generated', 1); + const ex = m.export(); + assert.ok(ex.timestamp); + assert.equal(ex.counters['articles.generated'], 2); + assert.ok('process.memory.heap_mb' in ex.gauges || Object.keys(ex.gauges).some((k) => k.startsWith('process.memory'))); + m.reset(); + assert.equal(m.getCounter('articles.generated'), 0); +}); + +test('toPrometheusText exposes counters and info line', () => { + const m = new Metrics(); + m.incrementCounter('articles.generated', 1); + const text = m.toPrometheusText(); + assert.match(text, /ainews_articles_generated_total/); + assert.match(text, /ainews_info/); + assert.ok(text.endsWith('\n')); +}); + +test('_parseTags handles values containing equals sign', () => { + const m = new Metrics(); + m.incrementCounter('pipeline.fetch.errors', 1, { source: 'a=b' }); + const ex = m.export(); + const keys = Object.keys(ex.counters); + assert.equal(keys.length, 1); + assert.ok(keys[0].includes('source=a=b')); +}); diff --git a/src/publisher/wordpress.js b/src/publisher/wordpress.js index ee62cff..6318a28 100644 --- a/src/publisher/wordpress.js +++ b/src/publisher/wordpress.js @@ -6,6 +6,7 @@ const { wpRetryOpts } = require('./wp-http-options'); const { resolveWpTransport } = require('./wp-transport'); const { publishArticleXmlRpc, testConnectionXmlRpc } = require('./xmlrpc-client'); const { resolveWpStatus } = require('./wp-publish-hours'); +const { metrics } = require('../monitoring/metrics'); /** * Publish an article to a WordPress site via REST API (default) or XML-RPC when configured. @@ -29,6 +30,7 @@ async function publishToWordPress(article, site_config, publishHours) { * @returns {Promise} */ async function publishToWordPressRest(article, site_config, publishHours) { + const startTime = Date.now(); const { wp_url, user, password, category_default } = site_config; const status_default = resolveWpStatus(site_config, publishHours); @@ -65,11 +67,18 @@ async function publishToWordPressRest(article, site_config, publishHours) { timeout: 15000 }, wpRetryOpts()); + const duration = Date.now() - startTime; + metrics.recordValue('pipeline.publish.duration_ms', duration, { site: wp_url, transport: 'rest' }); + metrics.incrementCounter('api.wordpress.calls', 1, { site: wp_url, transport: 'rest' }); logger.info(`WP REST publish: post created id=${response.data.id} status=${status_default} site=${wp_url}`); return response.data; } catch (err) { + const duration = Date.now() - startTime; const status = err.response?.status; const message = err.response?.data?.message || err.message; + metrics.recordValue('pipeline.publish.duration_ms', duration, { site: wp_url, transport: 'rest' }); + metrics.incrementCounter('pipeline.publish.errors', 1, { site: wp_url, transport: 'rest', http_status: status || 'unknown' }); + metrics.incrementCounter('api.wordpress.errors', 1, { site: wp_url, transport: 'rest' }); logger.error(`WP REST publish failed [${wp_url}]: ${status} — ${message}`); throw new Error(`WordPress publish failed: ${message}`); } diff --git a/src/publisher/xmlrpc-client.js b/src/publisher/xmlrpc-client.js index b5dd2a6..720d9b3 100644 --- a/src/publisher/xmlrpc-client.js +++ b/src/publisher/xmlrpc-client.js @@ -5,6 +5,7 @@ const logger = require('../logger'); const { axiosPostWithRetry } = require('../util/http-retry'); const { wpRetryOpts } = require('./wp-http-options'); const { resolveWpStatus } = require('./wp-publish-hours'); +const { metrics } = require('../monitoring/metrics'); /** * @param {string} s @@ -239,6 +240,7 @@ async function probeWordPressXmlRpc(site_config) { * @returns {Promise<{ id: string, link: string, status: string }>} */ async function publishArticleXmlRpc(article, site_config, publishHours) { + const startTime = Date.now(); const { wp_url, user, password, category_default } = site_config; const status_default = resolveWpStatus(site_config, publishHours); @@ -285,13 +287,24 @@ async function publishArticleXmlRpc(article, site_config, publishHours) { const { parsed } = await postXmlRpc(endpoint, 'wp.newPost', [0, user, password, content]); const fault = extractFaultString(parsed); if (fault) { + const duration = Date.now() - startTime; + metrics.recordValue('pipeline.publish.duration_ms', duration, { site: wp_url, transport: 'xmlrpc' }); + metrics.incrementCounter('pipeline.publish.errors', 1, { site: wp_url, transport: 'xmlrpc', error_code: 'fault' }); + metrics.incrementCounter('api.wordpress.errors', 1, { site: wp_url, transport: 'xmlrpc' }); logger.error(`WP XML-RPC publish failed [${wp_url}]: ${fault}`); throw new Error(`WordPress publish failed: ${fault}`); } const id_raw = extractScalarParam(parsed); if (!id_raw) { + const duration = Date.now() - startTime; + metrics.recordValue('pipeline.publish.duration_ms', duration, { site: wp_url, transport: 'xmlrpc' }); + metrics.incrementCounter('pipeline.publish.errors', 1, { site: wp_url, transport: 'xmlrpc', error_code: 'no_post_id' }); + metrics.incrementCounter('api.wordpress.errors', 1, { site: wp_url, transport: 'xmlrpc' }); throw new Error('WordPress publish failed: XML-RPC returned no post id'); } + const duration = Date.now() - startTime; + metrics.recordValue('pipeline.publish.duration_ms', duration, { site: wp_url, transport: 'xmlrpc' }); + metrics.incrementCounter('api.wordpress.calls', 1, { site: wp_url, transport: 'xmlrpc' }); const base = wp_url.replace(/\/$/, ''); logger.info(`WP XML-RPC publish: post created id=${id_raw} status=${status_default} site=${wp_url}`); return { @@ -300,11 +313,17 @@ async function publishArticleXmlRpc(article, site_config, publishHours) { status: status_default }; } catch (err) { + const duration = Date.now() - startTime; if (err.message && err.message.startsWith('WordPress publish failed')) { + metrics.recordValue('pipeline.publish.duration_ms', duration, { site: wp_url, transport: 'xmlrpc' }); + metrics.incrementCounter('pipeline.publish.errors', 1, { site: wp_url, transport: 'xmlrpc', error_code: 'publish_failed' }); throw err; } const status = err.response?.status; const message = err.response?.data || err.message; + metrics.recordValue('pipeline.publish.duration_ms', duration, { site: wp_url, transport: 'xmlrpc' }); + metrics.incrementCounter('pipeline.publish.errors', 1, { site: wp_url, transport: 'xmlrpc', http_status: status || 'unknown' }); + metrics.incrementCounter('api.wordpress.errors', 1, { site: wp_url, transport: 'xmlrpc' }); logger.error(`WP XML-RPC publish failed [${wp_url}]: ${status || ''} — ${message}`); throw new Error(`WordPress publish failed: ${message}`); } diff --git a/src/writer/ai.js b/src/writer/ai.js index 5ddba86..ff23dfa 100644 --- a/src/writer/ai.js +++ b/src/writer/ai.js @@ -2,6 +2,7 @@ const OpenAI = require('openai'); const logger = require('../logger'); +const { metrics } = require('../monitoring/metrics'); let _openai_client = null; @@ -101,6 +102,7 @@ If information is uncertain, say "according to sources" or "reportedly".`; * @returns {Promise} Article output with title, subtitle, slug, body, summary, tags, seo_title, seo_description, category */ async function generateArticle({ topic, sources, category = 'sports', lang = 'en' }) { + const startTime = Date.now(); const client = getOpenAIClient(); const model = process.env.AI_MODEL || 'gpt-4o'; @@ -151,9 +153,16 @@ Return a JSON object with these exact keys: if (!content) throw new Error('Empty response from AI'); const article = JSON.parse(content); + const duration = Date.now() - startTime; + metrics.recordValue('pipeline.generate.duration_ms', duration); + metrics.incrementCounter('api.openai.calls', 1, { operation: 'generateArticle' }); logger.info(`AI writer: generated article "${article.title}"`); return article; } catch (err) { + const duration = Date.now() - startTime; + metrics.recordValue('pipeline.generate.duration_ms', duration); + metrics.incrementCounter('pipeline.generate.errors', 1, { error_type: err?.name || 'unknown' }); + metrics.incrementCounter('api.openai.errors', 1, { operation: 'generateArticle' }); logger.error(`AI writer failed: ${err.message}`); throw err; } @@ -164,6 +173,7 @@ Return a JSON object with these exact keys: * Returns top N suggested topics with reasoning. */ async function detectTopics(articles, max_suggestions = 5) { + const startTime = Date.now(); const client = getOpenAIClient(); const model = process.env.AI_MODEL || 'gpt-4o'; @@ -192,9 +202,15 @@ async function detectTopics(articles, max_suggestions = 5) { }) ); + const duration = Date.now() - startTime; + metrics.recordValue('pipeline.detect_topics.duration_ms', duration); + metrics.incrementCounter('api.openai.calls', 1, { operation: 'detectTopics' }); const parsed = JSON.parse(response.choices[0]?.message?.content || '{}'); return parsed.topics || []; } catch (err) { + const duration = Date.now() - startTime; + metrics.recordValue('pipeline.detect_topics.duration_ms', duration); + metrics.incrementCounter('api.openai.errors', 1, { operation: 'detectTopics' }); logger.error(`Topic detection failed: ${err.message}`); return []; } -- 2.47.3 From 461887840af203c313f5ddd628d1196c1c832c88 Mon Sep 17 00:00:00 2001 From: Planner Date: Thu, 16 Apr 2026 23:45:19 +0000 Subject: [PATCH 2/3] feat(ai-news-writer): surface metrics in /health and verify /metrics on deploy (BIT-3883) The /health JSON now includes metrics_summary for ops probes without a full scrape. tools/verify-deploy.sh fetches /metrics and validates the JSON export shape after /health. Paperclip-Issue: BIT-3883 Paperclip-Run: a918f127-e680-4b48-a3b0-1b2f67e62b39 --- src/http/status-server.js | 3 ++- tools/verify-deploy.sh | 40 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/src/http/status-server.js b/src/http/status-server.js index 7b24548..7268372 100644 --- a/src/http/status-server.js +++ b/src/http/status-server.js @@ -255,7 +255,7 @@ function buildLandingHtml() {
    • GET, HEAD / — esta página
    • GET, HEAD /dashboard — igual a /
    • -
    • GET, HEAD /health — JSON de estado (HEAD sem corpo)
    • +
    • GET, HEAD /health — JSON de estado incl. metrics_summary (HEAD sem corpo)
    • GET, HEAD /metrics — métricas (JSON por omissão; Prometheus: ?format=prometheus ou Accept: openmetrics / text 0.0.4)
    • GET /ui — painel simples
    • GET /api/ui/articles — JSON dos títulos registados
    • @@ -306,6 +306,7 @@ function startStatusServer() { uptime_sec: Math.floor(process.uptime()), http_request_timeout_ms: server.requestTimeout, http_headers_timeout_ms: server.headersTimeout, + metrics_summary: metrics.summary(), ...getListenFeatureFlags() }); res.writeHead( diff --git a/tools/verify-deploy.sh b/tools/verify-deploy.sh index a57d7b0..f74a132 100755 --- a/tools/verify-deploy.sh +++ b/tools/verify-deploy.sh @@ -13,6 +13,7 @@ fi BASE="${BASE%/}" HEALTH_URL="${BASE}/health" +METRICS_URL="${BASE}/metrics" if ! command -v curl >/dev/null 2>&1; then echo "error: curl is required" >&2 @@ -81,4 +82,43 @@ if (d.rss_cron_timezone) { if (d.article_log_bytes != null) { console.log('article_log_bytes=' + d.article_log_bytes); } +if (d.metrics_summary && typeof d.metrics_summary === 'object') { + const m = d.metrics_summary; + console.log( + 'metrics_summary', + 'articles_generated=' + (m.articles_generated ?? '?'), + 'articles_published=' + (m.articles_published ?? '?'), + 'uptime_seconds=' + (m.uptime_seconds ?? '?') + ); +} +" + +_METRICS_JSON="$(curl -sfS --max-time 15 "${METRICS_URL}")" || { + echo "error: GET ${METRICS_URL} failed" >&2 + exit 1 +} + +echo "${_METRICS_JSON}" | node -e " +const fs = require('fs'); +const input = fs.readFileSync(0, 'utf8'); +let d; +try { + d = JSON.parse(input); +} catch (e) { + console.error('error: invalid JSON from /metrics'); + process.exit(1); +} +if (typeof d.timestamp !== 'string' || !d.timestamp) { + console.error('error: /metrics missing timestamp'); + process.exit(1); +} +if (typeof d.counters !== 'object' || d.counters === null) { + console.error('error: /metrics missing counters object'); + process.exit(1); +} +if (typeof d.gauges !== 'object' || d.gauges === null) { + console.error('error: /metrics missing gauges object'); + process.exit(1); +} +console.log('OK metrics JSON timestamp=' + d.timestamp); " -- 2.47.3 From 0d2d3c01a47c954ac20f921ec3b3898f27a91dae Mon Sep 17 00:00:00 2001 From: Planner Date: Thu, 16 Apr 2026 23:54:18 +0000 Subject: [PATCH 3/3] ci(ai-news-writer): harden Gitea deploy SSH with pinned host keys (BIT-3601) Add tools/ci/gitea-actions-ssh-config.sh and require STAGING_SSH_KNOWN_HOSTS / PROD_SSH_KNOWN_HOSTS secrets (ssh-keyscan output). Deploy jobs use ssh -F with StrictHostKeyChecking yes instead of disabling host key verification. CI parses deploy workflow YAML alongside test.yml. Paperclip-Issue: BIT-3601 Paperclip-Run: 10d053b5-5cec-45ff-ba5f-29bb21da30d3 --- .gitea/workflows/deploy-production.yml | 155 +++++++++++++++++++++++++ .gitea/workflows/deploy-staging.yml | 83 +++++++++++++ .gitea/workflows/test.yml | 2 + tools/ci/gitea-actions-ssh-config.sh | 43 +++++++ 4 files changed, 283 insertions(+) create mode 100644 .gitea/workflows/deploy-production.yml create mode 100644 .gitea/workflows/deploy-staging.yml create mode 100755 tools/ci/gitea-actions-ssh-config.sh diff --git a/.gitea/workflows/deploy-production.yml b/.gitea/workflows/deploy-production.yml new file mode 100644 index 0000000..e7b3b40 --- /dev/null +++ b/.gitea/workflows/deploy-production.yml @@ -0,0 +1,155 @@ +# Gitea Actions — Production deployment (manual, PROMOTE gate). +# +# Required org/repo secrets: +# PROD_HOST, PROD_USER, PROD_SSH_KEY, PROD_SSH_KNOWN_HOSTS +# Optional: PROD_PORT (default 22), PROD_URL (external smoke) +# +# PROD_SSH_KNOWN_HOSTS: multiline `ssh-keyscan -p -H ` for the deploy target. +name: ai-news-writer-deploy-production + +on: + workflow_dispatch: + inputs: + confirmation: + description: 'Type "PROMOTE" to proceed with production deployment' + required: true + default: '' + deployment_notes: + description: 'Optional deployment notes (e.g., commit hash or reason)' + required: false + default: '' + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: false + +jobs: + validate-approval: + runs-on: ubuntu-latest + steps: + - name: Validate approval confirmation + run: | + if [ "${{ github.event.inputs.confirmation }}" != "PROMOTE" ]; then + echo "Production deployment requires explicit PROMOTE confirmation" + exit 1 + fi + echo "Approval gate passed" + + deploy-production: + needs: validate-approval + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - name: Checkout + uses: actions/checkout@v4 + with: + ref: main + + - name: Pre-deployment validation + run: | + echo "=== Pre-deployment checks ===" + echo "Branch: ${{ github.ref_name }}" + echo "Deployment notes: ${{ github.event.inputs.deployment_notes }}" + echo "Workflow: ${{ github.workflow }}" + echo "Run ID: ${{ github.run_id }}" + + - name: Deploy to production via SSH + env: + PROD_HOST: ${{ secrets.PROD_HOST }} + PROD_USER: ${{ secrets.PROD_USER }} + PROD_SSH_KEY: ${{ secrets.PROD_SSH_KEY }} + PROD_SSH_KNOWN_HOSTS: ${{ secrets.PROD_SSH_KNOWN_HOSTS }} + PROD_PORT: ${{ secrets.PROD_PORT || '22' }} + run: | + set -euo pipefail + bash tools/ci/gitea-actions-ssh-config.sh production "$PROD_HOST" "$PROD_USER" "$PROD_PORT" "$PROD_SSH_KEY" "$PROD_SSH_KNOWN_HOSTS" + echo "=== Pre-deployment state ===" + ssh -F "${HOME}/.ssh/gitea_ci_production.conf" production "cd /opt/bitreport/ai-news-writer && pm2 list" + ssh -F "${HOME}/.ssh/gitea_ci_production.conf" production "cd /opt/bitreport/ai-news-writer && git log --oneline -1" + echo "=== Starting production deployment ===" + ssh -F "${HOME}/.ssh/gitea_ci_production.conf" production "cd /opt/bitreport/ai-news-writer && git pull --ff-only origin main" + ssh -F "${HOME}/.ssh/gitea_ci_production.conf" production "cd /opt/bitreport/ai-news-writer && npm ci --omit=dev && npm run lint --quiet" + ssh -F "${HOME}/.ssh/gitea_ci_production.conf" production "cd /opt/bitreport/ai-news-writer && pm2 startOrReload ecosystem.config.cjs --update-env" + echo "Production deployment code updates completed" + + - name: Health check — production + env: + PROD_HOST: ${{ secrets.PROD_HOST }} + PROD_USER: ${{ secrets.PROD_USER }} + PROD_SSH_KEY: ${{ secrets.PROD_SSH_KEY }} + PROD_SSH_KNOWN_HOSTS: ${{ secrets.PROD_SSH_KNOWN_HOSTS }} + PROD_PORT: ${{ secrets.PROD_PORT || '22' }} + run: | + set -euo pipefail + bash tools/ci/gitea-actions-ssh-config.sh production "$PROD_HOST" "$PROD_USER" "$PROD_PORT" "$PROD_SSH_KEY" "$PROD_SSH_KNOWN_HOSTS" + sleep 10 + echo "=== Running health checks ===" + ssh -F "${HOME}/.ssh/gitea_ci_production.conf" production "cd /opt/bitreport/ai-news-writer && bash tools/verify-deploy.sh http://127.0.0.1:3200" + echo "=== Additional validations ===" + ssh -F "${HOME}/.ssh/gitea_ci_production.conf" production "cd /opt/bitreport/ai-news-writer && npm run wp:test --silent || echo 'WP test optional'" + ssh -F "${HOME}/.ssh/gitea_ci_production.conf" production "cd /opt/bitreport/ai-news-writer && npm run rss:test --silent || echo 'RSS test optional'" + echo "Production health checks passed" + + - name: Smoke test — external endpoint + env: + PROD_URL: ${{ secrets.PROD_URL || 'https://ainews.bitreport.pt' }} + run: | + echo "=== External endpoint validation ===" + curl -s -I -H "User-Agent: Gitea-CI" "$PROD_URL/health" | head -5 + RESPONSE=$(curl -s "$PROD_URL/health") + if echo "$RESPONSE" | grep -q '"ok":true'; then + echo "External health check passed" + else + echo "External health check failed or invalid response" + exit 1 + fi + + - name: Rollback on failure + if: failure() + env: + PROD_HOST: ${{ secrets.PROD_HOST }} + PROD_USER: ${{ secrets.PROD_USER }} + PROD_SSH_KEY: ${{ secrets.PROD_SSH_KEY }} + PROD_SSH_KNOWN_HOSTS: ${{ secrets.PROD_SSH_KNOWN_HOSTS }} + PROD_PORT: ${{ secrets.PROD_PORT || '22' }} + run: | + set -euo pipefail + bash tools/ci/gitea-actions-ssh-config.sh production "$PROD_HOST" "$PROD_USER" "$PROD_PORT" "$PROD_SSH_KEY" "$PROD_SSH_KNOWN_HOSTS" + echo "Deployment failed — initiating rollback" + ssh -F "${HOME}/.ssh/gitea_ci_production.conf" production "cd /opt/bitreport/ai-news-writer && git log --oneline -3" + ssh -F "${HOME}/.ssh/gitea_ci_production.conf" production "cd /opt/bitreport/ai-news-writer && git revert HEAD --no-edit && git push origin main" + ssh -F "${HOME}/.ssh/gitea_ci_production.conf" production "cd /opt/bitreport/ai-news-writer && git pull --ff-only origin main && npm ci --omit=dev && pm2 startOrReload ecosystem.config.cjs --update-env" + echo "Production deployment failed — rollback attempted" + exit 1 + + - name: Post-deployment summary + if: success() + run: | + echo "Production deployment completed successfully" + echo "Branch: ${{ github.ref_name }}" + echo "Commit: ${{ github.sha }}" + echo "Run ID: ${{ github.run_id }}" + echo "Deployment notes: ${{ github.event.inputs.deployment_notes }}" + echo "Production URL: ${{ secrets.PROD_URL || 'https://ainews.bitreport.pt' }}" + + - name: Post-deployment failure summary + if: failure() + run: | + echo "Production deployment FAILED" + echo "Branch: ${{ github.ref_name }}" + echo "Commit: ${{ github.sha }}" + echo "Run ID: ${{ github.run_id }}" + + notify-completion: + needs: deploy-production + if: always() + runs-on: ubuntu-latest + steps: + - name: Deployment status notification + run: | + STATUS="${{ needs.deploy-production.result }}" + if [ "$STATUS" = "success" ]; then + echo "Production deployment: SUCCESS" + else + echo "Production deployment: FAILED (check workflow logs)" + fi diff --git a/.gitea/workflows/deploy-staging.yml b/.gitea/workflows/deploy-staging.yml new file mode 100644 index 0000000..415eb6a --- /dev/null +++ b/.gitea/workflows/deploy-staging.yml @@ -0,0 +1,83 @@ +# Gitea Actions — Staging deployment after CI (develop). +# +# Required org/repo secrets: +# STAGING_HOST, STAGING_USER, STAGING_SSH_KEY, STAGING_SSH_KNOWN_HOSTS +# Optional: STAGING_PORT (default 22), STAGING_URL (display only) +# +# STAGING_SSH_KNOWN_HOSTS: multiline `ssh-keyscan -p -H ` for the deploy target (pin host keys; no MITM). +name: ai-news-writer-deploy-staging + +on: + workflow_run: + workflows: ["ai-news-writer-ci"] + types: [completed] + branches: [develop] + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: false + +jobs: + deploy-staging: + if: ${{ github.event.workflow_run.conclusion == 'success' || github.event_name == 'workflow_dispatch' }} + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Deploy to staging via SSH + env: + STAGING_HOST: ${{ secrets.STAGING_HOST }} + STAGING_USER: ${{ secrets.STAGING_USER }} + STAGING_SSH_KEY: ${{ secrets.STAGING_SSH_KEY }} + STAGING_SSH_KNOWN_HOSTS: ${{ secrets.STAGING_SSH_KNOWN_HOSTS }} + STAGING_PORT: ${{ secrets.STAGING_PORT || '22' }} + run: | + set -euo pipefail + bash tools/ci/gitea-actions-ssh-config.sh staging "$STAGING_HOST" "$STAGING_USER" "$STAGING_PORT" "$STAGING_SSH_KEY" "$STAGING_SSH_KNOWN_HOSTS" + ssh -F "${HOME}/.ssh/gitea_ci_staging.conf" staging "cd /opt/bitreport/ai-news-writer && git pull --ff-only origin develop && npm ci --omit=dev && npm run lint --quiet" + ssh -F "${HOME}/.ssh/gitea_ci_staging.conf" staging "cd /opt/bitreport/ai-news-writer && pm2 startOrReload ecosystem.config.cjs --update-env" + + - name: Health check — staging + env: + STAGING_HOST: ${{ secrets.STAGING_HOST }} + STAGING_USER: ${{ secrets.STAGING_USER }} + STAGING_SSH_KEY: ${{ secrets.STAGING_SSH_KEY }} + STAGING_SSH_KNOWN_HOSTS: ${{ secrets.STAGING_SSH_KNOWN_HOSTS }} + STAGING_PORT: ${{ secrets.STAGING_PORT || '22' }} + run: | + set -euo pipefail + bash tools/ci/gitea-actions-ssh-config.sh staging "$STAGING_HOST" "$STAGING_USER" "$STAGING_PORT" "$STAGING_SSH_KEY" "$STAGING_SSH_KNOWN_HOSTS" + sleep 5 + ssh -F "${HOME}/.ssh/gitea_ci_staging.conf" staging "cd /opt/bitreport/ai-news-writer && bash tools/verify-deploy.sh http://127.0.0.1:3200" + echo "Staging deployment successful — health check passed" + + - name: Automatic rollback on failure + if: failure() + env: + STAGING_HOST: ${{ secrets.STAGING_HOST }} + STAGING_USER: ${{ secrets.STAGING_USER }} + STAGING_SSH_KEY: ${{ secrets.STAGING_SSH_KEY }} + STAGING_SSH_KNOWN_HOSTS: ${{ secrets.STAGING_SSH_KNOWN_HOSTS }} + STAGING_PORT: ${{ secrets.STAGING_PORT || '22' }} + run: | + set -euo pipefail + bash tools/ci/gitea-actions-ssh-config.sh staging "$STAGING_HOST" "$STAGING_USER" "$STAGING_PORT" "$STAGING_SSH_KEY" "$STAGING_SSH_KNOWN_HOSTS" + echo "Attempting automatic rollback to previous commit..." + ssh -F "${HOME}/.ssh/gitea_ci_staging.conf" staging "cd /opt/bitreport/ai-news-writer && git log --oneline -2" + ssh -F "${HOME}/.ssh/gitea_ci_staging.conf" staging "cd /opt/bitreport/ai-news-writer && git revert HEAD --no-edit && git push origin develop" + ssh -F "${HOME}/.ssh/gitea_ci_staging.conf" staging "cd /opt/bitreport/ai-news-writer && git pull --ff-only origin develop && npm ci --omit=dev && pm2 startOrReload ecosystem.config.cjs --update-env" + echo "Staging deployment failed — rollback attempted" + exit 1 + + - name: Post deployment status + if: always() + run: | + if [ "${{ job.status }}" = "success" ]; then + echo "Staging deployment completed successfully" + echo "Environment: ${{ secrets.STAGING_URL || 'https://ainews-staging.bitreport.pt' }}" + else + echo "Staging deployment failed with status: ${{ job.status }}" + fi diff --git a/.gitea/workflows/test.yml b/.gitea/workflows/test.yml index 14e8c7b..9e2fed0 100644 --- a/.gitea/workflows/test.yml +++ b/.gitea/workflows/test.yml @@ -57,3 +57,5 @@ jobs: run: | python3 -m pip install --disable-pip-version-check --quiet pyyaml python3 -c "import yaml; yaml.safe_load(open('.gitea/workflows/test.yml'))" + python3 -c "import yaml; yaml.safe_load(open('.gitea/workflows/deploy-staging.yml'))" + python3 -c "import yaml; yaml.safe_load(open('.gitea/workflows/deploy-production.yml'))" diff --git a/tools/ci/gitea-actions-ssh-config.sh b/tools/ci/gitea-actions-ssh-config.sh new file mode 100755 index 0000000..cac2a42 --- /dev/null +++ b/tools/ci/gitea-actions-ssh-config.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +# Write a dedicated OpenSSH client config for Gitea Actions deploy (no global ~/.ssh/config append). +# Writes ~/.ssh/gitea_ci_.conf — use: ssh -F "$HOME/.ssh/gitea_ci_staging.conf" staging "cmd" +# +# Usage: +# bash tools/ci/gitea-actions-ssh-config.sh staging "$STAGING_HOST" "$STAGING_USER" "$STAGING_PORT" "$STAGING_SSH_KEY" "$STAGING_SSH_KNOWN_HOSTS" +# ssh -F "$HOME/.ssh/gitea_ci_staging.conf" staging "remote command" +set -euo pipefail + +ALIAS="${1:?host alias (staging|production)}" +HOST="${2:?SSH host}" +USER="${3:?SSH user}" +PORT="${4:?SSH port}" +KEY_BODY="${5:?private key PEM}" +KNOWN_HOSTS="${6:-}" + +if [[ "${#KNOWN_HOSTS}" -lt 12 ]]; then + echo "error: known-hosts secret missing or too short — add multiline output of: ssh-keyscan -p PORT -H HOST" >&2 + exit 1 +fi + +mkdir -p "${HOME}/.ssh" +chmod 700 "${HOME}/.ssh" + +KEY_FILE="${HOME}/.ssh/${ALIAS}_gitea_deploy_key" +printf '%s\n' "${KEY_BODY}" >"${KEY_FILE}" +chmod 600 "${KEY_FILE}" + +KNOWN_FILE="${HOME}/.ssh/known_hosts.${ALIAS}.gitea" +printf '%s\n' "${KNOWN_HOSTS}" >"${KNOWN_FILE}" +chmod 644 "${KNOWN_FILE}" + +CONF="${HOME}/.ssh/gitea_ci_${ALIAS}.conf" +{ + printf 'Host %s\n' "${ALIAS}" + printf ' HostName %s\n' "${HOST}" + printf ' User %s\n' "${USER}" + printf ' Port %s\n' "${PORT}" + printf ' IdentityFile %s\n' "${KEY_FILE}" + printf ' UserKnownHostsFile %s\n' "${KNOWN_FILE}" + printf ' StrictHostKeyChecking yes\n' +} >"${CONF}" +chmod 600 "${CONF}" -- 2.47.3