feat(scraper): bound article enrichment diagnostics (#40)
This commit is contained in:
@ -1,4 +1,5 @@
|
||||
const { enrichArticles, canonicalURL, TOTAL_TIMEOUT_MS } = require('./article-content')
|
||||
const { createFetchMetrics } = require('./fetch-metrics')
|
||||
const { withDatesFromLoadedHtml } = require('./publication-date')
|
||||
const { inspectLoginState, classifyLoginState, authenticatedDestination, trustedLoginOrigin, typeVisibleInput, submitInputForm } = require('./bloomberg-login')
|
||||
const express = require('express')
|
||||
@ -128,6 +129,7 @@ async function scrapeBloombergViaPuppeteer(username, password, enrichment) {
|
||||
let browser
|
||||
let abortBrowser
|
||||
let loginTimer
|
||||
enrichment?.metrics?.setLogin('unconfirmed')
|
||||
try {
|
||||
const login = async () => {
|
||||
browser = await launchBrowser()
|
||||
@ -153,6 +155,7 @@ async function scrapeBloombergViaPuppeteer(username, password, enrichment) {
|
||||
await new Promise(r => setTimeout(r, 2000))
|
||||
|
||||
const failLogin = reason => {
|
||||
enrichment?.metrics?.setLogin(['access_denied','auth_rejected'].includes(reason) ? 'refused' : 'unconfirmed')
|
||||
console.log('[bloomberg] login outcome:', reason)
|
||||
throw new Error('authentication unavailable')
|
||||
}
|
||||
@ -203,6 +206,7 @@ async function scrapeBloombergViaPuppeteer(username, password, enrichment) {
|
||||
const outcome = classifyLoginState(await page.evaluate(inspectLoginState))
|
||||
if (outcome !== 'authenticated') failLogin(outcome)
|
||||
if (!authenticatedDestination(page.url())) failLogin('authentication_unconfirmed')
|
||||
enrichment?.metrics?.setLogin('confirmed')
|
||||
console.log('[bloomberg] login outcome: authenticated')
|
||||
|
||||
return page
|
||||
@ -231,14 +235,15 @@ async function scrapeBloombergViaPuppeteer(username, password, enrichment) {
|
||||
try {
|
||||
if (options.signal.aborted) throw new Error('article expired')
|
||||
const navigation = await articlePage.goto(url, { waitUntil: 'domcontentloaded', timeout: options.timeoutMs })
|
||||
if (navigation) options.observeHTTPStatus?.(navigation.status())
|
||||
if (!navigation || navigation.status() !== 200) throw new Error('article response unavailable')
|
||||
if (canonicalURL(articlePage.url()) !== canonicalURL(url)) throw new Error('article association unavailable')
|
||||
if (canonicalURL(articlePage.url()) !== canonicalURL(url)) {options.observeIdentityMismatch?.();throw new Error('article association unavailable')}
|
||||
return await articlePage.content()
|
||||
} finally {
|
||||
options.signal.removeEventListener('abort', close)
|
||||
await articlePage.close().catch(() => {})
|
||||
}
|
||||
}, { concurrency: 2, totalTimeoutMs: remaining, signal: enrichment.signal })
|
||||
}, { concurrency: 2, totalTimeoutMs: remaining, signal: enrichment.signal, metrics:enrichment.metrics })
|
||||
}
|
||||
|
||||
const targetPages = [
|
||||
@ -312,11 +317,13 @@ app.post('/bloomberg/scrape', async (req, res) => {
|
||||
|
||||
// Enrichment is a separate RPC: the backend has already applied ArticleLimit.
|
||||
app.post('/bloomberg/enrich', async (req, res) => {
|
||||
const { username, password, urls } = req.body || {}
|
||||
const { username, password, urls, measure_fetches } = req.body || {}
|
||||
if (!username || !password || !Array.isArray(urls) || urls.some(url => typeof url !== 'string')) return res.status(400).json({ error: 'invalid enrichment request' })
|
||||
if (!urls.length) return res.json({ articles: [] })
|
||||
const metrics = measure_fetches === true ? createFetchMetrics() : null
|
||||
const respond = articles => res.json(metrics ? {articles,fetch_metrics:metrics.finish()} : {articles})
|
||||
if (!urls.length) return respond([])
|
||||
const empty = () => urls.map(url => ({ url, content: '', published_at: null, content_truncated: false, content_state: 'unavailable' }))
|
||||
if (!urls.some(url => canonicalURL(url))) return res.json({ articles: empty() })
|
||||
if (!urls.some(url => canonicalURL(url))) return respond(empty())
|
||||
const controller = new AbortController()
|
||||
const deadline = Date.now() + TOTAL_TIMEOUT_MS
|
||||
let finish
|
||||
@ -328,9 +335,9 @@ app.post('/bloomberg/enrich', async (req, res) => {
|
||||
try {
|
||||
// Section discovery still uses Byparr. Article bodies require the existing
|
||||
// authenticated browser session, with no anonymous transport fallback.
|
||||
const operation = scrapeBloombergViaPuppeteer(username, password, { urls, signal: controller.signal, deadline })
|
||||
const operation = scrapeBloombergViaPuppeteer(username, password, { urls, signal: controller.signal, deadline, metrics })
|
||||
const articles = await Promise.race([operation.catch(empty), expired])
|
||||
if (!res.destroyed) res.json({ articles })
|
||||
if (!res.destroyed) respond(articles)
|
||||
} finally {
|
||||
clearTimeout(timer)
|
||||
controller.abort()
|
||||
|
||||
Reference in New Issue
Block a user