feat(scraper): bound article enrichment diagnostics (#40)

This commit is contained in:
2026-11-25 00:07:45 +01:00
parent a3c70670f6
commit 6883b3976b
53 changed files with 4049 additions and 68 deletions

View File

@ -44,16 +44,23 @@ function articleEvidence ($, expectedURL) {
return { associated, mismatch, blocked, fullBody }
}
function extractArticle (html, articleURL) {
function extractArticle (html, articleURL, observation) {
const empty = { content: '', published_at: null, content_truncated: false, content_state: 'unavailable' }
if (typeof html !== 'string' || Buffer.byteLength(html) > MAX_HTML_BYTES) return empty
const $ = cheerio.load(html)
const evidence = articleEvidence($, articleURL)
if (evidence.mismatch) return empty
const roots = $('article.articleLayout_basic__gcpQk div.body-content, article div.FeatureContent_body__NTf8M')
const root = roots.length === 1 ? roots.first() : $()
const excludedRoot = 'aside, nav, footer, [hidden], [aria-hidden="true"], [data-component="related-stories"]'
if (root.is(excludedRoot) || root.parents(excludedRoot).length) return empty
const rootExcluded = root.is(excludedRoot) || root.parents(excludedRoot).length > 0
const accessMarkers = $('[class*="giftarticle" i], [class*="paywall" i], [id*="captcha" i], [class*="captcha" i], [id^="cf-chl"], [id^="challenge"], script[src*="challenge-platform"], [data-test="paywall"], [data-testid="paywall"], [data-content-state="incomplete"], [data-content-state="partial"], [data-content-truncated="true"]').length > 0
const missing = root.find('[class*="placeholder" i], [class*="skeleton" i], [data-component="placeholder"]').addBack('[class*="placeholder" i], [class*="skeleton" i]').length > 0
if (observation) {
observation.root = roots.length === 1 && !rootExcluded ? 'yes' : 'no'
observation.identity = evidence.mismatch ? 'mismatch' : evidence.associated ? 'yes' : 'no'
observation.blocking = evidence.blocked || accessMarkers || missing ? 'yes' : 'no'
}
if (evidence.mismatch || rootExcluded) return empty
const paragraphs = []
root.find('p.ArticleBodyText_articleBodyContent__17wqE, p.typography_articleBody___5jDr, h1, h2, h3, h4, h5, h6, li, blockquote, pre, figcaption, tr').each((_, node) => {
const excluded = 'script, style, noscript, nav, aside, footer, button, form, svg, [hidden], [aria-hidden="true"], [class*="placeholder" i], [class*="skeleton" i], .disclaimer, [data-component="placeholder"], [data-component="disclaimer"], [data-component="related-stories"]'
@ -68,10 +75,7 @@ function extractArticle (html, articleURL) {
if (text) paragraphs.push(text)
})
const full = paragraphs.join('\n\n')
// Keep the full editorial extraction; resource limits reject an extraction
// rather than turning a prefix into a supposedly complete article.
const accessMarkers = $('[class*="giftarticle" i], [class*="paywall" i], [id*="captcha" i], [class*="captcha" i], [id^="cf-chl"], [id^="challenge"], script[src*="challenge-platform"], [data-test="paywall"], [data-testid="paywall"], [data-content-state="incomplete"], [data-content-state="partial"], [data-content-truncated="true"]').length > 0
const missing = root.find('[class*="placeholder" i], [class*="skeleton" i], [data-component="placeholder"]').addBack('[class*="placeholder" i], [class*="skeleton" i]').length > 0
if (observation) { observation.characters = 0; for (const _ of full) { if (++observation.characters > 2000) break } }
const normalized = value => value.normalize('NFC').replace(/\s+/gu, ' ').trim()
const bodyConflict = evidence.fullBody !== null && normalized(evidence.fullBody) !== normalized(full)
const blocked = evidence.blocked || accessMarkers || missing || bodyConflict || !evidence.associated
@ -120,21 +124,29 @@ async function enrichArticles (urls, loadHtml, options = {}) {
controllers.add(controller)
const remaining = Math.max(1, Math.min(poolArticleTimeoutMs, deadline - Date.now()))
const articleDeadline = Date.now() + remaining
const observation = {state:'unavailable',characters:0}
let recorded = false; let started = false
const finishObservation = () => {if (!recorded && started) {recorded=true;options.metrics?.record(observation)}}
controller.signal.addEventListener('abort',finishObservation,{once:true})
const timer = setTimeout(() => controller.abort(), remaining)
// A slot is not reused until the actual loader settles. If it ignores
// cancellation, the total budget ends the response without starting more
// work in that slot; underlying concurrency remains <=2.
const operation = Promise.resolve().then(() => {
if (expired || controller.signal.aborted || Date.now() >= deadline) throw new Error('enrichment expired')
return loadHtml(key, { signal: controller.signal, timeoutMs: remaining })
started = true
return loadHtml(key, { signal: controller.signal, timeoutMs: remaining,
observeHTTPStatus: status => {if(!recorded)observation.httpStatus=status},
observeIdentityMismatch: () => {if(!recorded)observation.identity='mismatch'}
})
})
.then(html => {
if (!expired && !controller.signal.aborted && Date.now() < articleDeadline && Date.now() < deadline) {
const extracted = extractArticle(html, key)
if (Date.now() < articleDeadline && Date.now() < deadline) results.set(key, extracted)
const extracted = extractArticle(html, key, options.metrics ? observation : undefined)
if (Date.now() < articleDeadline && Date.now() < deadline) {results.set(key, extracted);observation.state=extracted.content_state}
}
}).catch(() => { /* Empty content, never log raw loader errors. */ })
.finally(() => { clearTimeout(timer); controllers.delete(controller) })
.finally(() => { finishObservation(); controller.signal.removeEventListener('abort',finishObservation); clearTimeout(timer); controllers.delete(controller) })
await Promise.race([operation, budgetDone])
}
}