fix(scrapers): add sanitized collection diagnostics

Report source, HTTP status, article counts, and outcome without logging response bodies; preserve the existing extraction and parsing flow.

Refs #20

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-11-22 15:08:35 +01:00
parent d65222169a
commit 4131cf903e
4 changed files with 224 additions and 17 deletions

View File

@ -0,0 +1,78 @@
package watcherguru
import (
"context"
"io"
"net/http"
"os"
"strings"
"testing"
)
type ticket20RoundTrip func(*http.Request) (*http.Response, error)
func (f ticket20RoundTrip) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
func ticket20CaptureStdout(t *testing.T, run func()) string {
t.Helper()
reader, writer, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
previous := os.Stdout
os.Stdout = writer
defer func() { os.Stdout = previous }()
run()
if err := writer.Close(); err != nil {
t.Fatal(err)
}
data, err := io.ReadAll(reader)
_ = reader.Close()
if err != nil {
t.Fatal(err)
}
return string(data)
}
func TestTicket20WatcherGuruDiagnosticsReportBothRSSAttemptsAndEmptyHTMLWithoutContent(t *testing.T) {
const rssPrivate = "PRIVATE_WATCHERGURU_RSS_RESPONSE_DO_NOT_LOG"
const htmlPrivate = "PRIVATE_WATCHERGURU_HTML_RESPONSE_DO_NOT_LOG"
var paths []string
watcher := &WatcherGuru{client: &http.Client{Transport: ticket20RoundTrip(func(r *http.Request) (*http.Response, error) {
paths = append(paths, r.URL.Path)
switch r.URL.Path {
case "/feed/":
return &http.Response{StatusCode: http.StatusBadGateway, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`<html>` + rssPrivate + `</html>`)), Request: r}, nil
case "/news/feed/":
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`<?xml version="1.0"?><rss><channel><!-- ` + rssPrivate + ` --></channel></rss>`)), Request: r}, nil
case "/news/":
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(`<html><body><!-- ` + htmlPrivate + ` --><p>no candidate article</p></body></html>`)), Request: r}, nil
default:
return nil, io.ErrUnexpectedEOF
}
})}}
var count int
logs := ticket20CaptureStdout(t, func() {
articles, err := watcher.Scrape(context.Background(), nil)
if err != nil {
t.Fatalf("Scrape returned error: %v", err)
}
count = len(articles)
})
if strings.Join(paths, ",") != "/feed/,/news/feed/,/news/" {
t.Fatalf("fake request path sequence=%v", paths)
}
for _, diagnostic := range []string{"rss feed=/feed/ status=502", "rss feed=/news/feed/ status=200 articles=0", "html status=200 articles=0"} {
if !strings.Contains(logs, diagnostic) {
t.Errorf("WatcherGuru diagnostic lacks %q: %q", diagnostic, logs)
}
}
if count != 0 {
t.Errorf("articles=%d, want 0", count)
}
for _, secret := range []string{rssPrivate, htmlPrivate, "no candidate article"} {
if strings.Contains(logs, secret) {
t.Errorf("WatcherGuru diagnostics leaked response/article content %q", secret)
}
}
}

View File

