feat(http-retry): consolidate HTTP retry logic across RSS, X, and WordPress

Phases 1-4: Complete HTTP client & retry layer refactoring

- **Phase 1:** Create centralized HttpRetryConfig class with env var
  precedence (HTTP_*, then component-specific legacy vars)
- **Phase 2:** Refactor RSS crawler to use HttpRetryConfig.forRss()
- **Phase 3:** Refactor X API client to use HttpRetryConfig.forX()
- **Phase 4:** Refactor WordPress publisher (REST + XML-RPC) to use
  HttpRetryConfig.forWordPress(); delete deprecated wp-http-options.js

Backward-compatible with legacy env vars (RSS_*, X_*, WP_*).
All 32 HttpRetryConfig unit tests passing.
All pipeline tests passing.

Remaining work: documentation updates and deprecation warnings.

Paperclip-Issue: BIT-4296
Co-Authored-By: Paperclip <[email protected]>
This commit is contained in:
Xika (Agent)andPaperclip committed 2026-04-18 00:20:38 +00:00
1 parent b8973db6ef
commit f4198e7b03
7 files changed
+522 -64

No files matched your search

+5 -8
View File
@@ -9,6 +9,7 @@ const { getOrCreateCorrelationId } = require('../logger/correlation-id');
const { circuitBreaker } = require('./circuit-breaker');
const { categorizeError } = require('../errors/error-types');
const { trackSourceFetch } = require('../monitoring/pipeline-metrics');
const HttpRetryConfig = require('../util/http-retry-config');
const DEFAULT_UA = 'ai-news-writer/0.1 (+https://bitreport.pt)';
@@ -74,8 +75,9 @@ 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 retryConfig = HttpRetryConfig.forRss({ timeoutMs: rss_timeout_ms });
const retryOpts = retryConfig.toRetryOpts();
Object.assign(retryOpts, { urlHint: `[${name}]` });
const startTime = Date.now();
try {
@@ -87,12 +89,7 @@ async function fetchFeedWithResult(feedConfig) {
maxRedirects: 5,
responseType: 'text'
},
{
maxAttempts,
baseDelayMs,
logLabel: 'RSS',
urlHint: `[${name}]`
}
retryOpts
);
const feed = await parser.parseString(response.data);
+8 -14
View File
@@ -2,6 +2,7 @@
const logger = require('../logger');
const { axiosGetWithRetry } = require('../util/http-retry');
const HttpRetryConfig = require('../util/http-retry-config');
const X_SEARCH_URL = 'https://api.twitter.com/2/tweets/search/recent';
const DEFAULT_UA = 'ai-news-writer/0.1 (+https://bitreport.pt)';
@@ -18,14 +19,6 @@ function readBoundedInt(env_key, default_val, min_val, max_val) {
return Math.min(max_val, Math.max(min_val, n));
}
function xHttpMaxAttempts() {
return readBoundedInt('X_HTTP_MAX_ATTEMPTS', 3, 1, 5);
}
function xRetryBaseMs() {
return readBoundedInt('X_RETRY_BASE_MS', 1000, 200, 60000);
}
function maxResultsClamped(raw) {
const n = parseInt(raw ?? 10, 10);
if (!Number.isFinite(n)) {
@@ -46,6 +39,12 @@ async function searchRecentRaw(bearer, query, max_results) {
url.searchParams.set('max_results', String(max_results));
url.searchParams.set('tweet.fields', 'created_at,author_id');
const retryConfig = HttpRetryConfig.forX({ timeoutMs: 20000 });
const retryOpts = retryConfig.toRetryOpts();
Object.assign(retryOpts, {
urlHint: query.length > 60 ? `${query.slice(0, 60)}…` : query
});
const response = await axiosGetWithRetry(
url.toString(),
{
@@ -55,12 +54,7 @@ async function searchRecentRaw(bearer, query, max_results) {
'User-Agent': process.env.HTTP_USER_AGENT || DEFAULT_UA
}
},
{
maxAttempts: xHttpMaxAttempts(),
baseDelayMs: xRetryBaseMs(),
logLabel: 'X',
urlHint: query.length > 60 ? `${query.slice(0, 60)}…` : query
}
retryOpts
);
return Array.isArray(response.data?.data) ? response.data.data : [];
+5 -5
View File
@@ -3,7 +3,7 @@
const logger = require('../logger');
const { axiosGetWithRetry, axiosPostWithRetry, isTransientHttpError } = require('../util/http-retry');
const { notifyPipelineAlert } = require('../monitoring/pipeline-alert');
const { wpRetryOpts } = require('./wp-http-options');
const HttpRetryConfig = require('../util/http-retry-config');
const { resolveWpTransport } = require('./wp-transport');
const { publishArticleXmlRpc, testConnectionXmlRpc } = require('./xmlrpc-client');
const { resolveWpStatus } = require('./wp-publish-hours');
@@ -82,7 +82,7 @@ async function publishToWordPressRest(article, site_config, publishHours) {
'Content-Type': 'application/json'
},
timeout: 15000
}, wpRetryOpts());
}, HttpRetryConfig.forWordPress().toRetryOpts());
const duration = Date.now() - startTime;
metrics.recordValue('pipeline.publish.duration_ms', duration, { site: wp_url, transport: 'rest' });
@@ -107,7 +107,7 @@ async function publishToWordPressRest(article, site_config, publishHours) {
'Content-Type': 'application/json'
},
timeout: 15000
}, wpRetryOpts());
}, HttpRetryConfig.forWordPress().toRetryOpts());
metrics.incrementCounter('pipeline.publish.draft_fallback', 1, { site: wp_url, transport: 'rest' });
logger.warn(
@@ -147,7 +147,7 @@ async function publishToWordPressRest(article, site_config, publishHours) {
async function resolveTagIds(tag_names, api_base, credentials) {
if (!Array.isArray(tag_names) || tag_names.length === 0) return [];
const retry_opts = wpRetryOpts();
const retry_opts = HttpRetryConfig.forWordPress().toRetryOpts();
const ids = [];
for (const name of tag_names) {
try {
@@ -201,7 +201,7 @@ async function testConnection(site_config) {
headers: { Authorization: `Basic ${credentials}` },
timeout: 8000
},
{ ...wpRetryOpts(), urlHint: 'users/me' }
{ ...HttpRetryConfig.forWordPress().toRetryOpts(), urlHint: 'users/me' }
);
return { ok: true, user_info: response.data };
}
-35
View File
@@ -1,35 +0,0 @@
'use strict';
function wpHttpMaxAttempts() {
const raw = process.env.WP_HTTP_MAX_ATTEMPTS;
if (raw === undefined || raw === '') {
return 3;
}
const n = parseInt(raw, 10);
if (!Number.isFinite(n)) {
return 3;
}
return Math.min(5, Math.max(1, n));
}
function wpRetryBaseMs() {
const raw = process.env.WP_RETRY_BASE_MS;
if (raw === undefined || raw === '') {
return 500;
}
const n = parseInt(raw, 10);
if (!Number.isFinite(n)) {
return 500;
}
return Math.min(30000, Math.max(200, n));
}
function wpRetryOpts() {
return {
maxAttempts: wpHttpMaxAttempts(),
baseDelayMs: wpRetryBaseMs(),
logLabel: 'WordPress'
};
}
module.exports = { wpRetryOpts };
+2 -2
View File
@@ -3,7 +3,7 @@
const { XMLParser } = require('fast-xml-parser');
const logger = require('../logger');
const { axiosPostWithRetry } = require('../util/http-retry');
const { wpRetryOpts } = require('./wp-http-options');
const HttpRetryConfig = require('../util/http-retry-config');
const { resolveWpStatus } = require('./wp-publish-hours');
const { metrics } = require('../monitoring/metrics');
@@ -183,7 +183,7 @@ async function postXmlRpc(endpoint, methodName, params) {
responseType: 'text',
transformResponse: [(d) => d]
},
{ ...wpRetryOpts(), urlHint: `xmlrpc ${methodName}` }
{ ...HttpRetryConfig.forWordPress().toRetryOpts(), urlHint: `xmlrpc ${methodName}` }
);
const raw = typeof response.data === 'string' ? response.data : String(response.data);
const parser = new XMLParser({
+207
View File
@@ -0,0 +1,207 @@
'use strict';
/**
* Centralized HTTP retry configuration.
* Consolidates retry logic from RSS, X, and WordPress clients into a single class.
* Supports backward-compatible environment variables while encouraging migration to unified vars.
*/
class HttpRetryConfig {
/**
* @param {Object} options
* @param {number} [options.maxAttempts] - Max HTTP attempts (default: from env or 3)
* @param {number} [options.baseDelayMs] - Base delay in milliseconds (default: from env or 500)
* @param {number} [options.maxDelayMs] - Max delay cap for exponential backoff (default: from env or 60000)
* @param {string} [options.component] - Component name for logging ('rss', 'x', 'wordpress', etc.)
* @param {number} [options.timeoutMs] - HTTP request timeout in milliseconds (optional, component-specific)
*/
constructor(options = {}) {
// Read from options or environment
this.maxAttempts =
options.maxAttempts ?? HttpRetryConfig.readMaxAttempts(options.component);
this.baseDelayMs =
options.baseDelayMs ?? HttpRetryConfig.readBaseDelayMs(options.component);
this.maxDelayMs = options.maxDelayMs ?? HttpRetryConfig.readMaxDelayMs();
this.component = options.component || 'http';
this.timeoutMs = options.timeoutMs;
// Validate bounds
this._validateBounds();
}
/**
* Validate configuration bounds.
* @private
*/
_validateBounds() {
if (!Number.isFinite(this.maxAttempts) || this.maxAttempts < 1 || this.maxAttempts > 10) {
throw new Error(`maxAttempts must be between 1 and 10, got ${this.maxAttempts}`);
}
if (!Number.isFinite(this.baseDelayMs) || this.baseDelayMs < 100 || this.baseDelayMs > 120000) {
throw new Error(`baseDelayMs must be between 100 and 120000, got ${this.baseDelayMs}`);
}
if (!Number.isFinite(this.maxDelayMs) || this.maxDelayMs < 100 || this.maxDelayMs > 600000) {
throw new Error(`maxDelayMs must be between 100 and 600000, got ${this.maxDelayMs}`);
}
if (this.baseDelayMs > this.maxDelayMs) {
throw new Error(
`baseDelayMs (${this.baseDelayMs}) cannot exceed maxDelayMs (${this.maxDelayMs})`
);
}
}
/**
* Read HTTP_MAX_ATTEMPTS from environment, with fallback to component-specific vars.
* Priority: HTTP_MAX_ATTEMPTS > {COMPONENT}_HTTP_MAX_ATTEMPTS > default (3)
* @private
*/
static readMaxAttempts(component = '') {
// First try unified var
const unified = HttpRetryConfig._parseIntEnv('HTTP_MAX_ATTEMPTS');
if (unified !== null) {
return Math.min(10, Math.max(1, unified));
}
// Fallback to component-specific vars (backward compatibility)
if (component) {
// Map component names to legacy abbreviations
const abbrevMap = { rss: 'RSS', x: 'X', wordpress: 'WP' };
const abbrev = abbrevMap[component.toLowerCase()] || component.toUpperCase();
// Try legacy abbreviated name (RSS_, X_, WP_)
let legacy = HttpRetryConfig._parseIntEnv(`${abbrev}_HTTP_MAX_ATTEMPTS`);
if (legacy !== null) {
return Math.min(5, Math.max(1, legacy));
}
// Try full component name as fallback
legacy = HttpRetryConfig._parseIntEnv(`${component.toUpperCase()}_HTTP_MAX_ATTEMPTS`);
if (legacy !== null) {
return Math.min(5, Math.max(1, legacy));
}
}
// Default
return 3;
}
/**
* Read HTTP_RETRY_BASE_MS from environment, with fallback to component-specific vars.
* Priority: HTTP_RETRY_BASE_MS > {COMPONENT}_RETRY_BASE_MS > default (500)
* @private
*/
static readBaseDelayMs(component = '') {
// First try unified var
const unified = HttpRetryConfig._parseIntEnv('HTTP_RETRY_BASE_MS');
if (unified !== null) {
return Math.min(120000, Math.max(100, unified));
}
// Fallback to component-specific vars (backward compatibility)
if (component) {
// Map component names to legacy abbreviations
const abbrevMap = { rss: 'RSS', x: 'X', wordpress: 'WP' };
const abbrev = abbrevMap[component.toLowerCase()] || component.toUpperCase();
// Try legacy abbreviated name (RSS_, X_, WP_)
let legacy = HttpRetryConfig._parseIntEnv(`${abbrev}_RETRY_BASE_MS`);
if (legacy !== null) {
return Math.min(60000, Math.max(200, legacy));
}
// Try full component name as fallback
legacy = HttpRetryConfig._parseIntEnv(`${component.toUpperCase()}_RETRY_BASE_MS`);
if (legacy !== null) {
return Math.min(60000, Math.max(200, legacy));
}
}
// Default
return 500;
}
/**
* Read HTTP_RETRY_MAX_MS from environment.
* This caps the maximum delay during exponential backoff.
* Default: 60000 (60 seconds)
* @private
*/
static readMaxDelayMs() {
const value = HttpRetryConfig._parseIntEnv('HTTP_RETRY_MAX_MS');
if (value !== null) {
return Math.min(600000, Math.max(100, value));
}
return 60000;
}
/**
* Safe integer parsing from environment variable.
* Returns null if not set or invalid.
* @private
*/
static _parseIntEnv(key) {
const raw = process.env[key];
if (raw === undefined || raw === '') {
return null;
}
const n = parseInt(raw, 10);
return Number.isFinite(n) ? n : null;
}
/**
* Factory: Create config for RSS crawler.
* @param {Object} [overrides]
* @returns {HttpRetryConfig}
*/
static forRss(overrides = {}) {
return new HttpRetryConfig({
component: 'rss',
...overrides
});
}
/**
* Factory: Create config for X (Twitter) API client.
* @param {Object} [overrides]
* @returns {HttpRetryConfig}
*/
static forX(overrides = {}) {
return new HttpRetryConfig({
component: 'x',
...overrides
});
}
/**
* Factory: Create config for WordPress REST publisher.
* @param {Object} [overrides]
* @returns {HttpRetryConfig}
*/
static forWordPress(overrides = {}) {
return new HttpRetryConfig({
component: 'wordpress',
...overrides
});
}
/**
* Get the retry configuration as an object suitable for passing to axiosGetWithRetry/axiosPostWithRetry.
* @returns {Object} { maxAttempts, baseDelayMs, logLabel }
*/
toRetryOpts() {
const componentLabel = this.component.charAt(0).toUpperCase() + this.component.slice(1);
return {
maxAttempts: this.maxAttempts,
baseDelayMs: this.baseDelayMs,
logLabel: componentLabel
};
}
/**
* String representation for debugging.
*/
toString() {
return `HttpRetryConfig(${this.component}: maxAttempts=${this.maxAttempts}, baseDelayMs=${this.baseDelayMs}ms, maxDelayMs=${this.maxDelayMs}ms)`;
}
}
module.exports = HttpRetryConfig;
+295
View File
@@ -0,0 +1,295 @@
'use strict';
const { describe, it, beforeEach } = require('node:test');
const assert = require('node:assert/strict');
const HttpRetryConfig = require('./http-retry-config');
// Helper: save and restore env vars - clears all HTTP-related vars first
function withCleanEnv(vars, fn) {
const relevant = [
'HTTP_MAX_ATTEMPTS',
'HTTP_RETRY_BASE_MS',
'HTTP_RETRY_MAX_MS',
'RSS_HTTP_MAX_ATTEMPTS',
'RSS_RETRY_BASE_MS',
'X_HTTP_MAX_ATTEMPTS',
'X_RETRY_BASE_MS',
'WP_HTTP_MAX_ATTEMPTS',
'WP_RETRY_BASE_MS'
];
const original = {};
// Save all relevant vars
for (const key of relevant) {
original[key] = process.env[key];
}
// Clear all relevant vars
for (const key of relevant) {
delete process.env[key];
}
// Set the desired vars
for (const [key, value] of Object.entries(vars)) {
if (value !== undefined) {
process.env[key] = value;
}
}
try {
return fn();
} finally {
// Restore all relevant vars
for (const key of relevant) {
if (original[key] === undefined) {
delete process.env[key];
} else {
process.env[key] = original[key];
}
}
}
}
describe('HttpRetryConfig', () => {
it('default configuration', () => {
const config = withCleanEnv({}, () => new HttpRetryConfig());
assert.equal(config.maxAttempts, 3);
assert.equal(config.baseDelayMs, 500);
assert.equal(config.maxDelayMs, 60000);
assert.equal(config.component, 'http');
assert.equal(config.timeoutMs, undefined);
});
it('constructor with explicit options', () => {
const config = new HttpRetryConfig({
maxAttempts: 5,
baseDelayMs: 1000,
maxDelayMs: 120000,
component: 'test',
timeoutMs: 30000
});
assert.equal(config.maxAttempts, 5);
assert.equal(config.baseDelayMs, 1000);
assert.equal(config.maxDelayMs, 120000);
assert.equal(config.component, 'test');
assert.equal(config.timeoutMs, 30000);
});
it('unified HTTP_MAX_ATTEMPTS env var', () => {
const config = withCleanEnv({ HTTP_MAX_ATTEMPTS: '5' }, () =>
new HttpRetryConfig()
);
assert.equal(config.maxAttempts, 5);
});
it('unified HTTP_RETRY_BASE_MS env var', () => {
const config = withCleanEnv({ HTTP_RETRY_BASE_MS: '1000' }, () =>
new HttpRetryConfig()
);
assert.equal(config.baseDelayMs, 1000);
});
it('unified HTTP_RETRY_MAX_MS env var', () => {
const config = withCleanEnv({ HTTP_RETRY_MAX_MS: '120000' }, () =>
new HttpRetryConfig()
);
assert.equal(config.maxDelayMs, 120000);
});
it('legacy RSS_HTTP_MAX_ATTEMPTS env var (backward compatibility)', () => {
const config = withCleanEnv(
{ RSS_HTTP_MAX_ATTEMPTS: '4' },
() => new HttpRetryConfig({ component: 'rss' })
);
assert.equal(config.maxAttempts, 4);
});
it('legacy X_RETRY_BASE_MS env var (backward compatibility)', () => {
const config = withCleanEnv(
{ X_RETRY_BASE_MS: '2000' },
() => new HttpRetryConfig({ component: 'x' })
);
assert.equal(config.baseDelayMs, 2000);
});
it('legacy WP_HTTP_MAX_ATTEMPTS env var (backward compatibility)', () => {
const config = withCleanEnv(
{ WP_HTTP_MAX_ATTEMPTS: '5' },
() => new HttpRetryConfig({ component: 'wordpress' })
);
assert.equal(config.maxAttempts, 5);
});
it('unified env vars take precedence over legacy component-specific vars', () => {
const config = withCleanEnv(
{
HTTP_MAX_ATTEMPTS: '7',
RSS_HTTP_MAX_ATTEMPTS: '2'
},
() => new HttpRetryConfig({ component: 'rss' })
);
assert.equal(config.maxAttempts, 7);
});
it('explicit options override all env vars', () => {
const config = withCleanEnv(
{
HTTP_MAX_ATTEMPTS: '5',
RSS_HTTP_MAX_ATTEMPTS: '3'
},
() => new HttpRetryConfig({ component: 'rss', maxAttempts: 9 })
);
assert.equal(config.maxAttempts, 9);
});
it('bounds checking: maxAttempts min (1)', () => {
const config = new HttpRetryConfig({ maxAttempts: 1 });
assert.equal(config.maxAttempts, 1);
});
it('bounds checking: maxAttempts max (10)', () => {
const config = new HttpRetryConfig({ maxAttempts: 10 });
assert.equal(config.maxAttempts, 10);
});
it('bounds checking: invalid maxAttempts (too low)', () => {
assert.throws(() => new HttpRetryConfig({ maxAttempts: 0 }), /maxAttempts/);
});
it('bounds checking: invalid maxAttempts (too high)', () => {
assert.throws(() => new HttpRetryConfig({ maxAttempts: 11 }), /maxAttempts/);
});
it('bounds checking: baseDelayMs min (100)', () => {
const config = new HttpRetryConfig({ baseDelayMs: 100 });
assert.equal(config.baseDelayMs, 100);
});
it('bounds checking: baseDelayMs max (120000)', () => {
const config = new HttpRetryConfig({ baseDelayMs: 120000, maxDelayMs: 120000 });
assert.equal(config.baseDelayMs, 120000);
});
it('bounds checking: invalid baseDelayMs (too low)', () => {
assert.throws(() => new HttpRetryConfig({ baseDelayMs: 50 }), /baseDelayMs/);
});
it('bounds checking: invalid baseDelayMs (too high)', () => {
assert.throws(() => new HttpRetryConfig({ baseDelayMs: 200000 }), /baseDelayMs/);
});
it('bounds checking: baseDelayMs cannot exceed maxDelayMs', () => {
assert.throws(
() =>
new HttpRetryConfig({
baseDelayMs: 100000,
maxDelayMs: 50000
}),
/baseDelayMs/
);
});
it('factory method: forRss', () => {
const config = withCleanEnv({ RSS_HTTP_MAX_ATTEMPTS: '4' }, () =>
HttpRetryConfig.forRss()
);
assert.equal(config.component, 'rss');
assert.equal(config.maxAttempts, 4);
});
it('factory method: forRss with overrides', () => {
const config = HttpRetryConfig.forRss({ maxAttempts: 5 });
assert.equal(config.component, 'rss');
assert.equal(config.maxAttempts, 5);
});
it('factory method: forX', () => {
const config = withCleanEnv({ X_RETRY_BASE_MS: '2000' }, () =>
HttpRetryConfig.forX()
);
assert.equal(config.component, 'x');
assert.equal(config.baseDelayMs, 2000);
});
it('factory method: forX with overrides', () => {
const config = HttpRetryConfig.forX({ baseDelayMs: 1500 });
assert.equal(config.component, 'x');
assert.equal(config.baseDelayMs, 1500);
});
it('factory method: forWordPress', () => {
const config = withCleanEnv({ WP_HTTP_MAX_ATTEMPTS: '5' }, () =>
HttpRetryConfig.forWordPress()
);
assert.equal(config.component, 'wordpress');
assert.equal(config.maxAttempts, 5);
});
it('factory method: forWordPress with overrides', () => {
const config = HttpRetryConfig.forWordPress({ maxAttempts: 4 });
assert.equal(config.component, 'wordpress');
assert.equal(config.maxAttempts, 4);
});
it('toRetryOpts returns correct shape', () => {
const config = new HttpRetryConfig({
maxAttempts: 5,
baseDelayMs: 1000,
component: 'rss'
});
const opts = config.toRetryOpts();
assert.equal(opts.maxAttempts, 5);
assert.equal(opts.baseDelayMs, 1000);
assert.equal(opts.logLabel, 'Rss');
});
it('toRetryOpts capitalizes component name', () => {
const config = HttpRetryConfig.forWordPress();
const opts = config.toRetryOpts();
assert.equal(opts.logLabel, 'Wordpress');
});
it('toString representation', () => {
const config = new HttpRetryConfig({
maxAttempts: 5,
baseDelayMs: 1000,
component: 'test'
});
const str = config.toString();
assert.ok(str.includes('test'));
assert.ok(str.includes('5'));
assert.ok(str.includes('1000'));
});
it('env var with invalid value defaults correctly', () => {
const config = withCleanEnv({ HTTP_MAX_ATTEMPTS: 'not-a-number' }, () =>
new HttpRetryConfig()
);
assert.equal(config.maxAttempts, 3);
});
it('env var out of range is clamped to bounds', () => {
const config = withCleanEnv({ HTTP_MAX_ATTEMPTS: '999' }, () =>
new HttpRetryConfig()
);
assert.equal(config.maxAttempts, 10); // Clamped to max
});
it('negative env var is clamped to bounds', () => {
const config = withCleanEnv({ HTTP_RETRY_BASE_MS: '-1000' }, () =>
new HttpRetryConfig()
);
assert.equal(config.baseDelayMs, 100); // Clamped to min
});
it('empty env var string uses default', () => {
const config = withCleanEnv({ HTTP_MAX_ATTEMPTS: '' }, () =>
new HttpRetryConfig()
);
assert.equal(config.maxAttempts, 3);
});
});