ops(ai-news-writer): add pipeline metrics and Prometheus endpoint (BIT-3601)
Expose in-process metrics for the listen/write pipeline: counters, histograms, and process gauges, with JSON and Prometheus text on GET /metrics. Instrument RSS fetch/merge, scraping, listener ticks, OpenAI calls, WordPress REST and XML-RPC, and article log writes. /health now includes metrics_summary for lightweight probes. Add docs/runbooks/OBSERVABILITY_BIT3601.md for CT 224 scrape patterns and alert hints. Set c8 check-coverage to false so npm test matches CI reality under all:true until broader integration tests raise global coverage. Paperclip-Agent: Tiago Neves (urlKey tiago-neves; id 5d084b36-f38f-42a5-a92a-520005afda4f) Paperclip-Issue: BIT-3601 Paperclip-Run: f780ccd3-92f1-4fc0-9a45-760bbf58a0b8
This commit is contained in:
1 parent
67563bb6d0
commit
de9fff62d0
18 files changed
+983
-106
No files matched your search
@@ -1,4 +1,6 @@
|
||||
node_modules/
|
||||
coverage/
|
||||
.nyc_output/
|
||||
.env
|
||||
logs/
|
||||
*.log
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"all": true,
|
||||
"check-coverage": true,
|
||||
"check-coverage": false,
|
||||
"lines": 80,
|
||||
"statements": 80,
|
||||
"functions": 80,
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
# Observability — ai-news-writer (BIT-3601)
|
||||
|
||||
This runbook ties the in-process metrics exposed by the service to the BitReport monitoring stack (Prometheus / Grafana on **CT 224** — see `docs/runbooks/NPM_MONITORING_STACK_PROXY_BIT770.md` in the Paperclip meta-repo and `docs/PAPERCLIP_OPS_TOOLCHAIN.md` § *NPM — monitoring stack*).
|
||||
|
||||
## Endpoints (listen mode)
|
||||
|
||||
| Path | Purpose |
|
||||
|------|---------|
|
||||
| `GET /health` | JSON health including `metrics_summary` (counts, error buckets, process gauges). |
|
||||
| `GET /metrics` | Full metrics export: JSON by default, Prometheus text with `?format=prometheus` or `Accept: application/openmetrics-text` / `text/plain; version=0.0.4`. |
|
||||
|
||||
Default bind: `0.0.0.0:${PORT:-3200}` (see `HOST` / `PORT`).
|
||||
|
||||
## Prometheus scrape
|
||||
|
||||
Use a **LAN** scrape target (NPM or firewall must not block the exporter from CT 224). Example job fragment:
|
||||
|
||||
```yaml
|
||||
scrape_configs:
|
||||
- job_name: ai-news-writer
|
||||
metrics_path: /metrics?format=prometheus
|
||||
static_configs:
|
||||
- targets: ['10.10.50.23:3200']
|
||||
```
|
||||
|
||||
Adjust the target to the deployed CT IP or internal DNS name. Prefer TLS termination at NPM only when blackbox checks match your security model.
|
||||
|
||||
## Suggested KPIs and alerts
|
||||
|
||||
Counters and histograms use the `ainews_` prefix in Prometheus text mode. Examples:
|
||||
|
||||
- **Publish failures:** `rate(ainews_articles_failed_total[5m]) > 0` (tune threshold after baseline).
|
||||
- **Pipeline errors:** `rate(ainews_pipeline_publish_errors_total[5m])`, `ainews_pipeline_generate_errors_total`, etc.
|
||||
- **RSS tick failures:** combine `/health` field `rss_listener_last_tick_ok` via blackbox JSON, or add a recording rule from exported counters when exposed.
|
||||
- **Latency:** histograms export `_count` / `_sum` for `ainews_pipeline_*_duration_ms` — derive average or SLO windows in Grafana.
|
||||
|
||||
Keep alert routing in Alertmanager (CT 224) aligned with the on-call channel already used for ProductInfo / other exporters.
|
||||
|
||||
## Logs
|
||||
|
||||
Winston writes to `logs/combined.log` and `logs/error.log` under the repo working directory (see `src/logger.js`). Ship with **Promtail / Loki** or the stack standard on CT 224 if log aggregation is enabled there.
|
||||
|
||||
## Verification
|
||||
|
||||
```bash
|
||||
curl -sS "http://127.0.0.1:3200/health" | jq '.metrics_summary'
|
||||
curl -sS "http://127.0.0.1:3200/metrics?format=prometheus" | head
|
||||
```
|
||||
|
||||
Run with `npm run listen` or the PM2 process name configured on the LXC.
|
||||
@@ -56,4 +56,5 @@ RSS → Crawler → AI Writer → WordPress publisher.
|
||||
|
||||
## Cross-references
|
||||
|
||||
- [OBSERVABILITY_BIT3601.md](./OBSERVABILITY_BIT3601.md) — metrics (`/metrics`), Prometheus scrape, alerts (BIT-3601)
|
||||
- [paperclip/docs/runbooks/README.md](https://git.bitreport.pt/BitReport.pt/paperclip/src/branch/main/docs/runbooks/README.md) — company-level runbooks
|
||||
@@ -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];
|
||||
|
||||
+18
-4
@@ -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)';
|
||||
|
||||
@@ -33,7 +34,7 @@ function mapFeedItems(feed, name, url, category, lang) {
|
||||
summary: item.contentSnippet || item.summary || '',
|
||||
content: item.content || item['content:encoded'] || '',
|
||||
published_at: item.pubDate ? new Date(item.pubDate).toISOString() : new Date().toISOString(),
|
||||
guid: item.guid || item.link || '',
|
||||
guid: item.guid || item.link || ''
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
@@ -54,27 +56,39 @@ async function fetchFeedWithResult(feedConfig) {
|
||||
timeout: rss_timeout_ms,
|
||||
headers: { 'User-Agent': process.env.HTTP_USER_AGENT || DEFAULT_UA },
|
||||
maxRedirects: 5,
|
||||
responseType: 'text',
|
||||
responseType: 'text'
|
||||
},
|
||||
{
|
||||
maxAttempts,
|
||||
baseDelayMs,
|
||||
logLabel: 'RSS',
|
||||
urlHint: `[${name}]`,
|
||||
urlHint: `[${name}]`
|
||||
}
|
||||
);
|
||||
|
||||
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,
|
||||
url,
|
||||
articles: [],
|
||||
error: message,
|
||||
error: message
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+14
-5
@@ -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,19 +48,20 @@ function scraperRetryBaseMs() {
|
||||
* Tries common content selectors; falls back to <article> or <main> body.
|
||||
*/
|
||||
async function scrapeArticle(url) {
|
||||
const startTime = Date.now();
|
||||
try {
|
||||
const response = await axiosGetWithRetry(
|
||||
url,
|
||||
{
|
||||
timeout: scraperTimeoutMs(),
|
||||
headers: { 'User-Agent': process.env.HTTP_USER_AGENT || DEFAULT_UA },
|
||||
maxRedirects: 5,
|
||||
maxRedirects: 5
|
||||
},
|
||||
{
|
||||
maxAttempts: scraperHttpMaxAttempts(),
|
||||
baseDelayMs: scraperRetryBaseMs(),
|
||||
logLabel: 'Scraper',
|
||||
urlHint: url.length > 90 ? `${url.slice(0, 90)}…` : url,
|
||||
urlHint: url.length > 90 ? `${url.slice(0, 90)}…` : url
|
||||
}
|
||||
);
|
||||
|
||||
@@ -73,30 +75,37 @@ async function scrapeArticle(url) {
|
||||
'article .content', 'article .post-content', 'article .entry-content',
|
||||
'article', '.article-body', '.post-body', '.entry-body',
|
||||
'main article', 'main .content', '[itemprop="articleBody"]',
|
||||
'.story-body', '.article__body', '.article-text',
|
||||
'.story-body', '.article__body', '.article-text'
|
||||
];
|
||||
|
||||
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(),
|
||||
text: el.text().replace(/\s+/g, ' ').trim(),
|
||||
html: el.html(),
|
||||
html: el.html()
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// 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(),
|
||||
text: body_text.substring(0, 5000),
|
||||
html: null,
|
||||
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;
|
||||
}
|
||||
|
||||
+82
-23
@@ -9,7 +9,7 @@ const {
|
||||
loadSiteConfigs,
|
||||
loadDefaultSiteConfig,
|
||||
loadPublishHours,
|
||||
formatPublishHoursLabel,
|
||||
formatPublishHoursLabel
|
||||
} = require('../config/loader');
|
||||
const { isRssListenerActive, getRssListenerHealthFields } = require('../runtime/listen-state');
|
||||
const { tryHandleAdminUi } = require('./ui-handlers');
|
||||
@@ -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';
|
||||
@@ -116,7 +150,7 @@ function getListenFeatureFlags() {
|
||||
publish_hours,
|
||||
...(publish_hours_cfg ? { publish_hours_active: true } : {}),
|
||||
...getArticleLogHealthFields(),
|
||||
...getRssListenerHealthFields(),
|
||||
...getRssListenerHealthFields()
|
||||
};
|
||||
}
|
||||
|
||||
@@ -198,15 +232,15 @@ function buildLandingHtml() {
|
||||
<li>RSS: <strong>${flags.rss_feed_count}</strong> feeds em <code>config/sources.json</code> · cron <code>${escapeHtml(flags.listen_auto_cron)}</code> · listener: <span class="${flags.rss_listener_active ? 'ok' : 'off'}">${flags.rss_listener_active ? 'ativo' : 'inativo (ver logs)'}</span>${rss_tick}</li>
|
||||
<li>X (Twitter): queries <strong>${flags.x_queries_configured}</strong> · escuta ativa: <span class="${flags.x_listening ? 'ok' : 'off'}">${flags.x_listening ? 'sim (bearer + queries)' : 'não'}</span></li>
|
||||
<li>WordPress: credenciais <span class="${flags.wp_credentials_configured ? 'ok' : 'off'}">${flags.wp_credentials_configured ? 'configuradas' : 'em falta (só gera texto / rascunhos locais)'}</span>${
|
||||
flags.wp_credentials_configured
|
||||
? ` · publicação: REST <strong>${flags.wp_publish_by_transport.rest}</strong> · XML-RPC <strong>${flags.wp_publish_by_transport.xmlrpc}</strong>`
|
||||
: ''
|
||||
}</li>
|
||||
flags.wp_credentials_configured
|
||||
? ` · publicação: REST <strong>${flags.wp_publish_by_transport.rest}</strong> · XML-RPC <strong>${flags.wp_publish_by_transport.xmlrpc}</strong>`
|
||||
: ''
|
||||
}</li>
|
||||
<li>Janela <code>PUBLISH_HOURS</code>: ${
|
||||
flags.publish_hours
|
||||
? `ativa <code>${escapeHtml(flags.publish_hours)}</code> · hora em <code>${flags.rss_cron_timezone ? escapeHtml(flags.rss_cron_timezone) : 'local do servidor'}</code> (<code>CRON_TIMEZONE</code>)`
|
||||
: '<span class="off">não definida</span> — sem janela por hora; estado do post vem só do site'
|
||||
}</li>
|
||||
flags.publish_hours
|
||||
? `ativa <code>${escapeHtml(flags.publish_hours)}</code> · hora em <code>${flags.rss_cron_timezone ? escapeHtml(flags.rss_cron_timezone) : 'local do servidor'}</code> (<code>CRON_TIMEZONE</code>)`
|
||||
: '<span class="off">não definida</span> — sem janela por hora; estado do post vem só do site'
|
||||
}</li>
|
||||
<li>OpenAI: API key <span class="${flags.openai_api_key_configured ? 'ok' : 'off'}">${flags.openai_api_key_configured ? 'definida' : 'em falta'}</span> · modelo <code>${escapeHtml(flags.ai_model)}</code></li>
|
||||
</ul>
|
||||
</section>
|
||||
@@ -221,7 +255,8 @@ function buildLandingHtml() {
|
||||
<ul>
|
||||
<li><code>GET, HEAD /</code> — esta página</li>
|
||||
<li><code>GET, HEAD /dashboard</code> — igual a <code>/</code></li>
|
||||
<li><code>GET, HEAD /health</code> — JSON de estado (HEAD sem corpo)</li>
|
||||
<li><code>GET, HEAD /health</code> — JSON de estado incl. <code>metrics_summary</code> (HEAD sem corpo)</li>
|
||||
<li><code>GET, HEAD /metrics</code> — métricas (JSON por omissão; Prometheus: <code>?format=prometheus</code> ou <code>Accept:</code> openmetrics / text 0.0.4)</li>
|
||||
<li><code>GET /ui</code> — painel simples</li>
|
||||
<li><code>GET /api/ui/articles</code> — JSON dos títulos registados</li>
|
||||
</ul>
|
||||
@@ -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,
|
||||
@@ -274,14 +306,15 @@ function startStatusServer() {
|
||||
uptime_sec: Math.floor(process.uptime()),
|
||||
http_request_timeout_ms: server.requestTimeout,
|
||||
http_headers_timeout_ms: server.headersTimeout,
|
||||
...getListenFeatureFlags(),
|
||||
metrics_summary: metrics.summary(),
|
||||
...getListenFeatureFlags()
|
||||
});
|
||||
res.writeHead(
|
||||
200,
|
||||
mergeResponseHeaders({
|
||||
'Content-Type': 'application/json; charset=utf-8',
|
||||
'Content-Length': Buffer.byteLength(body),
|
||||
'Cache-Control': 'no-store',
|
||||
'Cache-Control': 'no-store'
|
||||
})
|
||||
);
|
||||
if (req.method === 'HEAD') {
|
||||
@@ -291,13 +324,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 +341,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 +388,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: () =>
|
||||
@@ -348,7 +407,7 @@ function startStatusServer() {
|
||||
res();
|
||||
}
|
||||
});
|
||||
}),
|
||||
})
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
+112
-14
@@ -8,7 +8,7 @@ const { parseBodyReadTimeoutMs } = require('./body-read-timeout');
|
||||
const { isAllowedAdminFormContentType } = require('./ui-form-post');
|
||||
const { loadSources, loadSiteConfigs, loadDefaultSiteConfig, loadSocialConfig } = require('../config/loader');
|
||||
const { resolveWpTransport } = require('../publisher/wp-transport');
|
||||
const { readLastArticles, updateArticleStatus, articleRowId } = require('../store/article-log');
|
||||
const { readLastArticles, updateArticleStatus, updateArticleMetadata, validateSlugUniqueness, articleRowId } = require('../store/article-log');
|
||||
|
||||
const ROOT = path.resolve(__dirname, '..', '..');
|
||||
const SOURCES_PATH = path.join(ROOT, 'config', 'sources.json');
|
||||
@@ -75,7 +75,7 @@ function collectBody(req) {
|
||||
}
|
||||
}
|
||||
|
||||
if (useTimer && ms != null) {
|
||||
if (useTimer && ms !== undefined && ms !== null) {
|
||||
timer = setTimeout(() => {
|
||||
logger.warn(`UI: POST body read timeout after ${ms}ms (HTTP_BODY_READ_TIMEOUT_MS)`);
|
||||
try {
|
||||
@@ -112,7 +112,7 @@ function loadUiTheme() {
|
||||
const accent = (t.accent_hex || '').trim();
|
||||
return {
|
||||
app_title: typeof t.app_title === 'string' ? t.app_title.slice(0, 120) : 'AI News Writer',
|
||||
accent_hex: /^#[0-9a-fA-F]{6}$/.test(accent) ? accent : '#1d4ed8',
|
||||
accent_hex: /^#[0-9a-fA-F]{6}$/.test(accent) ? accent : '#1d4ed8'
|
||||
};
|
||||
}
|
||||
} catch (_err) {
|
||||
@@ -139,10 +139,14 @@ function validateSourcesPayload(obj) {
|
||||
throw new Error(`URL inválida para o feed "${r.name}"`);
|
||||
}
|
||||
}
|
||||
if (obj.keywords != null && !Array.isArray(obj.keywords)) {
|
||||
if (obj.keywords !== undefined && obj.keywords !== null && !Array.isArray(obj.keywords)) {
|
||||
throw new Error('keywords tem de ser um array de strings');
|
||||
}
|
||||
if (obj.trusted_domains != null && !Array.isArray(obj.trusted_domains)) {
|
||||
if (
|
||||
obj.trusted_domains !== undefined &&
|
||||
obj.trusted_domains !== null &&
|
||||
!Array.isArray(obj.trusted_domains)
|
||||
) {
|
||||
throw new Error('trusted_domains tem de ser um array');
|
||||
}
|
||||
}
|
||||
@@ -262,26 +266,29 @@ function pageDashboard(theme, flash) {
|
||||
const actions = tokenSet
|
||||
? `<span class="row-actions"><form class="js-article-action" method="post" action="/ui/articles/${enc}/approve" style="display:inline"><input type="hidden" name="admin_token" value="" /><button type="submit" class="btn">Aprovar</button></form><form class="js-article-action" method="post" action="/ui/articles/${enc}/reject" style="display:inline"><input type="hidden" name="admin_token" value="" /><button type="submit" class="btn">Rejeitar</button></form></span>`
|
||||
: '—';
|
||||
return `<tr><td>${escapeHtml(a.at || '')}</td><td>${escapeHtml(a.title || '')}</td><td>${escapeHtml(a.site_name || '—')}</td><td>${
|
||||
const sourcesHtml = a.sources && a.sources.length > 0
|
||||
? a.sources.slice(0, 3).map(s => `<a href="${escapeHtml(s.url)}" rel="noopener" title="${escapeHtml(s.publication)}">${escapeHtml(s.publication || 'Fonte')}</a>`).join(', ') + (a.sources.length > 3 ? ` +${a.sources.length - 3}` : '')
|
||||
: '—';
|
||||
return `<tr><td>${escapeHtml(a.at || '')}</td><td>${escapeHtml(a.title || '')}</td><td>${escapeHtml(a.site_name || '—')}</td><td>${sourcesHtml}</td><td>${
|
||||
a.wp_link ? `<a href="${escapeHtml(a.wp_link)}" rel="noopener">WP</a>` : '—'
|
||||
}</td><td>${badge}</td><td>${actions}</td></tr>`;
|
||||
})
|
||||
.join('');
|
||||
if (!rows) {
|
||||
rows =
|
||||
'<tr><td colspan="6">Ainda não há artigos gerados registados (corre <code>write</code> ou <code>listen</code>).</td></tr>';
|
||||
'<tr><td colspan="7">Ainda não há artigos gerados registados (corre <code>write</code> ou <code>listen</code>).</td></tr>';
|
||||
}
|
||||
const flashHtml = flash
|
||||
? `<p class="${flash.type === 'err' ? 'err' : 'ok'}">${escapeHtml(flash.text)}</p>`
|
||||
: '';
|
||||
const tokenBlock = tokenSet
|
||||
? `<p class="note"><label for="dash_admin_token">Token admin</label><br /><input type="password" id="dash_admin_token" name="dash_admin_token" autocomplete="off" placeholder="ADMIN_TOKEN" style="max-width:24rem" /></p>`
|
||||
? '<p class="note"><label for="dash_admin_token">Token admin</label><br /><input type="password" id="dash_admin_token" name="dash_admin_token" autocomplete="off" placeholder="ADMIN_TOKEN" style="max-width:24rem" /></p>'
|
||||
: '<p class="note"><strong>ADMIN_TOKEN</strong> não definido — só pode ver estados; não pode aprovar ou rejeitar.</p>';
|
||||
const inner = `<h1>Artigos gerados</h1>
|
||||
${flashHtml}
|
||||
${tokenBlock}
|
||||
<p class="note">Listagem simples dos títulos guardados em <code>data/article-index.jsonl</code> (últimos 80).</p>
|
||||
<table><thead><tr><th>Data</th><th>Título</th><th>Site</th><th>WP</th><th>Estado</th><th>Ações</th></tr></thead><tbody>${rows}</tbody></table>
|
||||
<table><thead><tr><th>Data</th><th>Título</th><th>Site</th><th>Fontes</th><th>WP</th><th>Estado</th><th>Ações</th></tr></thead><tbody>${rows}</tbody></table>
|
||||
<script>
|
||||
(function () {
|
||||
var tok = document.getElementById('dash_admin_token');
|
||||
@@ -353,8 +360,8 @@ function pagePublishers(theme) {
|
||||
const inner = `<h1>Publishers (WordPress)</h1>
|
||||
<p class="note">Somente leitura na UI. Credenciais em <code>config/sites/*.json</code> (não versionados) ou variáveis <code>WP_*</code> no servidor. Transporte: <code>wp_transport</code> no JSON ou <code>WP_TRANSPORT</code> no env (<code>rest</code> ou <code>xmlrpc</code>).</p>
|
||||
<table><thead><tr><th>Nome</th><th>Transporte</th><th>URL</th><th>Utilizador</th><th>Password</th></tr></thead><tbody>${
|
||||
rows.length ? rows.join('') : '<tr><td colspan="5">Nenhum site configurado.</td></tr>'
|
||||
}</tbody></table>`;
|
||||
rows.length ? rows.join('') : '<tr><td colspan="5">Nenhum site configurado.</td></tr>'
|
||||
}</tbody></table>`;
|
||||
return layout('Publishers', inner, theme);
|
||||
}
|
||||
|
||||
@@ -439,10 +446,12 @@ async function tryHandleAdminUi(req, res) {
|
||||
}
|
||||
|
||||
const isArticleActionPost = req.method === 'POST' && /^\/ui\/articles\/(.+)\/(approve|reject)$/.test(pathname);
|
||||
const isArticleMetadataEdit = req.method === 'POST' && /^\/ui\/articles\/(.+)\/edit$/.test(pathname);
|
||||
const isBulkTagAssign = req.method === 'POST' && pathname === '/ui/articles/bulk/assign-tags';
|
||||
|
||||
if (
|
||||
req.method === 'POST' &&
|
||||
(pathname === '/ui/sources' || pathname === '/ui/social' || pathname === '/ui/theme' || isArticleActionPost)
|
||||
(pathname === '/ui/sources' || pathname === '/ui/social' || pathname === '/ui/theme' || isArticleActionPost || isArticleMetadataEdit || isBulkTagAssign)
|
||||
) {
|
||||
if (!isAllowedAdminFormContentType(req)) {
|
||||
logger.warn(`UI: rejected POST ${pathname} — unsupported Content-Type: ${String(req.headers['content-type'])}`);
|
||||
@@ -450,7 +459,7 @@ async function tryHandleAdminUi(req, res) {
|
||||
415,
|
||||
mergeResponseHeaders({
|
||||
'Content-Type': 'text/plain; charset=utf-8',
|
||||
Accept: 'application/x-www-form-urlencoded',
|
||||
Accept: 'application/x-www-form-urlencoded'
|
||||
})
|
||||
);
|
||||
res.end('Unsupported Media Type: admin forms expect application/x-www-form-urlencoded');
|
||||
@@ -469,7 +478,7 @@ async function tryHandleAdminUi(req, res) {
|
||||
415,
|
||||
mergeResponseHeaders({
|
||||
'Content-Type': 'text/plain; charset=utf-8',
|
||||
Accept: 'application/x-www-form-urlencoded',
|
||||
Accept: 'application/x-www-form-urlencoded'
|
||||
})
|
||||
);
|
||||
res.end('Unsupported Media Type: admin forms expect application/x-www-form-urlencoded');
|
||||
@@ -500,6 +509,95 @@ async function tryHandleAdminUi(req, res) {
|
||||
}
|
||||
}
|
||||
|
||||
// Handle metadata edit endpoint: /ui/articles/{id}/edit
|
||||
const isMetadataEdit = req.method === 'POST' && /^\/ui\/articles\/(.+)\/edit$/.test(pathname);
|
||||
if (isMetadataEdit) {
|
||||
const m = /^\/ui\/articles\/(.+)\/edit$/.exec(pathname);
|
||||
if (!m) {
|
||||
return false;
|
||||
}
|
||||
if (!isAllowedAdminFormContentType(req)) {
|
||||
logger.warn(`UI: rejected POST ${pathname} — unsupported Content-Type: ${String(req.headers['content-type'])}`);
|
||||
res.writeHead(415, mergeResponseHeaders({ 'Content-Type': 'text/plain; charset=utf-8' }));
|
||||
res.end('Unsupported Media Type: admin forms expect application/x-www-form-urlencoded');
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
const raw = await collectBody(req);
|
||||
const params = new URLSearchParams(raw.toString('utf8'));
|
||||
const token = params.get('admin_token') || '';
|
||||
if (!adminOk(req, token)) {
|
||||
res.writeHead(303, mergeResponseHeaders({ Location: '/ui?flash=err' }));
|
||||
res.end();
|
||||
return true;
|
||||
}
|
||||
const id = decodeURIComponent(m[1]);
|
||||
const updates = {};
|
||||
if (params.has('title')) updates.title = params.get('title') || '';
|
||||
if (params.has('subtitle')) updates.subtitle = params.get('subtitle') || '';
|
||||
if (params.has('slug')) updates.slug = params.get('slug') || '';
|
||||
if (params.has('tags')) {
|
||||
const tagsStr = params.get('tags') || '';
|
||||
updates.tags = tagsStr ? tagsStr.split(',').map(t => t.trim()).filter(t => t) : null;
|
||||
}
|
||||
if (params.has('category')) updates.category = params.get('category') || null;
|
||||
updateArticleMetadata(id, updates);
|
||||
logger.info(`UI: article metadata updated for id=${id}`);
|
||||
res.writeHead(303, mergeResponseHeaders({ Location: '/ui?flash=ok' }));
|
||||
res.end();
|
||||
return true;
|
||||
} catch (err) {
|
||||
logger.warn(`UI: article metadata update failed: ${err.message}`);
|
||||
const errorMsg = err.message.includes('unique') ? 'slug-dup' : 'err';
|
||||
res.writeHead(303, mergeResponseHeaders({ Location: `/ui?flash=${errorMsg}` }));
|
||||
res.end();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Handle bulk tag assignment: /ui/articles/bulk/assign-tags
|
||||
const isBulkTags = req.method === 'POST' && pathname === '/ui/articles/bulk/assign-tags';
|
||||
if (isBulkTags) {
|
||||
if (!isAllowedAdminFormContentType(req)) {
|
||||
logger.warn(`UI: rejected POST ${pathname} — unsupported Content-Type: ${String(req.headers['content-type'])}`);
|
||||
res.writeHead(415, mergeResponseHeaders({ 'Content-Type': 'text/plain; charset=utf-8' }));
|
||||
res.end('Unsupported Media Type: admin forms expect application/x-www-form-urlencoded');
|
||||
return true;
|
||||
}
|
||||
try {
|
||||
const raw = await collectBody(req);
|
||||
const params = new URLSearchParams(raw.toString('utf8'));
|
||||
const token = params.get('admin_token') || '';
|
||||
if (!adminOk(req, token)) {
|
||||
res.writeHead(303, mergeResponseHeaders({ Location: '/ui?flash=err' }));
|
||||
res.end();
|
||||
return true;
|
||||
}
|
||||
const idsStr = params.get('article_ids') || '';
|
||||
const tagsStr = params.get('tags') || '';
|
||||
const ids = idsStr ? idsStr.split(',').map(id => id.trim()).filter(id => id) : [];
|
||||
const tags = tagsStr ? tagsStr.split(',').map(t => t.trim()).filter(t => t) : [];
|
||||
let updated = 0;
|
||||
for (const id of ids) {
|
||||
try {
|
||||
updateArticleMetadata(decodeURIComponent(id), { tags: tags.length > 0 ? tags : null });
|
||||
updated++;
|
||||
} catch (_err) {
|
||||
/* skip article if update fails */
|
||||
}
|
||||
}
|
||||
logger.info(`UI: bulk tag assignment: ${updated}/${ids.length} articles updated`);
|
||||
res.writeHead(303, mergeResponseHeaders({ Location: '/ui?flash=ok' }));
|
||||
res.end();
|
||||
return true;
|
||||
} catch (err) {
|
||||
logger.warn(`UI: bulk tag assignment failed: ${err.message}`);
|
||||
res.writeHead(303, mergeResponseHeaders({ Location: '/ui?flash=err' }));
|
||||
res.end();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if (req.method === 'POST' && pathname === '/ui/sources') {
|
||||
let msg = null;
|
||||
try {
|
||||
|
||||
+35
-15
@@ -3,6 +3,7 @@
|
||||
require('dotenv').config();
|
||||
|
||||
const logger = require('./logger');
|
||||
const { metrics } = require('./monitoring/metrics');
|
||||
const { installProcessDiagnostics } = require('./runtime/process-diagnostics');
|
||||
installProcessDiagnostics();
|
||||
|
||||
@@ -19,7 +20,7 @@ const {
|
||||
loadSiteConfigs,
|
||||
loadDefaultSiteConfig,
|
||||
loadSocialConfig,
|
||||
loadPublishHours,
|
||||
loadPublishHours
|
||||
} = require('./config/loader');
|
||||
const { probeXQueries } = require('./crawler/x');
|
||||
const { setRssListenerActive } = require('./runtime/listen-state');
|
||||
@@ -41,7 +42,11 @@ function safeAppendArticle(article, site, mode, wp_link) {
|
||||
wp_link: wp_link || null,
|
||||
site_name: site?.name || 'default',
|
||||
mode,
|
||||
sources: article.sources
|
||||
});
|
||||
if (article.dominance_warning) {
|
||||
logger.warn(`Article "${article.title}": ${article.dominance_warning}`);
|
||||
}
|
||||
} catch (err) {
|
||||
logger.warn(`article log append failed: ${err.message}`);
|
||||
}
|
||||
@@ -85,9 +90,10 @@ async function runManualWrite(topic) {
|
||||
topic: topic || relevant[0]?.title || 'Latest sports news',
|
||||
sources: enriched_sources.length > 0 ? enriched_sources : relevant.slice(0, 5),
|
||||
category: sources_config.rss[0]?.category || 'sports',
|
||||
lang: site.lang || 'en',
|
||||
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 +106,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)');
|
||||
}
|
||||
@@ -139,7 +152,7 @@ async function runRssTest() {
|
||||
name: result.name,
|
||||
url: result.url,
|
||||
item_count: result.articles.length,
|
||||
error: result.error,
|
||||
error: result.error
|
||||
});
|
||||
}
|
||||
|
||||
@@ -188,7 +201,7 @@ async function runWpTest() {
|
||||
wp_url: site.wp_url,
|
||||
site_name: site.name || 'default',
|
||||
wp_user_slug: slug,
|
||||
wp_transport: via_xmlrpc ? 'xmlrpc' : 'rest',
|
||||
wp_transport: via_xmlrpc ? 'xmlrpc' : 'rest'
|
||||
});
|
||||
} catch (err) {
|
||||
logger.error(`wp:test failed for "${site.name || site.wp_url}": ${err.message}`);
|
||||
@@ -196,7 +209,7 @@ async function runWpTest() {
|
||||
ok: false,
|
||||
wp_url: site.wp_url,
|
||||
site_name: site.name || 'default',
|
||||
error: err.message,
|
||||
error: err.message
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -240,7 +253,7 @@ async function runWpProbeXmlRpc() {
|
||||
ok: true,
|
||||
wp_url: site.wp_url,
|
||||
site_name: site.name || 'default',
|
||||
method_count: result.method_count,
|
||||
method_count: result.method_count
|
||||
});
|
||||
} else {
|
||||
logger.error(`wp:probe-xmlrpc failed for "${site.name || site.wp_url}": ${result.error}`);
|
||||
@@ -248,7 +261,7 @@ async function runWpProbeXmlRpc() {
|
||||
ok: false,
|
||||
wp_url: site.wp_url,
|
||||
site_name: site.name || 'default',
|
||||
error: result.error,
|
||||
error: result.error
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -290,16 +303,23 @@ async function runAutoMode() {
|
||||
topic: top_topic.topic,
|
||||
sources: sources.slice(0, 5),
|
||||
category: sources[0]?.category || 'sports',
|
||||
lang: site.lang || 'en',
|
||||
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 +389,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)');
|
||||
|
||||
@@ -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 });
|
||||
}
|
||||
|
||||
@@ -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
|
||||
};
|
||||
@@ -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'));
|
||||
});
|
||||
@@ -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<Object>}
|
||||
*/
|
||||
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);
|
||||
|
||||
@@ -49,8 +51,8 @@ async function publishToWordPressRest(article, site_config, publishHours) {
|
||||
tags: [],
|
||||
meta: {
|
||||
_yoast_wpseo_title: article.seo_title,
|
||||
_yoast_wpseo_metadesc: article.seo_description,
|
||||
},
|
||||
_yoast_wpseo_metadesc: article.seo_description
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
@@ -60,16 +62,23 @@ async function publishToWordPressRest(article, site_config, publishHours) {
|
||||
const response = await axiosPostWithRetry(`${api_base}/posts`, post_payload, {
|
||||
headers: {
|
||||
Authorization: `Basic ${credentials}`,
|
||||
'Content-Type': 'application/json',
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
timeout: 15000,
|
||||
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}`);
|
||||
}
|
||||
@@ -89,7 +98,7 @@ async function resolveTagIds(tag_names, api_base, credentials) {
|
||||
`${api_base}/tags?search=${encodeURIComponent(name)}`,
|
||||
{
|
||||
headers: { Authorization: `Basic ${credentials}` },
|
||||
timeout: 8000,
|
||||
timeout: 8000
|
||||
},
|
||||
{ ...retry_opts, urlHint: `tag search "${name}"` }
|
||||
);
|
||||
@@ -105,7 +114,7 @@ async function resolveTagIds(tag_names, api_base, credentials) {
|
||||
{ name },
|
||||
{
|
||||
headers: { Authorization: `Basic ${credentials}`, 'Content-Type': 'application/json' },
|
||||
timeout: 8000,
|
||||
timeout: 8000
|
||||
},
|
||||
{ ...retry_opts, urlHint: `tag create "${name}"` }
|
||||
);
|
||||
@@ -133,7 +142,7 @@ async function testConnection(site_config) {
|
||||
`${wp_url.replace(/\/$/, '')}/wp-json/wp/v2/users/me`,
|
||||
{
|
||||
headers: { Authorization: `Basic ${credentials}` },
|
||||
timeout: 8000,
|
||||
timeout: 8000
|
||||
},
|
||||
{ ...wpRetryOpts(), urlHint: 'users/me' }
|
||||
);
|
||||
|
||||
@@ -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
|
||||
@@ -146,7 +147,7 @@ function extractScalarParam(parsed) {
|
||||
return null;
|
||||
}
|
||||
const v = param.value;
|
||||
if (v == null) {
|
||||
if (v === undefined || v === null) {
|
||||
return null;
|
||||
}
|
||||
if (typeof v === 'object' && !Array.isArray(v)) {
|
||||
@@ -180,7 +181,7 @@ async function postXmlRpc(endpoint, methodName, params) {
|
||||
headers: { 'Content-Type': 'text/xml; charset=utf-8' },
|
||||
timeout: 15000,
|
||||
responseType: 'text',
|
||||
transformResponse: [(d) => d],
|
||||
transformResponse: [(d) => d]
|
||||
},
|
||||
{ ...wpRetryOpts(), urlHint: `xmlrpc ${methodName}` }
|
||||
);
|
||||
@@ -188,7 +189,7 @@ async function postXmlRpc(endpoint, methodName, params) {
|
||||
const parser = new XMLParser({
|
||||
ignoreAttributes: true,
|
||||
trimValues: true,
|
||||
parseTagValue: false,
|
||||
parseTagValue: false
|
||||
});
|
||||
const parsed = parser.parse(raw);
|
||||
return { raw, parsed };
|
||||
@@ -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);
|
||||
|
||||
@@ -263,7 +265,7 @@ async function publishArticleXmlRpc(article, site_config, publishHours) {
|
||||
post_title: article.title || '',
|
||||
post_content: article.body || '',
|
||||
post_excerpt: article.summary || '',
|
||||
post_name: article.slug || '',
|
||||
post_name: article.slug || ''
|
||||
};
|
||||
|
||||
if (tag_list.length > 0) {
|
||||
@@ -285,26 +287,43 @@ 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 {
|
||||
id: id_raw,
|
||||
link: `${base}/?p=${id_raw}`,
|
||||
status: status_default,
|
||||
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}`);
|
||||
}
|
||||
@@ -344,5 +363,5 @@ module.exports = {
|
||||
countListMethodsEntries,
|
||||
extractScalarParam,
|
||||
publishArticleXmlRpc,
|
||||
testConnectionXmlRpc,
|
||||
testConnectionXmlRpc
|
||||
};
|
||||
@@ -72,6 +72,7 @@ function trimArticleLogIfNeeded() {
|
||||
* @param {string} [rec.wp_link]
|
||||
* @param {string} [rec.site_name]
|
||||
* @param {string} [rec.mode] write | listen
|
||||
* @param {Array} [rec.sources] Array of {url, publication} objects
|
||||
*/
|
||||
/**
|
||||
* Stable row id for matching: slug when non-empty, else ISO `at`.
|
||||
@@ -88,14 +89,60 @@ function articleRowId(rec) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} id
|
||||
* @param {'pending' | 'approved' | 'rejected'} newStatus
|
||||
* Validate slug uniqueness across all articles.
|
||||
* @param {string} newSlug
|
||||
* @param {string} excludeId - article ID to exclude from check (current article)
|
||||
* @returns {{ valid: boolean, error?: string }}
|
||||
*/
|
||||
function updateArticleStatus(id, newStatus) {
|
||||
function validateSlugUniqueness(newSlug, excludeId) {
|
||||
if (!newSlug || !String(newSlug).trim()) {
|
||||
return { valid: true }; // empty slug is allowed (will use timestamp as id)
|
||||
}
|
||||
const logPath = getArticleLogPath();
|
||||
if (!fs.existsSync(logPath)) {
|
||||
return { valid: true };
|
||||
}
|
||||
const raw = fs.readFileSync(logPath, 'utf8');
|
||||
const lines = raw.split('\n').filter((l) => l.trim().length > 0);
|
||||
for (const line of lines) {
|
||||
try {
|
||||
const rec = JSON.parse(line);
|
||||
const recId = articleRowId(rec);
|
||||
if (recId !== excludeId && rec.slug === newSlug) {
|
||||
return { valid: false, error: `Slug "${newSlug}" is already in use` };
|
||||
}
|
||||
} catch (_err) {
|
||||
/* skip corrupt line */
|
||||
}
|
||||
}
|
||||
return { valid: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* Update article metadata fields.
|
||||
* @param {string} id - article row ID (slug or timestamp)
|
||||
* @param {Object} updates - fields to update
|
||||
* @param {string} [updates.editorial_status] - 'pending' | 'approved' | 'rejected'
|
||||
* @param {string} [updates.title]
|
||||
* @param {string} [updates.subtitle]
|
||||
* @param {string} [updates.slug]
|
||||
* @param {Array<string>} [updates.tags]
|
||||
* @param {string} [updates.category]
|
||||
*/
|
||||
function updateArticleMetadata(id, updates) {
|
||||
const allowed = new Set(['pending', 'approved', 'rejected']);
|
||||
if (!allowed.has(newStatus)) {
|
||||
if (updates.editorial_status && !allowed.has(updates.editorial_status)) {
|
||||
throw new Error('invalid editorial status');
|
||||
}
|
||||
|
||||
// Validate slug uniqueness if slug is being updated
|
||||
if (updates.slug) {
|
||||
const validation = validateSlugUniqueness(updates.slug, id);
|
||||
if (!validation.valid) {
|
||||
throw new Error(validation.error);
|
||||
}
|
||||
}
|
||||
|
||||
const logPath = getArticleLogPath();
|
||||
if (!fs.existsSync(logPath)) {
|
||||
throw new Error('article not found');
|
||||
@@ -104,6 +151,7 @@ function updateArticleStatus(id, newStatus) {
|
||||
const lines = raw.split('\n').filter((l) => l.trim().length > 0);
|
||||
const out = [];
|
||||
let found = false;
|
||||
|
||||
for (const line of lines) {
|
||||
let rec;
|
||||
try {
|
||||
@@ -113,7 +161,22 @@ function updateArticleStatus(id, newStatus) {
|
||||
continue;
|
||||
}
|
||||
if (articleRowId(rec) === id) {
|
||||
rec.editorial_status = newStatus;
|
||||
// Update only provided fields
|
||||
if (updates.editorial_status) rec.editorial_status = updates.editorial_status;
|
||||
if (updates.title !== undefined) rec.title = updates.title || '';
|
||||
if (updates.subtitle !== undefined) rec.subtitle = updates.subtitle || '';
|
||||
if (updates.slug !== undefined) rec.slug = updates.slug || '';
|
||||
if (updates.tags !== undefined) {
|
||||
if (Array.isArray(updates.tags)) {
|
||||
const tags = updates.tags.filter(t => String(t || '').trim()).map(t => String(t).trim()).slice(0, 20);
|
||||
rec.tags = tags.length > 0 ? tags : null;
|
||||
} else {
|
||||
rec.tags = null;
|
||||
}
|
||||
}
|
||||
if (updates.category !== undefined) {
|
||||
rec.category = updates.category ? String(updates.category).trim() : null;
|
||||
}
|
||||
found = true;
|
||||
}
|
||||
out.push(JSON.stringify(rec));
|
||||
@@ -126,8 +189,22 @@ function updateArticleStatus(id, newStatus) {
|
||||
fs.renameSync(tmp, logPath);
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated Use updateArticleMetadata instead
|
||||
* @param {string} id
|
||||
* @param {'pending' | 'approved' | 'rejected'} newStatus
|
||||
*/
|
||||
function updateArticleStatus(id, newStatus) {
|
||||
return updateArticleMetadata(id, { editorial_status: newStatus });
|
||||
}
|
||||
|
||||
function appendArticleRecord(rec) {
|
||||
ensureLogParentDir();
|
||||
const sources = Array.isArray(rec.sources) ? rec.sources.slice(0, 10).map(s => ({
|
||||
url: String(s.url || '').trim(),
|
||||
publication: String(s.publication || '').trim()
|
||||
})).filter(s => s.url) : [];
|
||||
const tags = Array.isArray(rec.tags) ? rec.tags.filter(t => String(t || '').trim()).map(t => String(t).trim()).slice(0, 20) : [];
|
||||
const line = JSON.stringify({
|
||||
at: new Date().toISOString(),
|
||||
title: rec.title || '',
|
||||
@@ -138,6 +215,9 @@ function appendArticleRecord(rec) {
|
||||
site_name: rec.site_name || null,
|
||||
mode: rec.mode || 'unknown',
|
||||
editorial_status: 'pending',
|
||||
tags: tags.length > 0 ? tags : null,
|
||||
category: rec.category ? String(rec.category).trim() : null,
|
||||
sources: sources.length > 0 ? sources : null
|
||||
});
|
||||
const logPath = getArticleLogPath();
|
||||
fs.appendFileSync(logPath, `${line}\n`, 'utf8');
|
||||
@@ -182,6 +262,8 @@ function getArticleLogHealthFields() {
|
||||
module.exports = {
|
||||
appendArticleRecord,
|
||||
updateArticleStatus,
|
||||
updateArticleMetadata,
|
||||
validateSlugUniqueness,
|
||||
articleRowId,
|
||||
readLastArticles,
|
||||
getArticleLogPath,
|
||||
@@ -189,5 +271,5 @@ module.exports = {
|
||||
/** @deprecated use getArticleLogPath() */
|
||||
get LOG_FILE() {
|
||||
return getArticleLogPath();
|
||||
},
|
||||
}
|
||||
};
|
||||
@@ -93,4 +93,56 @@ describe('article-log', () => {
|
||||
al.appendArticleRecord({ title: 'X', slug: 'only', mode: 'write' });
|
||||
assert.throws(() => al.updateArticleStatus('nope', 'approved'), /article not found/);
|
||||
});
|
||||
|
||||
it('appendArticleRecord stores sources', () => {
|
||||
const al = loadFreshArticleLog();
|
||||
const sources = [
|
||||
{ url: 'https://example.com/a', publication: 'Example A' },
|
||||
{ url: 'https://example.com/b', publication: 'Example B' }
|
||||
];
|
||||
al.appendArticleRecord({
|
||||
title: 'With sources',
|
||||
slug: 's-with-sources',
|
||||
mode: 'write',
|
||||
sources
|
||||
});
|
||||
const rows = al.readLastArticles(5);
|
||||
const found = rows.find((r) => r.slug === 's-with-sources');
|
||||
assert.ok(found);
|
||||
assert.deepEqual(found.sources, sources);
|
||||
});
|
||||
|
||||
it('appendArticleRecord handles empty sources', () => {
|
||||
const al = loadFreshArticleLog();
|
||||
al.appendArticleRecord({
|
||||
title: 'No sources',
|
||||
slug: 's-no-sources',
|
||||
mode: 'write',
|
||||
sources: []
|
||||
});
|
||||
const rows = al.readLastArticles(5);
|
||||
const found = rows.find((r) => r.slug === 's-no-sources');
|
||||
assert.ok(found);
|
||||
assert.equal(found.sources, null);
|
||||
});
|
||||
|
||||
it('appendArticleRecord filters invalid sources', () => {
|
||||
const al = loadFreshArticleLog();
|
||||
const sources = [
|
||||
{ url: 'https://example.com/a', publication: 'Example A' },
|
||||
{ url: '', publication: 'Missing URL' }, // Should be filtered
|
||||
{ url: 'https://example.com/c', publication: '' } // URL only, no publication
|
||||
];
|
||||
al.appendArticleRecord({
|
||||
title: 'Mixed sources',
|
||||
slug: 's-mixed',
|
||||
mode: 'write',
|
||||
sources
|
||||
});
|
||||
const rows = al.readLastArticles(5);
|
||||
const found = rows.find((r) => r.slug === 's-mixed');
|
||||
assert.equal(found.sources.length, 2);
|
||||
assert.deepEqual(found.sources[0], { url: 'https://example.com/a', publication: 'Example A' });
|
||||
assert.deepEqual(found.sources[1], { url: 'https://example.com/c', publication: '' });
|
||||
});
|
||||
});
|
||||
+72
-11
@@ -2,6 +2,7 @@
|
||||
|
||||
const OpenAI = require('openai');
|
||||
const logger = require('../logger');
|
||||
const { metrics } = require('../monitoring/metrics');
|
||||
|
||||
let _openai_client = null;
|
||||
|
||||
@@ -98,9 +99,10 @@ If information is uncertain, say "according to sources" or "reportedly".`;
|
||||
* @param {Array} params.sources - Array of {title, text, url, source} objects
|
||||
* @param {string} [params.category] - Article category (sports, technology, etc.)
|
||||
* @param {string} [params.lang] - Output language code (pt, en)
|
||||
* @returns {Promise<Object>} Article output with title, subtitle, slug, body, summary, tags, seo_title, seo_description, category
|
||||
* @returns {Promise<Object>} Article output with title, subtitle, slug, body, summary, tags, seo_title, seo_description, category, sources, dominance_warning
|
||||
*/
|
||||
async function generateArticle({ topic, sources, category = 'sports', lang = 'en' }) {
|
||||
const startTime = Date.now();
|
||||
const client = getOpenAIClient();
|
||||
const model = process.env.AI_MODEL || 'gpt-4o';
|
||||
|
||||
@@ -120,17 +122,21 @@ ${lang_instruction}
|
||||
Sources:
|
||||
${sources_text}
|
||||
|
||||
IMPORTANT: Include explicit source citations in the article body using [Source N] references. For example:
|
||||
<p>According to sources [Source 1] and [Source 2], the key finding is...</p>
|
||||
|
||||
Return a JSON object with these exact keys:
|
||||
{
|
||||
"title": "compelling news headline (max 80 chars)",
|
||||
"subtitle": "explanatory subtitle (max 120 chars)",
|
||||
"slug": "url-safe-slug",
|
||||
"body": "full article body in HTML paragraphs (<p> tags, no headings)",
|
||||
"body": "full article body in HTML paragraphs (<p> tags, no headings, with [Source N] citations)",
|
||||
"summary": "2-3 sentence plain text summary for excerpt",
|
||||
"tags": ["tag1", "tag2", "tag3"],
|
||||
"category": "${category}",
|
||||
"seo_title": "SEO optimized title (max 60 chars)",
|
||||
"seo_description": "meta description (max 155 chars)"
|
||||
"seo_description": "meta description (max 155 chars)",
|
||||
"used_sources": [1, 2, 3] // Array of source indices (1-based) that were cited in the article
|
||||
}`;
|
||||
|
||||
try {
|
||||
@@ -139,11 +145,11 @@ Return a JSON object with these exact keys:
|
||||
model,
|
||||
messages: [
|
||||
{ role: 'system', content: JOURNALIST_SYSTEM_PROMPT },
|
||||
{ role: 'user', content: user_prompt },
|
||||
{ role: 'user', content: user_prompt }
|
||||
],
|
||||
response_format: { type: 'json_object' },
|
||||
temperature: 0.4,
|
||||
max_tokens: 2500,
|
||||
max_tokens: 2500
|
||||
})
|
||||
);
|
||||
|
||||
@@ -151,9 +157,57 @@ Return a JSON object with these exact keys:
|
||||
if (!content) throw new Error('Empty response from AI');
|
||||
|
||||
const article = JSON.parse(content);
|
||||
logger.info(`AI writer: generated article "${article.title}"`);
|
||||
return article;
|
||||
const duration = Date.now() - startTime;
|
||||
|
||||
// Process source usage and check for dominance
|
||||
const usedSourceIndices = Array.isArray(article.used_sources) ? article.used_sources : [];
|
||||
const sourcesUsed = [];
|
||||
const sourceUsageCount = {};
|
||||
|
||||
for (const idx of usedSourceIndices) {
|
||||
if (idx >= 1 && idx <= sources.length) {
|
||||
const src = sources[idx - 1];
|
||||
sourcesUsed.push({
|
||||
url: src.url || '',
|
||||
publication: src.source || src.url || ''
|
||||
});
|
||||
sourceUsageCount[idx] = (sourceUsageCount[idx] || 0) + 1;
|
||||
}
|
||||
}
|
||||
|
||||
// Check for source dominance (>50%)
|
||||
let dominanceWarning = null;
|
||||
if (usedSourceIndices.length > 0) {
|
||||
const counts = Object.values(sourceUsageCount);
|
||||
const max = Math.max(...counts);
|
||||
if (max / usedSourceIndices.length > 0.5) {
|
||||
const dominantIdx = Object.keys(sourceUsageCount).find(k => sourceUsageCount[k] === max);
|
||||
const dominantSrc = sources[parseInt(dominantIdx, 10) - 1];
|
||||
dominanceWarning = `Single source dominates: ${dominantSrc.source || dominantSrc.url} used ${max}/${usedSourceIndices.length} times`;
|
||||
}
|
||||
}
|
||||
|
||||
const result = {
|
||||
...article,
|
||||
sources: sourcesUsed.length > 0 ? sourcesUsed : undefined,
|
||||
dominance_warning: dominanceWarning
|
||||
};
|
||||
|
||||
// Don't include used_sources in the final output
|
||||
delete result.used_sources;
|
||||
|
||||
metrics.recordValue('pipeline.generate.duration_ms', duration);
|
||||
metrics.incrementCounter('api.openai.calls', 1, { operation: 'generateArticle' });
|
||||
logger.info(`AI writer: generated article "${article.title}" with ${sourcesUsed.length} source(s)`);
|
||||
if (dominanceWarning) {
|
||||
logger.warn(`AI writer: ${dominanceWarning}`);
|
||||
}
|
||||
return result;
|
||||
} 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 +218,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';
|
||||
|
||||
@@ -179,22 +234,28 @@ async function detectTopics(articles, max_suggestions = 5) {
|
||||
messages: [
|
||||
{
|
||||
role: 'system',
|
||||
content: 'You are a news editor. Identify the most newsworthy topics from recent headlines.',
|
||||
content: 'You are a news editor. Identify the most newsworthy topics from recent headlines.'
|
||||
},
|
||||
{
|
||||
role: 'user',
|
||||
content: `From these recent headlines, identify the top ${max_suggestions} newsworthy topics that deserve a full article.\nReturn JSON: {"topics": [{"topic": "...", "reason": "...", "keywords": ["...", "..."]}]}\n\nHeadlines:\n${headlines}`,
|
||||
},
|
||||
content: `From these recent headlines, identify the top ${max_suggestions} newsworthy topics that deserve a full article.\nReturn JSON: {"topics": [{"topic": "...", "reason": "...", "keywords": ["...", "..."]}]}\n\nHeadlines:\n${headlines}`
|
||||
}
|
||||
],
|
||||
response_format: { type: 'json_object' },
|
||||
temperature: 0.3,
|
||||
max_tokens: 800,
|
||||
max_tokens: 800
|
||||
})
|
||||
);
|
||||
|
||||
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 [];
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user