diff --git a/README.md b/README.md index 44638e9..ea59003 100644 --- a/README.md +++ b/README.md @@ -45,7 +45,7 @@ RSS Feeds / News Sites ↓ src/writer/ai.js — OpenAI journalist AI ↓ - src/publisher/wordpress.js — WP REST API export + src/publisher/wordpress.js — WP REST API export (retries on 429 / 5xx / transient network) ↓ WordPress (draft/publish) ``` diff --git a/src/publisher/wordpress.js b/src/publisher/wordpress.js index 958ea60..25ecfd8 100644 --- a/src/publisher/wordpress.js +++ b/src/publisher/wordpress.js @@ -3,6 +3,46 @@ const axios = require('axios'); const logger = require('../logger'); +const WP_POST_MAX_ATTEMPTS = 3; +const WP_RETRY_BASE_MS = 500; + +function shouldRetryWpRequest(err) { + if (!err.response) { + const code = err.code || ''; + if (['ECONNRESET', 'ETIMEDOUT', 'ECONNABORTED', 'ENOTFOUND', 'EAI_AGAIN'].includes(code)) { + return true; + } + return typeof err.message === 'string' && err.message.toLowerCase().includes('timeout'); + } + const status = err.response.status; + return status === 429 || status === 502 || status === 503 || status === 504; +} + +async function sleepMs(ms) { + await new Promise((resolve) => setTimeout(resolve, ms)); +} + +/** + * POST with exponential backoff on transient failures. + */ +async function axiosPostWithRetry(url, data, axios_config) { + let last_err = null; + for (let attempt = 1; attempt <= WP_POST_MAX_ATTEMPTS; attempt++) { + try { + return await axios.post(url, data, axios_config); + } catch (err) { + last_err = err; + if (!shouldRetryWpRequest(err) || attempt === WP_POST_MAX_ATTEMPTS) { + throw err; + } + const delay_ms = WP_RETRY_BASE_MS * 2 ** (attempt - 1); + logger.warn(`WP POST retry ${attempt}/${WP_POST_MAX_ATTEMPTS} after error (${err.message}), waiting ${delay_ms}ms`); + await sleepMs(delay_ms); + } + } + throw last_err; +} + /** * Publish an article to a WordPress site via REST API (Application Passwords). * @@ -39,7 +79,7 @@ async function publishToWordPress(article, site_config) { const tag_ids = await resolveTagIds(article.tags || [], api_base, credentials); post_payload.tags = tag_ids; - const response = await axios.post(`${api_base}/posts`, post_payload, { + const response = await axiosPostWithRetry(`${api_base}/posts`, post_payload, { headers: { Authorization: `Basic ${credentials}`, 'Content-Type': 'application/json',