fix(writer-pipeline): retry WP draft POSTs; demote transient fetch noise (BIT-30583) #49
No files matched your search
@@ -35,6 +35,34 @@ describe('cycleErrorMessageLevel', () => {
|
||||
'warning',
|
||||
);
|
||||
});
|
||||
|
||||
it('downgrades per-item draft undici fetch failed to warning (BIT-30583)', () => {
|
||||
assert.equal(
|
||||
cycleErrorMessageLevel(
|
||||
'draft https://www.record.pt/modalidades/andebol/detalhe/benfica-bate-abc-e-comanda-o-campeonato-feminino?ref=Andebol_DestaquesPrincipais: fetch failed',
|
||||
),
|
||||
'warning',
|
||||
);
|
||||
assert.equal(
|
||||
cycleErrorMessageLevel(
|
||||
'draft https://example.com/a: WP draft network error: fetch failed',
|
||||
),
|
||||
'warning',
|
||||
);
|
||||
});
|
||||
|
||||
it('keeps non-network draft failures as error', () => {
|
||||
assert.equal(
|
||||
cycleErrorMessageLevel('draft https://example.com/a: WP draft failed 401: unauthorized'),
|
||||
'error',
|
||||
);
|
||||
assert.equal(
|
||||
cycleErrorMessageLevel(
|
||||
'draft https://example.com/a: Mandatory featured image: no og:image for https://example.com/a',
|
||||
),
|
||||
'error',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('reportCycleErrors', () => {
|
||||
|
||||
@@ -58,20 +58,52 @@ export async function fetchTextWithRetry(
|
||||
export async function fetchBinaryWithRetry(
|
||||
url: string,
|
||||
opts: FetchBinaryOptions = {},
|
||||
): Promise<Response> {
|
||||
return fetchResponseWithRetry(url, {
|
||||
method: 'GET',
|
||||
timeoutMs: opts.timeoutMs ?? 20_000,
|
||||
retries: opts.retries ?? 2,
|
||||
headers: {
|
||||
'User-Agent': opts.userAgent ?? DEFAULT_UA,
|
||||
...(opts.headers ?? {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export interface FetchResponseOptions {
|
||||
method?: string;
|
||||
timeoutMs?: number;
|
||||
retries?: number;
|
||||
headers?: Record<string, string>;
|
||||
body?: BodyInit | null;
|
||||
/** Retry on HTTP 5xx (default true). */
|
||||
retryOn5xx?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* fetch with bounded retries for transient network errors (and optional 5xx).
|
||||
* Used for WP REST POSTs that previously threw bare undici "fetch failed" (BIT-30583).
|
||||
*/
|
||||
export async function fetchResponseWithRetry(
|
||||
url: string,
|
||||
opts: FetchResponseOptions = {},
|
||||
): Promise<Response> {
|
||||
const timeoutMs = opts.timeoutMs ?? 20_000;
|
||||
const retries = Math.max(0, opts.retries ?? 2);
|
||||
const ua = opts.userAgent ?? DEFAULT_UA;
|
||||
const extraHeaders = opts.headers ?? {};
|
||||
const method = opts.method ?? 'GET';
|
||||
const headers = opts.headers ?? {};
|
||||
const retryOn5xx = opts.retryOn5xx !== false;
|
||||
let lastErr: unknown;
|
||||
for (let attempt = 0; attempt <= retries; attempt += 1) {
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
method,
|
||||
redirect: 'follow',
|
||||
headers: { 'User-Agent': ua, ...extraHeaders },
|
||||
headers,
|
||||
body: opts.body ?? undefined,
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
});
|
||||
if (res.status >= 500 && attempt < retries) {
|
||||
if (retryOn5xx && res.status >= 500 && attempt < retries) {
|
||||
await sleep(400 * (attempt + 1));
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -2,6 +2,16 @@ import { reportError, reportMessage } from './errorReporter.js';
|
||||
|
||||
/** Map ingest cycle strings to hub severity (partial sitemap page failures are warnings, not loops). */
|
||||
export function cycleErrorMessageLevel(message: string): 'warning' | 'error' {
|
||||
// Per-item draft publish: undici transient network (BIT-30583 / ERRSIG f723b02cf00e).
|
||||
// Cycle still records the miss; Error Loop must not open high-sev tickets for one-off fetch blips.
|
||||
if (
|
||||
/^draft https?:\/\//i.test(message) &&
|
||||
/fetch failed|network error|aborted|ECONNRESET|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|socket hang up/i.test(
|
||||
message,
|
||||
)
|
||||
) {
|
||||
return 'warning';
|
||||
}
|
||||
if (!message.startsWith('sitemap')) return 'error';
|
||||
if (message.includes('truncating')) return 'warning';
|
||||
// Per-URL HTML probe failed but other pages in the same source may have succeeded.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Buffer } from 'node:buffer';
|
||||
import type { AggregatedItem } from './types.js';
|
||||
import { fetchArticleHtmlForMeta } from './legacy-fetch.js';
|
||||
import { fetchBinaryWithRetry } from './http-retry.js';
|
||||
import { fetchBinaryWithRetry, fetchResponseWithRetry } from './http-retry.js';
|
||||
import { absolutizeImageUrl, extractFeaturedImageFromHtml } from './html-meta.js';
|
||||
import {
|
||||
readWebDavArchiveFromEnv,
|
||||
@@ -198,6 +198,12 @@ export async function resolveFeaturedImageForDraft(item: AggregatedItem): Promis
|
||||
);
|
||||
}
|
||||
|
||||
function isTransientNetworkMessage(msg: string): boolean {
|
||||
return /fetch failed|aborted|ECONNRESET|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|socket hang up/i.test(
|
||||
msg,
|
||||
);
|
||||
}
|
||||
|
||||
async function downloadBinaryImage(
|
||||
imageUrl: string,
|
||||
extraHeaders?: Record<string, string>,
|
||||
@@ -206,12 +212,21 @@ async function downloadBinaryImage(
|
||||
'User-Agent': 'BitReport-news-writer-pipeline/1.0 (media)',
|
||||
...(extraHeaders ?? {}),
|
||||
};
|
||||
const res = await fetchBinaryWithRetry(imageUrl, {
|
||||
timeoutMs: 20_000,
|
||||
retries: 2,
|
||||
userAgent: headers['User-Agent'],
|
||||
headers,
|
||||
});
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetchBinaryWithRetry(imageUrl, {
|
||||
timeoutMs: 20_000,
|
||||
retries: 2,
|
||||
userAgent: headers['User-Agent'],
|
||||
headers,
|
||||
});
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
if (isTransientNetworkMessage(msg)) {
|
||||
throw new Error(`Featured image network error for ${imageUrl}: ${msg}`);
|
||||
}
|
||||
throw e instanceof Error ? e : new Error(String(e));
|
||||
}
|
||||
if (!res.ok) {
|
||||
throw new Error(`Featured image fetch failed ${res.status} for ${imageUrl}`);
|
||||
}
|
||||
@@ -255,12 +270,20 @@ async function uploadFeaturedMedia(
|
||||
const form = new FormData();
|
||||
form.append('file', blob, filename);
|
||||
|
||||
const res = await fetch(`${base}/wp/v2/media`, {
|
||||
method: 'POST',
|
||||
headers: mediaPostHeaders(cfg),
|
||||
body: form,
|
||||
signal: AbortSignal.timeout(30_000),
|
||||
});
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetchResponseWithRetry(`${base}/wp/v2/media`, {
|
||||
method: 'POST',
|
||||
headers: mediaPostHeaders(cfg),
|
||||
body: form,
|
||||
timeoutMs: 30_000,
|
||||
retries: 2,
|
||||
retryOn5xx: false,
|
||||
});
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
throw new Error(`WP media upload network error: ${msg}`);
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
const errText = await res.text().catch(() => '');
|
||||
@@ -272,15 +295,23 @@ async function uploadFeaturedMedia(
|
||||
if (!mediaId) throw new Error('WP media upload returned no id');
|
||||
|
||||
if (credit) {
|
||||
const patch = await fetch(`${base}/wp/v2/media/${mediaId}`, {
|
||||
method: 'POST',
|
||||
headers: jsonHeaders(cfg),
|
||||
body: JSON.stringify({
|
||||
alt_text: credit.slice(0, 500),
|
||||
caption: credit.slice(0, 2000),
|
||||
}),
|
||||
signal: AbortSignal.timeout(15_000),
|
||||
});
|
||||
let patch: Response;
|
||||
try {
|
||||
patch = await fetchResponseWithRetry(`${base}/wp/v2/media/${mediaId}`, {
|
||||
method: 'POST',
|
||||
headers: jsonHeaders(cfg),
|
||||
body: JSON.stringify({
|
||||
alt_text: credit.slice(0, 500),
|
||||
caption: credit.slice(0, 2000),
|
||||
}),
|
||||
timeoutMs: 15_000,
|
||||
retries: 2,
|
||||
retryOn5xx: false,
|
||||
});
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
throw new Error(`WP media caption/alt network error: ${msg}`);
|
||||
}
|
||||
if (!patch.ok) {
|
||||
const errText = await patch.text().catch(() => '');
|
||||
throw new Error(`WP media caption/alt failed ${patch.status}: ${errText.slice(0, 400)}`);
|
||||
@@ -321,12 +352,20 @@ export async function attachFeaturedImageToPost(
|
||||
): Promise<number> {
|
||||
const base = cfg.wpBase.replace(/\/$/, '');
|
||||
const mediaId = await uploadFeaturedMedia(cfg, base, imageUrl, credit, fetchHeaders);
|
||||
const res = await fetch(`${base}/wp/v2/posts/${postId}`, {
|
||||
method: 'POST',
|
||||
headers: jsonHeaders(cfg),
|
||||
body: JSON.stringify({ featured_media: mediaId }),
|
||||
signal: AbortSignal.timeout(20_000),
|
||||
});
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetchResponseWithRetry(`${base}/wp/v2/posts/${postId}`, {
|
||||
method: 'POST',
|
||||
headers: jsonHeaders(cfg),
|
||||
body: JSON.stringify({ featured_media: mediaId }),
|
||||
timeoutMs: 20_000,
|
||||
retries: 2,
|
||||
retryOn5xx: false,
|
||||
});
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
throw new Error(`WP post featured_media patch network error: ${msg}`);
|
||||
}
|
||||
if (!res.ok) {
|
||||
const errText = await res.text().catch(() => '');
|
||||
throw new Error(`WP post featured_media patch failed ${res.status}: ${errText.slice(0, 500)}`);
|
||||
@@ -358,12 +397,20 @@ export async function createDraftFromAggregatedItem(
|
||||
if (mediaId) body.featured_media = mediaId;
|
||||
if (categoryId) body.categories = [categoryId];
|
||||
|
||||
const res = await fetch(`${base}/wp/v2/posts`, {
|
||||
method: 'POST',
|
||||
headers: jsonHeaders(cfg),
|
||||
body: JSON.stringify(body),
|
||||
signal: AbortSignal.timeout(20_000),
|
||||
});
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetchResponseWithRetry(`${base}/wp/v2/posts`, {
|
||||
method: 'POST',
|
||||
headers: jsonHeaders(cfg),
|
||||
body: JSON.stringify(body),
|
||||
timeoutMs: 20_000,
|
||||
retries: 2,
|
||||
retryOn5xx: false,
|
||||
});
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
throw new Error(`WP draft network error: ${msg}`);
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
const errText = await res.text().catch(() => '');
|
||||
|
||||
Reference in new issue
Block a user