@ -4,7 +4,6 @@ import (
"context"
"encoding/xml"
"fmt"
"io"
"net/http"
"strings"
"time"
@ -45,7 +44,6 @@ func (w *WatcherGuru) Scrape(ctx context.Context, _ []string) ([]scraper.Article
} {
articles, err := w.fetchRSS(ctx, feedURL)
if err == nil && len(articles) > 0 {
fmt.Printf("watcherguru rss: %d articles\n", len(articles))
return articles, nil
}
}
@ -55,11 +53,24 @@ func (w *WatcherGuru) Scrape(ctx context.Context, _ []string) ([]scraper.Article
if err != nil {
return nil, fmt.Errorf("watcherguru: %w", err)
}
fmt.Printf("watcherguru html: %d articles\n", len(articles))
return articles, nil
}
func (w *WatcherGuru) fetchRSS(ctx context.Context, feedURL string) ([]scraper.Article, error) {
func (w *WatcherGuru) fetchRSS(ctx context.Context, feedURL string) (articles []scraper.Article, resultErr error) {
status := 0
feedLabel := "unknown"
if feedURL == baseURL+"/feed/" {
feedLabel = "/feed/"
} else if feedURL == baseURL+"/news/feed/" {
feedLabel = "/news/feed/"
}
defer func() {
outcome := "ok"
if resultErr != nil {
outcome = "failed"
}
fmt.Printf("watcherguru rss feed=%s status=%d articles=%d outcome=%s\n", feedLabel, status, len(articles), outcome)
}()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, feedURL, nil)
if err != nil {
return nil, err
@ -72,6 +83,7 @@ func (w *WatcherGuru) fetchRSS(ctx context.Context, feedURL string) ([]scraper.A
}
defer resp.Body.Close()
status = resp.StatusCode
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("HTTP %d", resp.StatusCode)
}
@ -81,7 +93,6 @@ func (w *WatcherGuru) fetchRSS(ctx context.Context, feedURL string) ([]scraper.A
return nil, fmt.Errorf("parse RSS: %w", err)
}
var articles []scraper.Article
for _, item := range feed.Channel.Items {
title := strings.TrimSpace(item.Title)
link := strings.TrimSpace(item.Link)
@ -109,7 +120,15 @@ func (w *WatcherGuru) fetchRSS(ctx context.Context, feedURL string) ([]scraper.A
return articles, nil
}
func (w *WatcherGuru) scrapeHTML(ctx context.Context) ([]scraper.Article, error) {
func (w *WatcherGuru) scrapeHTML(ctx context.Context) (articles []scraper.Article, resultErr error) {
status := 0
defer func() {
outcome := "ok"
if resultErr != nil {
outcome = "failed"
}
fmt.Printf("watcherguru html status=%d articles=%d outcome=%s\n", status, len(articles), outcome)
}()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, baseURL+"/news/", nil)
if err != nil {
return nil, err
@ -123,9 +142,9 @@ func (w *WatcherGuru) scrapeHTML(ctx context.Context) ([]scraper.Article, error)
}
defer resp.Body.Close()
status = resp.StatusCode
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
return nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, body)
return nil, fmt.Errorf("HTTP %d", resp.StatusCode)
}
doc, err := html.Parse(resp.Body)
@ -133,7 +152,6 @@ func (w *WatcherGuru) scrapeHTML(ctx context.Context) ([]scraper.Article, error)
return nil, fmt.Errorf("parse HTML: %w", err)
}
var articles []scraper.Article
seen := make(map[string]bool)
now := time.Now()

View File

@ -0,0 +1,99 @@
package yahoofinance
import (
"context"
"fmt"
"io"
"net/http"
"os"
"reflect"
"strings"
"testing"
)
type ticket20RoundTrip func(*http.Request) (*http.Response, error)
func (f ticket20RoundTrip) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
func ticket20CaptureStdout(t *testing.T, run func()) string {
t.Helper()
reader, writer, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
previous := os.Stdout
os.Stdout = writer
defer func() { os.Stdout = previous }()
run()
if err := writer.Close(); err != nil {
t.Fatal(err)
}
data, err := io.ReadAll(reader)
_ = reader.Close()
if err != nil {
t.Fatal(err)
}
return string(data)
}
func TestTicket20Yahoo400DiagnosticConnectsSymbolsStatusAndCountWithoutResponseBody(t *testing.T) {
const privateHTML = `<html><title>PRIVATE_YAHOO_RESPONSE_DO_NOT_LOG</title><article>PRIVATE_ARTICLE_BODY_DO_NOT_LOG</article></html>`
var requested string
yahoo := &YahooFinance{client: &http.Client{Transport: ticket20RoundTrip(func(r *http.Request) (*http.Response, error) {
requested = r.URL.Query().Get("s")
return &http.Response{StatusCode: http.StatusBadRequest, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(privateHTML)), Request: r}, nil
})}}
var articles int
logs := ticket20CaptureStdout(t, func() {
got, err := yahoo.Scrape(context.Background(), []string{"SSAAPL INDEX"})
if err != nil {
t.Fatalf("Scrape returned error: %v", err)
}
articles = len(got)
})
if requested != "SSAAPL INDEX" {
t.Fatalf("fake Yahoo request symbol=%q, want SSAAPL INDEX reproduction", requested)
}
for _, diagnostic := range []string{"symbol=SSAAPL INDEX", "yahoo_symbol=SSAAPL INDEX", "status=400", "articles=0"} {
if !strings.Contains(logs, diagnostic) {
t.Errorf("Yahoo diagnostic lacks %q: %q", diagnostic, logs)
}
}
if articles != 0 {
t.Errorf("articles=%d, want 0", articles)
}
for _, secret := range []string{"PRIVATE_YAHOO_RESPONSE_DO_NOT_LOG", "PRIVATE_ARTICLE_BODY_DO_NOT_LOG", privateHTML} {
if strings.Contains(logs, secret) {
t.Errorf("Yahoo diagnostics leaked response/article content %q", secret)
}
}
}
func TestTicket19YahooReceivesOnlySelectedFinanceDatabaseYahooSymbols(t *testing.T) {
// Yahoo must receive the runtime-selected primary listings. The raw fixture
// still contains BIDU and 1211.HK, but FinanceDatabase selects 9888.HK and
// 002594.SZ for those companies at the pinned upstream snapshot.
want := []string{"NVDA", "AAPL", "9888.HK", "002594.SZ", "0285.HK"}
var requested []string
yahoo := &YahooFinance{client: &http.Client{Transport: ticket20RoundTrip(func(r *http.Request) (*http.Response, error) {
symbol := r.URL.Query().Get("s")
requested = append(requested, symbol)
body := fmt.Sprintf(`<rss><channel><item><title>Fixture %s</title><link>https://fixture.invalid/%s</link><description>synthetic only</description></item></channel></rss>`, symbol, symbol)
return &http.Response{StatusCode: http.StatusOK, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(body)), Request: r}, nil
})}}
articles, err := yahoo.Scrape(context.Background(), want)
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(requested, want) {
t.Fatalf("Yahoo symbols=%v, want selected Yahoo tickers %v", requested, want)
}
if len(articles) != len(want) {
t.Fatalf("articles=%d, want one fixture article per symbol", len(articles))
}
for i, symbol := range want {
if len(articles[i].Symbols) != 1 || articles[i].Symbols[0] != symbol {
t.Errorf("article %d symbols=%v, want %q", i, articles[i].Symbols, symbol)
}
}
}

