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

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

View File

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

View File

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

View File

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

View File

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