fix(bloomberg): avoid collection timeouts
This commit is contained in:
@ -1,4 +1,4 @@
|
||||
const { withPublicationDates } = require('./publication-date')
|
||||
const { withDatesFromLoadedHtml } = require('./publication-date')
|
||||
const express = require('express')
|
||||
const cheerio = require('cheerio')
|
||||
const puppeteer = require('puppeteer-extra')
|
||||
@ -21,21 +21,24 @@ async function byparrRequest(body) {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
if (!resp.ok) throw new Error(`byparr HTTP ${resp.status}: ${await resp.text()}`)
|
||||
if (!resp.ok) {
|
||||
try { await resp.body?.cancel() } catch { /* Release without reading/logging the body. */ }
|
||||
throw new Error(`byparr HTTP ${resp.status}`)
|
||||
}
|
||||
return resp.json()
|
||||
}
|
||||
|
||||
async function byparrFetch(url, quiet = false) {
|
||||
if (!quiet) console.log('[byparr] GET', url)
|
||||
if (!quiet) console.log('[byparr] section request')
|
||||
const data = await byparrRequest({ cmd: 'request.get', url, maxTimeout: 60000 })
|
||||
const html = data.solution?.response
|
||||
if (!html) throw new Error(`byparr returned no HTML for ${url}`)
|
||||
if (!html) throw new Error('byparr returned no HTML')
|
||||
return { html }
|
||||
}
|
||||
|
||||
// ---------- Article parsing ----------
|
||||
|
||||
function parseArticlesFromHtml(html) {
|
||||
function parseArticlesFromHtml(html, loadedURL) {
|
||||
const $ = cheerio.load(html)
|
||||
const results = []
|
||||
const seen = new Set()
|
||||
@ -56,7 +59,7 @@ function parseArticlesFromHtml(html) {
|
||||
results.push({ title, url: clean })
|
||||
})
|
||||
|
||||
return results
|
||||
return withDatesFromLoadedHtml(results, html, loadedURL, $)
|
||||
}
|
||||
|
||||
// ---------- Bloomberg scraping via Byparr ----------
|
||||
@ -81,20 +84,23 @@ async function scrapeBloombergViaByparr(username, password) {
|
||||
for (const url of byparrPages) {
|
||||
try {
|
||||
const { html } = await byparrFetch(url)
|
||||
const items = parseArticlesFromHtml(html)
|
||||
const items = parseArticlesFromHtml(html, url)
|
||||
for (const item of items) {
|
||||
if (!seen.has(item.url)) {
|
||||
seen.add(item.url)
|
||||
articles.push(item)
|
||||
} else if (item.published_at) {
|
||||
const existing = articles.find(article => article.url === item.url)
|
||||
if (existing && !existing.published_at) existing.published_at = item.published_at
|
||||
}
|
||||
}
|
||||
console.log('[bloomberg]', url, '->', items.length, 'articles')
|
||||
console.log('[bloomberg] section articles:', items.length)
|
||||
} catch (e) {
|
||||
console.error('[bloomberg] error on', url, ':', e.message)
|
||||
console.error('[bloomberg] section unavailable')
|
||||
}
|
||||
}
|
||||
|
||||
return withPublicationDates(articles, async url => (await byparrFetch(url, true)).html)
|
||||
return articles
|
||||
}
|
||||
|
||||
// ---------- Bloomberg scraping via Puppeteer (fallback, may be blocked) ----------
|
||||
@ -161,8 +167,8 @@ async function scrapeBloombergViaPuppeteer(username, password) {
|
||||
type: i.type, name: i.name, id: i.id, placeholder: i.placeholder, visible: i.offsetParent !== null
|
||||
}))
|
||||
)
|
||||
console.log('[bloomberg] inputs on login page:', JSON.stringify(pageInputs))
|
||||
console.log('[bloomberg] page title:', await page.title())
|
||||
console.log('[bloomberg] login input count:', pageInputs.length)
|
||||
|
||||
|
||||
const emailOk = await tryType(page, [
|
||||
'#email-form-input',
|
||||
@ -194,7 +200,7 @@ async function scrapeBloombergViaPuppeteer(username, password) {
|
||||
} catch {
|
||||
await new Promise(r => setTimeout(r, 3000))
|
||||
}
|
||||
console.log('[bloomberg] after email submit, url:', page.url())
|
||||
console.log('[bloomberg] email step completed')
|
||||
|
||||
const pwdOk = await tryType(page, [
|
||||
'input[type="password"]',
|
||||
@ -211,10 +217,9 @@ async function scrapeBloombergViaPuppeteer(username, password) {
|
||||
])
|
||||
|
||||
const currentURL = page.url()
|
||||
console.log('[bloomberg] after login, url:', currentURL)
|
||||
console.log('[bloomberg] login navigation completed')
|
||||
if (currentURL.includes('/account/signin')) {
|
||||
const bodyText = await page.evaluate(() => document.body.innerText.slice(0, 500))
|
||||
throw new Error(`login did not redirect — page content: ${bodyText}`)
|
||||
throw new Error('login did not redirect')
|
||||
}
|
||||
|
||||
const targetPages = [
|
||||
@ -228,29 +233,29 @@ async function scrapeBloombergViaPuppeteer(username, password) {
|
||||
|
||||
for (const url of targetPages) {
|
||||
try {
|
||||
console.log('[bloomberg] scraping', url)
|
||||
console.log('[bloomberg] loading section')
|
||||
await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 })
|
||||
await page.waitForSelector('a[data-component="story-link"]', { timeout: 15000 }).catch(() => {})
|
||||
|
||||
const html = await page.content()
|
||||
const items = parseArticlesFromHtml(html)
|
||||
const items = parseArticlesFromHtml(html, url)
|
||||
|
||||
for (const item of items) {
|
||||
if (!seen.has(item.url)) {
|
||||
seen.add(item.url)
|
||||
articles.push(item)
|
||||
} else if (item.published_at) {
|
||||
const existing = articles.find(article => article.url === item.url)
|
||||
if (existing && !existing.published_at) existing.published_at = item.published_at
|
||||
}
|
||||
}
|
||||
console.log('[bloomberg]', url, '->', items.length, 'articles')
|
||||
console.log('[bloomberg] section articles:', items.length)
|
||||
} catch (e) {
|
||||
console.error('[bloomberg] error on', url, ':', e.message)
|
||||
console.error('[bloomberg] section unavailable')
|
||||
}
|
||||
}
|
||||
|
||||
return await withPublicationDates(articles, async url => {
|
||||
await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 30000 })
|
||||
return page.content()
|
||||
})
|
||||
return articles
|
||||
} finally {
|
||||
if (browser) await browser.close()
|
||||
}
|
||||
@ -279,8 +284,8 @@ app.post('/bloomberg/scrape', async (req, res) => {
|
||||
console.log('[bloomberg] total:', articles.length, 'articles')
|
||||
res.json({ articles })
|
||||
} catch (e) {
|
||||
console.error('[bloomberg] scrape error:', e.message)
|
||||
res.status(500).json({ error: e.message })
|
||||
console.error('[bloomberg] scrape unavailable')
|
||||
res.status(500).json({ error: 'scrape unavailable' })
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@ -58,14 +58,60 @@ function isArticleURL(value) {
|
||||
} catch { return false }
|
||||
}
|
||||
|
||||
async function withPublicationDates(articles, loadHtml) {
|
||||
const result = []
|
||||
for (const article of articles) {
|
||||
let published_at = null
|
||||
try { if (isArticleURL(article.url)) published_at = extractPublicationDate(await loadHtml(article.url)) } catch { /* Date stays unknown. */ }
|
||||
result.push({ ...article, published_at })
|
||||
// Only associate metadata with an article identified in this already-loaded
|
||||
// document. Section-level publication dates must never be copied onto its links.
|
||||
function withDatesFromLoadedHtml(articles, html, loadedURL, parsed) {
|
||||
const $ = parsed || cheerio.load(html)
|
||||
const dates = new Map()
|
||||
function key(value) {
|
||||
try {
|
||||
if (typeof value !== 'string' || !value.trim()) return null
|
||||
const url = new URL(value, loadedURL)
|
||||
url.search = ''
|
||||
url.hash = ''
|
||||
return isArticleURL(url.href) ? url.href : null
|
||||
} catch { return null }
|
||||
}
|
||||
return result
|
||||
const wanted = new Set(articles.map(article => key(article.url)).filter(Boolean))
|
||||
const pageKey = key(loadedURL)
|
||||
if (pageKey && wanted.has(pageKey)) {
|
||||
const date = extractPublicationDate(html)
|
||||
if (date) dates.set(pageKey, date)
|
||||
}
|
||||
for (const anchor of $('a[data-component="story-link"]').toArray()) {
|
||||
const articleKey = key($(anchor).attr('href'))
|
||||
if (!articleKey || !wanted.has(articleKey) || dates.has(articleKey)) continue
|
||||
let scope = $(anchor)
|
||||
const card = scope.closest('article')
|
||||
if (card.length) {
|
||||
const links = new Set(card.find('a[data-component="story-link"]').toArray()
|
||||
.map(link => key($(link).attr('href'))).filter(Boolean))
|
||||
if (links.size === 1 && links.has(articleKey)) scope = card
|
||||
}
|
||||
for (const [selector, attribute] of [['meta[name="iso-8601-publish-date"]', 'content'], ['time[datetime]', 'datetime']]) {
|
||||
for (const element of scope.find(selector).toArray()) {
|
||||
const date = reliableISO($(element).attr(attribute))
|
||||
if (date) { dates.set(articleKey, date); break }
|
||||
}
|
||||
if (dates.has(articleKey)) break
|
||||
}
|
||||
}
|
||||
let visited = 0
|
||||
function collect(node, depth = 0) {
|
||||
if (!node || typeof node !== 'object' || depth > 32 || ++visited > 2000) return
|
||||
const types = Array.isArray(node['@type']) ? node['@type'] : [node['@type']]
|
||||
if (types.some(type => ['Article', 'NewsArticle', 'ReportageNewsArticle'].includes(type))) {
|
||||
const identity = node.url || node.mainEntityOfPage
|
||||
const articleKey = key(typeof identity === 'string' ? identity : identity?.['@id'])
|
||||
const date = reliableISO(node.datePublished)
|
||||
if (articleKey && wanted.has(articleKey) && !dates.has(articleKey) && date) dates.set(articleKey, date)
|
||||
}
|
||||
for (const child of Object.values(node)) collect(child, depth + 1)
|
||||
}
|
||||
for (const script of $('script[type="application/ld+json"]').toArray()) {
|
||||
try { collect(JSON.parse($(script).text())) } catch { /* Unknown date, no raw metadata logging. */ }
|
||||
}
|
||||
return articles.map(article => ({ ...article, published_at: dates.get(key(article.url)) || null }))
|
||||
}
|
||||
|
||||
module.exports = { extractPublicationDate, withPublicationDates }
|
||||
module.exports = { extractPublicationDate, withDatesFromLoadedHtml }
|
||||
|
||||
@ -1,6 +1,6 @@
|
||||
const { test } = require('node:test')
|
||||
const assert = require('node:assert/strict')
|
||||
const { extractPublicationDate, withPublicationDates } = require('../publication-date')
|
||||
const { extractPublicationDate, withDatesFromLoadedHtml } = require('../publication-date')
|
||||
|
||||
test('minimal metadata fixtures preserve genuine dates with explicit zones', () => {
|
||||
assert.equal(extractPublicationDate('<meta name="iso-8601-publish-date" content="2026-01-02T03:04:05Z">'), '2026-01-02T03:04:05.000Z')
|
||||
@ -12,27 +12,30 @@ test('invalid or missing metadata never manufactures a collection date', () => {
|
||||
assert.equal(extractPublicationDate(html), null)
|
||||
}
|
||||
})
|
||||
test('metadata priority and failed hydration retain order and nullable dates', async () => {
|
||||
test('already-loaded section metadata is associated per article, never by page date', () => {
|
||||
const a = { title: 'fixture-a', url: 'https://www.bloomberg.com/news/articles/fixture-a' }
|
||||
const b = { title: 'fixture-b', url: 'https://www.bloomberg.com/news/articles/fixture-b' }
|
||||
const seen = []
|
||||
const result = await withPublicationDates([a, b], async url => {
|
||||
seen.push(url)
|
||||
if (url === b.url) throw new Error('fixture only')
|
||||
return '<meta name="iso-8601-publish-date" content="2026-01-02T03:04:05Z"><time datetime="2026-01-03T00:00:00Z"></time>'
|
||||
})
|
||||
assert.deepEqual(seen, [a.url, b.url])
|
||||
assert.equal(result[0].published_at, '2026-01-02T03:04:05.000Z')
|
||||
assert.equal(result[1].published_at, null)
|
||||
const c = { title: 'fixture-c', url: 'https://www.bloomberg.com/news/articles/fixture-c' }
|
||||
const html = '<meta name="iso-8601-publish-date" content="2026-12-31T00:00:00Z">' +
|
||||
'<article><a data-component="story-link" href="/news/articles/fixture-a"></a><time datetime="2026-01-02T03:04:05Z"></time></article>' +
|
||||
'<script type="application/ld+json">{"@type":"NewsArticle","url":"https://www.bloomberg.com/news/articles/fixture-b","datePublished":"2026-02-03T04:05:06Z"}</script>'
|
||||
const result = withDatesFromLoadedHtml([a, b, c], html, 'https://www.bloomberg.com/markets/stocks')
|
||||
assert.deepEqual(result.map(article => article.url), [a.url, b.url, c.url])
|
||||
assert.deepEqual(result.map(article => article.published_at), ['2026-01-02T03:04:05.000Z', '2026-02-03T04:05:06.000Z', null])
|
||||
assert.equal(a.published_at, undefined)
|
||||
})
|
||||
|
||||
test('date hydration never fetches unrelated hosts or non-article URLs', async () => {
|
||||
let calls = 0
|
||||
const urls = ['http://127.0.0.1/news/articles/x', 'https://other.invalid/news/articles/x', 'https://www.bloomberg.com@other.invalid/news/articles/x', 'https://www.bloomberg.com:8443/news/articles/x', 'https://www.bloomberg.com/markets']
|
||||
const result = await withPublicationDates(urls.map(url => ({ url })), async () => { calls++; return '' })
|
||||
assert.equal(calls, 0)
|
||||
assert.ok(result.every(item => item.published_at === null))
|
||||
test('ambiguous cards, invalid metadata and unrelated URLs remain date-null', () => {
|
||||
const urls = ['https://www.bloomberg.com/news/articles/a', 'https://www.bloomberg.com/news/articles/b', 'http://127.0.0.1/news/articles/x', 'https://other.invalid/news/articles/x']
|
||||
const html = '<article><a data-component="story-link" href="/news/articles/a"></a><a data-component="story-link" href="/news/articles/b"></a><time datetime="2026-01-02T03:04:05Z"></time></article>' +
|
||||
'<script type="application/ld+json">{"@type":"NewsArticle","url":"http://127.0.0.1/news/articles/x","datePublished":"2026-01-02T03:04:05Z"}</script>'
|
||||
const result = withDatesFromLoadedHtml(urls.map(url => ({ url })), html, 'https://www.bloomberg.com/markets')
|
||||
assert.ok(result.every(article => article.published_at === null))
|
||||
})
|
||||
test('page-level publication metadata applies only to the already-loaded article', () => {
|
||||
const urls = ['https://www.bloomberg.com/news/articles/a', 'https://www.bloomberg.com/news/articles/b']
|
||||
const result = withDatesFromLoadedHtml(urls.map(url => ({ url })), '<meta name="iso-8601-publish-date" content="2026-01-02T03:04:05Z">', urls[0])
|
||||
assert.equal(result[0].published_at, '2026-01-02T03:04:05.000Z')
|
||||
assert.equal(result[1].published_at, null)
|
||||
})
|
||||
|
||||
test('the three observed page shapes expose all publication metadata keys', () => {
|
||||
|
||||
96
scraper-service/tests/reliability.test.js
Normal file
96
scraper-service/tests/reliability.test.js
Normal file
@ -0,0 +1,96 @@
|
||||
const { test } = require('node:test')
|
||||
const assert = require('node:assert/strict')
|
||||
const fs = require('node:fs')
|
||||
const vm = require('node:vm')
|
||||
const { createRequire } = require('node:module')
|
||||
const path = require('node:path')
|
||||
|
||||
const dated = '<article><a data-component="story-link" href="/news/articles/fixture-a"><div data-testid="headline"><span>Synthetic fixture headline</span></div></a><time datetime="2026-01-02T03:04:05Z"></time></article>'
|
||||
const undated = dated.replace('<time datetime="2026-01-02T03:04:05Z"></time>', '')
|
||||
|
||||
// Exercise actual collection/route code with fake transports, browser and timers.
|
||||
// No server, browser process or source network request is started.
|
||||
async function runFixture ({ byparr = true, httpError = false, launchError = false } = {}) {
|
||||
const route = {}
|
||||
const calls = []
|
||||
const navigations = []
|
||||
const logs = []
|
||||
let bodyReads = 0
|
||||
let contents = 0
|
||||
let result
|
||||
let status = 200
|
||||
let closed = false
|
||||
const app = { use () {}, get () {}, post (name, handler) { route[name] = handler }, listen () {} }
|
||||
const express = () => app
|
||||
express.json = () => () => {}
|
||||
const index = path.resolve(__dirname, '../index.js')
|
||||
const localRequire = createRequire(index)
|
||||
const page = {
|
||||
async setViewport () {}, async evaluateOnNewDocument () {},
|
||||
async goto (url) { navigations.push(url) },
|
||||
async evaluate () { return true }, async waitForSelector () {}, async type () {},
|
||||
async waitForFunction () {}, async waitForNavigation () {}, async $ () { return null },
|
||||
keyboard: { async press () {} },
|
||||
url () { return 'https://www.bloomberg.com/markets' },
|
||||
async content () { return contents++ === 0 ? undated : dated }
|
||||
}
|
||||
const browser = { async newPage () { return page }, async close () { closed = true } }
|
||||
vm.runInNewContext(fs.readFileSync(index, 'utf8'), {
|
||||
require (name) {
|
||||
if (name === 'express') return express
|
||||
if (name === 'puppeteer-extra') return {
|
||||
use () {},
|
||||
async launch () {
|
||||
if (launchError) throw new Error('PRIVATE_BODY https://PRIVATE_URL.invalid')
|
||||
return browser
|
||||
}
|
||||
}
|
||||
if (name === 'puppeteer-extra-plugin-stealth') return () => ({})
|
||||
return localRequire(name)
|
||||
},
|
||||
process: { env: { BYPARR_URL: byparr ? 'http://fixture.invalid' : '' } },
|
||||
setTimeout (callback) { queueMicrotask(callback) },
|
||||
console: { log (...args) { logs.push(args.join(' ')) }, error (...args) { logs.push(args.join(' ')) } },
|
||||
async fetch (_url, options) {
|
||||
const requested = JSON.parse(options.body).url
|
||||
calls.push(requested)
|
||||
return {
|
||||
ok: !httpError, status: httpError ? 503 : 200,
|
||||
async text () { bodyReads++; return 'PRIVATE_BODY https://PRIVATE_URL.invalid' },
|
||||
async json () { return { solution: { response: calls.length === 1 ? undated : dated } } }
|
||||
}
|
||||
}
|
||||
})
|
||||
await route['/bloomberg/scrape']({ body: { username: 'PRIVATE_USER', password: 'PRIVATE_SECRET' } }, {
|
||||
json (body) { result = body }, status (code) { status = code; return this }
|
||||
})
|
||||
return { result, status, calls, navigations, logs, bodyReads, closed }
|
||||
}
|
||||
|
||||
test('Byparr loads only seven existing sections and enriches a repeated link in place', async () => {
|
||||
const { result, calls, logs } = await runFixture()
|
||||
assert.equal(calls.length, 7)
|
||||
assert.ok(calls.every(url => !url.includes('/news/articles/')))
|
||||
assert.equal(result.articles.length, 1)
|
||||
assert.equal(result.articles[0].published_at, '2026-01-02T03:04:05.000Z')
|
||||
assert.ok(logs.every(line => !line.includes('http') && !line.includes('Synthetic fixture headline')))
|
||||
})
|
||||
test('Puppeteer loads only login and three existing sections, no article revisits', async () => {
|
||||
const { result, navigations, calls, closed, logs } = await runFixture({ byparr: false })
|
||||
assert.equal(navigations.length, 4)
|
||||
assert.ok(navigations.every(url => !url.includes('/news/articles/')))
|
||||
assert.equal(calls.length, 0)
|
||||
assert.equal(result.articles.length, 1)
|
||||
assert.equal(result.articles[0].published_at, '2026-01-02T03:04:05.000Z')
|
||||
assert.equal(closed, true)
|
||||
assert.ok(logs.every(line => !line.includes('http') && !line.includes('PRIVATE')))
|
||||
})
|
||||
test('scraper failures never expose response bodies, URLs or credentials', async () => {
|
||||
const http = await runFixture({ httpError: true })
|
||||
assert.equal(http.bodyReads, 0)
|
||||
assert.ok(http.logs.every(line => !line.includes('http') && !line.includes('PRIVATE')))
|
||||
const browser = await runFixture({ byparr: false, launchError: true })
|
||||
assert.equal(browser.status, 500)
|
||||
assert.equal(browser.result.error, 'scrape unavailable')
|
||||
assert.ok(browser.logs.every(line => !line.includes('http') && !line.includes('PRIVATE')))
|
||||
})
|
||||
Reference in New Issue
Block a user