feat(bloomberg): enrich article content for summaries (#36)

This commit is contained in:
2026-11-24 13:44:52 +01:00
parent 686f66a437
commit a53aec7947
22 changed files with 1148 additions and 127 deletions

View File

@ -0,0 +1,92 @@
const { test } = require('node:test')
const assert = require('node:assert/strict')
const { extractArticle, enrichArticles, MAX_CONTENT_BYTES } = require('../article-content')
const paragraph = 'ArticleBodyText_articleBodyContent__17wqE typography_articleBody___5jDr'
const basic = text => `<article class="articleLayout_basic__gcpQk"><div class="body-content"><p class="${paragraph}">${text}</p><div class="placeholder"><p class="${paragraph}">excluded placeholder</p></div></div></article>`
test('observed basic and feature layouts extract only editorial paragraphs within the observed root', () => {
for (const html of [basic(' First <em>synthetic</em> paragraph. '), `<article><div class="FeatureContent_body__NTf8M"><p class="${paragraph}"> First <em>synthetic</em> paragraph. </p></div></article>`]) {
const result = extractArticle(`<nav>excluded navigation</nav><meta name="iso-8601-publish-date" content="2026-01-02T03:04:05Z">${html}`)
assert.equal(result.content, 'First synthetic paragraph.')
assert.equal(result.published_at, '2026-01-02T03:04:05.000Z')
}
})
test('no broad article/main or JSON-LD content fallback; paragraph normalization', () => {
assert.equal(extractArticle('<main><article><p>excluded generic body</p></article></main><script type="application/ld+json">bad</script>').content, '')
assert.equal(extractArticle('<script type="application/ld+json">{"@type":"NewsArticle","articleBody":"excluded"}</script>').content, '')
assert.equal(extractArticle(basic('one&nbsp; two<script>excluded</script>') .replace('</div></article>', `<p class="${paragraph}"> three\n four </p></div></article>`)).content, 'one two\n\nthree four')
})
test('oversized non-ASCII content is deterministically bounded on UTF-8 boundaries', () => {
const html = basic('é漢🙂'.repeat(MAX_CONTENT_BYTES))
const first = extractArticle(html)
assert.equal(first.content, extractArticle(html).content)
assert.ok(Buffer.byteLength(first.content) <= MAX_CONTENT_BYTES)
assert.ok(!first.content.includes('\ufffd'))
assert.equal(first.content_truncated, true)
})
test('enrichment deduplicates loads, bounds concurrency and preserves input order', async () => {
const urls = ['a', 'b', 'a', 'c'].map(id => `https://www.bloomberg.com/news/articles/${id}`)
const calls = []; let active = 0; let peak = 0
const result = await enrichArticles(urls, async url => {
calls.push(url); active++; peak = Math.max(peak, active)
await new Promise(resolve => setTimeout(resolve, url.endsWith('/a') ? 10 : 1))
active--; return basic('synthetic ' + url.slice(-1))
}, { concurrency: 2, articleTimeoutMs: 100, totalTimeoutMs: 200 })
assert.equal(calls.length, 3); assert.equal(peak, 2)
assert.deepEqual(result.map(v => v.url), urls)
assert.deepEqual(result.map(v => v.content), ['synthetic a', 'synthetic b', 'synthetic a', 'synthetic c'])
})
test('failure and ignored cancellation stay bounded without reusing occupied slots', async () => {
const urls = ['a', 'b', 'c'].map(id => `https://www.bloomberg.com/news/articles/${id}`)
let calls = 0
const result = await enrichArticles(urls, async () => { calls++; return new Promise(() => {}) }, { concurrency: 2, articleTimeoutMs: 5, totalTimeoutMs: 20 })
assert.equal(calls, 2); assert.ok(result.every(v => v.content === '' && v.published_at === null))
const failed = await enrichArticles(urls, async () => { throw new Error('private') }, { articleTimeoutMs: 10, totalTimeoutMs: 50 })
assert.ok(failed.every(v => v.content === '' && v.published_at === null))
})
test('JSON-LD belonging to another article cannot supply this article date', () => {
const html = basic('synthetic paragraph') + '<script type="application/ld+json">{"@type":"NewsArticle","url":"https://www.bloomberg.com/news/articles/other","datePublished":"2026-01-02T03:04:05Z"}</script>'
const result = extractArticle(html, 'https://www.bloomberg.com/news/articles/current')
assert.equal(result.content, 'synthetic paragraph')
assert.equal(result.published_at, null)
})
test('sanitized structural fixtures exclude placeholders, recommendations and disclaimers', () => {
const fs = require('node:fs'); const path = require('node:path')
const load = name => fs.readFileSync(path.join(__dirname, 'fixtures', name), 'utf8')
assert.equal(extractArticle(load('content-basic.html')).content, 'Synthetic first paragraph.\n\nSynthetic second paragraph.')
assert.equal(extractArticle(load('content-feature.html')).content, 'Synthetic feature paragraph.')
})
test('aborted enrichment and invalid URLs never invoke a loader', async () => {
let calls = 0; const controller = new AbortController(); controller.abort()
const urls = ['https://www.bloomberg.com/news/articles/a']
const result = await enrichArticles(urls, async () => { calls++; return basic('unused') }, { signal: controller.signal })
assert.equal(calls, 0); assert.equal(result[0].content, '')
await enrichArticles(['http://127.0.0.1/news/articles/a', 'https://other.invalid/news/articles/a'], async () => { calls++; return '' })
assert.equal(calls, 0)
})
test('remaining pool budget gives every candidate a bounded attempt with an offline clock', async t => {
t.mock.timers.enable({ apis: ['setTimeout', 'Date'] })
const urls = Array.from({ length: 30 }, (_, i) => `https://www.bloomberg.com/news/articles/pool-${i}`)
let active = 0; let peak = 0; let calls = 0; const slices = []
let done = false
const operation = enrichArticles(urls, async (_url, options) => {
calls++; active++; peak = Math.max(peak, active); slices.push(options.timeoutMs)
try { await new Promise((resolve, reject) => options.signal.addEventListener('abort', () => reject(new Error('private')), { once: true })) } finally { active-- }
}, { concurrency: 2, articleTimeoutMs: 100, totalTimeoutMs: 1000 }).then(result => { done = true; return result })
for (let i = 0; i < 20 && !done; i++) {
await new Promise(resolve => setImmediate(resolve))
t.mock.timers.tick(62)
}
const result = await operation
assert.equal(calls, 30); assert.equal(peak, 2); assert.equal(active, 0)
assert.ok(slices.every(ms => ms <= 62))
assert.deepEqual(result.map(a => a.url), urls)
assert.ok(result.every(a => a.content === '' && a.published_at === null))
})
test('editorial descendants preserve document order and exclude non-editorial ancestors', () => {
const html = `<article><div class="FeatureContent_body__NTf8M"><div><section><p class="${paragraph}">one</p></section></div><aside><div><p class="${paragraph}">excluded</p></div></aside><div hidden><p class="${paragraph}">excluded</p></div><div data-component="related-stories"><p class="${paragraph}">excluded</p></div><div><div><p class="${paragraph}">two</p></div></div></div></article>`
assert.equal(extractArticle(html).content,'one\n\ntwo')
})

View File

@ -0,0 +1,81 @@
const { test } = require('node:test')
const assert = require('node:assert/strict')
const fs = require('node:fs')
const path = require('node:path')
const vm = require('node:vm')
const { createRequire } = require('node:module')
const html = '<meta name="iso-8601-publish-date" content="2026-01-02T03:04:05Z"><article class="articleLayout_basic__gcpQk"><div class="body-content"><p class="ArticleBodyText_articleBodyContent__17wqE">Synthetic editorial paragraph.</p></div></article>'
async function request (byparr, failOne = false, poolSize = 2, authTimeout = false) {
const routes = {}; const loads = []; const logs = []; const timers = []; let pages = 0; let closed = false; let active = 0; let peak = 0
const app = { use () {}, get () {}, post (url, handler) { routes[url] = handler }, listen () {} }
const express = () => app; express.json = () => () => {}
function page (auth) {
let url = ''; let evals = 0
return {
async setViewport () {}, async evaluateOnNewDocument () {}, async waitForSelector () {}, async type () {}, async waitForFunction () {},
async waitForNavigation () { url = 'https://www.bloomberg.com/markets' }, async evaluate () { return evals++ === 0 ? [] : true },
async $ () { return null }, keyboard: { async press () {} },
async goto (value) { url = value; if (auth && authTimeout) return new Promise(() => {}); if (!auth) { loads.push(value); active++; peak = Math.max(peak, active); await new Promise(resolve => setTimeout(resolve, 1)); active-- } }, url () { return url },
async content () { return html }, async close () {}
}
}
const browser = { async newPage () { return page(pages++ === 0) }, async close () { closed = true } }
const index = path.resolve(__dirname, '../index.js'); const localRequire = createRequire(index)
vm.runInNewContext(fs.readFileSync(index, 'utf8'), {
require (name) {
if (name === 'express') return express
if (name === 'puppeteer-extra') return { use () {}, async launch () { return browser } }
if (name === 'puppeteer-extra-plugin-stealth') return () => ({})
return localRequire(name)
},
process: { env: { BYPARR_URL: byparr ? 'http://fixture.invalid' : '' } }, AbortController,
setTimeout (fn, ms) { timers.push(ms); if (authTimeout && ms === 30000) { queueMicrotask(fn); return undefined }; if ([2000, 800, 500, 3000].includes(ms)) { queueMicrotask(fn); return undefined }; return setTimeout(fn, ms) }, clearTimeout,
console: { log (...values) { logs.push(values.join(' ')) }, error (...values) { logs.push(values.join(' ')) } },
async fetch (_url, options) {
const body = JSON.parse(options.body); loads.push(body.url); active++; peak = Math.max(peak, active)
assert.ok(body.maxTimeout <= 30000); assert.ok(options.signal)
await new Promise(resolve => setTimeout(resolve, 1)); active--
if (failOne && body.url.endsWith('/b')) throw new Error('PRIVATE_BODY http://private.invalid')
return { ok: true, async json () { return { solution: { url: body.url, response: html } } } }
}
})
const urls = (poolSize === 2 ? ['a', 'b', 'a'] : Array.from({ length: poolSize }, (_, i) => `pool-${i}`)).map(id => `https://www.bloomberg.com/news/articles/${id}`)
let result
await routes['/bloomberg/enrich']({ body: { username: 'PRIVATE_USER', password: 'PRIVATE_SECRET', urls } }, { json (value) { result = value }, status () { return this } })
assert.deepEqual(result.articles.map(a => a.url), urls)
assert.equal(loads.length, authTimeout ? 0 : poolSize)
assert.ok(logs.every(line => !line.includes('PRIVATE') && !line.includes('http') && !line.includes('Synthetic editorial')))
return { result, pages, peak, closed, timers }
}
test('Byparr enrichment endpoint returns content and date from each unique HTML load', async () => {
const { result, peak } = await request(true)
assert.equal(peak, 2)
assert.ok(result.articles.every(a => a.content === 'Synthetic editorial paragraph.' && a.published_at === '2026-01-02T03:04:05.000Z'))
})
test('one fetch failure is empty and does not lose successful candidates', async () => {
const { result } = await request(true, true)
assert.equal(result.articles[0].content, 'Synthetic editorial paragraph.')
assert.equal(result.articles[1].content, ''); assert.equal(result.articles[1].published_at, null)
})
test('Puppeteer reuses the existing login flow and closes all enrichment resources', async () => {
const { result, pages, closed, peak } = await request(false)
assert.equal(peak, 2)
assert.equal(pages, 3); assert.equal(closed, true)
assert.ok(result.articles.every(a => a.content === 'Synthetic editorial paragraph.'))
})
test('Puppeteer loads a full pool with two pages and one shared authenticated session', async () => {
const {result,pages,peak,closed,timers} = await request(false,false,30)
assert.ok(timers.includes(30000), "login must reserve article-pool time with a 30s deadline")
assert.equal(pages,31); assert.equal(peak,2); assert.equal(closed,true)
assert.equal(result.articles.length,30)
assert.ok(result.articles.every(a => a.content === 'Synthetic editorial paragraph.'))
})
test('Puppeteer login deadline returns safe empty results and closes the shared session', async () => {
const {result,closed,timers} = await request(false,false,30,true)
assert.equal(closed,true);assert.ok(timers.includes(30000))
assert.equal(result.articles.length,30)
assert.ok(result.articles.every(a => a.content === '' && a.published_at === null))
})

View File

@ -0,0 +1,11 @@
<nav>excluded navigation</nav>
<article class="articleLayout_basic__gcpQk">
<header>excluded heading</header>
<div class="body-content">
<div class="editorial-wrapper"><div><p class="ArticleBodyText_articleBodyContent__17wqE typography_articleBody___5jDr">Synthetic <em>first</em> paragraph.</p></div></div>
<div class="placeholder"><p class="ArticleBodyText_articleBodyContent__17wqE">excluded placeholder</p></div>
<p class="typography_articleBody___5jDr">Synthetic&nbsp;second<br>paragraph.</p>
<p class="typography_articleBody___5jDr" data-component="disclaimer">excluded disclaimer</p>
</div>
<aside>excluded recommendations</aside>
</article>

View File

@ -0,0 +1,7 @@
<article>
<div class="FeatureContent_body__NTf8M">
<div><div class="editorial-wrapper"><p class="ArticleBodyText_articleBodyContent__17wqE typography_articleBody___5jDr">Synthetic feature paragraph.</p></div></div>
<div data-component="related-stories"><p class="typography_articleBody___5jDr">excluded recommendation</p></div>
</div>
<footer>excluded footer</footer>
</article>