feat(sources): replace WatcherGuru with CNBC Business
Add the CNBC Business RSS source, switch supported-source wiring and reporting, and migrate existing WatcherGuru rows to disabled historical status without rewriting references. Refs #23 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@ -13,7 +13,7 @@ import (
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
"github.com/tradarr/backend/internal/scraper/bloomberg"
|
||||
"github.com/tradarr/backend/internal/scraper/watcherguru"
|
||||
"github.com/tradarr/backend/internal/scraper/cnbcbusiness"
|
||||
"github.com/tradarr/backend/internal/scraper/yahoofinance"
|
||||
"github.com/tradarr/backend/internal/server"
|
||||
)
|
||||
@ -52,7 +52,7 @@ func main() {
|
||||
feeds := map[string]scraper.Scraper{
|
||||
models.SourceBloomberg: bloomberg.NewDynamic(repo, enc, cfg.ScraperURL),
|
||||
models.SourceYahooFinance: yahoofinance.New(),
|
||||
models.SourceWatcherGuru: watcherguru.New(),
|
||||
models.SourceCNBCBusiness: cnbcbusiness.New(),
|
||||
}
|
||||
|
||||
app := server.New(repo, cfg, server.Dependencies{CompanyCatalog: catalog, LayaRanker: laya, Feeds: feeds, IndexSearcher: openfigi.New(openfigi.Config{APIKey: cfg.OpenFIGIAPIKey, Timeout: cfg.OpenFIGITimeout}, nil), EnableScheduler: true})
|
||||
|
||||
@ -0,0 +1,3 @@
|
||||
-- Non-destructive retirement on downgrade: retain CNBC identity/history and
|
||||
-- permissive historical constraint values. Never auto-reactivate WatcherGuru.
|
||||
UPDATE sources SET enabled=false WHERE source_key='cnbc_business';
|
||||
@ -0,0 +1,16 @@
|
||||
-- Atomic even when executed as a standalone statement. Preserve retired source
|
||||
-- IDs, source keys, caps and all referencing history; never repurpose a row.
|
||||
DO $migration$
|
||||
BEGIN
|
||||
LOCK TABLE sources IN ACCESS EXCLUSIVE MODE;
|
||||
ALTER TABLE sources DROP CONSTRAINT sources_type_check;
|
||||
ALTER TABLE sources ADD CONSTRAINT sources_type_check
|
||||
CHECK (type IN ('bloomberg','stocktwits','reuters','watcherguru','cnbc_business'));
|
||||
ALTER TABLE sources DROP CONSTRAINT sources_source_key_check;
|
||||
ALTER TABLE sources ADD CONSTRAINT sources_source_key_check
|
||||
CHECK (source_key IN ('yahoo_finance','bloomberg','watcher_guru','cnbc_business'));
|
||||
UPDATE sources SET enabled=false WHERE source_key='watcher_guru';
|
||||
INSERT INTO sources(id,name,type,enabled,article_limit,source_key)
|
||||
VALUES(gen_random_uuid(),'CNBC Business','cnbc_business',true,20,'cnbc_business');
|
||||
END
|
||||
$migration$;
|
||||
104
backend/internal/database/migrations/cnbc_business_test.go
Normal file
104
backend/internal/database/migrations/cnbc_business_test.go
Normal file
@ -0,0 +1,104 @@
|
||||
package migrations
|
||||
|
||||
import (
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCNBCMigrationRetainsWatcherIdentityAndHistoricalReferencesPostgres(t *testing.T) {
|
||||
db, cleanup := ticket13Database(t)
|
||||
defer cleanup()
|
||||
for _, q := range []string{
|
||||
`ALTER TABLE sources ADD CONSTRAINT sources_type_check CHECK(type IN ('bloomberg','stocktwits','reuters','watcherguru'))`,
|
||||
`INSERT INTO sources(id,name,type,enabled,article_limit) VALUES('y','Yahoo Finance','stocktwits',true,83),('b','Bloomberg','bloomberg',false,77),('w','Watcher.Guru','watcherguru',true,64)`,
|
||||
`INSERT INTO articles(id,source_id,title,url) VALUES('old-article','w','historic','https://fixture.invalid/history')`,
|
||||
} {
|
||||
if _, err := db.Exec(q); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
applyTicket13(t, db)
|
||||
migration, err := os.ReadFile("000018_cnbc_business.up.sql")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.Exec(string(migration)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var name, typ, key string
|
||||
var enabled bool
|
||||
var cap int
|
||||
if err = db.QueryRow(`SELECT name,type,source_key,enabled,article_limit FROM sources WHERE id='w'`).Scan(&name, &typ, &key, &enabled, &cap); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if name != "Watcher.Guru" || typ != "watcherguru" || key != "watcher_guru" || enabled || cap != 64 {
|
||||
t.Fatal("Watcher identity/cap changed or still enabled")
|
||||
}
|
||||
var cnbcID string
|
||||
if err = db.QueryRow(`SELECT id,enabled,article_limit FROM sources WHERE source_key='cnbc_business'`).Scan(&cnbcID, &enabled, &cap); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cnbcID == "w" || !regexp.MustCompile(`^[0-9a-f-]{36}$`).MatchString(cnbcID) || !enabled || cap != 20 {
|
||||
t.Fatalf("new identity=%s enabled=%v cap=%d", cnbcID, enabled, cap)
|
||||
}
|
||||
var source string
|
||||
if err = db.QueryRow(`SELECT source_id FROM articles WHERE id='old-article'`).Scan(&source); err != nil || source != "w" {
|
||||
t.Fatalf("historical reference=%s err=%v", source, err)
|
||||
}
|
||||
if _, err = db.Exec(`UPDATE sources SET source_key='watcher_guru' WHERE id='w'`); err != nil {
|
||||
t.Fatalf("legacy key no longer permitted by constraint: %v", err)
|
||||
}
|
||||
if _, err = db.Exec(`UPDATE sources SET source_key='unsupported' WHERE id='w'`); err == nil {
|
||||
t.Fatal("unknown key accepted")
|
||||
}
|
||||
if _, err = db.Exec(`UPDATE sources SET type='unsupported' WHERE id='w'`); err == nil {
|
||||
t.Fatal("unknown type accepted")
|
||||
}
|
||||
var count int
|
||||
if err = db.QueryRow(`SELECT count(*) FROM sources`).Scan(&count); err != nil || count != 4 {
|
||||
t.Fatalf("unexpected source count=%d %v", count, err)
|
||||
}
|
||||
var yahooCap, bloombergCap int
|
||||
if err = db.QueryRow(`SELECT article_limit FROM sources WHERE id='y'`).Scan(&yahooCap); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = db.QueryRow(`SELECT article_limit FROM sources WHERE id='b'`).Scan(&bloombergCap); err != nil || yahooCap != 83 || bloombergCap != 77 {
|
||||
t.Fatal("other caps changed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCNBCMigrationFailureRollsBackWatcherAndConstraintChangesPostgres(t *testing.T) {
|
||||
db, cleanup := ticket13Database(t)
|
||||
defer cleanup()
|
||||
for _, q := range []string{
|
||||
`ALTER TABLE sources ADD CONSTRAINT sources_type_check CHECK(type IN ('bloomberg','stocktwits','reuters','watcherguru'))`,
|
||||
`INSERT INTO sources(id,name,type,enabled,article_limit) VALUES('y','Yahoo Finance','stocktwits',true,83),('b','Bloomberg','bloomberg',false,77),('w','Watcher.Guru','watcherguru',true,64)`,
|
||||
`ALTER TABLE sources ADD CONSTRAINT fixture_refuse_cnbc CHECK(name <> 'CNBC Business')`,
|
||||
} {
|
||||
if _, err := db.Exec(q); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
applyTicket13(t, db)
|
||||
migration, err := os.ReadFile("000018_cnbc_business.up.sql")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.Exec(string(migration)); err == nil {
|
||||
t.Fatal("expected insert failure")
|
||||
}
|
||||
var enabled bool
|
||||
var count int
|
||||
var constraint string
|
||||
if err = db.QueryRow(`SELECT enabled FROM sources WHERE id='w'`).Scan(&enabled); err != nil || !enabled {
|
||||
t.Fatal("failed migration disabled WatcherGuru")
|
||||
}
|
||||
if err = db.QueryRow(`SELECT count(*) FROM sources`).Scan(&count); err != nil || count != 3 {
|
||||
t.Fatal("failed migration changed source rows")
|
||||
}
|
||||
if err = db.QueryRow(`SELECT pg_get_constraintdef(oid) FROM pg_constraint WHERE conrelid='sources'::regclass AND conname='sources_source_key_check'`).Scan(&constraint); err != nil || strings.Contains(constraint, "cnbc_business") {
|
||||
t.Fatal("failed migration changed source key constraint")
|
||||
}
|
||||
}
|
||||
@ -29,18 +29,18 @@ func (f *symbolFeed) Scrape(_ context.Context, s []string) ([]scraper.Article, e
|
||||
}
|
||||
|
||||
func TestPerSourceCompanyHintsDoNotChangeOtherFeeds(t *testing.T) {
|
||||
yahoo, bloomberg, watcher := &symbolFeed{}, &symbolFeed{}, &symbolFeed{}
|
||||
yahoo, bloomberg, cnbc, watcher := &symbolFeed{}, &symbolFeed{}, &symbolFeed{}, &symbolFeed{}
|
||||
input := UserInput{Language: "fr", RankingMode: "title", GlobalLimit: 20, Assets: []models.UserAsset{{CompanyID: pointer("isin:company"), Name: "Company", Symbol: "HISTORIC INDEX", YahooSymbol: pointer("9888.HK")}}}
|
||||
for _, key := range []string{models.SourceYahooFinance, models.SourceBloomberg, models.SourceWatcherGuru} {
|
||||
for _, key := range []string{models.SourceYahooFinance, models.SourceBloomberg, models.SourceCNBCBusiness, models.SourceWatcherGuru} {
|
||||
key := key
|
||||
input.Sources = append(input.Sources, models.Source{ID: key, SourceKey: &key, Enabled: true, ArticleLimit: 20})
|
||||
}
|
||||
repo := &contractRepository{inputs: map[string]UserInput{"owner": input}, saved: map[string][]GenerationRecord{}}
|
||||
uc := NewUseCase(Dependencies{Repository: repo, LayaRanker: &contractRanker{}, Summarizer: &contractSummarizer{}, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: yahoo, models.SourceBloomberg: bloomberg, models.SourceWatcherGuru: watcher}})
|
||||
uc := NewUseCase(Dependencies{Repository: repo, LayaRanker: &contractRanker{}, Summarizer: &contractSummarizer{}, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: yahoo, models.SourceBloomberg: bloomberg, models.SourceCNBCBusiness: cnbc, models.SourceWatcherGuru: watcher}})
|
||||
if _, err := uc.Generate(context.Background(), "owner"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(yahoo.symbols, []string{"9888.HK"}) || !reflect.DeepEqual(bloomberg.symbols, []string{"HISTORIC INDEX"}) || !reflect.DeepEqual(watcher.symbols, bloomberg.symbols) {
|
||||
if !reflect.DeepEqual(yahoo.symbols, []string{"9888.HK"}) || !reflect.DeepEqual(bloomberg.symbols, []string{"HISTORIC INDEX"}) || !reflect.DeepEqual(cnbc.symbols, bloomberg.symbols) || watcher.symbols != nil {
|
||||
t.Fatalf("Yahoo=%v Bloomberg=%v Watcher=%v", yahoo.symbols, bloomberg.symbols, watcher.symbols)
|
||||
}
|
||||
}
|
||||
|
||||
@ -14,6 +14,7 @@ func TestGenerationRoutesOnlyAllowlistedSourceKeysEvenWhenLegacyRowsAreEnabled(t
|
||||
if err := json.Unmarshal([]byte(`[
|
||||
{"id":"y","name":"Yahoo Finance","type":"stocktwits","source_key":"yahoo_finance","enabled":true,"article_limit":20},
|
||||
{"id":"b","name":"Bloomberg","type":"bloomberg","source_key":"bloomberg","enabled":true,"article_limit":20},
|
||||
{"id":"c","name":"CNBC Business","type":"cnbc_business","source_key":"cnbc_business","enabled":true,"article_limit":20},
|
||||
{"id":"w","name":"Watcher.Guru","type":"watcherguru","source_key":"watcher_guru","enabled":true,"article_limit":20},
|
||||
{"id":"s","name":"StockTwits","type":"stocktwits","source_key":null,"enabled":true,"article_limit":20},
|
||||
{"id":"r","name":"Reuters","type":"reuters","source_key":null,"enabled":true,"article_limit":20}
|
||||
@ -22,7 +23,7 @@ func TestGenerationRoutesOnlyAllowlistedSourceKeysEvenWhenLegacyRowsAreEnabled(t
|
||||
}
|
||||
repo := &contractRepository{inputs: map[string]UserInput{"user": {Language: "fr", RankingMode: "title", GlobalLimit: 10, Assets: []models.UserAsset{{Symbol: "SPX"}}, Sources: sources}}, saved: map[string][]GenerationRecord{}}
|
||||
feeds := map[string]*contractScraper{}
|
||||
for _, key := range []string{"yahoo_finance", "bloomberg", "watcher_guru", "stocktwits", "reuters"} {
|
||||
for _, key := range []string{"yahoo_finance", "bloomberg", "cnbc_business", "watcher_guru", "stocktwits", "reuters"} {
|
||||
feeds[key] = &contractScraper{name: key, articles: []scraper.Article{{Title: key}}}
|
||||
}
|
||||
scrapers := map[string]scraper.Scraper{}
|
||||
@ -33,12 +34,12 @@ func TestGenerationRoutesOnlyAllowlistedSourceKeysEvenWhenLegacyRowsAreEnabled(t
|
||||
if err != nil || result.Summary == nil {
|
||||
t.Fatalf("generation result=%+v err=%v", result, err)
|
||||
}
|
||||
for _, key := range []string{"yahoo_finance", "bloomberg", "watcher_guru"} {
|
||||
for _, key := range []string{"yahoo_finance", "bloomberg", "cnbc_business"} {
|
||||
if len(feeds[key].calls) != 1 {
|
||||
t.Errorf("target %s calls=%d, want one", key, len(feeds[key].calls))
|
||||
}
|
||||
}
|
||||
for _, key := range []string{"stocktwits", "reuters"} {
|
||||
for _, key := range []string{"watcher_guru", "stocktwits", "reuters"} {
|
||||
if len(feeds[key].calls) != 0 {
|
||||
t.Errorf("unsupported enabled source %s was invoked %d times", key, len(feeds[key].calls))
|
||||
}
|
||||
|
||||
@ -149,7 +149,7 @@ func (r *Repository) ListSources() ([]Source, error) {
|
||||
func (r *Repository) GetSourceByType(sourceType string) (*Source, error) {
|
||||
s := &Source{}
|
||||
err := r.db.QueryRow(`
|
||||
SELECT id, name, type, enabled, created_at, article_limit, source_key FROM sources WHERE type=$1 AND source_key IN ('yahoo_finance','bloomberg','watcher_guru')`, sourceType,
|
||||
SELECT id, name, type, enabled, created_at, article_limit, source_key FROM sources WHERE type=$1 AND source_key IN ('yahoo_finance','bloomberg','cnbc_business')`, sourceType,
|
||||
).Scan(&s.ID, &s.Name, &s.Type, &s.Enabled, &s.CreatedAt, &s.ArticleLimit, &s.SourceKey)
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, nil
|
||||
|
||||
@ -3,12 +3,13 @@ package models
|
||||
const (
|
||||
SourceYahooFinance = "yahoo_finance"
|
||||
SourceBloomberg = "bloomberg"
|
||||
SourceWatcherGuru = "watcher_guru"
|
||||
SourceWatcherGuru = "watcher_guru" // Historical identity; no longer executable.
|
||||
SourceCNBCBusiness = "cnbc_business"
|
||||
)
|
||||
|
||||
func SupportedSourceKey(key string) bool {
|
||||
switch key {
|
||||
case SourceYahooFinance, SourceBloomberg, SourceWatcherGuru:
|
||||
case SourceYahooFinance, SourceBloomberg, SourceCNBCBusiness:
|
||||
return true
|
||||
}
|
||||
return false
|
||||
|
||||
@ -22,3 +22,18 @@ func TestSourceSupportUsesOnlyCanonicalKeyAndPersistedEnabled(t *testing.T) {
|
||||
t.Fatal("disabled target support/operational mismatch")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCNBCReplacesWatcherGuruWithoutAliasingHistoricalIdentity(t *testing.T) {
|
||||
cnbc, watcher := SourceCNBCBusiness, SourceWatcherGuru
|
||||
sources := []Source{{ID: "new-cnbc", SourceKey: &cnbc, Enabled: true, ArticleLimit: 37}, {ID: "old-watcher", SourceKey: &watcher, Enabled: true, ArticleLimit: 64}}
|
||||
if !sources[0].Supported() || sources[1].Supported() || sources[1].Operational() {
|
||||
t.Fatal("retired WatcherGuru remains executable or CNBC unsupported")
|
||||
}
|
||||
operational := OperationalSources(sources)
|
||||
if len(operational) != 1 || operational[0].ID != "new-cnbc" || operational[0].ArticleLimit != 37 {
|
||||
t.Fatalf("operational=%+v", operational)
|
||||
}
|
||||
if *sources[1].SourceKey != "watcher_guru" || sources[1].ArticleLimit != 64 {
|
||||
t.Fatal("historical identity or cap mutated")
|
||||
}
|
||||
}
|
||||
|
||||
@ -46,14 +46,15 @@ func TestScheduledGenerationUsesSameThreeSourceAllowlistForEnabledLegacyRows(t *
|
||||
if err := json.Unmarshal([]byte(`[
|
||||
{"id":"y","type":"stocktwits","source_key":"yahoo_finance","enabled":true,"article_limit":10},
|
||||
{"id":"b","type":"bloomberg","source_key":"bloomberg","enabled":true,"article_limit":10},
|
||||
{"id":"w","type":"watcherguru","source_key":"watcher_guru","enabled":true,"article_limit":10},
|
||||
{"id":"c","name":"CNBC Business","type":"cnbc_business","source_key":"cnbc_business","enabled":true,"article_limit":20},
|
||||
{"id":"w","type":"watcherguru","source_key":"watcher_guru","enabled":true,"article_limit":10},
|
||||
{"id":"s","name":"StockTwits","type":"stocktwits","source_key":null,"enabled":true,"article_limit":10},
|
||||
{"id":"r","name":"Reuters","type":"reuters","source_key":null,"enabled":true,"article_limit":10}]`), &sources); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
feeds := map[string]*ticket13Feed{}
|
||||
scrapers := map[string]scraper.Scraper{}
|
||||
for _, key := range []string{"yahoo_finance", "bloomberg", "watcher_guru", "stocktwits", "reuters"} {
|
||||
for _, key := range []string{"yahoo_finance", "bloomberg", "cnbc_business", "watcher_guru", "stocktwits", "reuters"} {
|
||||
f := &ticket13Feed{}
|
||||
feeds[key] = f
|
||||
scrapers[key] = f
|
||||
@ -61,12 +62,12 @@ func TestScheduledGenerationUsesSameThreeSourceAllowlistForEnabledLegacyRows(t *
|
||||
uc := generation.NewUseCase(generation.Dependencies{Repository: ticket13Repository{generation.UserInput{Language: "fr", RankingMode: "title", GlobalLimit: 10, Assets: []models.UserAsset{{Symbol: "SPX"}}, Sources: sources}}, Scrapers: scrapers, Ranker: ticket13Ranker{}, Summarizer: ticket13Summary{}})
|
||||
s := &Scheduler{users: ticket13Users{}, generationUseCase: uc}
|
||||
s.run()
|
||||
for _, key := range []string{"yahoo_finance", "bloomberg", "watcher_guru"} {
|
||||
for _, key := range []string{"yahoo_finance", "bloomberg", "cnbc_business"} {
|
||||
if feeds[key].calls != 1 {
|
||||
t.Errorf("scheduled supported source %s calls=%d, want 1", key, feeds[key].calls)
|
||||
}
|
||||
}
|
||||
for _, key := range []string{"stocktwits", "reuters"} {
|
||||
for _, key := range []string{"watcher_guru", "stocktwits", "reuters"} {
|
||||
if feeds[key].calls != 0 {
|
||||
t.Errorf("scheduled legacy source %s was called %d times", key, feeds[key].calls)
|
||||
}
|
||||
|
||||
166
backend/internal/scraper/cnbcbusiness/cnbcbusiness.go
Normal file
166
backend/internal/scraper/cnbcbusiness/cnbcbusiness.go
Normal file
@ -0,0 +1,166 @@
|
||||
// Package cnbcbusiness reads only CNBC's configured Business RSS feed.
|
||||
// Article URLs are returned as metadata and are never fetched.
|
||||
package cnbcbusiness
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
"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 }
|
||||
|
||||
func New() *CNBCBusiness {
|
||||
return &CNBCBusiness{client: &http.Client{Timeout: 15 * time.Second, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}}
|
||||
}
|
||||
func (*CNBCBusiness) Name() string { return "cnbc_business" }
|
||||
|
||||
type rssItem struct {
|
||||
Title string `xml:"title"`
|
||||
Link string `xml:"link"`
|
||||
Description string `xml:"description"`
|
||||
PubDate string `xml:"pubDate"`
|
||||
}
|
||||
type rssChannel struct {
|
||||
Items []rssItem `xml:"item"`
|
||||
}
|
||||
type rssFeed struct {
|
||||
XMLName xml.Name `xml:"rss"`
|
||||
Channel *rssChannel `xml:"channel"`
|
||||
}
|
||||
|
||||
func (c *CNBCBusiness) Scrape(ctx context.Context, _ []string) (articles []scraper.Article, resultErr error) {
|
||||
status := 0
|
||||
cause := "none"
|
||||
defer func() {
|
||||
outcome := "ok"
|
||||
if resultErr != nil {
|
||||
outcome = "failed"
|
||||
}
|
||||
log.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 {
|
||||
cause = "request"
|
||||
return nil, errors.New("cnbc_business: request failed")
|
||||
}
|
||||
req.Header.Set("User-Agent", "Tradarr/1.0")
|
||||
req.Header.Set("Accept", "application/rss+xml, application/xml, text/xml")
|
||||
response, err := c.client.Do(req)
|
||||
if err != nil {
|
||||
cause = "transport"
|
||||
if ctx.Err() != nil {
|
||||
cause = "canceled_or_timeout"
|
||||
}
|
||||
return nil, errors.New("cnbc_business: transport or timeout failure")
|
||||
}
|
||||
defer response.Body.Close()
|
||||
status = response.StatusCode
|
||||
if status != http.StatusOK {
|
||||
cause = "http_status"
|
||||
return nil, errors.New("cnbc_business: unexpected HTTP status")
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(response.Body, maxFeedBytes+1))
|
||||
if err != nil {
|
||||
cause = "read"
|
||||
return nil, errors.New("cnbc_business: feed read failed")
|
||||
}
|
||||
if len(body) > maxFeedBytes {
|
||||
cause = "too_large"
|
||||
return nil, errors.New("cnbc_business: feed exceeds size limit")
|
||||
}
|
||||
decoder := xml.NewDecoder(bytes.NewReader(body))
|
||||
var feed rssFeed
|
||||
if decoder.Decode(&feed) != nil || feed.Channel == nil {
|
||||
cause = "parse"
|
||||
return nil, errors.New("cnbc_business: invalid RSS feed")
|
||||
}
|
||||
// Allow trailing XML whitespace/comments, but never a second document or text.
|
||||
for {
|
||||
token, err := decoder.Token()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
cause = "parse"
|
||||
return nil, errors.New("cnbc_business: invalid RSS framing")
|
||||
}
|
||||
switch value := token.(type) {
|
||||
case xml.CharData:
|
||||
if strings.TrimSpace(string(value)) == "" {
|
||||
continue
|
||||
}
|
||||
case xml.Comment:
|
||||
continue
|
||||
}
|
||||
cause = "parse"
|
||||
return nil, errors.New("cnbc_business: invalid RSS framing")
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
articles = make([]scraper.Article, 0, len(feed.Channel.Items))
|
||||
for _, item := range feed.Channel.Items {
|
||||
title := plainText(item.Title)
|
||||
link, err := url.Parse(strings.TrimSpace(item.Link))
|
||||
if title == "" || err != nil || link.Host == "" || link.User != nil || (link.Scheme != "https" && link.Scheme != "http") {
|
||||
continue
|
||||
}
|
||||
link.Fragment = ""
|
||||
canonical := link.String()
|
||||
if seen[canonical] {
|
||||
continue
|
||||
}
|
||||
seen[canonical] = true
|
||||
var published *time.Time
|
||||
for _, format := range []string{time.RFC1123Z, time.RFC1123, "Mon, 02 Jan 2006 15:04:05 -0700", time.RFC3339} {
|
||||
if parsed, err := time.Parse(format, strings.TrimSpace(item.PubDate)); err == nil {
|
||||
published = &parsed
|
||||
break
|
||||
}
|
||||
}
|
||||
articles = append(articles, scraper.Article{Title: title, URL: canonical, Content: plainText(item.Description), PublishedAt: published})
|
||||
}
|
||||
return articles, nil
|
||||
}
|
||||
|
||||
// Parse description markup locally. Scripts/styles and comments are not evidence;
|
||||
// no missing description, date or article body is fabricated.
|
||||
func plainText(value string) string {
|
||||
document, err := html.Parse(strings.NewReader(value))
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
var text strings.Builder
|
||||
var walk func(*html.Node)
|
||||
walk = func(node *html.Node) {
|
||||
if node.Type == html.ElementNode && (node.Data == "script" || node.Data == "style") {
|
||||
return
|
||||
}
|
||||
if node.Type == html.TextNode {
|
||||
text.WriteString(node.Data)
|
||||
}
|
||||
if node.Type == html.ElementNode && (node.Data == "p" || node.Data == "div" || node.Data == "br" || node.Data == "li") {
|
||||
text.WriteByte(' ')
|
||||
}
|
||||
for child := node.FirstChild; child != nil; child = child.NextSibling {
|
||||
walk(child)
|
||||
}
|
||||
if node.Type == html.ElementNode && (node.Data == "p" || node.Data == "div" || node.Data == "li") {
|
||||
text.WriteByte(' ')
|
||||
}
|
||||
}
|
||||
walk(document)
|
||||
return strings.Join(strings.Fields(text.String()), " ")
|
||||
}
|
||||
105
backend/internal/scraper/cnbcbusiness/cnbcbusiness_test.go
Normal file
105
backend/internal/scraper/cnbcbusiness/cnbcbusiness_test.go
Normal file
@ -0,0 +1,105 @@
|
||||
package cnbcbusiness
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type fakeTransport func(*http.Request) (*http.Response, error)
|
||||
|
||||
func (f fakeTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
|
||||
func TestCNBCBusinessRSSMapsMetadataWithoutArticleRequests(t *testing.T) {
|
||||
calls := 0
|
||||
feed := &CNBCBusiness{client: &http.Client{Transport: fakeTransport(func(r *http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
if r.Method != "GET" || r.URL.String() != "https://www.cnbc.com/id/10001147/device/rss/rss.html" {
|
||||
t.Fatalf("unexpected request %s %s", r.Method, r.URL)
|
||||
}
|
||||
body := `<rss version="2.0"><channel><item><title> Business & markets </title><link>https://www.cnbc.com/fixture.html</link><description><![CDATA[<p>Available <b>RSS</b> evidence.</p><script>PRIVATE_SCRIPT</script>]]></description><pubDate>Mon, 02 Jan 2006 15:04:05 -0700</pubDate></item><item><title>Duplicate</title><link>https://www.cnbc.com/fixture.html</link></item><item><title>No description</title><link>https://www.cnbc.com/empty.html</link><pubDate>invalid</pubDate></item><item><title>Unsafe</title><link>javascript:alert(1)</link></item><item><title>Missing link</title></item></channel></rss>`
|
||||
return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(body)), Header: make(http.Header)}, nil
|
||||
})}}
|
||||
got, err := feed.Scrape(context.Background(), []string{"IGNORED"})
|
||||
if err != nil || len(got) != 2 || calls != 1 {
|
||||
t.Fatalf("articles=%+v calls=%d err=%v", got, calls, err)
|
||||
}
|
||||
if feed.Name() != "cnbc_business" || got[0].Title != "Business & markets" || got[0].Content != "Available RSS evidence." || got[0].PublishedAt == nil || got[0].PublishedAt.Year() != 2006 {
|
||||
t.Fatalf("mapping=%+v", got[0])
|
||||
}
|
||||
if got[1].Content != "" || got[1].PublishedAt != nil {
|
||||
t.Fatalf("invented missing data=%+v", got[1])
|
||||
}
|
||||
}
|
||||
func TestCNBCBusinessFailsSafelyAndLogsOnlyDiagnostics(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
status int
|
||||
body string
|
||||
}{
|
||||
{"http", 503, "PRIVATE_RESPONSE https://secret.invalid/?key=PRIVATE_SECRET"},
|
||||
{"malformed", 200, "<rss><PRIVATE_ARTICLE"}, {"html", 200, "<html>PRIVATE_TITLE</html>"},
|
||||
{"trailing", 200, "<rss><channel/></rss>PRIVATE_PROMPT"}, {"oversize", 200, strings.Repeat("x", 2*1024*1024+1)},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
var logs bytes.Buffer
|
||||
old := log.Writer()
|
||||
log.SetOutput(&logs)
|
||||
defer log.SetOutput(old)
|
||||
feed := &CNBCBusiness{client: &http.Client{Transport: fakeTransport(func(*http.Request) (*http.Response, error) {
|
||||
return &http.Response{StatusCode: tc.status, Body: io.NopCloser(strings.NewReader(tc.body)), Header: make(http.Header)}, nil
|
||||
})}}
|
||||
got, err := feed.Scrape(context.Background(), nil)
|
||||
if err == nil || len(got) != 0 {
|
||||
t.Fatalf("not fail-closed: %d %v", len(got), err)
|
||||
}
|
||||
if !strings.Contains(logs.String(), "cnbc_business") || !strings.Contains(logs.String(), "status=") || !strings.Contains(logs.String(), "articles=0") {
|
||||
t.Fatalf("missing diagnostics: %q", logs.String())
|
||||
}
|
||||
if strings.Contains(logs.String(), "PRIVATE_") || strings.Contains(logs.String(), "https://") || strings.Contains(err.Error(), "PRIVATE_") || strings.Contains(err.Error(), "https://") {
|
||||
t.Fatal("sensitive response leaked")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCNBCBusinessDoesNotFollowRedirectOrLeakTransportError(t *testing.T) {
|
||||
for _, redirect := range []bool{false, true} {
|
||||
var logs bytes.Buffer
|
||||
previous := log.Writer()
|
||||
log.SetOutput(&logs)
|
||||
feed := New()
|
||||
calls := 0
|
||||
feed.client.Transport = fakeTransport(func(r *http.Request) (*http.Response, error) {
|
||||
calls++
|
||||
if r.URL.String() != feedURL {
|
||||
t.Errorf("followed redirect to an article")
|
||||
}
|
||||
if !redirect {
|
||||
return nil, errors.New("PRIVATE_TRANSPORT https://private.invalid/article?key=secret")
|
||||
}
|
||||
return &http.Response{StatusCode: 302, Header: http.Header{"Location": []string{"https://private.invalid/article?key=secret"}}, Body: io.NopCloser(strings.NewReader("PRIVATE_RESPONSE"))}, nil
|
||||
})
|
||||
got, err := feed.Scrape(context.Background(), nil)
|
||||
log.SetOutput(previous)
|
||||
if err == nil || len(got) != 0 || calls != 1 {
|
||||
t.Fatalf("calls=%d err=%v", calls, err)
|
||||
}
|
||||
if strings.Contains(logs.String(), "PRIVATE_") || strings.Contains(logs.String(), "https://") || strings.Contains(err.Error(), "https://") {
|
||||
t.Fatal("transport/redirect data leaked")
|
||||
}
|
||||
}
|
||||
}
|
||||
func TestCNBCBusinessEmptyRSSIsNoResults(t *testing.T) {
|
||||
feed := &CNBCBusiness{client: &http.Client{Transport: fakeTransport(func(*http.Request) (*http.Response, error) {
|
||||
return &http.Response{StatusCode: 200, Header: make(http.Header), Body: io.NopCloser(strings.NewReader("<rss><channel/></rss>"))}, nil
|
||||
})}}
|
||||
got, err := feed.Scrape(context.Background(), nil)
|
||||
if err != nil || len(got) != 0 {
|
||||
t.Fatalf("empty RSS: %v %v", got, err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user