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

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