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

View File

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

View File

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

View File

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