Files
TradarrV2/scraper-service/article-content.js

161 lines
10 KiB
JavaScript

const cheerio = require('cheerio')
const { extractPublicationDate } = require('./publication-date')
const MAX_CONTENT_BYTES = 16 * 1024
const MAX_HTML_BYTES = 16 * 1024 * 1024
const CONCURRENCY = 2
const ARTICLE_TIMEOUT_MS = 30000
const TOTAL_TIMEOUT_MS = 90000
// Identity is established from primary page metadata or an associated Article
// object, never from an arbitrary anchor or the presence of editorial classes.
function articleEvidence ($, expectedURL) {
const expected = canonicalURL(expectedURL)
const key = value => {
if (typeof value !== 'string' || !value.trim()) return null
try { return canonicalURL(new URL(value, expectedURL).href) } catch { return null }
}
const primary = $('link[rel="canonical"], meta[property="og:url"]').toArray().map(n => $(n).attr(n.tagName === 'link' ? 'href' : 'content')).filter(Boolean)
let associated = Boolean(expected && primary.some(v => key(v) === expected))
let mismatch = Boolean(expected && primary.some(v => key(v) !== expected))
let blocked = false; let fullBody = null; let articleIdentities = 0; let matching = false
for (const script of $('script[type="application/ld+json"]').toArray()) {
try {
const stack = [[JSON.parse($(script).text()), 0]]; let visited = 0
while (stack.length && ++visited <= 2000) {
const [node, depth] = stack.pop()
if (!node || typeof node !== 'object' || depth > 32) continue
const types = Array.isArray(node['@type']) ? node['@type'] : [node['@type']]
if (types.some(t => ['Article', 'NewsArticle', 'ReportageNewsArticle'].includes(t))) {
const identity = node.url || node.mainEntityOfPage || node['@id']
const value = typeof identity === 'string' ? identity : identity?.['@id']
if (value) articleIdentities++
if (expected && key(value) === expected) {
associated = matching = true
if (node.isAccessibleForFree === false || String(node.isAccessibleForFree).toLowerCase() === 'false') blocked = true
if (typeof node.articleBody === 'string') fullBody = node.articleBody
}
}
for (const child of Object.values(node)) if (child && typeof child === 'object') stack.push([child, depth + 1])
}
} catch { /* Unusable metadata cannot prove completeness. */ }
}
if (!primary.length && articleIdentities && !matching) mismatch = true
return { associated, mismatch, blocked, fullBody }
}
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)
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"]'
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"]'
if ($(node).parentsUntil(root).addBack().is(excluded)) return
// A nested paragraph is already represented by its enclosing editorial block.
if ($(node).parentsUntil(root, 'li, blockquote, pre, figcaption, tr').length) return
const p = $(node).clone()
if (p.is('[hidden], [aria-hidden="true"], .disclaimer, [data-component="disclaimer"], [data-component="related-stories"]')) return
p.find(excluded).remove()
p.find('br').replaceWith(' ')
const text = p.text().normalize('NFC').replace(/\s+/gu, ' ').trim()
if (text) paragraphs.push(text)
})
const full = paragraphs.join('\n\n')
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
return { content: full, published_at: evidence.associated ? extractPublicationDate(html, articleURL) : null, content_truncated: false, content_state: full ? (blocked ? 'incomplete' : 'complete') : 'unavailable' }
}
function canonicalURL (value) {
try {
if (typeof value !== 'string' || value.length > 4096) return null
const url = new URL(value)
if (url.protocol !== 'https:' || !['www.bloomberg.com', 'bloomberg.com'].includes(url.hostname) || url.username || url.password || url.port || !/^\/(news\/articles|news\/features|features)\//.test(url.pathname)) return null
url.search = ''; url.hash = ''
return url.href
} catch { return null }
}
async function enrichArticles (urls, loadHtml, options = {}) {
const concurrency = options.concurrency ?? CONCURRENCY
const articleTimeoutMs = options.articleTimeoutMs ?? ARTICLE_TIMEOUT_MS
const totalTimeoutMs = options.totalTimeoutMs ?? TOTAL_TIMEOUT_MS
if (!Number.isInteger(concurrency) || concurrency < 1 || concurrency > CONCURRENCY || !(articleTimeoutMs > 0 && articleTimeoutMs <= ARTICLE_TIMEOUT_MS) || !(totalTimeoutMs > 0 && totalTimeoutMs <= TOTAL_TIMEOUT_MS)) throw new Error('invalid enrichment budget')
const empty = () => ({ content: '', published_at: null, content_truncated: false, content_state: 'unavailable' })
const keys = urls.map(canonicalURL)
const unique = [...new Set(keys.filter(Boolean))]
const results = new Map()
const controllers = new Set()
const deadline = Date.now() + totalTimeoutMs
// Reserve one wave for scheduling/cleanup. Every unique candidate gets a
// bounded opportunity within the remaining pool budget, even after login.
const poolArticleTimeoutMs = Math.max(1, Math.min(articleTimeoutMs,
Math.floor(totalTimeoutMs / (Math.ceil(unique.length / concurrency) + 1))))
let expired = false
let next = 0
let finishBudget
const budgetDone = new Promise(resolve => { finishBudget = resolve })
const expire = () => {
expired = true
for (const controller of controllers) controller.abort()
finishBudget()
}
const totalTimer = setTimeout(expire, totalTimeoutMs)
options.signal?.addEventListener('abort', expire, { once: true })
if (options.signal?.aborted) expire()
async function worker () {
while (next < unique.length && !expired && Date.now() < deadline) {
const key = unique[next++]
const controller = new AbortController()
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')
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, 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(() => { finishObservation(); controller.signal.removeEventListener('abort',finishObservation); clearTimeout(timer); controllers.delete(controller) })
await Promise.race([operation, budgetDone])
}
}
try { await Promise.all(Array.from({ length: Math.min(concurrency, unique.length) }, worker)) } finally {
clearTimeout(totalTimer)
options.signal?.removeEventListener('abort', expire)
for (const controller of controllers) controller.abort()
}
return urls.map((url, i) => ({ url, ...(results.get(keys[i]) || empty()) }))
}
module.exports = { extractArticle, enrichArticles, canonicalURL, MAX_CONTENT_BYTES, ARTICLE_TIMEOUT_MS, TOTAL_TIMEOUT_MS }