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

104 lines
6.0 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
function extractArticle (html, articleURL) {
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 roots = $('article.articleLayout_basic__gcpQk div.body-content, article div.FeatureContent_body__NTf8M')
const root = roots.length === 1 ? roots.first() : $()
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"], .placeholder, .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')
// Keep the full editorial extraction; resource limits reject an extraction
// rather than turning a prefix into a supposedly complete article.
const blocked = $('[class*="paywall"], [data-test="paywall"], [data-testid="paywall"], [data-content-state="incomplete"], [data-content-truncated="true"]').length > 0
return { content: full, published_at: extractPublicationDate(html, articleURL), 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 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 })
})
.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)
}
}).catch(() => { /* Empty content, never log raw loader errors. */ })
.finally(() => { 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 }