feat(scraper): bound article enrichment diagnostics (#40)
This commit is contained in:
19
backend/Dockerfile.ingestion-bench
Normal file
19
backend/Dockerfile.ingestion-bench
Normal 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"]
|
||||
12
backend/Dockerfile.ingestion-bench.dockerignore
Normal file
12
backend/Dockerfile.ingestion-bench.dockerignore
Normal file
@ -0,0 +1,12 @@
|
||||
**
|
||||
!backend
|
||||
!backend/**
|
||||
!scraper-service
|
||||
!scraper-service/**
|
||||
**/node_modules
|
||||
**/.git
|
||||
**/.env
|
||||
**/.env.*
|
||||
**/test-results
|
||||
**/playwright-report
|
||||
**/*.log
|
||||
100
backend/cmd/ingestion-bench/main.go
Normal file
100
backend/cmd/ingestion-bench/main.go
Normal 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:])) }
|
||||
46
backend/cmd/ingestion-bench/main_test.go
Normal file
46
backend/cmd/ingestion-bench/main_test.go
Normal 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")
|
||||
}
|
||||
}
|
||||
}
|
||||
121
backend/internal/ingestionbench/architect_blockers_test.go
Normal file
121
backend/internal/ingestionbench/architect_blockers_test.go
Normal 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")
|
||||
}
|
||||
}
|
||||
118
backend/internal/ingestionbench/bench.go
Normal file
118
backend/internal/ingestionbench/bench.go
Normal 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
|
||||
}
|
||||
66
backend/internal/ingestionbench/bench_test.go
Normal file
66
backend/internal/ingestionbench/bench_test.go
Normal 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")
|
||||
}
|
||||
}
|
||||
}
|
||||
67
backend/internal/ingestionbench/offline.go
Normal file
67
backend/internal/ingestionbench/offline.go
Normal 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
|
||||
}
|
||||
153
backend/internal/ingestionbench/runtime.go
Normal file
153
backend/internal/ingestionbench/runtime.go
Normal 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
|
||||
}}
|
||||
}
|
||||
104
backend/internal/ingestionbench/runtime_test.go
Normal file
104
backend/internal/ingestionbench/runtime_test.go
Normal 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")
|
||||
}
|
||||
}
|
||||
}
|
||||
33
backend/internal/ingestionbench/sources.go
Normal file
33
backend/internal/ingestionbench/sources.go
Normal 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}},
|
||||
}
|
||||
}
|
||||
2
backend/internal/ingestionbench/testdata/body.html
vendored
Normal file
2
backend/internal/ingestionbench/testdata/body.html
vendored
Normal 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>
|
||||
@ -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")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@ -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)
|
||||
}
|
||||
}
|
||||
76
backend/internal/scraper/articlecontent/candidate_length.go
Normal file
76
backend/internal/scraper/articlecontent/candidate_length.go
Normal 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)
|
||||
}
|
||||
@ -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")
|
||||
}
|
||||
}
|
||||
}
|
||||
228
backend/internal/scraper/articlecontent/diagnostics.go
Normal file
228
backend/internal/scraper/articlecontent/diagnostics.go
Normal 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
|
||||
}
|
||||
}
|
||||
96
backend/internal/scraper/articlecontent/diagnostics_test.go
Normal file
96
backend/internal/scraper/articlecontent/diagnostics_test.go
Normal 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"})
|
||||
}
|
||||
@ -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
|
||||
}
|
||||
|
||||
@ -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")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@ -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
|
||||
|
||||
@ -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")
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -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)
|
||||
}
|
||||
}
|
||||
105
backend/internal/scraper/articlecontent/listing_identity_test.go
Normal file
105
backend/internal/scraper/articlecontent/listing_identity_test.go
Normal 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")
|
||||
}
|
||||
}
|
||||
@ -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")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@ -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
|
||||
}
|
||||
|
||||
|
||||
@ -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
|
||||
}
|
||||
|
||||
65
backend/internal/scraper/bloomberg/fetch_metrics_test.go
Normal file
65
backend/internal/scraper/bloomberg/fetch_metrics_test.go
Normal 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")
|
||||
}
|
||||
}
|
||||
}
|
||||
103
backend/internal/scraper/bloomberg/ingestion_regression_test.go
Normal file
103
backend/internal/scraper/bloomberg/ingestion_regression_test.go
Normal 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")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@ -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)
|
||||
}
|
||||
}
|
||||
@ -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 {
|
||||
|
||||
@ -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")
|
||||
}
|
||||
}
|
||||
@ -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")
|
||||
}
|
||||
}
|
||||
293
backend/internal/scraper/fetch_metrics.go
Normal file
293
backend/internal/scraper/fetch_metrics.go
Normal 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
|
||||
}
|
||||
106
backend/internal/scraper/fetch_metrics_test.go
Normal file
106
backend/internal/scraper/fetch_metrics_test.go
Normal 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")
|
||||
}
|
||||
}
|
||||
98
backend/internal/scraper/sourcehttp/transport.go
Normal file
98
backend/internal/scraper/sourcehttp/transport.go
Normal 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
|
||||
},
|
||||
}
|
||||
}
|
||||
149
backend/internal/scraper/sourcehttp/transport_test.go
Normal file
149
backend/internal/scraper/sourcehttp/transport_test.go
Normal 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")
|
||||
}
|
||||
}
|
||||
@ -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")
|
||||
}
|
||||
}
|
||||
@ -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")
|
||||
}
|
||||
}
|
||||
@ -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)
|
||||
}
|
||||
}
|
||||
@ -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®ion=US&lang=en-US",
|
||||
|
||||
Reference in New Issue
Block a user