feat(scraper): bound article enrichment diagnostics (#40)
This commit is contained in:
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>
|
||||
Reference in New Issue
Block a user