feat(scraper): bound article enrichment diagnostics (#40)
This commit is contained in:
@ -44,16 +44,23 @@ function articleEvidence ($, expectedURL) {
|
||||
return { associated, mismatch, blocked, fullBody }
|
||||
}
|
||||
|
||||
function extractArticle (html, articleURL) {
|
||||
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)
|
||||
if (evidence.mismatch) return empty
|
||||
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"]'
|
||||
if (root.is(excludedRoot) || root.parents(excludedRoot).length) return empty
|
||||
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"]'
|
||||
@ -68,10 +75,7 @@ function extractArticle (html, articleURL) {
|
||||
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 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.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
|
||||
@ -120,21 +124,29 @@ async function enrichArticles (urls, loadHtml, options = {}) {
|
||||
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')
|
||||
return loadHtml(key, { signal: controller.signal, timeoutMs: remaining })
|
||||
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)
|
||||
if (Date.now() < articleDeadline && Date.now() < deadline) results.set(key, extracted)
|
||||
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(() => { clearTimeout(timer); controllers.delete(controller) })
|
||||
.finally(() => { finishObservation(); controller.signal.removeEventListener('abort',finishObservation); clearTimeout(timer); controllers.delete(controller) })
|
||||
await Promise.race([operation, budgetDone])
|
||||
}
|
||||
}
|
||||
|
||||
73
scraper-service/bench/fixtures-server.js
Normal file
73
scraper-service/bench/fixtures-server.js
Normal file
@ -0,0 +1,73 @@
|
||||
// Offline transport/browser fixtures around the unmodified production routes.
|
||||
// No collector or article extractor is reimplemented here. No network fetch.
|
||||
const fs = require('node:fs')
|
||||
const path = require('node:path')
|
||||
const vm = require('node:vm')
|
||||
const { createRequire } = require('node:module')
|
||||
const express = require('express')
|
||||
const cheerio = require('cheerio')
|
||||
|
||||
function startFixture () {
|
||||
const stats = { sectionRequests: 0, browserSessions: 0, articleRequests: 0 }
|
||||
const urls = ['complete', 'partial', 'absent'].map(k => `https://www.bloomberg.com/news/articles/bench-${k}`)
|
||||
const section = urls.map((url,i) => `<article><a data-component="story-link" href="${url}"><span data-testid="headline"><span>Synthetic benchmark headline ${i}</span></span></a>${i ? '<meta name="iso-8601-publish-date" content="2026-01-02T03:04:05Z">' : ''}</article>`).join('')
|
||||
const allowedSections = new Set(['/markets/stocks','/markets/currencies','/markets/rates-bonds','/markets/commodities','/technology','/economics','/politics'])
|
||||
const body = url => `<link rel="canonical" href="${url}"><article class="articleLayout_basic__gcpQk"><div class="body-content"><p class="ArticleBodyText_articleBodyContent__17wqE">Synthetic complete editorial body.</p><p class="ArticleBodyText_articleBodyContent__17wqE">Synthetic final paragraph.</p>${url.endsWith('partial') ? '<div class="Placeholder_placeholder__fixture"></div>' : ''}</div></article>`
|
||||
const browser = {async newPage () {return page()}, async close () {}}
|
||||
function page () {
|
||||
let current = ''; let state = 'email'; let markup = ''; const values = new Map()
|
||||
function document () {
|
||||
const html = state === 'article' ? markup : state === 'authenticated' ? '<a href="/account/logout">Fixture account control</a>' : state === 'password' ? '<form><input type="password"><button type="submit">Submit</button></form>' : '<form><input id="email-form-input" type="email"><button type="submit">Continue</button></form>'
|
||||
const $ = cheerio.load(html)
|
||||
const wrap = n => ({
|
||||
hidden: $(n).is('[hidden]'), disabled: $(n).is('[disabled]'),
|
||||
getAttribute: k => $(n).attr(k) ?? null,
|
||||
getClientRects: () => $(n).parents().addBack().is('[hidden], [aria-hidden="true"]') ? [] : [{}],
|
||||
get form () { const p=$(n).closest('form')[0];return p ? wrap(p) : null },
|
||||
querySelectorAll: s => $(n).find(s).toArray().map(wrap),
|
||||
set value (v) {values.set(n,v)}, dispatchEvent () {},
|
||||
click () {state = state === 'email' ? 'password' : 'authenticated';if(state==='authenticated')current='https://www.bloomberg.com/markets'}
|
||||
})
|
||||
return {querySelectorAll:s=>$(s).toArray().map(wrap),querySelector:s=>{const n=$(s)[0];return n?wrap(n):null}}
|
||||
}
|
||||
return {
|
||||
async setViewport () {}, async evaluateOnNewDocument () {}, async close () {},
|
||||
url () {return current}, async content () {return markup},
|
||||
async goto (url) {
|
||||
current=url
|
||||
if(url==='https://www.bloomberg.com/account/signin'){stats.browserSessions++;state='email';return {status:()=>200}}
|
||||
if(!urls.includes(url))throw new Error('offline_navigation_rejected')
|
||||
stats.articleRequests++;state='article';markup=body(url)
|
||||
return {status:()=>url.endsWith('absent')?403:200}
|
||||
},
|
||||
async evaluate (fn,...args) {return vm.runInNewContext(`(${fn.toString()})(...args)`, {document:document(),args,Event:class {}})},
|
||||
async waitForSelector (selector) {if(!document().querySelector(selector))throw new Error('offline_element_missing')},
|
||||
async waitForFunction (fn,_options,...args) {if(!await this.evaluate(fn,...args))throw new Error('offline_state_missing')},
|
||||
async type (_selector,text) {if(text!=='offline-fixture')throw new Error('offline_credentials_rejected')}
|
||||
}
|
||||
}
|
||||
const index=path.resolve(__dirname,'../index.js');const localRequire=createRequire(index)
|
||||
let server
|
||||
const ready=new Promise((resolve,reject)=>{
|
||||
const factory=()=>{const app=express();const listen=app.listen.bind(app);app.listen=()=>{server=listen(0,'127.0.0.1',()=>resolve(server));server.once('error',()=>reject(new Error('fixture_service_unavailable')));return server};return app};factory.json=express.json
|
||||
vm.runInNewContext(fs.readFileSync(index,'utf8'),{
|
||||
require(name){if(name==='express')return factory;if(name==='puppeteer-extra')return {use(){},async launch(){return browser}};if(name==='puppeteer-extra-plugin-stealth')return ()=>({});return localRequire(name)},
|
||||
process:{env:{PORT:'0',BYPARR_URL:'http://offline-byparr.invalid'}},AbortController,
|
||||
setTimeout(fn,ms){if([2000,800,500,3000].includes(ms)){queueMicrotask(fn);return undefined};return setTimeout(fn,ms)},clearTimeout,
|
||||
console:{log(){},error(){}},
|
||||
async fetch(destination,options){
|
||||
if(destination!=='http://offline-byparr.invalid/v1')throw new Error('offline_network_rejected')
|
||||
const req=JSON.parse(options.body);const u=new URL(req.url)
|
||||
if(req.cmd!=='request.get'||u.origin!=='https://www.bloomberg.com'||!allowedSections.has(u.pathname))throw new Error('offline_request_rejected')
|
||||
stats.sectionRequests++
|
||||
return {ok:true,async json(){return {solution:{url:req.url,response:section}}}}
|
||||
}
|
||||
})
|
||||
})
|
||||
return {ready,stats,close:()=>new Promise(resolve=>server?server.close(resolve):resolve())}
|
||||
}
|
||||
module.exports={startFixture}
|
||||
if(require.main===module){
|
||||
const fixture=startFixture()
|
||||
fixture.ready.then(server=>process.stdout.write(JSON.stringify({port:server.address().port})+'\n')).catch(()=>{console.error('fixture_service_unavailable');process.exitCode=1})
|
||||
}
|
||||
25
scraper-service/fetch-metrics.js
Normal file
25
scraper-service/fetch-metrics.js
Normal file
@ -0,0 +1,25 @@
|
||||
// Numeric aggregates only. No array of observations, identifiers or raw errors.
|
||||
function createFetchMetrics () {
|
||||
let sealed = false
|
||||
const binary = () => ({yes:0,no:0,not_evaluated:0})
|
||||
const c = {schema_version:1,supported:true,granular_supported:false,attempted:0,http:{'2xx':0,'3xx':0,'4xx':0,'5xx':0,network:0},editorial_root:binary(),identity:{yes:0,no:0,mismatch:0,not_evaluated:0},blocking_marker:binary(),extracted_characters:{'0':0,'1-500':0,'501-2000':0,'>2000':0},completeness:{complete:0,incomplete:0,unavailable:0}}
|
||||
return {
|
||||
setLogin (outcome) {
|
||||
if (!sealed && ['confirmed','unconfirmed','refused'].includes(outcome)) c.login = outcome
|
||||
},
|
||||
record (o) {
|
||||
if (sealed) return
|
||||
c.attempted++
|
||||
const status = Number.isInteger(o.httpStatus) ? o.httpStatus : 0
|
||||
c.http[status>=200&&status<600 ? `${Math.floor(status/100)}xx` : 'network']++
|
||||
c.editorial_root[['yes','no'].includes(o.root)?o.root:'not_evaluated']++
|
||||
c.identity[['yes','no','mismatch'].includes(o.identity)?o.identity:'not_evaluated']++
|
||||
c.blocking_marker[['yes','no'].includes(o.blocking)?o.blocking:'not_evaluated']++
|
||||
const n = Number.isInteger(o.characters)&&o.characters>0 ? o.characters : 0
|
||||
c.extracted_characters[n===0?'0':n<=500?'1-500':n<=2000?'501-2000':'>2000']++
|
||||
c.completeness[['complete','incomplete'].includes(o.state)?o.state:'unavailable']++
|
||||
},
|
||||
finish () {sealed=true;return JSON.parse(JSON.stringify(c))}
|
||||
}
|
||||
}
|
||||
module.exports={createFetchMetrics}
|
||||
@ -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()
|
||||
|
||||
@ -26,14 +26,21 @@ test('large non-ASCII editorial content remains complete without truncation', ()
|
||||
assert.equal(first.content_truncated, false)
|
||||
assert.equal(first.content_state, 'complete')
|
||||
})
|
||||
test('enrichment deduplicates loads, bounds concurrency and preserves input order', async () => {
|
||||
test('enrichment deduplicates loads, bounds concurrency and preserves input order', async t => {
|
||||
t.mock.timers.enable({ apis: ['setTimeout', 'Date'] })
|
||||
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 => {
|
||||
let done = false
|
||||
const operation = 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 })
|
||||
}, { concurrency: 2, articleTimeoutMs: 100, totalTimeoutMs: 200 }).then(result => { done = true; return result })
|
||||
for (let i = 0; i < 20 && !done; i++) {
|
||||
await new Promise(resolve => setImmediate(resolve))
|
||||
t.mock.timers.tick(5)
|
||||
}
|
||||
const result = await operation
|
||||
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'])
|
||||
|
||||
@ -6,7 +6,7 @@ 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, httpDenied = false, loginOutcome = 'authenticated') {
|
||||
async function request (byparr, failOne = false, poolSize = 2, authTimeout = false, httpDenied = false, loginOutcome = 'authenticated', measure = false) {
|
||||
const routes = {}; const loads = []; const logs = []; const timers = []; let pages = 0; let closed = false; let active = 0; let peak = 0; let byparrCalls = 0; const typed = []
|
||||
const app = { use () {}, get () {}, post (url, handler) { routes[url] = handler }, listen () {} }
|
||||
const express = () => app; express.json = () => () => {}
|
||||
@ -47,7 +47,7 @@ async function request (byparr, failOne = false, poolSize = 2, authTimeout = fal
|
||||
})
|
||||
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 } })
|
||||
await routes['/bloomberg/enrich']({ body: { username: 'PRIVATE_USER', password: 'PRIVATE_SECRET', urls, measure_fetches:measure } }, { json (value) { result = value }, status () { return this } })
|
||||
assert.deepEqual(result.articles.map(a => a.url), urls)
|
||||
assert.equal(loads.length, authTimeout || loginOutcome !== 'authenticated' ? 0 : poolSize)
|
||||
assert.ok(logs.every(line => !line.includes('PRIVATE') && !/https?:\/\//i.test(line) && !line.includes('Synthetic editorial')))
|
||||
@ -122,3 +122,30 @@ test('unexpected login origin stops before credential entry', async () => {
|
||||
assert.equal(typed.length,0);assert.equal(byparrCalls,0)
|
||||
assert.ok(result.articles.every(a => a.content_state==='unavailable' && a.content===''))
|
||||
})
|
||||
|
||||
test('aggregate metrics distinguish login-blocked no-fetch from article HTTP denial', async () => {
|
||||
const blocked=await request(true,false,2,false,false,'two_factor_required',true)
|
||||
assert.equal(blocked.result.fetch_metrics.supported,true)
|
||||
assert.equal(blocked.result.fetch_metrics.attempted,0)
|
||||
assert.equal(blocked.result.fetch_metrics.http.network,0)
|
||||
const denied=await request(true,false,2,false,true,'authenticated',true)
|
||||
assert.equal(denied.result.fetch_metrics.attempted,2) // duplicated listing is one fetch
|
||||
assert.equal(denied.result.fetch_metrics.http['4xx'],2)
|
||||
assert.equal(denied.result.fetch_metrics.editorial_root.not_evaluated,2)
|
||||
assert.equal(denied.result.fetch_metrics.blocking_marker.not_evaluated,2)
|
||||
assert.equal(denied.result.fetch_metrics.extracted_characters['0'],2)
|
||||
assert.equal(denied.result.fetch_metrics.completeness.unavailable,2)
|
||||
})
|
||||
|
||||
test('aggregate login classification preserves not-fetched without disclosing authentication details', async () => {
|
||||
for (const [outcome, expected] of [['access_denied','refused'],['auth_rejected','refused'],['two_factor_required','unconfirmed'],['challenge','unconfirmed'],['authentication_unconfirmed','unconfirmed'],['authenticated','confirmed']]) {
|
||||
const {result}=await request(true,false,2,false,false,outcome,true)
|
||||
assert.equal(result.fetch_metrics.login,expected)
|
||||
if (expected!=='confirmed') {
|
||||
assert.equal(result.fetch_metrics.attempted,0)
|
||||
assert.deepEqual(result.fetch_metrics.http,{'2xx':0,'3xx':0,'4xx':0,'5xx':0,network:0})
|
||||
}
|
||||
const raw=JSON.stringify(result.fetch_metrics)
|
||||
assert.ok(!/PRIVATE|https?:\/\/|Synthetic/.test(raw))
|
||||
}
|
||||
})
|
||||
|
||||
69
scraper-service/tests/fetch-metrics.test.js
Normal file
69
scraper-service/tests/fetch-metrics.test.js
Normal file
@ -0,0 +1,69 @@
|
||||
const {test}=require('node:test')
|
||||
const assert=require('node:assert/strict')
|
||||
const {createFetchMetrics}=require('../fetch-metrics')
|
||||
const {enrichArticles}=require('../article-content')
|
||||
test('article observations are reduced to counters, including rejected HTTP without parsing',async()=>{
|
||||
const metrics=createFetchMetrics()
|
||||
const urls=['complete','denied','network'].map(v=>`https://www.bloomberg.com/news/articles/${v}`)
|
||||
const result=await enrichArticles(urls,async(url,options)=>{
|
||||
if(url.endsWith('network'))throw new Error('synthetic-private-error')
|
||||
options.observeHTTPStatus(url.endsWith('denied')?403:200)
|
||||
if(url.endsWith('denied'))throw new Error('synthetic-private-error')
|
||||
return `<link rel="canonical" href="${url}"><article class="articleLayout_basic__gcpQk"><div class="body-content"><p class="ArticleBodyText_articleBodyContent__17wqE">Synthetic paragraph.</p></div></article>`
|
||||
},{metrics})
|
||||
const c=metrics.finish()
|
||||
assert.equal(c.attempted,3);assert.equal(c.http['2xx'],1);assert.equal(c.http['4xx'],1);assert.equal(c.http.network,1)
|
||||
assert.equal(c.editorial_root.yes,1);assert.equal(c.editorial_root.not_evaluated,2)
|
||||
assert.equal(c.extracted_characters['0'],2);assert.equal(c.extracted_characters['1-500'],1)
|
||||
assert.equal(c.completeness.complete,1);assert.equal(c.completeness.unavailable,2)
|
||||
for(const a of result)assert.equal(Object.hasOwn(a,'fetch_metrics'),false)
|
||||
const raw=JSON.stringify(c);for(const v of ['synthetic-private-error','http://','https://','Synthetic paragraph'])assert.equal(raw.includes(v),false)
|
||||
metrics.record({httpStatus:500});assert.equal(metrics.finish().attempted,3)
|
||||
})
|
||||
test('public 200 parser evidence exposes unknown roots, identity mismatch and blocker independently',async()=>{
|
||||
const metrics=createFetchMetrics()
|
||||
const urls=['root','identity','mismatch','block'].map(v=>`https://www.bloomberg.com/news/articles/${v}`)
|
||||
await enrichArticles(urls,async(url,options)=>{
|
||||
options.observeHTTPStatus(200)
|
||||
const root=`<article class="articleLayout_basic__gcpQk"><div class="body-content"><p class="ArticleBodyText_articleBodyContent__17wqE">Synthetic retained text.</p></div></article>`
|
||||
if(url.endsWith('root'))return `<link rel="canonical" href="${url}"><div class="unknown-root">Unrecognized fixture layout</div>`
|
||||
if(url.endsWith('identity'))return root
|
||||
if(url.endsWith('mismatch'))return `<link rel="canonical" href="${url}-other">`+root
|
||||
return `<link rel="canonical" href="${url}">`+root+'<div class="paywall"></div>'
|
||||
},{metrics})
|
||||
const m=metrics.finish()
|
||||
assert.equal(m.attempted,4);assert.equal(m.http['2xx'],4)
|
||||
assert.equal(m.editorial_root.yes,3);assert.equal(m.editorial_root.no,1)
|
||||
assert.equal(m.identity.yes,2);assert.equal(m.identity.no,1);assert.equal(m.identity.mismatch,1)
|
||||
assert.equal(m.blocking_marker.yes,1);assert.equal(m.blocking_marker.no,3)
|
||||
assert.equal(m.extracted_characters['0'],2);assert.equal(m.extracted_characters['1-500'],2)
|
||||
assert.equal(m.completeness.incomplete,2);assert.equal(m.completeness.unavailable,2)
|
||||
})
|
||||
test('length buckets count Unicode characters and observations never escape in article DTOs',()=>{
|
||||
for(const n of [0,1,500,501,2000,2001]){
|
||||
const metrics=createFetchMetrics();metrics.record({httpStatus:200,characters:n,state:'incomplete'})
|
||||
const m=metrics.finish();const bucket=n===0?'0':n<=500?'1-500':n<=2000?'501-2000':'>2000'
|
||||
assert.equal(m.extracted_characters[bucket],1)
|
||||
}
|
||||
})
|
||||
test('real extraction places Unicode texts into character rather than byte buckets',async()=>{
|
||||
const metrics=createFetchMetrics();const lengths=[0,1,500,501,2000,2001]
|
||||
await enrichArticles(lengths.map(n=>`https://www.bloomberg.com/news/articles/length-${n}`),async(url,options)=>{
|
||||
options.observeHTTPStatus(200);const n=Number(url.split('-').pop())
|
||||
return `<link rel="canonical" href="${url}"><article class="articleLayout_basic__gcpQk"><div class="body-content"><p class="ArticleBodyText_articleBodyContent__17wqE">${'漢'.repeat(n)}</p></div></article>`
|
||||
},{metrics})
|
||||
assert.deepEqual(metrics.finish().extracted_characters,{'0':1,'1-500':2,'501-2000':2,'>2000':1})
|
||||
})
|
||||
|
||||
test('login metric accepts only fixed categories and cannot change a sealed aggregate', () => {
|
||||
const m=createFetchMetrics()
|
||||
m.setLogin('PRIVATE_RAW_AUTH_RESPONSE')
|
||||
assert.equal(m.finish().login,undefined)
|
||||
m.setLogin('confirmed')
|
||||
assert.equal(m.finish().login,undefined)
|
||||
const refused=createFetchMetrics()
|
||||
refused.setLogin('refused')
|
||||
assert.equal(refused.finish().login,'refused')
|
||||
refused.setLogin('confirmed')
|
||||
assert.equal(refused.finish().login,'refused')
|
||||
})
|
||||
20
scraper-service/tests/ingestion-bench.test.js
Normal file
20
scraper-service/tests/ingestion-bench.test.js
Normal file
@ -0,0 +1,20 @@
|
||||
const {test}=require('node:test')
|
||||
const assert=require('node:assert/strict')
|
||||
const {startFixture}=require('../bench/fixtures-server')
|
||||
test('offline benchmark executes production Byparr collector and authenticated enrichment routes',async()=>{
|
||||
const fixture=startFixture();const server=await fixture.ready
|
||||
try{
|
||||
const rpc=async(route,body)=>{const r=await fetch(`http://127.0.0.1:${server.address().port}${route}`,{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(body)});assert.equal(r.status,200);return r.json()}
|
||||
const creds={username:'offline-fixture',password:'offline-fixture'}
|
||||
const listed=await rpc('/bloomberg/scrape',creds)
|
||||
assert.equal(listed.articles.length,3);assert.equal(fixture.stats.sectionRequests,7)
|
||||
const result=await rpc('/bloomberg/enrich',{...creds,urls:listed.articles.map(a=>a.url),measure_fetches:true})
|
||||
assert.deepEqual(result.articles.map(a=>a.content_state),['complete','incomplete','unavailable'])
|
||||
assert.equal(result.articles[0].published_at,null)
|
||||
const m=result.fetch_metrics
|
||||
assert.equal(m.attempted,3);assert.equal(m.http['2xx'],2);assert.equal(m.http['4xx'],1)
|
||||
assert.equal(m.editorial_root.yes,2);assert.equal(m.editorial_root.not_evaluated,1)
|
||||
assert.equal(m.blocking_marker.yes,1);assert.equal(m.blocking_marker.no,1);assert.equal(m.blocking_marker.not_evaluated,1)
|
||||
assert.equal(fixture.stats.sectionRequests,7);assert.equal(fixture.stats.browserSessions,1);assert.equal(fixture.stats.articleRequests,3)
|
||||
}finally{await fixture.close()}
|
||||
})
|
||||
Reference in New Issue
Block a user