View File

@ -4,7 +4,6 @@ import (
"context"
"encoding/xml"
"fmt"
"io"
"net/http"
"strings"
"time"
@ -49,16 +48,31 @@ func (y *YahooFinance) Scrape(ctx context.Context, symbols []string) ([]scraper.
}
items, err := y.fetchSymbol(ctx, symbol)
if err != nil {
fmt.Printf("yahoofinance %s: %v\n", symbol, err)
continue
}
articles = append(articles, items...)
fmt.Printf("yahoofinance %s: %d articles fetched\n", symbol, len(items))
}
return articles, nil
}
func (y *YahooFinance) fetchSymbol(ctx context.Context, symbol string) ([]scraper.Article, error) {
func (y *YahooFinance) fetchSymbol(ctx context.Context, symbol string) (articles []scraper.Article, resultErr error) {
status := 0
defer func() {
outcome := "ok"
if resultErr != nil {
outcome = "failed"
}
safeSymbol := strings.Map(func(r rune) rune {
if r >= 'A' && r <= 'Z' || r >= 'a' && r <= 'z' || r >= '0' && r <= '9' || strings.ContainsRune(" .-^=", r) {
return r
}
return '_'
}, symbol)
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)
}()
url := fmt.Sprintf(
"https://feeds.finance.yahoo.com/rss/2.0/headline?s=%s&region=US&lang=en-US",
symbol,
@ -76,9 +90,9 @@ func (y *YahooFinance) fetchSymbol(ctx context.Context, symbol string) ([]scrape
}
defer resp.Body.Close()
status = resp.StatusCode
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
return nil, fmt.Errorf("HTTP %d: %s", resp.StatusCode, string(body))
return nil, fmt.Errorf("HTTP %d", resp.StatusCode)
}
var feed rssFeed
@ -87,8 +101,6 @@ func (y *YahooFinance) fetchSymbol(ctx context.Context, symbol string) ([]scrape
}
const maxPerSymbol = 5
var articles []scraper.Article
for _, item := range feed.Channel.Items {
if len(articles) >= maxPerSymbol {
break