feat(scraper): bound article enrichment diagnostics (#40)

This commit is contained in:
2026-11-25 00:07:45 +01:00
parent a3c70670f6
commit 6883b3976b
53 changed files with 4049 additions and 68 deletions

View File

@ -0,0 +1,19 @@
FROM golang:1.23-bookworm AS builder
WORKDIR /src
COPY backend/go.mod backend/go.sum ./
RUN go mod download
COPY backend/ ./
RUN CGO_ENABLED=0 go build -trimpath -o /out/ingestion-bench ./cmd/ingestion-bench
FROM node:20-slim
ENV PUPPETEER_SKIP_DOWNLOAD=true PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true
WORKDIR /app/scraper-service
COPY scraper-service/package*.json ./
RUN npm install --omit=dev --no-package-lock --no-audit --no-fund
COPY scraper-service/ ./
COPY --from=builder /out/ingestion-bench /usr/local/bin/ingestion-bench
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
WORKDIR /app
USER node
ENTRYPOINT ["ingestion-bench"]
CMD ["--mode=offline", "--limit=3"]

View File

@ -0,0 +1,12 @@
**
!backend
!backend/**
!scraper-service
!scraper-service/**
**/node_modules
**/.git
**/.env
**/.env.*
**/test-results
**/playwright-report
**/*.log

View File

@ -0,0 +1,100 @@
// ingestion-bench deliberately imports ingestion only, not application startup,
// database, generation, ranking or synthesis composition.
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"github.com/tradarr/backend/internal/ingestionbench"
"io"
"net/http"
"os"
"regexp"
"time"
)
func run(args []string) int {
flags := flag.NewFlagSet("ingestion-bench", flag.ContinueOnError)
flags.SetOutput(io.Discard)
mode := flags.String("mode", "offline", "")
allow := flags.Bool("allow-live", false, "")
limit := flags.Int("limit", 3, "")
script := flags.String("fixture-script", "scraper-service/bench/fixtures-server.js", "")
if flags.Parse(args) != nil || flags.NArg() != 0 || *limit < 1 || *limit > 3 || ingestionbench.ValidateMode(*mode, *allow) != nil {
fmt.Fprintln(os.Stderr, "invalid_bench_options")
return 2
}
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
defer cancel()
var articleClient *http.Client
var rpcClient *http.Client
scraperURL, username, password, symbol := "", "offline-fixture", "offline-fixture", "FIXTURE"
if *mode == "offline" {
var cleanup func()
var err error
scraperURL, cleanup, err = ingestionbench.StartOfflineScraper(ctx, *script)
if err != nil {
fmt.Fprintln(os.Stderr, "fixture_service_unavailable")
return 1
}
defer cleanup()
rpcClient, err = ingestionbench.OfflineRPCClient(scraperURL)
if err != nil {
fmt.Fprintln(os.Stderr, "fixture_service_unavailable")
return 1
}
articleClient = &http.Client{Transport: ingestionbench.OfflineTransport{}}
} else {
var err error
scraperURL, err = ingestionbench.TrustedScraperURL(os.Getenv("INGESTION_SCRAPER_URL"))
if err != nil {
fmt.Fprintln(os.Stderr, "invalid_scraper_service")
return 2
}
username, err = ingestionbench.ReadCredentialFile(os.Getenv("BLOOMBERG_USERNAME_FILE"))
if err != nil {
fmt.Fprintln(os.Stderr, "credentials_unavailable")
return 2
}
password, err = ingestionbench.ReadCredentialFile(os.Getenv("BLOOMBERG_PASSWORD_FILE"))
if err != nil {
fmt.Fprintln(os.Stderr, "credentials_unavailable")
return 2
}
symbol = os.Getenv("INGESTION_YAHOO_SYMBOL")
if symbol == "" {
symbol = "AAPL"
}
if !regexp.MustCompile(`^[A-Za-z0-9.^= -]{1,64}$`).MatchString(symbol) {
fmt.Fprintln(os.Stderr, "invalid_bench_symbol")
return 2
}
articleClient = ingestionbench.LiveArticleClient()
rpcClient = ingestionbench.RPCClient()
}
sources := ingestionbench.ProductionSources(articleClient, rpcClient, scraperURL, username, password, symbol)
rows, err := ingestionbench.Run(ctx, sources, *limit)
if err != nil {
fmt.Fprintln(os.Stderr, "bench_unavailable")
return 1
}
if json.NewEncoder(os.Stdout).Encode(struct {
Mode string `json:"mode"`
Sources []ingestionbench.Row `json:"sources"`
}{*mode, rows}) != nil {
return 1
}
return 0
}
func execute(args []string) (code int) {
defer func() {
if recover() != nil {
fmt.Fprintln(os.Stderr, "bench_unavailable")
code = 1
}
}()
return run(args)
}
func main() { os.Exit(execute(os.Args[1:])) }

View File

@ -0,0 +1,46 @@
package main
import (
"io"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"sync/atomic"
"testing"
)
func TestInvalidOrUnconfirmedLiveModeNeverStartsIngestion(t *testing.T) {
for _, args := range [][]string{{"--mode=live"}, {"--mode=offline", "--allow-live"}, {"--limit=0"}, {"--limit=4"}, {"--mode=unknown"}} {
if run(args) != 2 {
t.Fatal("invalid configuration accepted")
}
}
}
func TestInvalidScraperEndpointIsRejectedBeforeCredentialReadAndAnyPOST(t *testing.T) {
var posted atomic.Int64
trap := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { posted.Add(1); w.WriteHeader(204) }))
defer trap.Close()
// Nonexistent fixture files make an accidental credential read observable as
// credentials_unavailable, without reading any real credential or going live.
for _, endpoint := range []string{trap.URL, "http://ingestion-scraper:22", "http://ingestion-scraper:8080", "http://127.0.0.1:3001"} {
t.Setenv("INGESTION_SCRAPER_URL", endpoint)
t.Setenv("BLOOMBERG_USERNAME_FILE", filepath.Join(t.TempDir(), "nonexistent-username"))
t.Setenv("BLOOMBERG_PASSWORD_FILE", filepath.Join(t.TempDir(), "nonexistent-password"))
previous := os.Stderr
r, w, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
os.Stderr = w
code := run([]string{"--mode=live", "--allow-live"})
os.Stderr = previous
w.Close()
message, _ := io.ReadAll(r)
r.Close()
if code != 2 || string(message) != "invalid_scraper_service\n" || posted.Load() != 0 {
t.Fatal("invalid service reached credential read or POST")
}
}
}

View File

@ -0,0 +1,121 @@
package ingestionbench
import (
"context"
"github.com/tradarr/backend/internal/scraper"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
)
type fixtureAudit struct {
feeds, articles int
t *testing.T
source string
}
func (a *fixtureAudit) RoundTrip(r *http.Request) (*http.Response, error) {
if r.URL.Host == "feeds.finance.yahoo.com" || r.URL.Path == "/id/10001147/device/rss/rss.html" {
a.feeds++
} else {
a.articles++
valid := r.URL.Scheme == "https"
if a.source == "yahoo_finance" {
valid = valid && r.URL.Host == "finance.yahoo.com" && strings.HasPrefix(r.URL.Path, "/news/") && strings.HasSuffix(r.URL.Path, ".html")
} else {
valid = valid && r.URL.Host == "www.cnbc.com" && strings.HasPrefix(r.URL.Path, "/2026/01/02/") && strings.HasSuffix(r.URL.Path, ".html")
}
if !valid {
a.t.Error("offline fixture article URL is incompatible with production path contracts")
}
}
return (OfflineTransport{}).RoundTrip(r)
}
func TestOfflineFixtureMatrixActuallyTraversesCollectorsAndEnrichers(t *testing.T) {
for _, index := range []int{0, 1} {
t.Run([]string{"yahoo_finance", "cnbc_business"}[index], func(t *testing.T) {
key := []string{"yahoo_finance", "cnbc_business"}[index]
audit := &fixtureAudit{t: t, source: key}
sources := ProductionSources(&http.Client{Transport: audit}, RPCClient(), "http://127.0.0.1:1", "offline-fixture", "offline-fixture", "FIXTURE")
listed, err := sources[index].Feed.Scrape(context.Background(), sources[index].Symbols)
if err != nil || len(listed) != 3 {
t.Fatal("fixture collector matrix failed")
}
enriched, err := sources[index].Feed.Enrich(context.Background(), listed)
if err != nil || len(enriched) != 3 || audit.feeds != 1 || audit.articles != 3 {
t.Fatal("production enrichment transport was not exercised three times")
}
for i, want := range []string{scraper.ContentComplete, scraper.ContentIncomplete, scraper.ContentUnavailable} {
if scraper.ContentStatus(enriched[i]) != want || enriched[i].URL != listed[i].URL || enriched[i].Title != listed[i].Title {
t.Fatal("fixture matrix state or listing association failed")
}
}
if enriched[0].PublishedAt != nil {
t.Fatal("complete fixture must retain nullable date")
}
expected := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
for _, a := range enriched[1:] {
if a.PublishedAt == nil || !a.PublishedAt.Equal(expected) {
t.Fatal("observed fixture date is not reliable")
}
}
})
}
}
func TestLiveScraperRejectsEveryUnapprovedOriginAndPort(t *testing.T) {
for _, base := range []string{"http://ingestion-scraper:22", "http://ingestion-scraper:8080", "https://ingestion-scraper:3001", "http://127.0.0.1:3001", "http://127.0.0.1:22", "http://[::1]:3001", "http://ingestion-scraper:3001/other"} {
if _, err := TrustedScraperURL(base); err == nil {
t.Error("unapproved live credential destination accepted")
}
}
}
func TestRejectedLiveDestinationReceivesNoCredentialPOST(t *testing.T) {
var requests atomic.Int64
trap := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests.Add(1)
io.Copy(io.Discard, r.Body)
w.WriteHeader(204)
}))
defer trap.Close()
req, _ := http.NewRequest("POST", trap.URL+"/bloomberg/scrape", strings.NewReader(`{"username":"synthetic-fixture","password":"synthetic-fixture"}`))
_, err := RPCClient().Do(req)
if err == nil || requests.Load() != 0 {
t.Fatal("rejected endpoint received a credential request")
}
}
type rpcAuditTransport struct{ calls int }
func (a *rpcAuditTransport) RoundTrip(r *http.Request) (*http.Response, error) {
a.calls++
return &http.Response{StatusCode: 204, Header: make(http.Header), Body: io.NopCloser(strings.NewReader("")), Request: r}, nil
}
func TestLiveRPCGuardAllowsOnlyTheExactServiceAndBothKnownOperations(t *testing.T) {
audit := &rpcAuditTransport{}
guard := credentialRPCTransport{endpoint: LiveScraperEndpoint, base: audit}
for _, target := range []string{"http://ingestion-scraper:22/bloomberg/scrape", "http://ingestion-scraper:8080/bloomberg/enrich", "http://127.0.0.1:3001/bloomberg/scrape", "https://ingestion-scraper:3001/bloomberg/scrape", "http://ingestion-scraper:3001/other", "http://ingestion-scraper:3001/bloomberg/scrape?forward=1"} {
req, _ := http.NewRequest("POST", target, strings.NewReader("synthetic-fixture"))
if _, err := guard.RoundTrip(req); err == nil {
t.Error("unapproved credential request accepted")
}
}
if audit.calls != 0 {
t.Fatal("credential request reached an unapproved transport")
}
for _, path := range []string{"/bloomberg/scrape", "/bloomberg/enrich"} {
req, _ := http.NewRequest("POST", LiveScraperEndpoint+path, strings.NewReader("synthetic-fixture"))
if _, err := guard.RoundTrip(req); err != nil {
t.Fatal("expected service operation blocked")
}
}
if audit.calls != 2 {
t.Fatal("approved operations not delegated")
}
if actual, err := TrustedScraperURL(LiveScraperEndpoint); err != nil || actual != LiveScraperEndpoint {
t.Fatal("exact service endpoint rejected")
}
}

View File

@ -0,0 +1,118 @@
// Package ingestionbench measures production ingestion ports, never ranking,
// synthesis, persistence or a second implementation of extraction.
package ingestionbench
import (
"context"
"errors"
"github.com/tradarr/backend/internal/scraper"
)
type Feed interface {
scraper.Scraper
scraper.ArticleEnricher
}
type Source struct {
Key string
Feed Feed
Symbols []string
}
type ContentCounts struct {
Complete int `json:"complete"`
Incomplete int `json:"incomplete"`
Unavailable int `json:"unavailable"`
}
type DateCounts struct {
Observed int `json:"observed"`
Missing int `json:"missing"`
}
type Row struct {
Fetch scraper.FetchMetrics `json:"article_fetch"`
NotFetched *int `json:"not_fetched"`
Source string `json:"source"`
ListStatus string `json:"list_status"`
EnrichStatus string `json:"enrich_status"`
Listed int `json:"listed"`
Enriched int `json:"enriched"`
Dates DateCounts `json:"dates"`
Content ContentCounts `json:"content"`
}
func Run(ctx context.Context, sources []Source, limit int) ([]Row, error) {
if limit < 1 || limit > 3 {
return nil, errors.New("invalid_bench_limit")
}
rows := make([]Row, 0, len(sources))
for _, s := range sources {
if s.Key != "yahoo_finance" && s.Key != "cnbc_business" && s.Key != "bloomberg" {
return nil, errors.New("invalid_bench_source")
}
row := Row{Fetch: scraper.FetchMetrics{SchemaVersion: 1}, Source: s.Key, ListStatus: "unavailable", EnrichStatus: "not_attempted"}
if s.Feed == nil {
rows = append(rows, row)
continue
}
a, err := s.Feed.Scrape(ctx, s.Symbols)
if err != nil {
rows = append(rows, row)
continue
}
row.ListStatus = "ok"
if len(a) > limit {
a = a[:limit]
}
row.Listed = len(a)
if len(a) == 0 {
rows = append(rows, row)
continue
}
measuredCtx, meter := scraper.WithFetchMetrics(ctx)
enriched, err := s.Feed.Enrich(measuredCtx, append([]scraper.Article(nil), a...))
row.Fetch = meter.Finish()
if row.Fetch.Supported {
n := max(0, len(a)-row.Fetch.Attempted)
row.NotFetched = &n
}
valid := err == nil && len(enriched) == len(a)
if valid {
for i, v := range enriched {
if v.URL != a[i].URL || v.Title != a[i].Title {
valid = false
break
}
}
}
if !valid {
row.EnrichStatus = "unavailable"
row.Content.Unavailable = len(a)
for _, v := range a {
if v.PublishedAt == nil {
row.Dates.Missing++
} else {
row.Dates.Observed++
}
}
rows = append(rows, row)
continue
}
row.EnrichStatus = "ok"
row.Enriched = len(enriched)
for _, v := range enriched {
if v.PublishedAt == nil {
row.Dates.Missing++
} else {
row.Dates.Observed++
}
switch scraper.ContentStatus(v) {
case scraper.ContentComplete:
row.Content.Complete++
case scraper.ContentIncomplete:
row.Content.Incomplete++
default:
row.Content.Unavailable++
}
}
rows = append(rows, row)
}
return rows, nil
}

View File

@ -0,0 +1,66 @@
package ingestionbench
import (
"context"
"encoding/json"
"github.com/tradarr/backend/internal/scraper"
"strings"
"testing"
)
type fixtureFeed struct{ size int }
func (*fixtureFeed) Name() string { return "fixture" }
func (*fixtureFeed) Scrape(context.Context, []string) ([]scraper.Article, error) {
return []scraper.Article{{Title: "PRIVATE", URL: "https://private.invalid", Content: "PRIVATE"}, {}, {}, {}}, nil
}
func (f *fixtureFeed) Enrich(_ context.Context, a []scraper.Article) ([]scraper.Article, error) {
f.size = len(a)
for i := range a {
a[i].Content = "PRIVATE full body"
a[i].ContentState = scraper.ContentComplete
}
return a, nil
}
func TestBenchBoundsAndRedactsAllArticleData(t *testing.T) {
f := &fixtureFeed{}
rows, err := Run(context.Background(), []Source{{Key: "yahoo_finance", Feed: f}}, 3)
if err != nil || f.size != 3 || rows[0].Listed != 3 || rows[0].Content.Complete != 3 || rows[0].Dates.Missing != 3 {
t.Fatal("bound/date independence failed")
}
raw, _ := json.Marshal(rows)
if strings.Contains(string(raw), "PRIVATE") || strings.Contains(string(raw), "https://") {
t.Fatal("article data leaked")
}
for _, n := range []int{0, 4} {
if _, err := Run(context.Background(), nil, n); err == nil {
t.Fatal("limit accepted")
}
}
}
type loginFixtureFeed struct {
fixtureFeed
login string
}
func (f *loginFixtureFeed) Enrich(ctx context.Context, a []scraper.Article) ([]scraper.Article, error) {
scraper.MergeFetchMetrics(ctx, scraper.FetchMetrics{SchemaVersion: 1, Supported: true, Login: f.login}, len(a))
for i := range a {
a[i].Content = ""
a[i].ContentState = scraper.ContentUnavailable
}
return a, nil
}
func TestBenchLoginGateKeepsArticlesNotFetched(t *testing.T) {
for _, login := range []string{"unconfirmed", "refused"} {
rows, err := Run(context.Background(), []Source{{Key: "bloomberg", Feed: &loginFixtureFeed{login: login}}}, 3)
if err != nil || len(rows) != 1 {
t.Fatal("login fixture failed")
}
row := rows[0]
if row.NotFetched == nil || *row.NotFetched != 3 || row.Fetch.Login != login || row.Fetch.Attempted != 0 || row.Content.Unavailable != 3 {
t.Fatal("login gate lost not-fetched semantics")
}
}
}

View File

@ -0,0 +1,67 @@
package ingestionbench
import (
"embed"
"errors"
"fmt"
"io"
"net/http"
"strings"
)
//go:embed testdata/body.html
var fixtureFiles embed.FS
// OfflineTransport serves synthetic responses only, rejecting every unlisted
// destination. It never delegates to a real network transport.
type OfflineTransport struct{}
func (OfflineTransport) RoundTrip(r *http.Request) (*http.Response, error) {
if r.Method != "GET" || r.URL.Scheme != "https" {
return nil, errors.New("offline_request_rejected")
}
urls := []string{}
root := "caas-body"
switch r.URL.Host {
case "feeds.finance.yahoo.com", "finance.yahoo.com":
urls = []string{"https://finance.yahoo.com/news/bench-complete.html", "https://finance.yahoo.com/news/bench-partial.html", "https://finance.yahoo.com/news/bench-absent.html"}
case "www.cnbc.com":
root = "ArticleBody-articleBody"
urls = []string{"https://www.cnbc.com/2026/01/02/bench-complete.html", "https://www.cnbc.com/2026/01/02/bench-partial.html", "https://www.cnbc.com/2026/01/02/bench-absent.html"}
default:
return nil, errors.New("offline_request_rejected")
}
body := ""
if r.URL.Host == "feeds.finance.yahoo.com" && r.URL.Path == "/rss/2.0/headline" || r.URL.Host == "www.cnbc.com" && r.URL.Path == "/id/10001147/device/rss/rss.html" {
body = "<rss><channel>"
for i, url := range urls {
date := ""
if i > 0 {
date = "<pubDate>Fri, 02 Jan 2026 03:04:05 +0000</pubDate>"
}
body += fmt.Sprintf("<item><title>Synthetic benchmark headline %d</title><link>%s</link><description>Synthetic RSS teaser.</description>%s</item>", i, url, date)
}
body += "</channel></rss>"
} else {
index := -1
for i, url := range urls {
if strings.Replace(url, "http://", "https://", 1) == r.URL.String() {
index = i
}
}
if index < 0 {
return nil, errors.New("offline_request_rejected")
}
raw, _ := fixtureFiles.ReadFile("testdata/body.html")
body = strings.ReplaceAll(strings.ReplaceAll(string(raw), "{{URL}}", r.URL.String()), "{{ROOT}}", root)
if index == 1 {
// Restriction belongs to the synthetic editorial body, not site chrome.
body = strings.Replace(body, "</div>", `<div class="paywall"></div></div>`, 1)
body += `<meta property="article:published_time" content="2026-01-02T03:04:05Z">`
}
if index == 2 {
body = `<div id="px-captcha"></div>`
}
}
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: r}, nil
}

View File

@ -0,0 +1,153 @@
package ingestionbench
import (
"bufio"
"context"
"encoding/json"
"errors"
"github.com/tradarr/backend/internal/scraper/sourcehttp"
"io"
"net/http"
"net/netip"
"net/url"
"os"
"os/exec"
"strconv"
"strings"
"time"
)
func ValidateMode(mode string, allowLive bool) error {
if mode != "offline" && mode != "live" || mode == "live" && !allowLive || mode == "offline" && allowLive {
return errors.New("invalid_bench_mode")
}
return nil
}
func StartOfflineScraper(ctx context.Context, script string) (string, func(), error) {
child := exec.CommandContext(ctx, "node", script)
child.Stderr = io.Discard
child.Env = []string{"PATH=" + os.Getenv("PATH"), "NODE_NO_WARNINGS=1"}
stdout, err := child.StdoutPipe()
if err != nil {
return "", nil, errors.New("fixture_service_unavailable")
}
if child.Start() != nil {
return "", nil, errors.New("fixture_service_unavailable")
}
cleanup := func() { _ = child.Process.Kill(); _ = child.Wait() }
ready := make(chan int, 1)
go func() {
scanner := bufio.NewScanner(io.LimitReader(stdout, 1024))
port := 0
if scanner.Scan() {
var v struct {
Port int `json:"port"`
}
if json.Unmarshal(scanner.Bytes(), &v) == nil {
port = v.Port
}
}
ready <- port
}()
select {
case port := <-ready:
if port > 0 && port < 65536 {
return "http://127.0.0.1:" + strconv.Itoa(port), cleanup, nil
}
case <-time.After(10 * time.Second):
case <-ctx.Done():
}
cleanup()
return "", nil, errors.New("fixture_service_unavailable")
}
const LiveScraperEndpoint = "http://ingestion-scraper:3001"
// Live credentials have exactly one configured service destination. Loopback
// ports belong exclusively to the separately constructed offline fixture client.
func TrustedScraperURL(value string) (string, error) {
if value != LiveScraperEndpoint && value != LiveScraperEndpoint+"/" {
return "", errors.New("invalid_scraper_service")
}
return LiveScraperEndpoint, nil
}
func ReadCredentialFile(path string) (string, error) {
f, err := os.Open(path)
if err != nil {
return "", errors.New("credentials_unavailable")
}
defer f.Close()
b, err := io.ReadAll(io.LimitReader(f, 16385))
if err != nil || len(b) > 16384 {
return "", errors.New("credentials_unavailable")
}
value := strings.TrimSuffix(strings.TrimSuffix(string(b), "\n"), "\r")
if value == "" {
return "", errors.New("credentials_unavailable")
}
return value, nil
}
type credentialRPCTransport struct {
endpoint string
base http.RoundTripper
}
func (t credentialRPCTransport) RoundTrip(r *http.Request) (*http.Response, error) {
base, err := url.Parse(t.endpoint)
if err != nil || r.Method != http.MethodPost || r.URL == nil || r.URL.Scheme != base.Scheme || r.URL.Host != base.Host || r.URL.User != nil || r.URL.Opaque != "" || r.URL.RawPath != "" || r.URL.RawQuery != "" || r.URL.ForceQuery || r.URL.Fragment != "" || (r.URL.Path != "/bloomberg/scrape" && r.URL.Path != "/bloomberg/enrich") {
return nil, errors.New("credential_destination_rejected")
}
return t.base.RoundTrip(r)
}
func rpcClientForEndpoint(endpoint string) *http.Client {
base := http.DefaultTransport.(*http.Transport).Clone()
base.Proxy = nil // Credentials must never be forwarded through an ambient proxy.
return &http.Client{Timeout: 10 * time.Minute, Transport: credentialRPCTransport{endpoint, base}, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
}
// RPCClient is the live client: only the exact Compose service can receive a POST.
func RPCClient() *http.Client { return rpcClientForEndpoint(LiveScraperEndpoint) }
// OfflineRPCClient is bound to the specific locally launched fixture server.
// The CLI never passes live credential files to this client.
func OfflineRPCClient(endpoint string) (*http.Client, error) {
u, err := url.Parse(endpoint)
if err != nil || u.Scheme != "http" || u.User != nil || u.Opaque != "" || u.Path != "" || u.RawPath != "" || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" || (u.Hostname() != "127.0.0.1" && u.Hostname() != "::1") {
return nil, errors.New("invalid_fixture_service")
}
port, err := strconv.Atoi(u.Port())
if err != nil || port < 1 || port > 65535 {
return nil, errors.New("invalid_fixture_service")
}
return rpcClientForEndpoint(u.String()), nil
}
func publicIP(ip netip.Addr) bool { return sourcehttp.IsPublicAddress(ip) }
type liveTransport struct{ base http.RoundTripper }
func allowedLiveRequest(r *http.Request) bool {
if r.Method != "GET" || r.URL.Scheme != "https" || r.URL.User != nil || r.URL.Port() != "" {
return false
}
switch r.URL.Host {
case "feeds.finance.yahoo.com", "finance.yahoo.com", "www.cnbc.com":
return true
}
return false
}
func (t liveTransport) RoundTrip(r *http.Request) (*http.Response, error) {
if !allowedLiveRequest(r) {
return nil, errors.New("source_request_rejected")
}
return t.base.RoundTrip(r)
}
func LiveArticleClient() *http.Client {
transport := sourcehttp.NewTransport(nil, nil)
return &http.Client{Timeout: 15 * time.Second, Transport: liveTransport{transport}, CheckRedirect: func(r *http.Request, via []*http.Request) error {
if len(via) >= 3 || !allowedLiveRequest(r) {
return http.ErrUseLastResponse
}
return nil
}}
}

View File

@ -0,0 +1,104 @@
package ingestionbench
import (
"context"
"io"
"net/http"
"net/http/httptest"
"net/netip"
"strings"
"testing"
)
func TestLiveNeedsExplicitOptIn(t *testing.T) {
for _, c := range []struct {
mode string
allow, want bool
}{{"offline", false, true}, {"live", false, false}, {"live", true, true}, {"offline", true, false}, {"", true, false}} {
if (ValidateMode(c.mode, c.allow) == nil) != c.want {
t.Fatal("unexpected mode gate")
}
}
}
func TestLiveEgressAndCredentialDestinationAreRestricted(t *testing.T) {
for _, s := range []string{"127.0.0.1", "10.0.0.1", "169.254.169.254", "::1", "fc00::1", "::ffff:127.0.0.1", "100.100.100.200", "198.18.0.1", "203.0.113.1"} {
if publicIP(netip.MustParseAddr(s)) {
t.Fatal("private IP accepted")
}
}
for _, s := range []string{"http://evil.invalid:3001", "http://user:secret@ingestion-scraper:3001", "http://ingestion-scraper:3001/other"} {
if _, err := TrustedScraperURL(s); err == nil {
t.Fatal("unsafe credential destination")
}
}
}
func TestOfflineProductionCollectorsAndEnrichersMeasureNullableDates(t *testing.T) {
// The RPC test transport verifies the Go production adapter; the actual Node
// route is covered by the offline fixture-service test and executable smoke.
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/bloomberg/scrape" {
io.WriteString(w, `{"articles":[]}`)
return
}
t.Error("unexpected RPC")
}))
defer s.Close()
rpc, err := OfflineRPCClient(s.URL)
if err != nil {
t.Fatal(err)
}
rows, err := Run(context.Background(), ProductionSources(&http.Client{Transport: OfflineTransport{}}, rpc, s.URL, "offline-fixture", "offline-fixture", "FIXTURE"), 3)
if err != nil || len(rows) != 3 {
t.Fatal("offline bench failed")
}
for _, row := range rows[:2] {
if row.Listed != 3 || row.Enriched != 3 || row.Content.Complete != 1 || row.Content.Incomplete != 1 || row.Content.Unavailable != 1 || row.Dates.Missing != 1 || row.Dates.Observed != 2 {
t.Fatalf("unexpected aggregates %+v", row)
}
}
req, _ := http.NewRequest("GET", "https://external.invalid/private", strings.NewReader(""))
if _, err := (OfflineTransport{}).RoundTrip(req); err == nil {
t.Fatal("offline transport escaped fixture set")
}
}
func TestBenchArticleMetricsAreProducedByActualOfflineFetches(t *testing.T) {
sources := ProductionSources(&http.Client{Transport: OfflineTransport{}}, RPCClient(), LiveScraperEndpoint, "offline-fixture", "offline-fixture", "FIXTURE")
rows, err := Run(context.Background(), sources[:2], 3)
if err != nil {
t.Fatal(err)
}
for _, r := range rows {
m := r.Fetch
if !m.Supported || m.Attempted != 3 || r.NotFetched == nil || *r.NotFetched != 0 || m.HTTP.TwoXX != 3 || m.Root.Yes != 2 || m.Root.No != 1 || m.Identity.Yes != 2 || m.Identity.No != 1 || m.Blocking.Yes != 2 || m.Blocking.No != 1 || m.Length.Zero != 1 || m.Length.Small != 2 || m.Content.Complete != 1 || m.Content.Incomplete != 1 || m.Content.Unavailable != 1 {
t.Fatalf("fetch evidence matrix invalid: %+v", m)
}
}
}
func TestBenchRetainsGranularAggregatesFromProductionEnrichers(t *testing.T) {
sources := ProductionSources(&http.Client{Transport: OfflineTransport{}}, RPCClient(), LiveScraperEndpoint, "offline-fixture", "offline-fixture", "FIXTURE")
rows, err := Run(context.Background(), sources[:2], 3)
if err != nil {
t.Fatal("offline aggregate fixture failed")
}
for _, row := range rows {
m := row.Fetch
if !m.GranularSupported || m.IdentityEvidence.Canonical.Associated != 2 || m.BlockingEvidence.Paywall.ArticleRoot != 1 || m.BlockingEvidence.Challenge.GlobalPage != 1 {
t.Fatal("bench lost granular evidence")
}
}
}
func TestBenchCarriesCandidateBodyLengthAggregates(t *testing.T) {
sources := ProductionSources(&http.Client{Transport: OfflineTransport{}}, RPCClient(), LiveScraperEndpoint, "offline-fixture", "offline-fixture", "FIXTURE")
rows, err := Run(context.Background(), sources[:2], 3)
if err != nil {
t.Fatal("offline bench failed")
}
for _, row := range rows {
m := row.Fetch
if !m.CandidateBodySupported || m.CandidateLength.Zero != 1 || m.CandidateLength.Small != 2 || m.CandidateLength.Medium != 0 || m.CandidateLength.Large != 0 {
t.Fatal("bench lost candidate body buckets")
}
}
}

View File

@ -0,0 +1,33 @@
package ingestionbench
import (
"context"
"github.com/tradarr/backend/internal/scraper"
"github.com/tradarr/backend/internal/scraper/bloomberg"
"github.com/tradarr/backend/internal/scraper/cnbcbusiness"
"github.com/tradarr/backend/internal/scraper/yahoofinance"
"io"
"net/http"
)
// This wrapper supplies the already-provided credentials to the production RPC
// methods. It contains no collector, parser or enrichment implementation.
type bloombergFeed struct {
client *bloomberg.Bloomberg
username, password string
}
func (b bloombergFeed) Name() string { return "bloomberg" }
func (b bloombergFeed) Scrape(ctx context.Context, s []string) ([]scraper.Article, error) {
return b.client.ScrapeWithCredentials(ctx, b.username, b.password, s)
}
func (b bloombergFeed) Enrich(ctx context.Context, a []scraper.Article) ([]scraper.Article, error) {
return b.client.EnrichWithCredentials(ctx, b.username, b.password, a)
}
func ProductionSources(articleClient, rpcClient *http.Client, scraperURL, username, password, symbol string) []Source {
return []Source{
{Key: "yahoo_finance", Feed: yahoofinance.NewWithClient(articleClient, io.Discard), Symbols: []string{symbol}},
{Key: "cnbc_business", Feed: cnbcbusiness.NewWithClient(articleClient, io.Discard)},
{Key: "bloomberg", Feed: bloombergFeed{bloomberg.NewWithClient(scraperURL, rpcClient, io.Discard), username, password}},
}
}

View File

@ -0,0 +1,2 @@
<!-- Synthetic ingestion fixture. No publisher HTML or prose. -->
<link rel="canonical" href="{{URL}}"><div class="{{ROOT}}"><h2>Synthetic heading.</h2><p>Synthetic complete editorial body.</p><p>Synthetic final paragraph.</p></div>

View File

@ -0,0 +1,82 @@
package articlecontent
import (
"context"
"github.com/tradarr/backend/internal/scraper"
"io"
"net/http"
"strings"
"testing"
)
func TestObservedYahooRedirectIdentities(t *testing.T) {
initial := "https://finance.yahoo.com/news/fixture-initial.html"
final := "https://finance.yahoo.com/news/fixture-final.html"
for _, tc := range []struct {
name, destination, identity string
complete bool
}{
{"canonical_initial", final, initial, true}, {"canonical_final", final, final, true},
{"unobserved", final, "https://finance.yahoo.com/news/fixture-other.html", false},
{"third_party_identity", final, "https://example.invalid/fixture.html", false},
{"external_redirect", "https://example.invalid/fixture.html", initial, false},
{"upgrade_before_fetch", "http://finance.yahoo.com/news/fixture-final.html", initial, true},
} {
for _, metadata := range []string{"canonical", "NewsArticle"} {
t.Run(tc.name+metadata, func(t *testing.T) {
calls := 0
client := &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
calls++
h := make(http.Header)
status := 200
body := ""
if calls == 1 {
status = 302
h.Set("Location", tc.destination)
} else {
if r.URL.String() != final {
t.Fatal("untrusted redirect fetched")
}
body = `<link rel="canonical" href="` + tc.identity + `">`
if metadata == "NewsArticle" {
body = `<script type="application/ld+json">{"@type":"NewsArticle","url":"` + tc.identity + `"}</script>`
}
body += `<article><div class="caas-body"><p>Synthetic full editorial body.</p></div></article>`
}
return &http.Response{StatusCode: status, Header: h, Body: io.NopCloser(strings.NewReader(body)), Request: r}, nil
})}
got, err := Enrich(context.Background(), client, "yahoo_finance", []scraper.Article{{URL: initial}})
if err != nil || (got[0].ContentState == scraper.ContentComplete) != tc.complete || got[0].URL != initial {
t.Fatal("redirect identity contract failed")
}
if strings.Contains(tc.name, "redirect") || tc.name == "downgrade" {
if calls != 1 {
t.Fatal("forbidden redirect fetched")
}
}
})
}
}
}
func TestCNBCEditorialMarkerScopeAndGlobalChallenges(t *testing.T) {
url := "https://www.cnbc.com/2026/01/02/fixture.html"
root := `<div data-module="ArticleBody"><p>Synthetic complete editorial body.</p></div>`
for _, tc := range []struct {
name, html string
state string
}{
{"detached_newsletter", root + `<aside class="newsletter-paywall"></aside>`, scraper.ContentComplete},
{"article_sibling_paywall", `<article>` + root + `<div class="paywall"></div></article>`, scraper.ContentIncomplete},
{"wrapper_partial", `<article data-content-truncated="true">` + root + `</article>`, scraper.ContentIncomplete},
{"global_challenge", root + `<div id="challenge-page"></div>`, scraper.ContentIncomplete},
{"replacement_challenge", `<div id="px-captcha"></div>`, scraper.ContentUnavailable},
} {
t.Run(tc.name, func(t *testing.T) {
got := ExtractHTML("cnbc_business", url, []byte(`<link rel="canonical" href="`+url+`">`+tc.html))
if got.ContentState != tc.state {
t.Fatal("editorial/challenge scope contract failed")
}
})
}
}

View File

@ -0,0 +1,64 @@
package articlecontent
import (
"context"
"io"
"net/http"
"strings"
"testing"
"github.com/tradarr/backend/internal/scraper"
)
func TestCandidateBodyLengthIsCountedBeforeIdentityRejection(t *testing.T) {
lengths := []int{0, 1, 500, 501, 2000, 2001}
pages := make(map[string]string, len(lengths))
articles := make([]scraper.Article, 0, len(lengths))
rawValues := []string{"candidate_title_canary", "placeholder_text_canary"}
for i, n := range lengths {
listed := "https://finance.yahoo.com/news/candidate-listed-" + string(rune('a'+i)) + ".html"
canonical := "https://finance.yahoo.com/news/candidate-canonical-mismatch-" + string(rune('a'+i)) + ".html"
og := "https://finance.yahoo.com/news/candidate-og-mismatch-" + string(rune('a'+i)) + ".html"
jsonld := "https://finance.yahoo.com/news/candidate-jsonld-mismatch-" + string(rune('a'+i)) + ".html"
candidate := strings.Repeat("x", n)
rawValues = append(rawValues, listed, canonical, og, jsonld)
if len(candidate) >= 10 {
rawValues = append(rawValues, candidate)
}
pages[listed] = `<link rel="canonical" href="` + canonical + `"><meta property="og:url" content="` + og + `"><script type="application/ld+json">{"@type":"NewsArticle","url":"` + jsonld + `"}</script><div class="caas-body"><p>` + candidate + `</p><div class="article-placeholder">placeholder_text_canary</div></div>`
articles = append(articles, scraper.Article{URL: listed, Title: "candidate_title_canary"})
}
ctx, meter := scraper.WithFetchMetrics(context.Background())
client := &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
body, ok := pages[r.URL.String()]
if !ok {
return nil, io.ErrUnexpectedEOF
}
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: r}, nil
})}
got, err := Enrich(ctx, client, "yahoo_finance", articles)
metrics := meter.Finish()
if err != nil || len(got) != len(lengths) {
t.Fatal("fixture enrichment failed")
}
for i, article := range got {
if article.Content != "" || scraper.ContentStatus(article) != scraper.ContentUnavailable {
t.Fatalf("identity-rejected fixture %d unexpectedly retained extracted content", i)
}
}
if metrics.Identity.Mismatch != len(lengths) || metrics.Length.Zero != len(lengths) || metrics.Content.Unavailable != len(lengths) {
t.Fatal("identity rejection changed the unavailable/empty extracted-content counters")
}
data := requireAnonymousAggregate(t, metrics, rawValues...)
for _, tc := range []struct {
bucket string
want int
}{
{"0", 1},
{"1-500", 2},
{"501-2000", 2},
{">2000", 1},
} {
requireAggregateCounter(t, data, []string{"candidate_body_characters", tc.bucket}, tc.want)
}
}

View File

@ -0,0 +1,76 @@
package articlecontent
import (
"strings"
"unicode"
"golang.org/x/net/html"
)
// candidateBodyLength measures a unique recognized editorial root without
// constructing or retaining candidate text. It runs before identity rejection,
// never feeds extraction, and saturates at the largest bucket's lower bound.
func candidateBodyLength(root *html.Node) int {
total, chunk, paragraphs := 0, 0, 0
pendingSpace := false
flush := func() {
if chunk > 0 {
if paragraphs > 0 {
total += 2
} // Existing editorial paragraph separator.
total += chunk
paragraphs++
}
chunk = 0
pendingSpace = false
}
var walk func(*html.Node)
walk = func(n *html.Node) {
if total+chunk > 2000 || excluded(n) {
return
}
marker := strings.ToLower(attr(n, "class") + " " + attr(n, "id") + " " + attr(n, "data-component"))
if strings.Contains(marker, "placeholder") || strings.Contains(marker, "skeleton") {
return
}
if n.Type == html.TextNode {
for _, r := range n.Data {
if unicode.IsSpace(r) {
if chunk > 0 {
pendingSpace = true
}
continue
}
if pendingSpace {
chunk++
pendingSpace = false
}
chunk++
if total+chunk > 2000 {
break
}
}
return
}
block := false
switch n.Data {
case "p", "div", "section", "h1", "h2", "h3", "h4", "h5", "h6", "li", "ul", "ol", "blockquote", "pre", "figcaption", "table", "tr", "td", "th":
block = true
}
if block {
flush()
}
if n.Data == "br" && chunk > 0 {
pendingSpace = true
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
walk(c)
}
if block {
flush()
}
}
walk(root)
flush()
return min(total, 2001)
}

View File

@ -0,0 +1,49 @@
package articlecontent
import (
"fmt"
"strings"
"testing"
"github.com/tradarr/backend/internal/scraper"
)
func TestCandidateLengthUnicodeBucketsAndExcludedText(t *testing.T) {
for _, source := range []string{"yahoo_finance", "cnbc_business"} {
pages := map[string]string{}
root, base := "caas-body", "https://finance.yahoo.com/news/fixture-"
if source == "cnbc_business" {
root = "ArticleBody-articleBody"
base = "https://www.cnbc.com/2026/02/01/fixture-"
}
for i, n := range []int{0, 1, 500, 501, 2000, 2001} {
target := fmt.Sprintf("%s%d.html", base, i)
pages[target] = `<link rel="canonical" href="` + base + `other.html"><div class="` + root + `"><p>` + strings.Repeat("界", n) + `</p><nav>Excluded navigation</nav><div hidden>Excluded hidden</div><script>Excluded script</script><div class="skeleton">Excluded skeleton</div><div id="article-placeholder">Excluded placeholder</div></div><p>Excluded outside text</p>`
}
m := fetchMetricsForFixturePages(t, source, pages)
if !m.CandidateBodySupported || m.CandidateLength != (scraper.LengthCounts{Zero: 1, Small: 2, Medium: 2, Large: 1}) || m.Length.Zero != 6 || m.Content.Unavailable != 6 {
t.Fatal("candidate Unicode/exclusion buckets changed article results")
}
}
}
func TestCandidateLengthNormalizesEditorialWhitespaceWithoutRetainingContent(t *testing.T) {
const target = "https://finance.yahoo.com/news/fixture.html"
pages := map[string]string{target: `<link rel="canonical" href="` + target + `"><div class="caas-body"><h2> Synthetic heading </h2><p>A <em> Unicode 界 </em> body<br> text.</p><aside>Excluded sidebar</aside></div>`}
m := fetchMetricsForFixturePages(t, "yahoo_finance", pages)
if m.CandidateLength.Small != 1 || m.Length.Small != 1 || m.Content.Complete != 1 {
t.Fatal("candidate length changed valid extraction")
}
}
func TestCandidateLengthDoesNotInventAnEditorialRoot(t *testing.T) {
const target = "https://finance.yahoo.com/news/fixture.html"
for _, raw := range []string{
`<main><p>Synthetic generic page text.</p></main>`,
`<div class="caas-body"><p>First ambiguous root.</p></div><div class="caas-body"><p>Second ambiguous root.</p></div>`,
`<aside><div class="caas-body"><p>Excluded root.</p></div></aside>`,
} {
m := fetchMetricsForFixturePages(t, "yahoo_finance", map[string]string{target: raw})
if m.CandidateLength.Zero != 1 || m.Content.Unavailable != 1 {
t.Fatal("unknown/ambiguous/excluded root was measured as editorial body")
}
}
}

View File

@ -0,0 +1,228 @@
package articlecontent
import (
"encoding/json"
"net/url"
"strconv"
"strings"
"github.com/tradarr/backend/internal/scraper"
"golang.org/x/net/html"
)
// observeGranular reduces existing transient DOM evidence into fixed flags.
// Each category/scope contributes at most once per fetch. Nothing here decides
// whether content is associated, complete, or usable by the product.
func observeGranular(doc *html.Node, roots []*html.Node, source, expected string, aliases []string, content string, extractionEvaluated bool, o *scraper.FetchObservation) {
o.GranularSupported = true
accepted := map[string]bool{}
for _, v := range append([]string{expected}, aliases...) {
if k, ok := articleIdentity(source, v); ok {
accepted[k] = true
}
}
base, _ := url.Parse(expected)
relation := func(value string) (bool, bool) {
if value == "" || base == nil {
return false, false
}
ref, err := url.Parse(value)
if err != nil {
return false, false
}
k, ok := articleIdentity(source, base.ResolveReference(ref).String())
return accepted[k], ok
}
scope := func(n *html.Node) bool {
for p := n; p != nil; p = p.Parent {
for _, root := range roots {
if p == root {
return true
}
}
}
// Article wrappers, including metadata beside the body, are editorial.
for _, root := range roots {
for p := root; p != nil; p = p.Parent {
if p.Type == html.ElementNode && p.Data == "article" {
for q := n; q != nil; q = q.Parent {
if q == p {
return true
}
}
break
}
}
}
return false
}
set := func(c *scraper.ScopedEvidenceCounts, inside bool) {
if inside {
c.ArticleRoot = 1
} else {
c.OutsideRoot = 1
}
}
identity := func(v any) string {
switch x := v.(type) {
case string:
return x
case map[string]any:
s, _ := x["@id"].(string)
return s
}
return ""
}
var metadata func(any, int, bool, *int)
metadata = func(value any, depth int, inside bool, visited *int) {
*visited++
if depth > 32 || *visited > 2000 {
return
}
switch x := value.(type) {
case []any:
for _, v := range x {
metadata(v, depth+1, inside, visited)
}
case map[string]any:
article := false
switch typ := x["@type"].(type) {
case string:
article = typ == "Article" || typ == "NewsArticle" || typ == "ReportageNewsArticle"
case []any:
for _, typ := range typ {
if typ == "Article" || typ == "NewsArticle" || typ == "ReportageNewsArticle" {
article = true
}
}
}
if article {
id := identity(x["url"])
if id == "" {
id = identity(x["mainEntityOfPage"])
}
if id == "" {
id = identity(x["@id"])
}
match, _ := relation(id)
if id != "" {
if match {
o.IdentityEvidence.JSONLD.Associated = 1
} else {
o.IdentityEvidence.JSONLD.Mismatch = 1
}
}
if match {
if x["isAccessibleForFree"] == false || strings.EqualFold(identity(x["isAccessibleForFree"]), "false") {
set(&o.BlockingEvidence.Accessibility, inside)
}
if body, ok := x["articleBody"].(string); ok && extractionEvaluated && len(roots) == 1 && strings.Join(strings.Fields(body), " ") != strings.Join(strings.Fields(content), " ") {
set(&o.BlockingEvidence.BodyConflict, inside)
}
}
}
for _, v := range x {
switch v.(type) {
case map[string]any, []any:
metadata(v, depth+1, inside, visited)
}
}
}
}
// Presence is tracked separately for each metadata family; absent means no
// nonempty value, rather than an invalid or a different identity.
canonicalPresent, ogPresent := false, false
recordIdentity := func(c *scraper.MetadataIdentityCounts, value string) {
ref, err := url.Parse(value)
if err != nil || base == nil || len(value) > 4096 {
c.Invalid = 1
return
}
u := base.ResolveReference(ref)
host := u.Hostname()
valid := (u.Scheme == "https" || u.Scheme == "http") && host != "" && u.User == nil && u.Opaque == "" && !strings.ContainsAny(host, " \t\r\n\\")
if port := u.Port(); port != "" {
n, err := strconv.Atoi(port)
valid = valid && err == nil && n > 0 && n <= 65535
}
if !valid {
c.Invalid = 1
return
}
match, _ := relation(value)
if match {
c.Associated = 1
return
}
if strings.EqualFold(host, base.Hostname()) {
c.SameSourceDifferentIdentity = 1
} else {
c.ValidOtherHost = 1
}
}
var walk func(*html.Node)
walk = func(n *html.Node) {
if n.Type == html.ElementNode {
inside := scope(n)
marker := strings.ToLower(attr(n, "class") + " " + attr(n, "id") + " " + attr(n, "data-component"))
if strings.Contains(marker, "paywall") || strings.Contains(marker, "giftarticle") || attr(n, "data-test") == "paywall" || attr(n, "data-testid") == "paywall" {
set(&o.BlockingEvidence.Paywall, inside)
}
if challengeMarker(n) {
o.BlockingEvidence.Challenge.GlobalPage = 1
}
if attr(n, "data-content-state") == "partial" || attr(n, "data-content-state") == "incomplete" {
set(&o.BlockingEvidence.Partial, inside)
}
if attr(n, "data-content-truncated") == "true" {
set(&o.BlockingEvidence.Truncated, inside)
}
if strings.Contains(marker, "placeholder") || strings.Contains(marker, "skeleton") {
set(&o.BlockingEvidence.Placeholder, inside)
}
kind, value := "", ""
if n.Data == "link" && strings.EqualFold(attr(n, "rel"), "canonical") {
kind = "canonical"
value = attr(n, "href")
}
if n.Data == "meta" && attr(n, "property") == "og:url" {
kind = "og"
value = attr(n, "content")
}
value = strings.TrimSpace(value)
if value != "" {
if kind == "canonical" {
canonicalPresent = true
recordIdentity(&o.IdentityEvidence.Canonical, value)
} else {
ogPresent = true
recordIdentity(&o.IdentityEvidence.OG, value)
}
}
if n.Data == "script" && attr(n, "type") == "application/ld+json" {
var text strings.Builder
for c := n.FirstChild; c != nil; c = c.NextSibling {
if c.Type == html.TextNode {
text.WriteString(c.Data)
}
}
var value any
if json.Unmarshal([]byte(text.String()), &value) == nil {
visited := 0
metadata(value, 0, inside, &visited)
}
}
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
walk(c)
}
}
walk(doc)
if !canonicalPresent {
o.IdentityEvidence.Canonical.Absent = 1
}
if !ogPresent {
o.IdentityEvidence.OG.Absent = 1
}
}

View File

@ -0,0 +1,96 @@
package articlecontent
import (
"context"
"io"
"net/http"
"reflect"
"strings"
"testing"
"github.com/tradarr/backend/internal/scraper"
)
func TestGranularInstrumentationDoesNotChangeArticleDecisions(t *testing.T) {
const target = "https://www.cnbc.com/2026/02/01/fixture.html"
for _, part := range []string{
`<div data-module="ArticleBody"><p>Synthetic editorial text.</p></div><aside class="paywall"></aside>`,
`<article><div data-module="ArticleBody"><p>Synthetic editorial text.</p></div><div class="paywall"></div></article>`,
`<div data-module="ArticleBody"><p>Synthetic editorial text.</p><div data-content-state="partial"></div></div>`,
`<aside id="challengeGate"></aside>`,
`<script type="application/ld+json">{"@type":"NewsArticle","url":"` + target + `","isAccessibleForFree":false,"articleBody":"conflicting synthetic metadata"}</script><div data-module="ArticleBody"><p>Synthetic editorial text.</p></div>`,
} {
client := &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
return &http.Response{StatusCode: 200, Header: make(http.Header), Request: r, Body: io.NopCloser(strings.NewReader(`<link rel="canonical" href="` + target + `">` + part))}, nil
})}
plain, _ := Enrich(context.Background(), client, "cnbc_business", []scraper.Article{{URL: target}})
ctx, meter := scraper.WithFetchMetrics(context.Background())
measured, _ := Enrich(ctx, client, "cnbc_business", []scraper.Article{{URL: target}})
if !reflect.DeepEqual(plain, measured) || !meter.Finish().GranularSupported {
t.Fatal("diagnostics altered article result")
}
}
}
func TestGranularEvidenceIsDeduplicatedPerFetchAndUnextractedBodiesAreNotConflicts(t *testing.T) {
const target = "https://finance.yahoo.com/news/fixture.html"
duplicate := `<link rel="canonical" href="` + target + `"><link rel="canonical" href="` + target + `"><div class="caas-body"><p>Synthetic body.</p><div class="paywall"></div><div class="paywall"></div></div>`
m := fetchMetricsForFixturePages(t, "yahoo_finance", map[string]string{target: duplicate})
if m.IdentityEvidence.Canonical.Associated != 1 || m.BlockingEvidence.Paywall.ArticleRoot != 1 {
t.Fatal("duplicate evidence inflated counters")
}
// Rejected association returns before extraction: do not invent a conflict
// by comparing metadata with an unextracted empty content string.
mismatch := `<link rel="canonical" href="https://finance.yahoo.com/news/other.html"><script type="application/ld+json">{"@type":"NewsArticle","url":"` + target + `","articleBody":"Synthetic body."}</script><div class="caas-body"><p>Synthetic body.</p></div>`
m = fetchMetricsForFixturePages(t, "yahoo_finance", map[string]string{target: mismatch})
if m.BlockingEvidence.BodyConflict.OutsideRoot != 0 || m.IdentityEvidence.JSONLD.Associated != 1 {
t.Fatal("unextracted body conflict was invented")
}
}
func TestMetadataDiagnosticValidityAndAbsenceAreIndependentOfParserTrust(t *testing.T) {
const target = "https://finance.yahoo.com/news/fixture.html"
for _, kind := range []string{"canonical", "og"} {
for _, tc := range []struct {
name, value string
want scraper.MetadataIdentityCounts
}{
{"associated", target, scraper.MetadataIdentityCounts{Associated: 1}},
{"relative_associated", "/news/fixture.html", scraper.MetadataIdentityCounts{Associated: 1}},
{"same_source_other", "/news/other.html", scraper.MetadataIdentityCounts{SameSourceDifferentIdentity: 1}},
{"valid_same_host_port", "https://finance.yahoo.com:444/news/fixture.html", scraper.MetadataIdentityCounts{SameSourceDifferentIdentity: 1}},
{"valid_other_host", "https://example.invalid/fixture", scraper.MetadataIdentityCounts{ValidOtherHost: 1}},
{"invalid_syntax", "http://[invalid", scraper.MetadataIdentityCounts{Invalid: 1}},
{"invalid_scheme", "javascript:fixture", scraper.MetadataIdentityCounts{Invalid: 1}},
{"invalid_port", "https://example.invalid:99999/fixture", scraper.MetadataIdentityCounts{Invalid: 1}},
{"invalid_credentials", "https://private:canary@example.invalid/fixture", scraper.MetadataIdentityCounts{Invalid: 1}},
{"empty", "", scraper.MetadataIdentityCounts{Absent: 1}},
} {
t.Run(kind+"/"+tc.name, func(t *testing.T) {
tag := `<link rel="canonical" href="` + tc.value + `">`
if kind == "og" {
tag = `<meta property="og:url" content="` + tc.value + `">`
}
m := fetchMetricsForFixturePages(t, "yahoo_finance", map[string]string{target: tag + `<div class="caas-body"><p>Synthetic editorial text.</p></div>`})
got, other := m.IdentityEvidence.Canonical, m.IdentityEvidence.OG
if kind == "og" {
got, other = other, got
}
if got != tc.want || other.Absent != 1 {
t.Fatal("metadata validity/absence category contract failed")
}
})
}
}
}
func TestChallengeIsOneGlobalPageSignalEvenAcrossBothScopes(t *testing.T) {
const target = "https://www.cnbc.com/2026/02/01/fixture.html"
raw := `<link rel="canonical" href="` + target + `"><aside id="challengeGate"></aside><div data-module="ArticleBody"><p>Synthetic editorial text.</p><div id="challengeGate"></div></div>`
m := fetchMetricsForFixturePages(t, "cnbc_business", map[string]string{target: raw})
if m.BlockingEvidence.Challenge.GlobalPage != 1 || m.Content.Incomplete != 1 {
t.Fatal("global challenge semantics changed")
}
data := requireAnonymousAggregate(t, m)
requireNoAggregateCounter(t, data, []string{"blocking_evidence", "challenge", "article_root"})
requireNoAggregateCounter(t, data, []string{"blocking_evidence", "challenge", "outside_root"})
}

View File

@ -10,6 +10,7 @@ import (
"net/url"
"strings"
"time"
"unicode/utf8"
"github.com/tradarr/backend/internal/scraper"
"golang.org/x/net/html"
@ -17,39 +18,54 @@ import (
const maxHTMLBytes = 16 * 1024 * 1024
// A listing may use an article path without a filename/date pattern. Trust
// only the exact source origin, upgrade HTTP before network I/O, and preserve
// semantic query parameters. The original Article.URL is never rewritten.
func safeURL(source, value string) (string, bool) {
u, err := url.Parse(value)
if err != nil || u.Scheme != "https" || u.User != nil || u.Port() != "" || len(value) > 4096 {
if err != nil || (u.Scheme != "https" && u.Scheme != "http") || u.Opaque != "" || u.User != nil || u.Port() != "" || len(value) > 4096 || u.Path == "" || u.Path == "/" {
return "", false
}
host := strings.ToLower(u.Hostname())
switch source {
case "yahoo_finance":
if u.Hostname() != "finance.yahoo.com" || !strings.HasPrefix(u.Path, "/news/") || !strings.HasSuffix(u.Path, ".html") {
if host != "finance.yahoo.com" {
return "", false
}
case "cnbc_business":
if u.Hostname() != "www.cnbc.com" || !strings.HasSuffix(u.Path, ".html") || len(u.Path) < 12 || u.Path[5] != '/' || u.Path[8] != '/' || u.Path[11] != '/' {
if host != "www.cnbc.com" {
return "", false
}
default:
return "", false
}
u.RawQuery = ""
u.Scheme = "https"
u.Host = host
u.Fragment = ""
return u.String(), true
}
func articleIdentity(source, value string) (string, bool) {
value, ok := safeURL(source, value)
if !ok {
return "", false
}
u, _ := url.Parse(value)
q := u.Query()
for k := range q {
if strings.HasPrefix(strings.ToLower(k), "utm_") || k == "guccounter" || k == "guce_referrer" || k == "guce_referrer_sig" {
q.Del(k)
}
}
u.RawQuery = q.Encode()
return u.String(), true
}
func Enrich(ctx context.Context, client *http.Client, source string, articles []scraper.Article) ([]scraper.Article, error) {
scraper.EnableFetchMetrics(ctx)
ctx, cancel := context.WithTimeout(ctx, 90*time.Second)
defer cancel()
out := append([]scraper.Article(nil), articles...)
bounded := *client
bounded.Timeout = 15 * time.Second
bounded.CheckRedirect = func(r *http.Request, via []*http.Request) error {
if _, ok := safeURL(source, r.URL.String()); !ok || len(via) >= 3 {
return http.ErrUseLastResponse
}
return nil
}
cache := map[string]scraper.Article{}
for i, a := range out {
out[i].Content = ""
@ -68,16 +84,54 @@ func Enrich(ctx context.Context, client *http.Client, source string, articles []
req.Header.Set("User-Agent", "Tradarr/1.0")
req.Header.Set("Accept", "text/html")
extracted = scraper.Article{ContentState: scraper.ContentUnavailable}
resp, err := bounded.Do(req)
// Only an observed, validated redirect chain may change the fetch
// identity. Metadata may identify the initial or observed final URL.
verifiedFinal := target
requestClient := bounded
requestClient.CheckRedirect = func(r *http.Request, via []*http.Request) error {
normalized, ok := safeURL(source, r.URL.String())
if !ok || len(via) >= 3 {
return http.ErrUseLastResponse
}
parsed, _ := url.Parse(normalized)
r.URL = parsed
verifiedFinal = normalized
return nil
}
observation := scraper.FetchObservation{State: scraper.ContentUnavailable, CandidateBodySupported: true}
var trace *scraper.FetchObservation
if scraper.FetchMetricsEnabled(ctx) {
trace = &observation
}
resp, err := requestClient.Do(req)
if err != nil {
observation.Network = true
}
if err == nil {
if resp.StatusCode == http.StatusOK && sameResponseArticle(source, target, resp) {
observation.HTTPStatus = resp.StatusCode
responseMatches := true
if resp.Request != nil && resp.Request.URL != nil {
actual, ok := articleIdentity(source, resp.Request.URL.String())
expected, _ := articleIdentity(source, verifiedFinal)
responseMatches = ok && actual == expected
}
if !responseMatches {
observation.Identity = scraper.IdentityMismatch
}
if resp.StatusCode == http.StatusOK && responseMatches {
raw, readErr := io.ReadAll(io.LimitReader(resp.Body, maxHTMLBytes+1))
if readErr == nil && len(raw) <= maxHTMLBytes {
extracted = ExtractHTML(source, target, raw)
var aliases []string
if source == "yahoo_finance" {
aliases = []string{target}
}
extracted = extractHTML(source, verifiedFinal, raw, trace, aliases...)
}
}
resp.Body.Close()
}
observation.State = extracted.ContentState
scraper.RecordFetch(ctx, observation)
cache[target] = extracted
}
out[i].Content = extracted.Content
@ -157,11 +211,20 @@ func missingMarker(n *html.Node) bool {
marker := strings.ToLower(attr(n, "class") + " " + attr(n, "id") + " " + attr(n, "data-component"))
return strings.Contains(marker, "placeholder") || strings.Contains(marker, "skeleton") || attr(n, "data-content-truncated") == "true" || attr(n, "data-content-state") == "partial" || attr(n, "data-content-state") == "incomplete"
}
// Challenges may replace or overlay editorial content, so their scope is global.
func challengeMarker(n *html.Node) bool {
marker := strings.ToLower(attr(n, "class") + " " + attr(n, "id"))
return strings.Contains(marker, "captcha") || strings.Contains(marker, "challenge") || strings.HasPrefix(attr(n, "id"), "cf-chl") || strings.Contains(attr(n, "src"), "challenge-platform")
}
func accessMarker(n *html.Node) bool {
marker := strings.ToLower(attr(n, "class") + " " + attr(n, "id"))
return strings.Contains(marker, "paywall") || strings.Contains(marker, "giftarticle") || strings.Contains(marker, "captcha") || strings.HasPrefix(attr(n, "id"), "cf-chl") || strings.HasPrefix(attr(n, "id"), "challenge") || strings.Contains(attr(n, "src"), "challenge-platform") || attr(n, "data-test") == "paywall" || attr(n, "data-testid") == "paywall" || attr(n, "data-content-state") == "partial" || attr(n, "data-content-state") == "incomplete" || attr(n, "data-content-truncated") == "true"
}
func ExtractHTML(source, articleURL string, raw []byte) scraper.Article {
return extractHTML(source, articleURL, raw, nil)
}
func extractHTML(source, articleURL string, raw []byte, observation *scraper.FetchObservation, aliases ...string) scraper.Article {
a := scraper.Article{ContentState: scraper.ContentUnavailable}
if len(raw) > maxHTMLBytes {
return a
@ -170,10 +233,7 @@ func ExtractHTML(source, articleURL string, raw []byte) scraper.Article {
if err != nil {
return a
}
evidence := inspectEvidence(doc, source, articleURL)
if evidence.mismatch {
return a
}
evidence := inspectEvidence(doc, source, articleURL, aliases...)
var roots []*html.Node
blocked := evidence.blocked
var walk func(*html.Node)
@ -190,7 +250,7 @@ func ExtractHTML(source, articleURL string, raw []byte) scraper.Article {
roots = append(roots, n)
}
}
if accessMarker(n) {
if accessMarker(n) && (source != "cnbc_business" || challengeMarker(n) || missingMarker(n)) {
blocked = true
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
@ -198,6 +258,61 @@ func ExtractHTML(source, articleURL string, raw []byte) scraper.Article {
}
}
walk(doc)
extractionEvaluated := false
if observation != nil {
// Read-only diagnostics: never influence association, dates or completeness.
defer func() {
observeGranular(doc, roots, source, articleURL, aliases, a.Content, extractionEvaluated, observation)
}()
}
if source == "cnbc_business" {
// Generic subscription chrome is unrelated; article wrappers and their
// descendants still carry access restrictions. Challenges remain global.
var scan func(*html.Node)
scan = func(n *html.Node) {
if accessMarker(n) || missingMarker(n) {
blocked = true
}
for c := n.FirstChild; c != nil; c = c.NextSibling {
scan(c)
}
}
for _, root := range roots {
scan(root)
for p := root.Parent; p != nil; p = p.Parent {
if accessMarker(p) || missingMarker(p) {
blocked = true
}
if p.Type == html.ElementNode && p.Data == "article" {
scan(p)
break
}
}
}
}
if observation != nil {
if len(roots) == 1 {
observation.CandidateBodyLength = candidateBodyLength(roots[0])
}
observation.Root = scraper.ObservedNo
if len(roots) == 1 {
observation.Root = scraper.ObservedYes
}
observation.Identity = scraper.IdentityNo
if evidence.associated {
observation.Identity = scraper.IdentityYes
}
if evidence.mismatch {
observation.Identity = scraper.IdentityMismatch
}
observation.Blocking = scraper.ObservedNo
if blocked {
observation.Blocking = scraper.ObservedYes
}
}
if evidence.mismatch {
return a
}
if evidence.associated && !evidence.dateConflict {
a.PublishedAt = evidence.date
}
@ -216,6 +331,9 @@ func ExtractHTML(source, articleURL string, raw []byte) scraper.Article {
var collect func(*html.Node)
collect = func(n *html.Node) {
if missingMarker(n) {
if observation != nil {
observation.Blocking = scraper.ObservedYes
}
blocked = true
}
if excluded(n) {
@ -246,6 +364,10 @@ func ExtractHTML(source, articleURL string, raw []byte) scraper.Article {
collect(roots[0])
flush()
a.Content = strings.Join(paragraphs, "\n\n")
extractionEvaluated = true
if observation != nil {
observation.Length = utf8.RuneCountInString(a.Content)
}
if evidence.fullBody != nil && strings.Join(strings.Fields(*evidence.fullBody), " ") != strings.Join(strings.Fields(a.Content), " ") {
blocked = true
}
@ -257,11 +379,3 @@ func ExtractHTML(source, articleURL string, raw []byte) scraper.Article {
}
return a
}
func sameResponseArticle(source, target string, resp *http.Response) bool {
if resp.Request == nil || resp.Request.URL == nil {
return true
}
actual, ok := safeURL(source, resp.Request.URL.String())
return ok && actual == target
}

View File

@ -25,8 +25,12 @@ func TestTicket39SourceFixtures(t *testing.T) {
t.Fatalf("bad full content: state=%s date=%v", a.ContentState, a.PublishedAt)
}
a = ExtractHTML(source, fixtureArticleURL(source), append(raw, []byte(`<div class="paywall">subscribe</div>`)...))
if a.ContentState != scraper.ContentIncomplete {
t.Fatal("paywall claimed complete")
expected := scraper.ContentIncomplete
if source == "cnbc_business" {
expected = scraper.ContentComplete
}
if a.ContentState != expected {
t.Fatal("detached paywall scope contract failed")
}
})
}

View File

@ -14,9 +14,18 @@ type articleEvidence struct {
fullBody *string
}
func inspectEvidence(doc *html.Node, source, expected string) articleEvidence {
func inspectEvidence(doc *html.Node, source, expected string, aliases ...string) articleEvidence {
e := articleEvidence{}
wanted, valid := safeURL(source, expected)
wanted, valid := articleIdentity(source, expected)
accepted := map[string]bool{}
if valid {
accepted[wanted] = true
}
for _, alias := range aliases {
if identity, ok := articleIdentity(source, alias); ok {
accepted[identity] = true
}
}
key := func(value string) string {
if value == "" {
return ""
@ -29,7 +38,7 @@ func inspectEvidence(doc *html.Node, source, expected string) articleEvidence {
if err != nil {
return ""
}
value, ok := safeURL(source, base.ResolveReference(ref).String())
value, ok := articleIdentity(source, base.ResolveReference(ref).String())
if !ok {
return ""
}
@ -96,7 +105,7 @@ func inspectEvidence(doc *html.Node, source, expected string) articleEvidence {
if value != "" {
articleIDs++
}
if valid && key(value) == wanted {
if accepted[key(value)] {
e.associated = true
matching = true
if x["isAccessibleForFree"] == false || strings.EqualFold(identity(x["isAccessibleForFree"]), "false") {
@ -132,7 +141,7 @@ func inspectEvidence(doc *html.Node, source, expected string) articleEvidence {
}
if value != "" {
primary++
if valid && key(value) == wanted {
if accepted[key(value)] {
e.associated = true
} else {
e.mismatch = true

View File

@ -0,0 +1,99 @@
package articlecontent
import (
"context"
"errors"
"github.com/tradarr/backend/internal/scraper"
"io"
"net/http"
"strings"
"testing"
)
type unreadableMetricBody struct{ t *testing.T }
func (b unreadableMetricBody) Read([]byte) (int, error) {
b.t.Fatal("non-200 body read for diagnostics")
return 0, io.EOF
}
func (unreadableMetricBody) Close() error { return nil }
func TestArticleFetchMetricsDescribeHTTPAndParserWithoutChangingClassification(t *testing.T) {
const target = "https://finance.yahoo.com/news/metrics.html"
base := `<link rel="canonical" href="` + target + `"><div class="caas-body"><p>Synthetic retained content.</p></div>`
for _, tc := range []struct {
name string
status int
html string
network bool
root scraper.EvidenceFlag
identity scraper.IdentityFlag
blocking scraper.EvidenceFlag
state string
}{
{"recognized", 200, base, false, scraper.ObservedYes, scraper.IdentityYes, scraper.ObservedNo, scraper.ContentComplete},
{"unknown_root", 200, strings.Replace(base, "caas-body", "unrecognized-root", 1), false, scraper.ObservedNo, scraper.IdentityYes, scraper.ObservedNo, scraper.ContentUnavailable},
{"unknown_identity", 200, `<div class="caas-body"><p>Synthetic retained content.</p></div>`, false, scraper.ObservedYes, scraper.IdentityNo, scraper.ObservedNo, scraper.ContentIncomplete},
{"mismatch", 200, strings.Replace(base, target, target+"-other", 1), false, scraper.ObservedYes, scraper.IdentityMismatch, scraper.ObservedNo, scraper.ContentUnavailable},
{"challenge", 200, `<div id="px-captcha"></div>`, false, scraper.ObservedNo, scraper.IdentityNo, scraper.ObservedYes, scraper.ContentUnavailable},
{"denied", 403, "", false, scraper.NotEvaluated, scraper.IdentityNotEvaluated, scraper.NotEvaluated, scraper.ContentUnavailable},
{"unavailable", 503, "", false, scraper.NotEvaluated, scraper.IdentityNotEvaluated, scraper.NotEvaluated, scraper.ContentUnavailable},
{"redirect_denied", 302, "", false, scraper.NotEvaluated, scraper.IdentityNotEvaluated, scraper.NotEvaluated, scraper.ContentUnavailable},
{"network", 0, "", true, scraper.NotEvaluated, scraper.IdentityNotEvaluated, scraper.NotEvaluated, scraper.ContentUnavailable},
} {
t.Run(tc.name, func(t *testing.T) {
ctx, m := scraper.WithFetchMetrics(context.Background())
client := &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
if tc.network {
return nil, errors.New("synthetic-private-error")
}
var body io.ReadCloser = io.NopCloser(strings.NewReader(tc.html))
if tc.status != 200 {
body = unreadableMetricBody{t}
}
return &http.Response{StatusCode: tc.status, Header: make(http.Header), Body: body, Request: r}, nil
})}
a, err := Enrich(ctx, client, "yahoo_finance", []scraper.Article{{URL: target}})
c := m.Finish()
if err != nil || len(a) != 1 || scraper.ContentStatus(a[0]) != tc.state || !c.Supported || c.Attempted != 1 {
t.Fatal("measurement changed outcome")
}
wantRoot := scraper.EvidenceCounts{}
add := func(v scraper.EvidenceFlag) *int {
switch v {
case scraper.ObservedYes:
return &wantRoot.Yes
case scraper.ObservedNo:
return &wantRoot.No
}
return &wantRoot.NotEvaluated
}
*add(tc.root) = 1
if c.Root != wantRoot {
t.Fatalf("root classification %+v", c.Root)
}
if tc.identity == scraper.IdentityMismatch && c.Identity.Mismatch != 1 || tc.identity == scraper.IdentityYes && c.Identity.Yes != 1 || tc.identity == scraper.IdentityNo && c.Identity.No != 1 || tc.identity == scraper.IdentityNotEvaluated && c.Identity.NotEvaluated != 1 {
t.Fatal("identity classification")
}
if tc.blocking == scraper.ObservedYes && c.Blocking.Yes != 1 || tc.blocking == scraper.ObservedNo && c.Blocking.No != 1 || tc.blocking == scraper.NotEvaluated && c.Blocking.NotEvaluated != 1 {
t.Fatal("block classification")
}
if tc.status == 200 && c.HTTP.TwoXX != 1 || tc.status == 302 && c.HTTP.ThreeXX != 1 || tc.status == 403 && c.HTTP.FourXX != 1 || tc.status == 503 && c.HTTP.FiveXX != 1 || tc.network && c.HTTP.Network != 1 {
t.Fatal("HTTP class")
}
})
}
}
func TestExtractedLengthBucketsCountUnicodeCharacters(t *testing.T) {
for _, n := range []int{0, 1, 500, 501, 2000, 2001} {
ctx, m := scraper.WithFetchMetrics(context.Background())
client := &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
body := `<link rel="canonical" href="` + r.URL.String() + `"><div class="caas-body"><p>` + strings.Repeat("漢", n) + `</p></div>`
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header), Request: r}, nil
})}
Enrich(ctx, client, "yahoo_finance", []scraper.Article{{URL: "https://finance.yahoo.com/news/length.html"}})
c := m.Finish()
if n == 0 && c.Length.Zero != 1 || n > 0 && n <= 500 && c.Length.Small != 1 || n > 500 && n <= 2000 && c.Length.Medium != 1 || n > 2000 && c.Length.Large != 1 {
t.Fatal("character bucket incorrect")
}
}
}

View File

@ -0,0 +1,254 @@
package articlecontent
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"strings"
"testing"
"github.com/tradarr/backend/internal/scraper"
)
const granularMetricCanary = "fixture_private_body_title_url_secret_canary"
func jsonLD(t *testing.T, value any) string {
t.Helper()
raw, err := json.Marshal(value)
if err != nil {
t.Fatal("could not build anonymous metrics fixture")
}
return `<script type="application/ld+json">` + string(raw) + `</script>`
}
func fetchMetricsForFixturePages(t *testing.T, source string, pages map[string]string) scraper.FetchMetrics {
t.Helper()
articles := make([]scraper.Article, 0, len(pages))
for target := range pages {
articles = append(articles, scraper.Article{URL: target, Title: granularMetricCanary})
}
ctx, meter := scraper.WithFetchMetrics(context.Background())
client := &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
body, ok := pages[r.URL.String()]
if !ok {
return nil, fmt.Errorf("fixture route not found")
}
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: r}, nil
})}
got, err := Enrich(ctx, client, source, articles)
if err != nil || len(got) != len(articles) {
t.Fatal("fixture enrichment failed")
}
return meter.Finish()
}
func requireAnonymousAggregate(t *testing.T, metrics scraper.FetchMetrics, fixtureValues ...string) map[string]any {
t.Helper()
raw, err := json.Marshal(metrics)
if err != nil {
t.Fatal("aggregate metrics were not JSON serializable")
}
serialized := string(raw)
for _, value := range append([]string{"http://", "https://", "finance.yahoo.com", "www.cnbc.com", granularMetricCanary}, fixtureValues...) {
if strings.Contains(serialized, value) {
t.Error("aggregate JSON exposed fixture source data")
}
}
var data map[string]any
if err := json.Unmarshal(raw, &data); err != nil {
t.Fatal("aggregate metrics JSON could not be inspected")
}
return data
}
func requireAggregateCounter(t *testing.T, data map[string]any, path []string, want int) {
t.Helper()
var value any = data
for _, key := range path {
parent, ok := value.(map[string]any)
if !ok {
t.Errorf("aggregate cause counter is missing: %s", strings.Join(path, "."))
return
}
value, ok = parent[key]
if !ok {
t.Errorf("aggregate cause counter is missing: %s", strings.Join(path, "."))
return
}
}
got, ok := value.(float64)
if !ok || int(got) != want {
t.Errorf("aggregate cause counter mismatch: %s", strings.Join(path, "."))
}
}
func requireNoAggregateCounter(t *testing.T, data map[string]any, path []string) {
t.Helper()
var value any = data
for _, key := range path {
parent, ok := value.(map[string]any)
if !ok {
return
}
value, ok = parent[key]
if !ok {
return
}
}
t.Errorf("global page challenge was incorrectly exposed as root-scoped: %s", strings.Join(path, "."))
}
func TestYahooIdentityCauseMetricsSeparateMetadataKindsAndRelations(t *testing.T) {
const sameHostOther = "https://finance.yahoo.com/news/other-fixture.html"
const otherHost = "https://www.cnbc.com/2026/01/02/other-fixture.html"
const fixtureBody = "Editorial body canary " + granularMetricCanary
targets := make([]string, 10)
for i := range targets {
targets[i] = fmt.Sprintf("https://finance.yahoo.com/news/identity-fixture-%02d.html", i+1)
}
pages := map[string]string{}
for i, target := range targets {
metadata := ""
switch i {
case 0:
metadata = `<link rel="canonical" href="` + sameHostOther + `">`
case 1:
metadata = `<link rel="canonical" href="` + otherHost + `">`
case 2:
metadata = `<link rel="canonical" href="http://[invalid">`
case 3:
metadata = ""
case 4:
metadata = `<meta property="og:url" content="` + sameHostOther + `">`
case 5:
metadata = `<meta property="og:url" content="` + otherHost + `">`
case 6:
metadata = `<meta property="og:url" content="http://[invalid">`
case 7:
metadata = ""
case 8:
metadata = jsonLD(t, map[string]any{"@type": "NewsArticle", "url": sameHostOther})
case 9:
metadata = jsonLD(t, map[string]any{"@type": "NewsArticle", "url": target, "articleBody": fixtureBody})
}
if i < 8 {
pages[target] = metadata + `<article><div class="caas-body"></div></article>`
} else {
pages[target] = metadata + `<article><div class="caas-body"><p>` + fixtureBody + `</p></div></article>`
}
}
metrics := fetchMetricsForFixturePages(t, "yahoo_finance", pages)
data := requireAnonymousAggregate(t, metrics, sameHostOther, otherHost, granularMetricCanary)
if metrics.Attempted != 10 || metrics.HTTP.TwoXX != 10 || metrics.Root.Yes != 10 {
t.Fatal("Yahoo fixture aggregate did not retain bounded anonymous fetch counts")
}
// Each family appears on 3 of the 10 pages; the remaining 7 are absent,
// including pages with only the other family or only JSON-LD.
for _, tc := range []struct {
kind, cause string
want int
}{
{"canonical", "same_source_different_identity", 1},
{"canonical", "valid_other_host", 1},
{"canonical", "invalid", 1},
{"canonical", "absent", 7},
{"og", "same_source_different_identity", 1},
{"og", "valid_other_host", 1},
{"og", "invalid", 1},
{"og", "absent", 7},
{"jsonld", "mismatch", 1},
{"jsonld", "associated", 1},
} {
requireAggregateCounter(t, data, []string{"identity_evidence", tc.kind, tc.cause}, tc.want)
}
}
func TestCNBCChallengeMetricsAreGlobalPageSignalsNotRootScoped(t *testing.T) {
const body = "Synthetic editorial paragraph " + granularMetricCanary + ". "
text := strings.Repeat(body, 100)
pages := map[string]string{}
for i, marker := range []string{`<aside id="challengeGate">verification overlay</aside>`, `<div id="challengeGate">verification overlay</div>`} {
url := fmt.Sprintf("https://www.cnbc.com/2026/02/02/challenge-fixture-%d.html", i+1)
outside, inside := marker, ""
if i == 1 {
outside, inside = "", marker
}
pages[url] = `<link rel="canonical" href="` + url + `">` + outside + `<div data-module="ArticleBody"><p>` + text + `</p>` + inside + `</div>`
}
metrics := fetchMetricsForFixturePages(t, "cnbc_business", pages)
data := requireAnonymousAggregate(t, metrics, "www.cnbc.com/2026/02/02/", granularMetricCanary, "verification overlay")
if metrics.Attempted != 2 || metrics.HTTP.TwoXX != 2 || metrics.Root.Yes != 2 || metrics.Identity.Yes != 2 || metrics.Length.Large != 2 {
t.Fatal("CNBC challenge fixtures did not retain anonymous page/root/body counters")
}
// Challenges can cover the entire rendered page, including when the marker
// sits beside or inside the editorial root. Measure them as page-global;
// they are never a root-scoped paywall category.
requireAggregateCounter(t, data, []string{"blocking_evidence", "challenge", "global_page"}, 2)
requireNoAggregateCounter(t, data, []string{"blocking_evidence", "challenge", "article_root"})
requireNoAggregateCounter(t, data, []string{"blocking_evidence", "challenge", "outside_root"})
}
func TestCNBCBlockingCauseMetricsSeparateCategoryAndEditorialScope(t *testing.T) {
const longFixtureBody = "Synthetic editorial paragraph " + granularMetricCanary + ". "
body := strings.Repeat(longFixtureBody, 100)
type scenario struct {
category string
inside string
outside string
}
scenarios := []scenario{
{"paywall", `<div class="paywall">restricted</div>`, `<aside class="paywall">subscription prompt</aside>`},
{"partial", `<div data-content-state="partial"></div>`, `<aside data-content-state="partial"></aside>`},
{"truncated", `<div data-content-truncated="true"></div>`, `<aside data-content-truncated="true"></aside>`},
{"placeholder", `<div class="article-placeholder"></div>`, `<aside class="article-placeholder"></aside>`},
}
pages := map[string]string{}
wants := make(map[string]int)
index := 0
for _, tc := range scenarios {
for _, scoped := range []struct {
name, marker string
}{{"article_root", tc.inside}, {"outside_root", tc.outside}} {
index++
url := fmt.Sprintf("https://www.cnbc.com/2026/02/01/fixture-%02d.html", index)
inside, outside := "", ""
if scoped.name == "article_root" {
inside = scoped.marker
} else {
outside = scoped.marker
}
pages[url] = `<link rel="canonical" href="` + url + `"><aside>` + outside + `</aside><div data-module="ArticleBody"><p>` + body + `</p>` + inside + `</div>`
wants[tc.category+"."+scoped.name] = 1
}
}
for _, scoped := range []string{"article_root", "outside_root"} {
for _, category := range []string{"accessibility", "body_conflict"} {
index++
url := fmt.Sprintf("https://www.cnbc.com/2026/02/01/fixture-%02d.html", index)
metadata := map[string]any{"@type": "NewsArticle", "url": url}
if category == "accessibility" {
metadata["isAccessibleForFree"] = false
} else {
metadata["articleBody"] = "metadata body does not match the extracted fixture body"
}
json := jsonLD(t, metadata)
if scoped == "article_root" {
pages[url] = `<link rel="canonical" href="` + url + `"><div data-module="ArticleBody">` + json + `<p>` + body + `</p></div>`
} else {
pages[url] = `<link rel="canonical" href="` + url + `">` + json + `<div data-module="ArticleBody"><p>` + body + `</p></div>`
}
wants[category+"."+scoped] = 1
}
}
metrics := fetchMetricsForFixturePages(t, "cnbc_business", pages)
data := requireAnonymousAggregate(t, metrics, "www.cnbc.com/2026/02/01/", granularMetricCanary, "metadata body does not match", "article-placeholder", "subscription prompt")
if metrics.Attempted != 12 || metrics.HTTP.TwoXX != 12 || metrics.Root.Yes != 12 || metrics.Identity.Yes != 12 || metrics.Length.Large != 12 {
t.Fatal("CNBC fixture aggregate did not retain root, identity and long-body counts")
}
for name, count := range wants {
parts := strings.SplitN(name, ".", 2)
requireAggregateCounter(t, data, []string{"blocking_evidence", parts[0], parts[1]}, count)
}
}

View File

@ -0,0 +1,105 @@
package articlecontent
import (
"context"
"github.com/tradarr/backend/internal/scraper"
"io"
"net/http"
"strings"
"testing"
)
func TestAcceptedListingURLsUseHTTPSAndKeepListingIdentity(t *testing.T) {
for _, tc := range []struct{ source, listing, fetch string }{{"yahoo_finance", "http://finance.yahoo.com/m/fixture/story?story=1#fragment", "https://finance.yahoo.com/m/fixture/story?story=1"}, {"cnbc_business", "http://www.cnbc.com/business/story?story=1#fragment", "https://www.cnbc.com/business/story?story=1"}} {
t.Run(tc.source, func(t *testing.T) {
calls := 0
root := "caas-body"
if tc.source == "cnbc_business" {
root = "ArticleBody-articleBody"
}
client := &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
calls++
if r.URL.String() != tc.fetch {
t.Fatal("unexpected fetch identity")
}
body := `<link rel="canonical" href="` + tc.fetch + `"><div class="` + root + `"><p>Entire fixture editorial body.</p></div>`
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header), Request: r}, nil
})}
got, err := Enrich(context.Background(), client, tc.source, []scraper.Article{{URL: tc.listing, Title: "listing title"}})
if err != nil || calls != 1 || len(got) != 1 || got[0].URL != tc.listing || got[0].Title != "listing title" || got[0].PublishedAt != nil || scraper.ContentStatus(got[0]) != scraper.ContentComplete {
t.Fatal("accepted listing identity or nullable-date body lost")
}
})
}
}
func TestUnsafeListingURLsNeverFetchOrDisappear(t *testing.T) {
for _, url := range []string{"https://127.0.0.1/private", "https://finance.yahoo.com.evil.invalid/story", "https://user:secret@finance.yahoo.com/story", "https://finance.yahoo.com:443/story", "file:///private", "https://www.cnbc.com/story"} {
calls := 0
c := &http.Client{Transport: roundTrip(func(*http.Request) (*http.Response, error) { calls++; t.Fatal("unsafe fetch"); return nil, nil })}
got, err := Enrich(context.Background(), c, "yahoo_finance", []scraper.Article{{URL: url, Title: "preserved"}})
if err != nil || calls != 0 || len(got) != 1 || got[0].URL != url || scraper.ContentStatus(got[0]) != scraper.ContentUnavailable {
t.Fatal("unsafe listing lost or fetched")
}
}
}
func TestSameSourceRedirectRequiresObservedChainAndKeepsListing(t *testing.T) {
original := "https://finance.yahoo.com/m/story"
final := "https://finance.yahoo.com/news/story"
calls := 0
c := &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
calls++
if calls == 1 {
return &http.Response{StatusCode: 302, Body: io.NopCloser(strings.NewReader("")), Header: http.Header{"Location": []string{final}}, Request: r}, nil
}
body := `<link rel="canonical" href="` + final + `"><div class="caas-body"><p>Entire fixture editorial body.</p></div>`
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header), Request: r}, nil
})}
got, err := Enrich(context.Background(), c, "yahoo_finance", []scraper.Article{{URL: original, Title: "preserved"}})
if err != nil || calls != 2 || len(got) != 1 || got[0].URL != original || scraper.ContentStatus(got[0]) != scraper.ContentComplete {
t.Fatal("verified same-source redirect lost listing association")
}
}
func TestQueryIdentitiesAndUnobservedRedirectsCannotCrossAssociateBodies(t *testing.T) {
first := "https://finance.yahoo.com/news/story?id=1"
second := "https://finance.yahoo.com/news/story?id=2"
calls := 0
c := &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
calls++
body := `<link rel="canonical" href="` + first + `"><div class="caas-body"><p>Entire fixture body.</p></div>`
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header), Request: r}, nil
})}
got, err := Enrich(context.Background(), c, "yahoo_finance", []scraper.Article{{URL: first}, {URL: second}})
if err != nil || calls != 2 || scraper.ContentStatus(got[0]) != scraper.ContentComplete || scraper.ContentStatus(got[1]) != scraper.ContentUnavailable {
t.Fatal("semantic query identities were merged")
}
c.Transport = roundTrip(func(r *http.Request) (*http.Response, error) {
fake, _ := http.NewRequest("GET", first, nil)
body := `<link rel="canonical" href="` + first + `"><div class="caas-body"><p>Entire fixture body.</p></div>`
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header), Request: fake}, nil
})
got, err = Enrich(context.Background(), c, "yahoo_finance", []scraper.Article{{URL: second}})
if err != nil || scraper.ContentStatus(got[0]) != scraper.ContentUnavailable {
t.Fatal("unobserved redirect accepted")
}
}
func TestRedirectUpgradeNeverSendsHTTPAndNullableDateDoesNotInvalidateBody(t *testing.T) {
first := "https://www.cnbc.com/business/original"
final := "https://www.cnbc.com/business/final"
calls := 0
c := &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
calls++
if r.URL.Scheme != "https" {
t.Fatal("plaintext request")
}
if calls == 1 {
return &http.Response{StatusCode: 302, Body: io.NopCloser(strings.NewReader("")), Header: http.Header{"Location": []string{strings.Replace(final, "https://", "http://", 1)}}, Request: r}, nil
}
body := `<link rel="canonical" href="` + final + `"><meta property="article:published_time" content="2026-01-02T03:04:05Z"><meta property="article:published_time" content="2026-01-03T03:04:05Z"><div class="ArticleBody-articleBody"><p>Entire fixture body.</p></div>`
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header), Request: r}, nil
})}
got, err := Enrich(context.Background(), c, "cnbc_business", []scraper.Article{{URL: first}})
if err != nil || calls != 2 || got[0].URL != first || got[0].PublishedAt != nil || scraper.ContentStatus(got[0]) != scraper.ContentComplete {
t.Fatal("redirect or independent date contract broken")
}
}

View File

@ -0,0 +1,42 @@
package articlecontent
import (
"context"
"io"
"net/http"
"strings"
"testing"
"github.com/tradarr/backend/internal/scraper"
)
func TestRedirectToLiteralPrivateOrReservedAddressNeverReachesTransport(t *testing.T) {
for _, target := range []string{
"https://127.0.0.1/private",
"https://[::1]/private",
"https://10.0.0.1/private",
"https://169.254.1.1/private",
"https://240.0.0.1/private",
"https://finance.yahoo.com.evil.invalid/private",
} {
t.Run("blocked_redirect", func(t *testing.T) {
calls := 0
client := &http.Client{Transport: roundTrip(func(r *http.Request) (*http.Response, error) {
calls++
if calls != 1 || r.URL.Host != "finance.yahoo.com" {
t.Fatal("redirect target unexpectedly reached the transport")
}
return &http.Response{
StatusCode: http.StatusFound,
Header: http.Header{"Location": []string{target}},
Body: io.NopCloser(strings.NewReader("")),
Request: r,
}, nil
})}
got, err := Enrich(context.Background(), client, "yahoo_finance", []scraper.Article{{URL: "https://finance.yahoo.com/news/fixture.html"}})
if err != nil || calls != 1 || len(got) != 1 || got[0].Content != "" || scraper.ContentStatus(got[0]) != scraper.ContentUnavailable {
t.Fatal("redirect to a forbidden IP or host was followed")
}
})
}
}

View File

@ -8,6 +8,7 @@ import (
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
@ -15,8 +16,9 @@ import (
)
type Bloomberg struct {
scraperURL string
client *http.Client
scraperURL string
client *http.Client
diagnostics io.Writer
}
func New(scraperURL string) *Bloomberg {
@ -29,6 +31,15 @@ func New(scraperURL string) *Bloomberg {
}
}
// NewWithClient uses the same production RPC DTOs and validation with injected I/O.
func NewWithClient(scraperURL string, client *http.Client, diagnostics io.Writer) *Bloomberg {
b := New(scraperURL)
if client != nil {
b.client = client
}
b.diagnostics = diagnostics
return b
}
func (b *Bloomberg) Name() string { return "bloomberg" }
type scraperRequest struct {
@ -99,7 +110,11 @@ func (b *Bloomberg) ScrapeWithCredentials(ctx context.Context, username, passwor
Symbols: syms,
})
}
fmt.Printf("bloomberg: %d articles fetched\n", len(articles))
writer := b.diagnostics
if writer == nil {
writer = os.Stdout
}
fmt.Fprintf(writer, "bloomberg: %d articles fetched\n", len(articles))
return articles, nil
}

View File

@ -30,7 +30,8 @@ func (b *Bloomberg) EnrichWithCredentials(ctx context.Context, username, passwor
Username string `json:"username"`
Password string `json:"password"`
URLs []string `json:"urls"`
}{username, password, urls})
Measure bool `json:"measure_fetches,omitempty"`
}{username, password, urls, scraper.FetchMetricsEnabled(ctx)})
req, err := http.NewRequestWithContext(ctx, http.MethodPost, b.scraperURL+"/bloomberg/enrich", bytes.NewReader(payload))
if err != nil {
return nil, errors.New("bloomberg: enrichment request failed")
@ -53,7 +54,8 @@ func (b *Bloomberg) EnrichWithCredentials(ctx context.Context, username, passwor
return nil, errors.New("bloomberg: enrichment response too large")
}
var result struct {
Articles []struct {
FetchMetrics *scraper.FetchMetrics `json:"fetch_metrics"`
Articles []struct {
ContentState string `json:"content_state"`
URL string `json:"url"`
Content string `json:"content"`
@ -89,5 +91,8 @@ func (b *Bloomberg) EnrichWithCredentials(ctx context.Context, username, passwor
}
}
}
if result.FetchMetrics != nil {
scraper.MergeFetchMetrics(ctx, *result.FetchMetrics, len(out))
}
return out, nil
}

View File

@ -0,0 +1,65 @@
package bloomberg
import (
"context"
"encoding/json"
"github.com/tradarr/backend/internal/scraper"
"io"
"net/http"
"strings"
"testing"
)
func TestOnlyAggregatedPublisherMetricsCrossTheEnrichmentRPC(t *testing.T) {
for _, supported := range []bool{true, false} {
t.Run(map[bool]string{true: "measured", false: "old_service_unsupported"}[supported], func(t *testing.T) {
remoteCtx, remote := scraper.WithFetchMetrics(context.Background())
scraper.EnableFetchMetrics(remoteCtx)
scraper.RecordFetch(remoteCtx, scraper.FetchObservation{HTTPStatus: 403, State: scraper.ContentUnavailable})
aggregate := remote.Finish()
b := New("http://fixture.invalid")
b.client = &http.Client{Transport: dateTransport(func(r *http.Request) (*http.Response, error) {
var req struct {
Measure bool `json:"measure_fetches"`
}
if json.NewDecoder(r.Body).Decode(&req) != nil || !req.Measure {
t.Fatal("bench did not opt in")
}
payload := map[string]any{"articles": []map[string]any{{"url": "https://www.bloomberg.com/news/articles/fixture", "content": "", "content_state": "unavailable"}}}
if supported {
payload["fetch_metrics"] = aggregate
}
data, _ := json.Marshal(payload)
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(string(data))), Header: make(http.Header)}, nil
})}
ctx, m := scraper.WithFetchMetrics(context.Background())
_, err := b.EnrichWithCredentials(ctx, "synthetic-fixture", "synthetic-fixture", []scraper.Article{{URL: "https://www.bloomberg.com/news/articles/fixture"}})
if err != nil {
t.Fatal("fixture RPC failed")
}
c := m.Finish()
if c.Supported != supported {
t.Fatal("missing metrics treated as measured zero")
}
if supported && (c.HTTP.FourXX != 1 || c.HTTP.TwoXX != 0 || c.Attempted != 1) {
t.Fatal("RPC HTTP 200 confused with publisher 403")
}
})
}
}
func TestLoginOutcomeAggregateRemainsNotFetched(t *testing.T) {
for _, login := range []string{"unconfirmed", "refused"} {
b := NewWithClient("http://fixture.invalid", &http.Client{Transport: dateTransport(func(r *http.Request) (*http.Response, error) {
payload := map[string]any{"fetch_metrics": scraper.FetchMetrics{SchemaVersion: 1, Supported: true, Login: login}, "articles": []map[string]any{{"url": "https://www.bloomberg.com/news/articles/fixture", "content": "", "content_state": "unavailable"}}}
raw, _ := json.Marshal(payload)
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(string(raw)))}, nil
})}, io.Discard)
ctx, m := scraper.WithFetchMetrics(context.Background())
got, err := b.EnrichWithCredentials(ctx, "offline-fixture", "offline-fixture", []scraper.Article{{URL: "https://www.bloomberg.com/news/articles/fixture"}})
c := m.Finish()
if err != nil || len(got) != 1 || got[0].ContentState != scraper.ContentUnavailable || c.Login != login || c.Attempted != 0 || c.HTTP.Network != 0 || c.HTTP.FourXX != 0 {
t.Fatal("login gate invented article fetches or lost category")
}
}
}

View File

@ -0,0 +1,103 @@
package bloomberg
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/tradarr/backend/internal/scraper"
)
const bloombergFixtureURL = "https://www.bloomberg.com/news/articles/fixture"
func TestIngestionPipelineBloombergListThenAuthenticatedEnrichmentPort(t *testing.T) {
shortSymptom := strings.Repeat("A", 320) + "\n\n" + strings.Repeat("B", 339) // 661 synthetic characters, two paragraphs.
for _, tc := range []struct {
name, content, state, date string
wantComplete, wantDate bool
badAssociation bool
}{
{name: "full editorial body and reliable date", content: "Synthetic initial paragraph.\n\nFinal editorial paragraph.", state: scraper.ContentComplete, date: "2026-01-02T03:04:05Z", wantComplete: true, wantDate: true},
{name: "list metadata without enriched body", content: "", state: scraper.ContentUnavailable},
{name: "partial paywall body", content: "Synthetic initial paragraph.", state: scraper.ContentIncomplete, date: "2026-01-02T03:04:05Z", wantDate: true},
{name: "challenge body", content: "Synthetic challenge placeholder.", state: scraper.ContentIncomplete, date: "2026-01-02T03:04:05Z", wantDate: true},
{name: "661-character body with nullable date", content: shortSymptom, state: scraper.ContentComplete, wantComplete: true},
{name: "wrong article association", content: "Synthetic foreign article body.", state: scraper.ContentComplete, date: "2026-01-02T03:04:05Z", wantDate: true, badAssociation: true},
} {
t.Run(tc.name, func(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/bloomberg/scrape":
var credentials scraperRequest
if r.Method != http.MethodPost || json.NewDecoder(r.Body).Decode(&credentials) != nil || credentials.Username != "fixture-user" || credentials.Password != "fixture-password" {
t.Error("Bloomberg list collector did not receive fixture authentication request")
w.WriteHeader(http.StatusBadRequest)
return
}
_ = json.NewEncoder(w).Encode(map[string]any{"articles": []any{map[string]any{"title": "Synthetic fixture headline", "url": bloombergFixtureURL}}})
case "/bloomberg/enrich":
var request struct {
Username string `json:"username"`
Password string `json:"password"`
URLs []string `json:"urls"`
}
if r.Method != http.MethodPost || json.NewDecoder(r.Body).Decode(&request) != nil || request.Username != "fixture-user" || request.Password != "fixture-password" || len(request.URLs) != 1 || request.URLs[0] != bloombergFixtureURL {
t.Error("Bloomberg enricher was not given the exact article selected by the list collector")
w.WriteHeader(http.StatusBadRequest)
return
}
articleURL := bloombergFixtureURL
if tc.badAssociation {
articleURL += "-other"
}
_ = json.NewEncoder(w).Encode(map[string]any{"articles": []any{map[string]any{
"url": articleURL, "content": tc.content, "content_state": tc.state,
"content_truncated": false, "published_at": tc.date,
}}})
default:
t.Error("unexpected Bloomberg fixture route")
http.Error(w, "fixture route unavailable", http.StatusNotFound)
}
}))
defer server.Close()
feed := New(server.URL)
listed, err := feed.ScrapeWithCredentials(context.Background(), "fixture-user", "fixture-password", nil)
if err != nil || len(listed) != 1 {
t.Fatal("Bloomberg fixture collector did not return the single listed article")
}
if listed[0].URL != bloombergFixtureURL || scraper.ContentStatus(listed[0]) == scraper.ContentComplete {
t.Fatal("Bloomberg list metadata was counted as a full body")
}
got, err := feed.EnrichWithCredentials(context.Background(), "fixture-user", "fixture-password", listed)
if tc.badAssociation {
if err == nil || len(got) != 0 {
t.Fatal("Bloomberg accepted enrichment for an article outside the collected list")
}
return
}
if err != nil || len(got) != 1 || got[0].URL != listed[0].URL {
t.Fatal("Bloomberg authenticated enrichment failed or detached the listed article")
}
if (scraper.ContentStatus(got[0]) == scraper.ContentComplete) != tc.wantComplete {
t.Fatal("Bloomberg full-body classification mismatch")
}
if (got[0].PublishedAt != nil) != tc.wantDate {
t.Fatal("Bloomberg publication-date availability mismatch")
}
if tc.wantComplete && tc.name != "661-character body with nullable date" && !strings.Contains(got[0].Content, "Final editorial paragraph.") {
t.Fatal("Bloomberg final editorial text was not collected")
}
if tc.name == "661-character body with nullable date" && len(got[0].Content) != 661 {
t.Fatal("Bloomberg synthetic full-body fixture was clipped")
}
if tc.wantDate && !got[0].PublishedAt.Equal(time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)) {
t.Fatal("Bloomberg did not associate the expected publication date")
}
})
}
}

View File

@ -0,0 +1,77 @@
package cnbcbusiness
import (
"context"
"io"
"net/http"
"strings"
"testing"
"github.com/tradarr/backend/internal/scraper"
)
type cnbcBlockMarkerScopeTransport struct{ pages map[string]string }
func (f cnbcBlockMarkerScopeTransport) RoundTrip(r *http.Request) (*http.Response, error) {
body, ok := f.pages[r.URL.String()]
if !ok {
return nil, io.ErrUnexpectedEOF
}
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: r}, nil
}
func TestCNBCBlockMarkerMustBelongToEditorialRoot(t *testing.T) {
urls := []string{
"https://www.cnbc.com/2026/01/02/fixture-outside.html",
"https://www.cnbc.com/2026/01/02/fixture-inside.html",
"https://www.cnbc.com/2026/01/02/fixture-unrelated.html",
}
body := strings.Repeat("Synthetic complete editorial text. ", 90)
pages := map[string]string{}
for i, articleURL := range urls {
marker := ""
switch i {
case 0:
// A detached site chrome/paywall block has no association with the
// article body and must not invalidate that body's completeness.
marker = `<aside class="paywall"><p>Subscription prompt fixture.</p></aside>`
case 1:
marker = `<div class="paywall"><p>Restricted article fixture.</p></div>`
}
rootContent := `<p>` + body + `</p>`
if i == 1 {
rootContent += marker
marker = ""
}
pages[articleURL] = `<link rel="canonical" href="` + articleURL + `"><div data-module="ArticleBody">` + rootContent + `</div>` + marker
}
feed := `<rss><channel>`
for i, articleURL := range urls {
feed += `<item><title>Synthetic fixture ` + string(rune('A'+i)) + `</title><link>` + articleURL + `</link><description>RSS teaser only.</description></item>`
}
feed += `</channel></rss>`
pages[feedURL] = feed
c := NewWithClient(&http.Client{Transport: cnbcBlockMarkerScopeTransport{pages: pages}}, io.Discard)
listed, err := c.Scrape(context.Background(), nil)
if err != nil || len(listed) != 3 {
t.Fatal("CNBC fixture collector did not return its three listed articles")
}
ctx, meter := scraper.WithFetchMetrics(context.Background())
got, err := c.Enrich(ctx, listed)
metrics := meter.Finish()
if err != nil || len(got) != 3 {
t.Fatal("CNBC fixture article enrichment failed")
}
if scraper.ContentStatus(got[0]) != scraper.ContentComplete || len(got[0].Content) < 2000 {
t.Errorf("CNBC detached marker invalidated body: outside_root_complete=%t outside_root_body_bucket_large=%t", scraper.ContentStatus(got[0]) == scraper.ContentComplete, len(got[0].Content) >= 2000)
}
if scraper.ContentStatus(got[1]) != scraper.ContentIncomplete {
t.Errorf("CNBC marker inside root classification incomplete=%t", scraper.ContentStatus(got[1]) == scraper.ContentIncomplete)
}
if scraper.ContentStatus(got[2]) != scraper.ContentComplete || len(got[2].Content) < 2000 {
t.Errorf("CNBC unrelated chrome invalidated body: no_marker_complete=%t no_marker_body_bucket_large=%t", scraper.ContentStatus(got[2]) == scraper.ContentComplete, len(got[2].Content) >= 2000)
}
if metrics.HTTP.TwoXX != 3 || metrics.Root.Yes != 3 || metrics.Identity.Yes != 3 || metrics.Length.Large != 3 || metrics.Blocking.Yes != 1 || metrics.Blocking.No != 2 {
t.Errorf("CNBC aggregate mismatch: http_2xx=%d root_yes=%d identity_yes=%d body_over_2000=%d blocking_yes=%d blocking_no=%d", metrics.HTTP.TwoXX, metrics.Root.Yes, metrics.Identity.Yes, metrics.Length.Large, metrics.Blocking.Yes, metrics.Blocking.No)
}
}

View File

@ -15,16 +15,34 @@ import (
"time"
"github.com/tradarr/backend/internal/scraper"
"github.com/tradarr/backend/internal/scraper/sourcehttp"
"golang.org/x/net/html"
)
const feedURL = "https://www.cnbc.com/id/10001147/device/rss/rss.html"
const maxFeedBytes = 2 * 1024 * 1024
type CNBCBusiness struct{ client *http.Client }
type CNBCBusiness struct {
client *http.Client
diagnostics io.Writer
}
func New() *CNBCBusiness {
return &CNBCBusiness{client: &http.Client{Timeout: 15 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}
return &CNBCBusiness{client: &http.Client{Transport: sourcehttp.NewTransport(nil, nil), Timeout: 15 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}
}
// NewWithClient preserves the production collector/enricher with injected I/O.
func NewWithClient(client *http.Client, diagnostics io.Writer) *CNBCBusiness {
c := New()
if client != nil {
injected := *client
// RSS discovery retains its production no-redirect policy. Article
// enrichment applies its own bounded same-source redirect validation.
injected.CheckRedirect = c.client.CheckRedirect
c.client = &injected
}
c.diagnostics = diagnostics
return c
}
func (*CNBCBusiness) Name() string { return "cnbc_business" }
@ -50,7 +68,11 @@ func (c *CNBCBusiness) Scrape(ctx context.Context, _ []string) (articles []scrap
if resultErr != nil {
outcome = "failed"
}
log.Printf("source=cnbc_business rss status=%d articles=%d outcome=%s cause=%s", status, len(articles), outcome, cause)
logger := log.Default()
if c.diagnostics != nil {
logger = log.New(c.diagnostics, "", 0)
}
logger.Printf("source=cnbc_business rss status=%d articles=%d outcome=%s cause=%s", status, len(articles), outcome, cause)
}()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, feedURL, nil)
if err != nil {

View File

@ -0,0 +1,14 @@
package cnbcbusiness
import (
"net/http"
"testing"
)
func TestCNBCProductionConstructorUsesExplicitDNSGuardedTransport(t *testing.T) {
client := New().client
transport, ok := client.Transport.(*http.Transport)
if !ok || transport.DialContext == nil {
t.Fatal("CNBC production constructor has no explicit DNS-guarded dial transport; standard transport can connect after a private DNS answer")
}
}

View File

@ -0,0 +1,116 @@
package cnbcbusiness
import (
"context"
"fmt"
"io"
"net/http"
"strings"
"testing"
"time"
"github.com/tradarr/backend/internal/scraper"
)
const cnbcFixtureURL = "https://www.cnbc.com/2026/01/02/fixture.html"
type cnbcIngestionTransport struct {
t *testing.T
html string
articleURL string
date bool
rssOnly bool
}
func (f cnbcIngestionTransport) RoundTrip(r *http.Request) (*http.Response, error) {
articleURL := f.articleURL
if articleURL == "" {
articleURL = cnbcFixtureURL
}
var body string
if r.URL.String() == feedURL {
pubDate := ""
if f.date {
pubDate = "<pubDate>Fri, 02 Jan 2026 03:04:05 +0000</pubDate>"
}
body = `<rss><channel><item><title>Synthetic fixture headline</title><link>` + articleURL + `</link><description><![CDATA[<p>Synthetic RSS teaser only.</p>]]></description>` + pubDate + `</item></channel></rss>`
} else if r.URL.String() == articleURL {
if f.rssOnly {
return &http.Response{StatusCode: 503, Header: make(http.Header), Body: io.NopCloser(strings.NewReader("fixture unavailable")), Request: r}, nil
}
body = f.html
} else {
f.t.Errorf("collector/enricher requested an unexpected fixture route")
return nil, fmt.Errorf("unexpected fixture route")
}
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: r}, nil
}
func TestIngestionPipelineCNBCRSSListThenArticleEnrichment(t *testing.T) {
raw := `<link rel="canonical" href="` + cnbcFixtureURL + `"><meta property="article:published_time" content="2026-01-02T03:04:05Z"><div data-module="ArticleBody"><div class="group"><h2>Synthetic heading.</h2><p>Synthetic initial paragraph.</p><p>Final editorial paragraph.</p></div></div>`
partial := raw + `<div data-content-state="partial"></div>`
challenge := raw + `<div id="px-captcha">Synthetic challenge marker</div>`
wrongArticle := strings.ReplaceAll(raw, cnbcFixtureURL, "https://www.cnbc.com/2026/01/02/other.html")
noDate := strings.Replace(raw, `<meta property="article:published_time" content="2026-01-02T03:04:05Z">`, "", 1)
for _, tc := range []struct {
name, html string
date, rssOnly, wantComplete, wantDate bool
}{
{name: "complete body and reliable date", html: raw, date: true, wantComplete: true, wantDate: true},
{name: "RSS description alone", html: "", rssOnly: true},
{name: "partial body", html: partial, date: true, wantDate: true},
{name: "challenge", html: challenge, date: true, wantDate: true},
{name: "complete body with nullable date", html: noDate, wantComplete: true},
{name: "wrong article association", html: wrongArticle, date: true, wantDate: true},
} {
t.Run(tc.name, func(t *testing.T) {
c := &CNBCBusiness{client: &http.Client{Transport: cnbcIngestionTransport{t: t, html: tc.html, date: tc.date, rssOnly: tc.rssOnly}}}
listed, err := c.Scrape(context.Background(), nil)
if err != nil || len(listed) != 1 {
t.Fatal("CNBC fixture collector did not return the single listed article")
}
if listed[0].URL != cnbcFixtureURL || listed[0].Content != "Synthetic RSS teaser only." || scraper.ContentStatus(listed[0]) == scraper.ContentComplete {
t.Fatal("RSS teaser was treated as the listed article body")
}
got, err := c.Enrich(context.Background(), listed)
if err != nil || len(got) != 1 {
t.Fatal("CNBC fixture article enrichment failed")
}
if got[0].URL != listed[0].URL || got[0].Title != listed[0].Title {
t.Fatal("CNBC enrichment changed or detached the listed article")
}
if (scraper.ContentStatus(got[0]) == scraper.ContentComplete) != tc.wantComplete {
t.Fatal("CNBC full-body classification mismatch")
}
if tc.wantComplete && !strings.Contains(got[0].Content, "Final editorial paragraph.") {
t.Fatal("CNBC final editorial text was not collected")
}
if (got[0].PublishedAt != nil) != tc.wantDate {
t.Fatal("CNBC publication-date availability mismatch")
}
if tc.wantDate && !got[0].PublishedAt.Equal(time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)) {
t.Fatal("CNBC did not associate the expected publication date")
}
if tc.name == "wrong article association" && (got[0].Content != "" || scraper.ContentStatus(got[0]) != scraper.ContentUnavailable) {
t.Fatal("CNBC accepted body content for another article")
}
})
}
}
func TestCNBCAcceptedRSSLinkPathIsNotDroppedByEnricher(t *testing.T) {
// The RSS collector accepts this same-source .html link, but the enrichment
// port currently permits only date-shaped paths.
articleURL := "https://www.cnbc.com/business/synthetic-story.html"
html := `<link rel="canonical" href="` + articleURL + `"><div data-module="ArticleBody"><h2>Synthetic heading.</h2><p>Final editorial paragraph.</p></div>`
c := &CNBCBusiness{client: &http.Client{Transport: cnbcIngestionTransport{t: t, html: html, articleURL: articleURL}}}
listed, err := c.Scrape(context.Background(), nil)
if err != nil || len(listed) != 1 {
t.Fatal("CNBC collector dropped an accepted RSS article")
}
got, err := c.Enrich(context.Background(), listed)
if err != nil || len(got) != 1 || scraper.ContentStatus(got[0]) != scraper.ContentComplete || !strings.Contains(got[0].Content, "Final editorial paragraph.") {
t.Fatal("CNBC enricher discarded a same-source RSS article URL with available full content")
}
}

View File

@ -0,0 +1,293 @@
package scraper
import (
"context"
"sync"
)
type EvidenceFlag uint8
const (
NotEvaluated EvidenceFlag = iota
ObservedYes
ObservedNo
)
type IdentityFlag uint8
const (
IdentityNotEvaluated IdentityFlag = iota
IdentityYes
IdentityNo
IdentityMismatch
)
// FetchObservation is transient and cannot contain identifiers, text or errors.
// It is immediately reduced into counters, never stored or logged individually.
type MetadataIdentityCounts struct {
Associated int `json:"associated"`
SameSourceDifferentIdentity int `json:"same_source_different_identity"`
ValidOtherHost int `json:"valid_other_host"`
Invalid int `json:"invalid"`
Absent int `json:"absent"`
}
type JSONLDIdentityCounts struct {
Mismatch int `json:"mismatch"`
Associated int `json:"associated"`
}
type IdentityEvidenceCounts struct {
Canonical MetadataIdentityCounts `json:"canonical"`
OG MetadataIdentityCounts `json:"og"`
JSONLD JSONLDIdentityCounts `json:"jsonld"`
}
type GlobalEvidenceCounts struct {
GlobalPage int `json:"global_page"`
}
type ScopedEvidenceCounts struct {
ArticleRoot int `json:"article_root"`
OutsideRoot int `json:"outside_root"`
}
type BlockingEvidenceCounts struct {
Paywall ScopedEvidenceCounts `json:"paywall"`
Challenge GlobalEvidenceCounts `json:"challenge"`
Partial ScopedEvidenceCounts `json:"partial"`
Truncated ScopedEvidenceCounts `json:"truncated"`
Placeholder ScopedEvidenceCounts `json:"placeholder"`
Accessibility ScopedEvidenceCounts `json:"accessibility"`
BodyConflict ScopedEvidenceCounts `json:"body_conflict"`
}
func granularCounters(i *IdentityEvidenceCounts, b *BlockingEvidenceCounts) []*int {
return []*int{&i.Canonical.Associated, &i.Canonical.SameSourceDifferentIdentity, &i.Canonical.ValidOtherHost, &i.Canonical.Invalid, &i.Canonical.Absent,
&i.OG.Associated, &i.OG.SameSourceDifferentIdentity, &i.OG.ValidOtherHost, &i.OG.Invalid, &i.OG.Absent, &i.JSONLD.Mismatch, &i.JSONLD.Associated,
&b.Paywall.ArticleRoot, &b.Paywall.OutsideRoot, &b.Challenge.GlobalPage, &b.Partial.ArticleRoot, &b.Partial.OutsideRoot, &b.Truncated.ArticleRoot, &b.Truncated.OutsideRoot, &b.Placeholder.ArticleRoot, &b.Placeholder.OutsideRoot, &b.Accessibility.ArticleRoot, &b.Accessibility.OutsideRoot, &b.BodyConflict.ArticleRoot, &b.BodyConflict.OutsideRoot}
}
type FetchObservation struct {
CandidateBodySupported bool
CandidateBodyLength int
GranularSupported bool
IdentityEvidence IdentityEvidenceCounts
BlockingEvidence BlockingEvidenceCounts
HTTPStatus int
Network bool
Root EvidenceFlag
Identity IdentityFlag
Blocking EvidenceFlag
Length int
State string
}
type HTTPCounts struct {
TwoXX int `json:"2xx"`
ThreeXX int `json:"3xx"`
FourXX int `json:"4xx"`
FiveXX int `json:"5xx"`
Network int `json:"network"`
}
type EvidenceCounts struct {
Yes int `json:"yes"`
No int `json:"no"`
NotEvaluated int `json:"not_evaluated"`
}
type IdentityCounts struct {
Yes int `json:"yes"`
No int `json:"no"`
Mismatch int `json:"mismatch"`
NotEvaluated int `json:"not_evaluated"`
}
type LengthCounts struct {
Zero int `json:"0"`
Small int `json:"1-500"`
Medium int `json:"501-2000"`
Large int `json:">2000"`
}
type FetchContentCounts struct {
Complete int `json:"complete"`
Incomplete int `json:"incomplete"`
Unavailable int `json:"unavailable"`
}
type FetchMetrics struct {
CandidateBodySupported bool `json:"candidate_body_supported"`
CandidateLength LengthCounts `json:"candidate_body_characters"`
GranularSupported bool `json:"granular_supported"`
IdentityEvidence IdentityEvidenceCounts `json:"identity_evidence"`
BlockingEvidence BlockingEvidenceCounts `json:"blocking_evidence"`
Login string `json:"login,omitempty"`
SchemaVersion int `json:"schema_version"`
Supported bool `json:"supported"`
Attempted int `json:"attempted"`
HTTP HTTPCounts `json:"http"`
Root EvidenceCounts `json:"editorial_root"`
Identity IdentityCounts `json:"identity"`
Blocking EvidenceCounts `json:"blocking_marker"`
Length LengthCounts `json:"extracted_characters"`
Content FetchContentCounts `json:"completeness"`
}
type FetchMeter struct {
mu sync.Mutex
closed bool
counts FetchMetrics
}
type fetchMetricsKey struct{}
func WithFetchMetrics(ctx context.Context) (context.Context, *FetchMeter) {
m := &FetchMeter{counts: FetchMetrics{SchemaVersion: 1}}
return context.WithValue(ctx, fetchMetricsKey{}, m), m
}
func fetchMeter(ctx context.Context) *FetchMeter {
m, _ := ctx.Value(fetchMetricsKey{}).(*FetchMeter)
return m
}
func FetchMetricsEnabled(ctx context.Context) bool { return fetchMeter(ctx) != nil }
func EnableFetchMetrics(ctx context.Context) {
if m := fetchMeter(ctx); m != nil {
m.mu.Lock()
defer m.mu.Unlock()
if !m.closed {
m.counts.Supported = true
}
}
}
func addEvidence(c *EvidenceCounts, v EvidenceFlag) {
switch v {
case ObservedYes:
c.Yes++
case ObservedNo:
c.No++
default:
c.NotEvaluated++
}
}
func addLength(c *LengthCounts, n int) {
switch {
case n <= 0:
c.Zero++
case n <= 500:
c.Small++
case n <= 2000:
c.Medium++
default:
c.Large++
}
}
func RecordFetch(ctx context.Context, o FetchObservation) {
m := fetchMeter(ctx)
if m == nil {
return
}
m.mu.Lock()
defer m.mu.Unlock()
if m.closed {
return
}
c := &m.counts
c.Supported = true
c.Attempted++
if o.GranularSupported {
c.GranularSupported = true
dst := granularCounters(&c.IdentityEvidence, &c.BlockingEvidence)
for n, v := range granularCounters(&o.IdentityEvidence, &o.BlockingEvidence) {
if *v > 0 {
*dst[n]++
}
}
}
switch {
case o.Network:
c.HTTP.Network++
case o.HTTPStatus >= 200 && o.HTTPStatus < 300:
c.HTTP.TwoXX++
case o.HTTPStatus >= 300 && o.HTTPStatus < 400:
c.HTTP.ThreeXX++
case o.HTTPStatus >= 400 && o.HTTPStatus < 500:
c.HTTP.FourXX++
case o.HTTPStatus >= 500 && o.HTTPStatus < 600:
c.HTTP.FiveXX++
default:
c.HTTP.Network++
}
addEvidence(&c.Root, o.Root)
addEvidence(&c.Blocking, o.Blocking)
switch o.Identity {
case IdentityYes:
c.Identity.Yes++
case IdentityNo:
c.Identity.No++
case IdentityMismatch:
c.Identity.Mismatch++
default:
c.Identity.NotEvaluated++
}
addLength(&c.Length, o.Length)
if o.CandidateBodySupported {
c.CandidateBodySupported = true
addLength(&c.CandidateLength, o.CandidateBodyLength)
}
switch o.State {
case ContentComplete:
c.Content.Complete++
case ContentIncomplete:
c.Content.Incomplete++
default:
c.Content.Unavailable++
}
}
func (m *FetchMeter) Finish() FetchMetrics {
m.mu.Lock()
defer m.mu.Unlock()
m.closed = true
return m.counts
}
// MergeFetchMetrics accepts only a complete, bounded aggregate from the scraper
// RPC. Missing/old RPC metrics remain unsupported, never fabricated zero fetches.
func MergeFetchMetrics(ctx context.Context, c FetchMetrics, maximum int) bool {
if c.SchemaVersion != 1 || !c.Supported || c.Attempted < 0 || c.Attempted > maximum {
return false
}
groups := [][]int{{c.HTTP.TwoXX, c.HTTP.ThreeXX, c.HTTP.FourXX, c.HTTP.FiveXX, c.HTTP.Network}, {c.Root.Yes, c.Root.No, c.Root.NotEvaluated}, {c.Identity.Yes, c.Identity.No, c.Identity.Mismatch, c.Identity.NotEvaluated}, {c.Blocking.Yes, c.Blocking.No, c.Blocking.NotEvaluated}, {c.Length.Zero, c.Length.Small, c.Length.Medium, c.Length.Large}, {c.Content.Complete, c.Content.Incomplete, c.Content.Unavailable}}
for _, g := range groups {
sum := 0
for _, n := range g {
if n < 0 || n > maximum {
return false
}
sum += n
}
if sum != c.Attempted {
return false
}
}
candidateSum := 0
for _, n := range []int{c.CandidateLength.Zero, c.CandidateLength.Small, c.CandidateLength.Medium, c.CandidateLength.Large} {
if n < 0 || n > c.Attempted {
return false
}
candidateSum += n
}
if (c.CandidateBodySupported && candidateSum != c.Attempted) || (!c.CandidateBodySupported && candidateSum != 0) {
return false
}
for _, n := range granularCounters(&c.IdentityEvidence, &c.BlockingEvidence) {
if *n < 0 || *n > c.Attempted || (!c.GranularSupported && *n != 0) {
return false
}
}
switch c.Login {
case "", "confirmed", "unconfirmed", "refused":
default:
return false
}
m := fetchMeter(ctx)
if m == nil {
return false
}
m.mu.Lock()
defer m.mu.Unlock()
if m.closed || m.counts.Attempted != 0 {
return false
}
m.counts = c
return true
}

View File

@ -0,0 +1,106 @@
package scraper
import (
"context"
"encoding/json"
"strings"
"testing"
)
func TestFetchMetricsContainOnlyAggregatesAndKnownBuckets(t *testing.T) {
ctx, m := WithFetchMetrics(context.Background())
EnableFetchMetrics(ctx)
RecordFetch(ctx, FetchObservation{HTTPStatus: 200, Root: ObservedYes, Identity: IdentityYes, Blocking: ObservedNo, Length: 501, State: ContentComplete})
RecordFetch(ctx, FetchObservation{Network: true, State: ContentUnavailable})
got := m.Finish()
if !got.Supported || got.Attempted != 2 || got.HTTP.TwoXX != 1 || got.HTTP.Network != 1 || got.Root.NotEvaluated != 1 || got.Length.Medium != 1 || got.Length.Zero != 1 {
t.Fatal("invalid aggregation")
}
b, _ := json.Marshal(got)
for _, s := range []string{"url", "title", `"body"`, "cookie", "secret", "error"} {
if strings.Contains(string(b), s) {
t.Fatal("unsafe diagnostic field")
}
}
RecordFetch(ctx, FetchObservation{HTTPStatus: 403})
if m.Finish().Attempted != 2 {
t.Fatal("late observation changed sealed snapshot")
}
}
func TestRPCMetricsAreBoundedAndInconsistentAggregatesRemainUnsupported(t *testing.T) {
ctx, m := WithFetchMetrics(context.Background())
EnableFetchMetrics(ctx)
RecordFetch(ctx, FetchObservation{HTTPStatus: 403, State: ContentUnavailable})
valid := m.Finish()
for _, mutate := range []func(*FetchMetrics){func(c *FetchMetrics) { c.Attempted = 5 }, func(c *FetchMetrics) { c.Root.Yes++ }, func(c *FetchMetrics) { c.HTTP.FourXX = -1 }, func(c *FetchMetrics) { c.SchemaVersion = 99 }} {
c := valid
mutate(&c)
ctx, m := WithFetchMetrics(context.Background())
if MergeFetchMetrics(ctx, c, 3) || m.Finish().Supported {
t.Fatal("invalid RPC metrics accepted")
}
}
ctx, m = WithFetchMetrics(context.Background())
if !MergeFetchMetrics(ctx, valid, 3) || m.Finish().HTTP.FourXX != 1 {
t.Fatal("valid aggregate rejected")
}
}
func TestGranularRPCBoundsAndLoginAllowlist(t *testing.T) {
ctx, m := WithFetchMetrics(context.Background())
RecordFetch(ctx, FetchObservation{HTTPStatus: 200, State: ContentComplete, GranularSupported: true, IdentityEvidence: IdentityEvidenceCounts{JSONLD: JSONLDIdentityCounts{Associated: 1}}, BlockingEvidence: BlockingEvidenceCounts{Paywall: ScopedEvidenceCounts{OutsideRoot: 1}}})
valid := m.Finish()
valid.Login = "unconfirmed"
for _, mutate := range []func(*FetchMetrics){
func(c *FetchMetrics) { c.IdentityEvidence.JSONLD.Associated = -1 },
func(c *FetchMetrics) { c.IdentityEvidence.Canonical.Invalid = -1 },
func(c *FetchMetrics) { c.IdentityEvidence.OG.Absent = 2 },
func(c *FetchMetrics) { c.BlockingEvidence.Challenge.GlobalPage = 2 },
func(c *FetchMetrics) { c.BlockingEvidence.Paywall.OutsideRoot = 2 },
func(c *FetchMetrics) { c.GranularSupported = false },
func(c *FetchMetrics) { c.Login = "PRIVATE_RAW_REASON" },
} {
bad := valid
mutate(&bad)
ctx, m := WithFetchMetrics(context.Background())
if MergeFetchMetrics(ctx, bad, 3) || m.Finish().Supported {
t.Fatal("untrusted granular aggregate accepted")
}
}
ctx, m = WithFetchMetrics(context.Background())
if !MergeFetchMetrics(ctx, valid, 3) {
t.Fatal("valid granular metrics rejected")
}
got := m.Finish()
if got.IdentityEvidence.JSONLD.Associated != 1 || got.BlockingEvidence.Paywall.OutsideRoot != 1 || got.Login != "unconfirmed" {
t.Fatal("aggregate lost evidence")
}
}
func TestCandidateLengthRPCValidationAndOldProducerCompatibility(t *testing.T) {
ctx, m := WithFetchMetrics(context.Background())
RecordFetch(ctx, FetchObservation{HTTPStatus: 200, CandidateBodySupported: true, CandidateBodyLength: 2001, State: ContentUnavailable})
valid := m.Finish()
for _, mutate := range []func(*FetchMetrics){
func(c *FetchMetrics) { c.CandidateLength.Large = -1 },
func(c *FetchMetrics) { c.CandidateLength.Small = 1 },
func(c *FetchMetrics) { c.CandidateBodySupported = false },
} {
bad := valid
mutate(&bad)
ctx, m := WithFetchMetrics(context.Background())
if MergeFetchMetrics(ctx, bad, 3) || m.Finish().Supported {
t.Fatal("invalid candidate aggregate accepted")
}
}
ctx, m = WithFetchMetrics(context.Background())
if !MergeFetchMetrics(ctx, valid, 3) || m.Finish().CandidateLength.Large != 1 {
t.Fatal("candidate aggregate lost at RPC boundary")
}
valid.CandidateBodySupported = false
valid.CandidateLength = LengthCounts{}
ctx, m = WithFetchMetrics(context.Background())
if !MergeFetchMetrics(ctx, valid, 3) || m.Finish().CandidateBodySupported {
t.Fatal("old producer was confused with measured empty bodies")
}
}

View File

@ -0,0 +1,98 @@
// Package sourcehttp provides DNS-pinned, proxy-free source connections.
package sourcehttp
import (
"context"
"errors"
"net"
"net/http"
"net/netip"
"strings"
"time"
)
type Resolver interface {
LookupNetIP(context.Context, string, string) ([]netip.Addr, error)
}
type DialFunc func(context.Context, string, string) (net.Conn, error)
var errUnavailable = errors.New("source connection unavailable")
var forbidden = prefixes(
"0.0.0.0/8", "10.0.0.0/8", "100.64.0.0/10", "127.0.0.0/8", "169.254.0.0/16", "172.16.0.0/12", "192.0.0.0/24", "192.0.2.0/24", "192.88.99.0/24", "192.168.0.0/16", "198.18.0.0/15", "198.51.100.0/24", "203.0.113.0/24", "224.0.0.0/4", "240.0.0.0/4",
"2001::/23", "2001:db8::/32", "2002::/16", "3fff::/20",
)
func prefixes(values ...string) []netip.Prefix {
out := make([]netip.Prefix, 0, len(values))
for _, v := range values {
out = append(out, netip.MustParsePrefix(v))
}
return out
}
// IsPublicAddress rejects special-use and non-global destinations.
func IsPublicAddress(ip netip.Addr) bool {
if !ip.IsValid() || ip.Zone() != "" {
return false
}
ip = ip.Unmap()
if !ip.IsGlobalUnicast() || ip.IsPrivate() || ip.IsLoopback() || ip.IsLinkLocalUnicast() {
return false
}
// Only currently allocated global IPv6 unicast, excluding transition/special ranges.
if ip.Is6() && !netip.MustParsePrefix("2000::/3").Contains(ip) {
return false
}
for _, p := range forbidden {
if p.Contains(ip) {
return false
}
}
return true
}
// NewTransport resolves exactly once per new connection, validates the entire
// answer set, and dials only numeric addresses. TLS still uses the request host.
// Nil dependencies select the production resolver and dialer; fixtures inject both.
func NewTransport(resolver Resolver, dial DialFunc) *http.Transport {
if resolver == nil {
resolver = net.DefaultResolver
}
if dial == nil {
dial = (&net.Dialer{Timeout: 15 * time.Second, KeepAlive: 30 * time.Second}).DialContext
}
return &http.Transport{
Proxy: nil, TLSHandshakeTimeout: 10 * time.Second, ResponseHeaderTimeout: 15 * time.Second,
IdleConnTimeout: 90 * time.Second, MaxIdleConns: 20, ForceAttemptHTTP2: true,
DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
host, port, err := net.SplitHostPort(address)
if err != nil || port != "443" {
return nil, errUnavailable
}
switch strings.ToLower(host) {
case "finance.yahoo.com", "feeds.finance.yahoo.com", "www.cnbc.com":
default:
return nil, errUnavailable
}
ips, err := resolver.LookupNetIP(ctx, "ip", host)
if err != nil || len(ips) == 0 {
return nil, errUnavailable
}
for _, ip := range ips {
if !IsPublicAddress(ip) {
return nil, errUnavailable
}
}
for _, ip := range ips {
conn, err := dial(ctx, network, net.JoinHostPort(ip.Unmap().String(), port))
if err == nil {
return conn, nil
}
if ctx.Err() != nil {
break
}
}
return nil, errUnavailable
},
}
}

View File

@ -0,0 +1,149 @@
package sourcehttp
import (
"bufio"
"context"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"errors"
"io"
"math/big"
"net"
"net/http"
"net/netip"
"testing"
"time"
)
type resolverFunc func(context.Context, string, string) ([]netip.Addr, error)
func (f resolverFunc) LookupNetIP(c context.Context, n, h string) ([]netip.Addr, error) {
return f(c, n, h)
}
func TestForbiddenDNSAnswersNeverDial(t *testing.T) {
for _, host := range []string{"finance.yahoo.com", "www.cnbc.com"} {
for _, value := range []string{"0.0.0.0", "10.0.0.1", "100.64.0.1", "127.0.0.1", "169.254.1.1", "172.16.0.1", "192.168.0.1", "192.0.0.9", "192.0.2.1", "198.18.0.1", "198.51.100.1", "203.0.113.1", "224.0.0.1", "240.0.0.1", "255.255.255.255", "::", "::1", "fc00::1", "fe80::1", "ff02::1", "2001:db8::1", "2002:0808:0808::1", "64:ff9b::808:808", "2001::1", "3fff::1", "::ffff:127.0.0.1"} {
t.Run(host+"/"+value, func(t *testing.T) {
dials := 0
tr := NewTransport(resolverFunc(func(context.Context, string, string) ([]netip.Addr, error) {
return []netip.Addr{netip.MustParseAddr(value)}, nil
}), func(context.Context, string, string) (net.Conn, error) { dials++; return nil, errors.New("fixture") })
// HTTP cannot reach a socket or send a request when DNS is rejected.
req, _ := http.NewRequest("GET", "https://"+host+"/fixture", nil)
if _, err := tr.RoundTrip(req); err == nil || dials != 0 {
t.Fatal("forbidden DNS answer reached dial")
}
})
}
}
}
func TestDNSFailsClosedAndNumericPinning(t *testing.T) {
for _, answers := range [][]netip.Addr{nil, {netip.MustParseAddr("8.8.8.8"), netip.MustParseAddr("127.0.0.1")}, {netip.Addr{}}, {netip.MustParseAddr("fe80::1%fixture")}} {
dials := 0
tr := NewTransport(resolverFunc(func(context.Context, string, string) ([]netip.Addr, error) { return answers, nil }), func(context.Context, string, string) (net.Conn, error) { dials++; return nil, errors.New("fixture") })
if _, err := tr.DialContext(context.Background(), "tcp", "finance.yahoo.com:443"); err == nil || dials != 0 {
t.Fatal("invalid/mixed answer allowed")
}
}
for _, value := range []string{"8.8.8.8", "2606:4700:4700::1111", "::ffff:8.8.8.8"} {
lookups, dials := 0, 0
tr := NewTransport(resolverFunc(func(context.Context, string, string) ([]netip.Addr, error) {
lookups++
return []netip.Addr{netip.MustParseAddr(value)}, nil
}), func(_ context.Context, _ string, address string) (net.Conn, error) {
dials++
if address != net.JoinHostPort(netip.MustParseAddr(value).Unmap().String(), "443") {
t.Fatal("dial was not pinned")
}
return nil, errors.New("fixture")
})
tr.DialContext(context.Background(), "tcp", "finance.yahoo.com:443")
if lookups != 1 || dials != 1 || tr.Proxy != nil {
t.Fatal("resolver/dial/proxy contract failed")
}
}
}
func TestPinnedTLSRetainsSNIAndHost(t *testing.T) {
for _, host := range []string{"finance.yahoo.com", "www.cnbc.com"} {
t.Run(host, func(t *testing.T) {
key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
template := &x509.Certificate{SerialNumber: big.NewInt(1), DNSNames: []string{host}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), KeyUsage: x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}}
der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key)
if err != nil {
t.Fatal("certificate fixture failed")
}
roots := x509.NewCertPool()
cert, _ := x509.ParseCertificate(der)
roots.AddCert(cert)
observed := make(chan bool, 1)
tr := NewTransport(resolverFunc(func(context.Context, string, string) ([]netip.Addr, error) {
return []netip.Addr{netip.MustParseAddr("8.8.8.8")}, nil
}), func(_ context.Context, _ string, address string) (net.Conn, error) {
if address != "8.8.8.8:443" {
t.Error("unpinned dial")
}
client, server := net.Pipe()
go func() {
defer server.Close()
server.SetDeadline(time.Now().Add(3 * time.Second))
conn := tls.Server(server, &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{der}, PrivateKey: key}}})
r, err := http.ReadRequest(bufio.NewReader(conn))
if err != nil {
observed <- false
return
}
observed <- r.Host == host && conn.ConnectionState().ServerName == host
io.WriteString(conn, "HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")
}()
return client, nil
})
tr.TLSClientConfig = &tls.Config{RootCAs: roots}
defer tr.CloseIdleConnections()
req, _ := http.NewRequest("GET", "https://"+host+"/fixture", nil)
resp, err := tr.RoundTrip(req)
if err != nil {
t.Fatal("pinned TLS fixture failed")
}
resp.Body.Close()
if !<-observed {
t.Fatal("TLS SNI or Host changed")
}
})
}
}
func TestEveryNewConnectionRevalidatesDNS(t *testing.T) {
for _, host := range []string{"finance.yahoo.com", "www.cnbc.com"} {
lookups, dials := 0, 0
tr := NewTransport(resolverFunc(func(context.Context, string, string) ([]netip.Addr, error) {
lookups++
if lookups == 1 {
return []netip.Addr{netip.MustParseAddr("8.8.8.8")}, nil
}
return []netip.Addr{netip.MustParseAddr("127.0.0.1")}, nil
}), func(context.Context, string, string) (net.Conn, error) { dials++; return nil, errors.New("fixture") })
tr.DialContext(context.Background(), "tcp", net.JoinHostPort(host, "443"))
tr.DialContext(context.Background(), "tcp", net.JoinHostPort(host, "443"))
if lookups != 2 || dials != 1 {
t.Fatal("rebound DNS reached dial")
}
}
}
func TestResolverErrorsAndDestinationGuardsNeverDial(t *testing.T) {
lookups, dials := 0, 0
tr := NewTransport(resolverFunc(func(context.Context, string, string) ([]netip.Addr, error) {
lookups++
return nil, errors.New("private resolver error")
}), func(context.Context, string, string) (net.Conn, error) { dials++; return nil, errors.New("fixture") })
for _, address := range []string{"finance.yahoo.com:443", "www.cnbc.com:443", "finance.yahoo.com:80", "finance.yahoo.com:444", "127.0.0.1:443", "[::1]:443", "finance.yahoo.com.evil.invalid:443"} {
if _, err := tr.DialContext(context.Background(), "tcp", address); err != errUnavailable {
t.Fatal("unsafe or raw connection error")
}
}
if lookups != 2 || dials != 0 {
t.Fatal("destination guard or failed DNS allowed dial")
}
}

View File

@ -0,0 +1,14 @@
package yahoofinance
import (
"net/http"
"testing"
)
func TestYahooProductionConstructorUsesExplicitDNSGuardedTransport(t *testing.T) {
client := New().client
transport, ok := client.Transport.(*http.Transport)
if !ok || transport.DialContext == nil {
t.Fatal("Yahoo production constructor has no explicit DNS-guarded dial transport; standard transport can connect after a private DNS answer")
}
}

View File

@ -0,0 +1,117 @@
package yahoofinance
import (
"context"
"fmt"
"io"
"net/http"
"strings"
"testing"
"time"
"github.com/tradarr/backend/internal/scraper"
)
const yahooFixtureURL = "https://finance.yahoo.com/news/fixture.html"
type yahooIngestionTransport struct {
t *testing.T
html string
articleURL string
date bool
rssOnly bool
}
func (f yahooIngestionTransport) RoundTrip(r *http.Request) (*http.Response, error) {
articleURL := f.articleURL
if articleURL == "" {
articleURL = yahooFixtureURL
}
var body string
if r.URL.Host == "feeds.finance.yahoo.com" {
pubDate := ""
if f.date {
pubDate = "<pubDate>Fri, 02 Jan 2026 03:04:05 +0000</pubDate>"
}
body = `<rss><channel><item><title>Synthetic fixture headline</title><link>` + articleURL + `</link><description>Synthetic RSS teaser only.</description>` + pubDate + `</item></channel></rss>`
} else if r.URL.String() == articleURL {
if f.rssOnly {
return &http.Response{StatusCode: 503, Header: make(http.Header), Body: io.NopCloser(strings.NewReader("fixture unavailable")), Request: r}, nil
}
body = f.html
} else {
f.t.Errorf("collector/enricher requested an unexpected fixture route")
return nil, fmt.Errorf("unexpected fixture route")
}
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: r}, nil
}
func TestIngestionPipelineYahooRSSListThenArticleEnrichment(t *testing.T) {
raw := `<link rel="canonical" href="` + yahooFixtureURL + `"><script type="application/ld+json">{"@type":"NewsArticle","url":"` + yahooFixtureURL + `","datePublished":"2026-01-02T03:04:05Z"}</script><article><div class="body yf-fixture"><h2>Synthetic heading.</h2><p>Synthetic initial paragraph.</p><p>Final editorial paragraph.</p></div></article>`
partial := raw + `<div class="paywall">Synthetic access marker</div>`
challenge := raw + `<div id="px-captcha">Synthetic challenge marker</div>`
wrongArticle := strings.ReplaceAll(raw, yahooFixtureURL, "https://finance.yahoo.com/news/other.html")
noDate := strings.Replace(raw, `,"datePublished":"2026-01-02T03:04:05Z"`, "", 1)
for _, tc := range []struct {
name, html string
date, rssOnly bool
wantComplete, wantDate bool
}{
{name: "complete body and reliable date", html: raw, date: true, wantComplete: true, wantDate: true},
{name: "RSS description alone", html: "", rssOnly: true},
{name: "partial paywall", html: partial, date: true, wantDate: true},
{name: "challenge", html: challenge, date: true, wantDate: true},
{name: "complete body with nullable date", html: noDate, wantComplete: true},
{name: "wrong article association", html: wrongArticle, date: true, wantDate: true},
} {
t.Run(tc.name, func(t *testing.T) {
y := &YahooFinance{client: &http.Client{Transport: yahooIngestionTransport{t: t, html: tc.html, date: tc.date, rssOnly: tc.rssOnly}}}
listed, err := y.Scrape(context.Background(), []string{"FIXTURE"})
if err != nil || len(listed) != 1 {
t.Fatal("Yahoo fixture collector did not return the single listed article")
}
if listed[0].URL != yahooFixtureURL || listed[0].Content != "Synthetic RSS teaser only." || scraper.ContentStatus(listed[0]) == scraper.ContentComplete {
t.Fatal("RSS teaser was treated as the listed article body")
}
got, err := y.Enrich(context.Background(), listed)
if err != nil || len(got) != 1 {
t.Fatal("Yahoo fixture article enrichment failed")
}
if got[0].URL != listed[0].URL || got[0].Title != listed[0].Title {
t.Fatal("Yahoo enrichment changed or detached the listed article")
}
if (scraper.ContentStatus(got[0]) == scraper.ContentComplete) != tc.wantComplete {
t.Fatal("Yahoo full-body classification mismatch")
}
if tc.wantComplete && !strings.Contains(got[0].Content, "Final editorial paragraph.") {
t.Fatal("Yahoo final editorial text was not collected")
}
if (got[0].PublishedAt != nil) != tc.wantDate {
t.Fatal("Yahoo publication-date availability mismatch")
}
if tc.wantDate && !got[0].PublishedAt.Equal(time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)) {
t.Fatal("Yahoo did not associate the expected publication date")
}
if tc.name == "wrong article association" && (got[0].Content != "" || scraper.ContentStatus(got[0]) != scraper.ContentUnavailable) {
t.Fatal("Yahoo accepted body content for another article")
}
})
}
}
func TestYahooAcceptedRSSArticlePathIsNotDroppedByEnricher(t *testing.T) {
// The RSS collector accepts any non-empty link; a same-host /news path
// without .html is currently filtered out by the stricter enrichment port.
articleURL := "https://finance.yahoo.com/news/synthetic-story"
html := `<link rel="canonical" href="` + articleURL + `"><article><div class="body yf-fixture"><h2>Synthetic heading.</h2><p>Final editorial paragraph.</p></div></article>`
y := &YahooFinance{client: &http.Client{Transport: yahooIngestionTransport{t: t, html: html, articleURL: articleURL}}}
listed, err := y.Scrape(context.Background(), []string{"FIXTURE"})
if err != nil || len(listed) != 1 {
t.Fatal("Yahoo collector dropped an accepted RSS article")
}
got, err := y.Enrich(context.Background(), listed)
if err != nil || len(got) != 1 || scraper.ContentStatus(got[0]) != scraper.ContentComplete || !strings.Contains(got[0].Content, "Final editorial paragraph.") {
t.Fatal("Yahoo enricher discarded a same-source RSS article URL with available full content")
}
}

View File

@ -0,0 +1,63 @@
package yahoofinance
import (
"context"
"io"
"net/http"
"strings"
"testing"
"github.com/tradarr/backend/internal/scraper"
)
type yahooRedirectIdentityTransport struct {
original string
final string
}
func (f yahooRedirectIdentityTransport) RoundTrip(r *http.Request) (*http.Response, error) {
var status int
var body string
header := make(http.Header)
switch r.URL.Host {
case "feeds.finance.yahoo.com":
status = http.StatusOK
body = `<rss><channel><item><title>Synthetic fixture headline</title><link>` + f.original + `</link><description>RSS teaser only.</description></item></channel></rss>`
case "finance.yahoo.com":
switch r.URL.String() {
case f.original:
status = http.StatusFound
header.Set("Location", f.final)
case f.final:
status = http.StatusOK
body = `<link rel="canonical" href="` + f.original + `"><article><div class="body yf-fixture"><p>` + strings.Repeat("Synthetic complete editorial text. ", 90) + `</p></div></article>`
default:
return nil, io.ErrUnexpectedEOF
}
default:
return nil, io.ErrUnexpectedEOF
}
return &http.Response{StatusCode: status, Header: header, Body: io.NopCloser(strings.NewReader(body)), Request: r}, nil
}
func TestYahooSameHostRedirectCanonicalMayIdentifyOriginalListing(t *testing.T) {
// Models a bounded same-host listing -> article redirect chain. The
// canonical is intentionally the initial URL from this observed chain;
// this fixture grants no trust to any other origin.
original := "https://finance.yahoo.com/m/synthetic-listing?story=fixture"
final := "https://finance.yahoo.com/news/synthetic-article.html"
y := NewWithClient(&http.Client{Transport: yahooRedirectIdentityTransport{original: original, final: final}}, io.Discard)
listed, err := y.Scrape(context.Background(), []string{"FIXTURE"})
if err != nil || len(listed) != 1 || listed[0].URL != original {
t.Fatal("Yahoo fixture collector did not preserve the redirect-chain listing identity")
}
ctx, meter := scraper.WithFetchMetrics(context.Background())
got, err := y.Enrich(ctx, listed)
metrics := meter.Finish()
if err != nil || len(got) != 1 || got[0].URL != original || scraper.ContentStatus(got[0]) != scraper.ContentComplete || len(got[0].Content) < 2000 {
t.Errorf("Yahoo redirect-chain body association failed: complete=%t body_bucket_large=%t", len(got) == 1 && scraper.ContentStatus(got[0]) == scraper.ContentComplete, len(got) == 1 && len(got[0].Content) >= 2000)
}
if metrics.HTTP.TwoXX != 1 || metrics.Identity.Yes != 1 || metrics.Identity.Mismatch != 0 || metrics.Content.Complete != 1 {
t.Errorf("Yahoo redirect-chain counters unexpected: http_2xx=%d identity_yes=%d identity_mismatch=%d complete=%d", metrics.HTTP.TwoXX, metrics.Identity.Yes, metrics.Identity.Mismatch, metrics.Content.Complete)
}
}

View File

@ -5,23 +5,42 @@ import (
"encoding/xml"
"errors"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
"github.com/tradarr/backend/internal/scraper"
"github.com/tradarr/backend/internal/scraper/sourcehttp"
)
type YahooFinance struct {
client *http.Client
client *http.Client
diagnostics io.Writer
}
func New() *YahooFinance {
return &YahooFinance{
client: &http.Client{Timeout: 15 * time.Second},
client: &http.Client{Transport: sourcehttp.NewTransport(nil, nil), Timeout: 15 * time.Second,
CheckRedirect: func(r *http.Request, via []*http.Request) error {
if len(via) == 0 || len(via) >= 3 || r.URL.Scheme != "https" || r.URL.User != nil || r.URL.Host != via[0].URL.Host {
return http.ErrUseLastResponse
}
return nil
}},
}
}
// NewWithClient injects transport/diagnostic sinks without replacing ingestion.
func NewWithClient(client *http.Client, diagnostics io.Writer) *YahooFinance {
y := New()
if client != nil {
y.client = client
}
y.diagnostics = diagnostics
return y
}
func (y *YahooFinance) Name() string { return "stocktwits" } // garde le même type en DB
type rssFeed struct {
@ -77,7 +96,11 @@ func (y *YahooFinance) fetchSymbol(ctx context.Context, symbol string) (articles
if len(safeSymbol) > 64 {
safeSymbol = safeSymbol[:64]
}
fmt.Printf("yahoofinance symbol=%s yahoo_symbol=%s status=%d articles=%d outcome=%s\n", safeSymbol, safeSymbol, status, len(articles), outcome)
writer := y.diagnostics
if writer == nil {
writer = os.Stdout
}
fmt.Fprintf(writer, "yahoofinance symbol=%s yahoo_symbol=%s status=%d articles=%d outcome=%s\n", safeSymbol, safeSymbol, status, len(articles), outcome)
}()
url := fmt.Sprintf(
"https://feeds.finance.yahoo.com/rss/2.0/headline?s=%s&region=US&lang=en-US",

View File

@ -0,0 +1,38 @@
# Deliberate opt-in file + profile + CLI gate. Never used by the offline bench.
services:
byparr:
profiles: ["live"]
image: ghcr.io/thephaseless/byparr:latest
logging:
driver: none
ingestion-scraper:
profiles: ["live"]
build:
context: ./scraper-service
environment:
BYPARR_URL: http://byparr:8191
depends_on: [byparr]
logging:
driver: none
tmpfs: ["/tmp"]
bench-live:
profiles: ["live"]
image: tradarr-ingestion-bench:ticket40
build:
context: .
dockerfile: backend/Dockerfile.ingestion-bench
command: ["--mode=live", "--allow-live", "--limit=3"]
environment:
INGESTION_SCRAPER_URL: http://ingestion-scraper:3001
INGESTION_YAHOO_SYMBOL: ${INGESTION_YAHOO_SYMBOL:-AAPL}
BLOOMBERG_USERNAME_FILE: /run/secrets/bloomberg_username
BLOOMBERG_PASSWORD_FILE: /run/secrets/bloomberg_password
secrets: [bloomberg_username, bloomberg_password]
depends_on: [ingestion-scraper]
read_only: true
tmpfs: ["/tmp"]
secrets:
bloomberg_username:
file: ${BLOOMBERG_USERNAME_FILE:?Path to existing private credential file required for live mode}
bloomberg_password:
file: ${BLOOMBERG_PASSWORD_FILE:?Path to existing private credential file required for live mode}

View File

@ -0,0 +1,11 @@
# Offline default: no publisher, Byparr, DB, Laya, application or scheduler.
services:
bench:
image: tradarr-ingestion-bench:ticket40
build:
context: .
dockerfile: backend/Dockerfile.ingestion-bench
command: ["--mode=offline", "--limit=3"]
network_mode: none
read_only: true
tmpfs: ["/tmp"]

341
docs/ingestion-bench.md Normal file
View File

@ -0,0 +1,341 @@
# Bench d'ingestion isolé — ticket #40
Ce programme exécute les **collectors et enrichers de production**, sans serveur
applicatif, scheduler, PostgreSQL, Laya ou modèle de synthèse. Il ne persiste ni
article ni candidat. Les fixtures sont synthétiques et ne reproduisent aucun
HTML éditeur complet.
## Offline par défaut — commande reproductible
Depuis la racine du worktree :
```sh
docker compose --env-file /dev/null -p tradarr-ingestion-offline -f compose.ingestion-bench.yml build bench
docker compose --env-file /dev/null -p tradarr-ingestion-offline -f compose.ingestion-bench.yml run --rm -T bench
```
Le conteneur a **`network_mode: none`**. Yahoo/CNBC reçoivent des réponses RSS/HTML
synthétiques via un transport injecté qui ne délègue jamais au réseau. Bloomberg
appelle son RPC de production en loopback vers un serveur fixture exécutant
`index.js` et ses parseurs réels ; seuls les ports Byparr et Puppeteer sont
simulés. Le test vérifie sept appels de rubriques Byparr, puis une connexion
Puppeteer et trois articles, sans fallback anonyme. Les variables privées du shell
ne sont pas transmises au sous-processus fixture.
Le résultat doit contenir `mode: "offline"`, trois lignes source et, à la limite
3, un état complet, un partiel et un indisponible par source. Deux dates sont
observées et une manque. Le corps complet sans date est intentionnel : la
complétude ne dépend pas de la date. Ce résultat **ne mesure pas des pages live**.
Pour examiner un seul article par source :
```sh
docker compose --env-file /dev/null -p tradarr-ingestion-offline -f compose.ingestion-bench.yml run --rm -T bench --mode=offline --limit=1
```
Les seules limites acceptées sont 1, 2 et 3. Elles s'appliquent après la collecte,
comme en production : un collector peut découvrir davantage de liens, mais au
plus trois entrées par source sont enrichies/comptées. Le bench n'introduit pas
une collecte parallèle ou un autre parseur pour réduire artificiellement ce pool.
Sans Docker, avec Go et Node et les dépendances du scraper déjà installées :
```sh
GOCACHE="$TMPDIR/go-cache" go -C backend build -o "$TMPDIR/ingestion-bench" ./cmd/ingestion-bench
"$TMPDIR/ingestion-bench" --limit=3
```
Lancer depuis la racine ; `--fixture-script` permet d'indiquer explicitement le
chemin du serveur fixture si le répertoire courant diffère.
## Live — opt-in distinct, jamais lancé par les tests
Le fichier `compose.ingestion-bench.live.yml`, le profil `live` et les deux options
CLI `--mode=live --allow-live` constituent une activation explicite. Sans ces
options, le programme refuse le mode live avant toute lecture de credential ou
requête. Il n'utilise pas le fichier Compose applicatif et ne démarre aucun
backend, scheduler, Laya ou DB.
Les variables `BLOOMBERG_USERNAME_FILE` et `BLOOMBERG_PASSWORD_FILE` désignent des
**fichiers privés déjà disponibles**, lisibles par l'utilisateur du conteneur
(uid 1000), montés comme secrets en lecture seule. Ne pas mettre les valeurs dans
la ligne de commande, un fichier du dépôt, les diagnostics ou un rapport de test.
Le bench ne consulte pas la DB/clé de chiffrement et ne récupère aucun nouveau
secret. `INGESTION_YAHOO_SYMBOL` permet de choisir l'unique symbole collecté
(défaut live : AAPL), sans l'afficher dans le résultat.
Une fois ces chemins configurés dans le shell, les commandes opt-in sont :
```sh
docker compose --env-file /dev/null -p tradarr-ingestion-live -f compose.ingestion-bench.live.yml --profile live build ingestion-scraper bench-live
docker compose --env-file /dev/null -p tradarr-ingestion-live -f compose.ingestion-bench.live.yml --profile live up -d byparr ingestion-scraper
docker compose --env-file /dev/null -p tradarr-ingestion-live -f compose.ingestion-bench.live.yml --profile live run --rm -T bench-live
# Après mesure : arrêter seulement cette stack isolée.
docker compose --env-file /dev/null -p tradarr-ingestion-live -f compose.ingestion-bench.live.yml --profile live down
```
Les services peuvent nécessiter un délai de démarrage. Un échec est rapporté par
les états agrégés, sans retry anonyme. Le live peut coûter du temps et contacter
les éditeurs ; il n'est jamais implicite. Les logs des services Byparr/scraper
sont désactivés dans cette stack dédiée et ne sont pas attachés au bench. Le
résultat du bench lui-même ne contient que le mode et les agrégats autorisés.
Aucune capture de page, cookie ou stockage navigateur n'est ajoutée. Un bench
live QA borné a été exécuté pour cette livraison ; aucun corps complet n'a été
confirmé avec l'accès courant. Aucun résultat par article n'est conservé ici :
ni contenu, URL, titre, credential ni erreur brute.
Bloomberg conserve **rubriques par Byparr, enrichissement par Puppeteer
authentifié**, avec les credentials transmis au RPC existant. Challenge, 2FA,
connexion non confirmée et HTTP article 403 restent indisponibles ; aucun
contournement ou fallback anonyme n'est introduit. Un défaut de connexion ne
permet pas de conclure que les credentials sont incorrects.
## Mesures et interprétation
Chaque ligne contient exclusivement :
- `source` : clé canonique ;
- `list_status`, `enrich_status` : `ok`, `unavailable` ou `not_attempted` ;
- `listed` : pool borné retenu après collecte ;
- `enriched` : entrées revenues d'un appel d'enrichissement valide, **pas** un
nombre de corps complets ;
- `dates.observed`, `dates.missing` : disponibilité d'une date fiable et associée ;
- `content.complete`, `content.incomplete`, `content.unavailable` : classification
effective du contenu par les adaptateurs de production.
`ok` signifie que le port a répondu sans erreur : un RPC réussi peut renvoyer
zéro article ou des corps tous indisponibles. Un exit 0 signifie que la mesure a
été rendue, pas qu'un texte intégral éditeur est disponible. Ni URL, titre,
contenu, timestamp individuel, symbole, prompt, credential ou erreur brute ne
figure dans ces diagnostics. Les erreurs de configuration sont des codes fixes.
Les writers de diagnostic sont injectés à `io.Discard` ; aucun stdout global
n'est détourné et la journalisation de production normale reste inchangée.
## Correction du lien listing → enrichissement
L'URL originale du listing, son titre et sa position sont conservés. Les liens
HTTP des **hôtes exacts** `finance.yahoo.com` et `www.cnbc.com` sont convertis en
HTTPS **avant** tout accès réseau. Les chemins d'article ne sont plus limités à
une extension `.html`, au préfixe `/news/` ou à un calendrier. Cela ne valide
pas le contenu d'une réponse : racine reconnue et preuves d'association restent
obligatoires, et blocages/partiels restent incomplets ou indisponibles.
Les liens externes, credentials dans l'URL, ports explicites et schémas non
HTTP(S) restent non récupérables ; leur entrée n'est pas effacée du pool et son
corps est compté indisponible. Les redirections sont bornées, validées à chaque
étape sur le même hôte source et mises en HTTPS avant suivi. Seule une chaîne
réellement observée peut changer l'identité de fetch ; les métadonnées doivent
correspondre à son dernier article. Le listing d'origine reste inchangé.
Les paramètres sémantiques de query sont conservés, notamment pour ne pas
confondre deux articles d'un même chemin. Seuls les paramètres de suivi connus
`utm_*`, `guccounter`, `guce_referrer`, `guce_referrer_sig` sont ignorés pour la
comparaison d'identité, pas pour la requête initiale. Une redirection externe ou
une identité de réponse non observée est refusée. Le client live du bench
restreint aussi les destinations et refuse les adresses privées/réservées.
Une date absente ou contradictoire reste nullable sans invalider un corps
qualifié complet. Une date fiable de RSS reste associée au listing quand
l'enrichissement n'apporte pas de date plus fiable. Aucun timestamp de collecte
n'est inventé en remplacement d'une date de publication.
## Tests
```sh
GOCACHE="$TMPDIR/go-cache" go -C backend test ./internal/scraper/... ./internal/ingestionbench ./cmd/ingestion-bench -count=1
npm test --prefix scraper-service
GOCACHE="$TMPDIR/go-cache" GOMODCACHE=/home/anthony/go/pkg/mod make test-postgres
```
Les rouges QA Yahoo/CNBC ont été reproduits avant correction. Les tests couvrent
HTTP→HTTPS, chemins variés, redirections observées, identité du listing,
paramètres sémantiques distincts, SSRF, date nullable/contradictoire, RSS seulement,
challenge/paywall, absence de données sensibles dans la sortie et opt-in live.
Les tests Node vérifient aussi le login Bloomberg corrigé et le fait que le
serveur fixture appelle les routes collecteur/enrichisseur réellement livrées.
## Durcissement après revue Architect — fixtures et destination des credentials
Les fixtures de référence utilisent désormais exclusivement des URLs HTTPS de
formes canoniques (`/news/*.html` pour Yahoo, `/YYYY/MM/DD/*.html` pour CNBC).
Le test audité ne se contente pas de l'exit code : il compte un appel RSS et
**trois requêtes article réelles dans le transport fixture** par source, puis
vérifie chaque état `complete` / `incomplete` / `unavailable`, la conservation du
listing et les dates associées. Le cas complet garde une date nulle ; les deux
autres conservent une date synthétique fiable. Les chemins alternatifs et la
conversion HTTP→HTTPS restent couverts séparément par les régressions métier.
En live, la seule base RPC admise est **`http://ingestion-scraper:3001`**, avec
éventuellement un slash final normalisé. Aucun port alternatif, loopback,
alias HTTPS, chemin additionnel, query ou userinfo n'est accepté. Cette validation
précède la lecture des fichiers de credentials. Le transport RPC contrôle aussi
chaque POST : seuls `/bloomberg/scrape` et `/bloomberg/enrich` sur cette origine
exacte sont autorisés ; les redirections et proxies ambiants sont désactivés.
Un test avec un serveur piège loopback vérifie qu'aucun POST ne lui parvient.
Le client RPC offline est construit séparément, lié à l'hôte/port exact du
serveur fixture lancé localement. Il n'est utilisé qu'avec les identifiants
synthétiques offline ; il ne rend aucun port loopback admissible en mode live.
## Métrologie agrégée des fetchs d'article
Chaque ligne ajoute `article_fetch` (schéma version 1) et `not_fetched`. La
métrologie est activée dans le contexte du bench uniquement ; elle n'ajoute aucun
champ à `Article`, au prompt, au bilan de génération ou aux tables historiques.
Aucune observation individuelle n'est journalisée ou conservée dans une liste.
`article_fetch` contient uniquement des compteurs :
- `supported` : producteur instrumenté disponible ;
- `attempted` : tentatives d'article uniques effectivement lancées ;
- `http` : `2xx`, `3xx`, `4xx`, `5xx`, `network` ;
- `editorial_root` : `yes`, `no`, `not_evaluated` ;
- `identity` : `yes`, `no`, `mismatch`, `not_evaluated` ;
- `blocking_marker` : `yes`, `no`, `not_evaluated` ;
- `extracted_characters` : buckets `0`, `1-500`, `501-2000`, `>2000` ;
- `candidate_body_characters` : mêmes buckets, avant rejet d’identité ;
- `candidate_body_supported` : disponibilité de cette mesure chez le producteur ;
- `completeness` : `complete`, `incomplete`, `unavailable`.
`not_fetched` vaut le nombre d'entrées bornées sans tentative unique mesurée
(cache/déduplication, URL non récupérable, login bloqué ou expiration avant
lancement). Il reste **null** si l'instrumentation est indisponible. Les
compteurs par fetch peuvent donc différer des compteurs de contenu par entrée.
Les dimensions sont des distributions agrégées, pas une liste ou un journal des
observations d'article.
La classe HTTP est celle du résultat final de la navigation principale de
l'article : pas les sous-ressources, redirections intermédiaires, pages de login,
ni le RPC scraper. `network` signifie absence de statut HTTP final exploitable
(transport/navigation/timeout), sans erreur brute. Une réponse non 200 n'est
**pas lue pour chercher des marqueurs** : racine, identité et blocage sont alors
`not_evaluated`, longueur 0 et contenu indisponible. Cela évite de transformer
une absence d'observation en « aucun challenge ».
Pour un HTML 200 analysé, la racine est reconnue seulement si elle est unique et
admissible. L'identité dépend des preuves et contradictions de métadonnées déjà
utilisées par le parseur. Un marqueur de blocage correspond aux restrictions ou
placeholders reconnus, pas à une déduction depuis un contenu court ou une
identité absente. Une incohérence `articleBody` peut rendre le contenu partiel
sans qu'un marqueur de blocage soit présent.
`extracted_characters` compte les caractères Unicode du texte **retenu par
l'extracteur**, pas les octets/tailles HTML. Une mauvaise association laisse ce
compteur à zéro et le contenu retourné vide.
`candidate_body_characters` mesure séparément le texte éditorial de l'unique
racine reconnue et admissible, avant rejet d'identité. Le comptage ne construit
ni ne conserve un corps candidat : parcours du DOM transitoire, espaces Unicode
normalisés et séparateurs de paragraphes de deux caractères, arrêt à 2001
caractères suffisant pour le dernier bucket. Navigation, scripts, éléments cachés,
promotions, placeholders et squelettes sont exclus. Aucun texte extérieur ou
racine ambiguë n'est utilisé pour inventer un corps. Le résultat de l'extraction,
la complétude, les dates et les règles d'accès restent strictement indépendants.
Un grand candidat ne prouve ni son association, ni sa complétude, ni son accès.
Pour les producteurs Yahoo/CNBC instrumentés, chaque tentative alimente un bucket
candidat. Le bucket zéro comprend aussi les réponses non analysées (non-200 ou
erreur réseau), les racines absentes/ambiguës et les racines vides ; il faut le
croiser avec les compteurs HTTP/racine. Aucun corps non-200 n'est lu pour le mesurer.
`candidate_body_supported: false` indique l'absence de cette instrumentation
(notamment Bloomberg et anciens RPC) : les buckets nuls ne sont alors pas une
mesure de corps vides. Le login Bloomberg bloqué reste `not_fetched`.
Aucun texte, identifiant, URL, timestamp individuel, cookie, header, credential ou
message d'erreur n'est ajouté à ces compteurs. La disponibilité d'une date reste
indépendante.
Bloomberg transmet seulement un objet agrégé `fetch_metrics` dans son RPC quand
le bench demande `measure_fetches: true`. Un login échoué avant les pages donne
`attempted: 0`, sans inventer trois erreurs réseau ou trois HTTP 403. Une erreur
RPC n'est pas attribuée à un fetch éditeur. Les anciens services qui ignorent
cette option donnent `supported: false`, sans faux zéro interprétable. Il faut
reconstruire **les deux images** bench et ingestion-scraper pour la prochaine
mesure live explicitement autorisée ; les commandes opt-in ci-dessus restent
inchangées. Aucun appel live n'est nécessaire aux tests.
Les fixtures offline de référence vérifient :
| Source | HTTP 2xx / 4xx | Racine oui / non / non évaluée | Blocage oui / non / non évalué | Longueur 0 / 1–500 |
| --- | --- | --- | --- | --- |
| Yahoo Finance | 3 / 0 | 2 / 1 / 0 | 2 / 1 / 0 | 1 / 2 |
| CNBC Business | 3 / 0 | 2 / 1 / 0 | 2 / 1 / 0 | 1 / 2 |
| Bloomberg | 2 / 1 | 2 / 0 / 1 | 1 / 1 / 1 | 1 / 2 |
Pour chaque source, l'état reste un complet, un partiel, un indisponible et deux
dates observées / une absente. Ce sont des résultats synthétiques, pas une
mesure des sources réelles.
Le premier bilan live seul (sans classes HTTP/preuves de parsing) ne permet pas
d'affirmer que Yahoo utilise un nouveau sélecteur ou que CNBC est derrière un
paywall. Un futur compteur 200 + racine/identité inconnue doit être reproduit avec
une fixture structurelle représentative et assainie avant d'élargir un parseur.
Aucun HTML live n'est exporté dans les diagnostics, relu pour enquête, affiché ou ajouté au dépôt ; les adaptateurs conservent uniquement leur lecture et parsing transitoires nécessaires à l'ingestion ;
aucun sélecteur n'est inventé à partir de ces seuls compteurs.
Le transport Yahoo/CNBC de production et du bench live partage la même garde DNS
(`internal/scraper/sourcehttp`). Chaque nouvelle connexion résout l’hôte autorisé,
rejette toute réponse contenant une adresse privée, locale, spéciale ou non globale,
puis compose le dial avec une IP numérique validée, sans deuxième résolution.
TLS conserve le SNI du domaine et HTTP son Host. Aucun proxy d’environnement n’est
utilisé. Les validations de domaine et de redirection restent en place ; le mode
offline conserve son transport fermé de fixtures et ne résout aucun nom public.
Les adresses publiques utilisées par les tests sont seulement des valeurs injectées :
les échanges TLS de test passent sur une connexion en mémoire.
### Granularité diagnostique Yahoo/CNBC
`article_fetch` ajoute des compteurs fixes, sans données individuelles :
- `identity_evidence.canonical` et `identity_evidence.og` : `associated`,
`same_source_different_identity`, `valid_other_host`, `invalid`, `absent`.
- `identity_evidence.jsonld` : `associated` et `mismatch`.
- `blocking_evidence` : `paywall`, `partial`, `truncated`, `placeholder`,
`accessibility`, `body_conflict`, chacun avec `article_root` et `outside_root`.
- `blocking_evidence.challenge.global_page` : présence d'au moins un marqueur
challenge sur toute la page, au plus une fois par fetch, même s'il apparaît
dans plusieurs scopes. Aucun champ challenge `article_root`/`outside_root`.
Pour canonical/OG, `associated` correspond aux identités admises par le parseur
(y compris les alias de redirection déjà validés). `same_source_different_identity`
signifie une URL HTTP(S) valide du même hôte, mais qui ne correspond pas à une
identité admise. `valid_other_host` signifie une URL HTTP(S) valide d'un autre hôte :
c'est une observation syntaxique, sans autorisation de fetch ni confiance accordée
au domaine. `invalid` couvre les références malformées, schémas autres que HTTP(S),
hôtes absents, credentials, ports hors plage et valeurs trop longues. Les références
relatives valides sont résolues par rapport à l'URL finale déjà observée ; elles ne
provoquent aucun accès réseau. Les URL bien formées du même hôte avec un port
explicite restent mesurées comme identités différentes si le parseur ne les admet
pas : la garde de production demeure inchangée.
`absent` est évalué séparément pour canonical et OG, lorsque ce type de métadonnée
n'a aucune valeur non vide. Une page ne contenant que OG compte donc comme
canonical absent, et réciproquement ; une page sans les deux compte dans les deux
absences. Une URL présente mais invalide n'est pas une absence. Aucun de ces
compteurs ne contient la valeur de la métadonnée.
Le challenge reste globalement bloquant selon les règles de complétude existantes ;
ce changement de libellé ne réduit pas sa portée.
Chaque catégorie/scope compte au plus une fois par fetch ; les catégories ne sont
pas exclusives et leur somme peut dépasser `attempted`. `article_root` couvre la
racine éditoriale et son conteneur `article` ; les métadonnées dans le head sont
`outside_root`. `accessibility` mesure le refus explicite d'accès dans le JSON-LD
associé ; `body_conflict` compare son `articleBody` au texte effectivement extrait,
uniquement lorsque l'extraction a été évaluée. Aucun conflit n'est inventé quand
l'association est rejetée avant extraction. Ces observations ne modifient aucune
règle d'association, de date ou de complétude. Un paywall extérieur peut donc être
mesuré sans rendre le corps incomplet.
`granular_supported: true` signifie que l'observateur détaillé a évalué au moins
une réponse HTML de ce bilan. Sinon les zéros ne prouvent pas l'absence de marqueur.
L'observateur détaillé est fourni pour Yahoo/CNBC ; Bloomberg reste
`granular_supported: false`.
Pour Bloomberg, `article_fetch.login`, lorsqu'il est disponible, vaut uniquement
`confirmed`, `unconfirmed` ou `refused` : ce dernier exige un refus déjà identifié
par le login (HTTP 401/403 ou état explicite de rejet). Challenge, 2FA, délai ou
absence de preuve positive restent `unconfirmed`. Ces catégories n'inventent pas
des fetchs d'article : en cas d'auth non aboutie, `attempted` reste zéro et les
articles restent `not_fetched`. Aucun détail du formulaire, identifiant ou motif
brut n'est transmis. Un ancien scraper peut omettre la catégorie.

View File

@ -111,7 +111,7 @@ Les paragraphes sont normalisés en Unicode NFC, espaces simples et séparation
La synthèse borne le **prompt complet à 24576 octets UTF-8** (24 Kio), instructions et JSON échappé compris, pour `num_ctx=32768`. Une même allocation maximale de préfixe par article est ajustée au budget agrégé ; titres, IDs candidats, identités suivies et ordre sont conservés. Chaque contenu réduit porte `content_truncated=true` et les instructions précisent qu’il s’agit d’extraits. Si les métadonnées immuables seules dépassent le budget, une erreur fixe est renvoyée sans appel fournisseur. Cette réserve est un proxy conservateur en octets pour le contexte, pas une mesure exacte des tokens du fournisseur. Aucun article n’est supprimé pour faire tenir le prompt.
Pour les dates JSON-LD d’une page article, une identité différente de l’URL chargée ne peut pas fournir sa date. Une absence/erreur conserve `null` côté service. Les tests utilisent uniquement des snippets structurels synthétiques pour les deux layouts, jamais les HTML utilisateur complets. L’inspection locale de ces trois fichiers n’émet que des nombres/booléens, aucun texte éditorial. Contenu, HTML et décisions restent transitoires : aucun fichier, ligne d’article ou journal ne les conserve. Le coût réel d’enrichissement et la disponibilité des contenus authentifiés n’ont pas été mesurés sur les sources.
Pour les dates JSON-LD d’une page article, une identité différente de l’URL chargée ne peut pas fournir sa date. Une absence/erreur conserve `null` côté service. Les tests utilisent uniquement des snippets structurels synthétiques pour les deux layouts, jamais les HTML utilisateur complets. L’inspection locale de ces trois fichiers n’émet que des nombres/booléens, aucun texte éditorial. Contenu, HTML et décisions restent transitoires : aucun fichier, ligne d’article ou journal ne les conserve. Un bench live QA borné a évalué la disponibilité des corps avec l’accès courant ; aucun corps complet n’a été confirmé. Ce bench ne constitue pas une mesure représentative du coût ou de la latence.
### Échecs de synthèse et budgets
@ -366,3 +366,11 @@ les défauts locaux et ces critères, sans affirmer que l'accès Bloomberg réel
rétabli. Si Bloomberg exige une interaction utilisateur, une vérification
supplémentaire ou refuse l'accès au navigateur automatisé, le résultat correct
reste indisponible ; aucun mécanisme de contournement n'est ajouté.
### Bench d'ingestion sans génération
Voir [le bench isolé offline et le mode live opt-in](ingestion-bench.md).
Il réutilise les collectors/enrichers de production, borne l'enrichissement à
1–3 articles/source et n'exécute ni Laya, ni synthèse, ni DB. L'image offline
s'exécute sans réseau ; les diagnostics ne contiennent que des agrégats. Un lien
réassocié n'est jamais, à lui seul, une preuve de corps complet.

View File

@ -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])
}
}

View 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})
}

View 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}

View File

@ -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()

View File

@ -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'])

View File

@ -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))
}
})

View 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')
})

View 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()}
})