feat(sources): enforce supported source allowlist

Assign stable keys to the three supported sources, preserve excluded historical rows, and expose history read-only in admin. Add migration, coverage, and responsive browser spec.

Refs #13

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-11-21 00:11:26 +01:00
parent 4459a81206
commit ac17d27f51
26 changed files with 924 additions and 61 deletions

View File

@ -109,7 +109,7 @@ func run(ctx context.Context) error {
if err = server.EnsureAdmin(repo, cfg); err != nil {
return err
}
feeds := map[string]scraper.Scraper{"stocktwits": e2estack.FakeScraper{URL: fakeURL, Client: client}}
feeds := map[string]scraper.Scraper{models.SourceYahooFinance: e2estack.FakeScraper{URL: fakeURL, Client: client}}
provider := e2estack.FakeProvider{URL: fakeURL, Client: client}
gin.SetMode(gin.TestMode)
gin.DefaultWriter = io.Discard
@ -222,7 +222,7 @@ func seed(db *sql.DB, fakeURL string) error {
if _, err = tx.Exec(`UPDATE sources SET enabled=false`); err != nil {
return err
}
if _, err = tx.Exec(`INSERT INTO sources(id,name,type,enabled,article_limit) VALUES('00000000-0000-0000-0000-000000001201','E2E fixture','stocktwits',true,20)`); err != nil {
if _, err = tx.Exec(`UPDATE sources SET enabled=true WHERE source_key='yahoo_finance'`); err != nil {
return err
}
if _, err = tx.Exec(`INSERT INTO ai_providers(id,name,model,endpoint,is_active) VALUES('00000000-0000-0000-0000-000000001202','ollama','fake-laya',$1,true)`, fakeURL); err != nil {

View File

@ -11,7 +11,6 @@ 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/reuters"
"github.com/tradarr/backend/internal/scraper/watcherguru"
"github.com/tradarr/backend/internal/scraper/yahoofinance"
"github.com/tradarr/backend/internal/server"
@ -40,9 +39,10 @@ func main() {
log.Printf("ensure admin: %v", err)
}
feeds := map[string]scraper.Scraper{}
for _, feed := range []scraper.Scraper{bloomberg.NewDynamic(repo, enc, cfg.ScraperURL), yahoofinance.New(), reuters.New(), watcherguru.New()} {
feeds[feed.Name()] = feed
feeds := map[string]scraper.Scraper{
models.SourceBloomberg: bloomberg.NewDynamic(repo, enc, cfg.ScraperURL),
models.SourceYahooFinance: yahoofinance.New(),
models.SourceWatcherGuru: watcherguru.New(),
}
app := server.New(repo, cfg, server.Dependencies{Feeds: feeds, IndexSearcher: openfigi.New(openfigi.Config{APIKey: cfg.OpenFIGIAPIKey, Timeout: cfg.OpenFIGITimeout}, nil), EnableScheduler: true})

View File

@ -39,10 +39,10 @@ func TestArticleCapsMigrationAndInvalidAdminUpdatesAreAtomicPostgres(t *testing.
`CREATE TABLE users (id TEXT PRIMARY KEY,email TEXT,password_hash TEXT,role TEXT,created_at TIMESTAMPTZ DEFAULT NOW(),updated_at TIMESTAMPTZ DEFAULT NOW())`,
`INSERT INTO users(id,email,password_hash,role) VALUES ('admin-id','admin@example.test','hash','admin')`,
`CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT NOT NULL)`,
`CREATE TABLE sources (id UUID PRIMARY KEY, name TEXT NOT NULL, type TEXT NOT NULL, enabled BOOLEAN NOT NULL DEFAULT TRUE, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
`CREATE TABLE sources (id UUID PRIMARY KEY, name TEXT NOT NULL, type TEXT NOT NULL, source_key TEXT, enabled BOOLEAN NOT NULL DEFAULT TRUE, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
`CREATE TABLE scrape_schedules (id UUID PRIMARY KEY, day_of_week INT NOT NULL, hour INT NOT NULL, minute INT NOT NULL)`,
`INSERT INTO settings (key,value) VALUES ('summary_max_articles','733')`,
`INSERT INTO sources (id,name,type) VALUES ('00000000-0000-0000-0000-000000000001','Yahoo Finance','stocktwits')`,
`INSERT INTO sources (id,name,type,source_key) VALUES ('00000000-0000-0000-0000-000000000001','Yahoo Finance','stocktwits','yahoo_finance')`,
} {
if _, err = db.Exec(statement); err != nil {
t.Fatal(err)

View File

@ -0,0 +1,117 @@
package api_test
import (
"bytes"
"database/sql"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/lib/pq"
"github.com/tradarr/backend/internal/api"
"github.com/tradarr/backend/internal/api/handlers"
"github.com/tradarr/backend/internal/auth"
"github.com/tradarr/backend/internal/config"
"github.com/tradarr/backend/internal/models"
)
func TestAdminSourcesExposeSupportStateAndRejectHistoricalUpdateAtomicallyPostgres(t *testing.T) {
dbURL := postgresTestURL(t)
db, err := sql.Open("postgres", dbURL)
if err != nil {
t.Fatal(err)
}
db.SetMaxOpenConns(1)
schema := fmt.Sprintf("ticket13_admin_sources_%d", time.Now().UnixNano())
if _, err = db.Exec(`CREATE SCHEMA ` + pq.QuoteIdentifier(schema)); err != nil {
_ = db.Close()
t.Fatal(err)
}
if _, err = db.Exec(`SET search_path TO ` + pq.QuoteIdentifier(schema)); err != nil {
_, _ = db.Exec(`DROP SCHEMA ` + pq.QuoteIdentifier(schema) + ` CASCADE`)
_ = db.Close()
t.Fatal(err)
}
t.Cleanup(func() { _, _ = db.Exec(`DROP SCHEMA ` + pq.QuoteIdentifier(schema) + ` CASCADE`); _ = db.Close() })
for _, q := range []string{`CREATE TABLE users(id TEXT PRIMARY KEY,email TEXT,role TEXT,password_hash TEXT,created_at TIMESTAMPTZ DEFAULT NOW(),updated_at TIMESTAMPTZ DEFAULT NOW())`, `INSERT INTO users(id,email,role,password_hash) VALUES('admin-id','admin@example.test','admin','hash')`, `CREATE TABLE sources(id TEXT PRIMARY KEY,name TEXT,type TEXT,enabled BOOLEAN,article_limit INTEGER DEFAULT 20,source_key TEXT,created_at TIMESTAMPTZ DEFAULT NOW())`, `INSERT INTO sources(id,name,type,enabled,article_limit,source_key) VALUES('old-id','Reuters','reuters',true,42,NULL),('y-id','Yahoo Finance','stocktwits',true,83,'yahoo_finance')`} {
if _, err = db.Exec(q); err != nil {
t.Fatal(err)
}
}
const secret = "ticket13-admin-route-test"
token, err := auth.GenerateToken("admin-id", "admin@example.test", "admin", secret)
if err != nil {
t.Fatal(err)
}
router := api.SetupRouter(handlers.New(models.NewRepository(db), &config.Config{JWTSecret: secret}, nil, nil, nil, nil), secret)
get := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/api/admin/sources", nil)
req.Header.Set("Authorization", "Bearer "+token)
router.ServeHTTP(get, req)
if get.Code != http.StatusOK {
t.Fatalf("GET sources status=%d body=%s", get.Code, get.Body.String())
}
var envelope struct {
Data []map[string]any `json:"data"`
}
if err := json.Unmarshal(get.Body.Bytes(), &envelope); err != nil {
t.Fatal(err)
}
rows := envelope.Data
var old map[string]any
var supported map[string]any
for _, row := range rows {
if row["id"] == "old-id" {
old = row
}
if row["id"] == "y-id" {
supported = row
}
}
if old == nil {
t.Fatalf("GET omitted historical source: %s", get.Body.String())
}
for field, want := range map[string]any{"source_key": nil, "supported": false, "enabled": true, "operational": false} {
if _, exists := old[field]; !exists {
t.Errorf("historical response omitted %s: row=%v", field, old)
}
if old[field] != want {
t.Errorf("historical %s=%v, want %v; row=%v", field, old[field], want, old)
}
}
for _, secretField := range []string{"api_key", "password", "credentials", "article", "content", "url"} {
if _, ok := old[secretField]; ok {
t.Errorf("GET sources exposed forbidden %q", secretField)
}
}
if supported == nil {
t.Fatalf("GET omitted supported source: %s", get.Body.String())
}
for field, want := range map[string]any{"source_key": "yahoo_finance", "supported": true, "operational": true} {
if supported[field] != want {
t.Errorf("supported source %s=%v, want %v; row=%v", field, supported[field], want, supported)
}
}
put := httptest.NewRecorder()
req = httptest.NewRequest(http.MethodPut, "/api/admin/sources/old-id", bytes.NewBufferString(`{"enabled":true,"article_limit":99}`))
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
router.ServeHTTP(put, req)
if put.Code != http.StatusConflict {
t.Errorf("PUT historical source status=%d body=%s, want 409 source_not_supported", put.Code, put.Body.String())
}
if !bytes.Contains(put.Body.Bytes(), []byte("source_not_supported")) {
t.Errorf("PUT error body=%s, want source_not_supported", put.Body.String())
}
var enabled bool
var cap int
if err := db.QueryRow(`SELECT enabled,article_limit FROM sources WHERE id='old-id'`).Scan(&enabled, &cap); err != nil {
t.Fatal(err)
}
if !enabled || cap != 42 {
t.Fatalf("rejected update mutated historical row enabled=%v cap=%d", enabled, cap)
}
}

View File

@ -36,11 +36,11 @@ func TestGenerationSucceedsWithoutArticleTablesAndRollsBackSummaryPostgres(t *te
for _, statement := range []string{
`CREATE TABLE users(id UUID PRIMARY KEY,language TEXT DEFAULT 'fr',ranking_mode TEXT DEFAULT 'title')`,
`CREATE TABLE user_assets(id UUID PRIMARY KEY,user_id UUID,symbol TEXT,name TEXT,figi TEXT NULL,created_at TIMESTAMPTZ DEFAULT NOW())`,
`CREATE TABLE sources(id UUID PRIMARY KEY,name TEXT,type TEXT,enabled BOOLEAN,article_limit INTEGER DEFAULT 20,created_at TIMESTAMPTZ DEFAULT NOW())`,
`CREATE TABLE sources(id UUID PRIMARY KEY,name TEXT,type TEXT,enabled BOOLEAN,article_limit INTEGER DEFAULT 20,source_key TEXT,created_at TIMESTAMPTZ DEFAULT NOW())`,
`CREATE TABLE settings(key TEXT PRIMARY KEY,value TEXT)`,
`CREATE TABLE summaries(id UUID PRIMARY KEY,user_id UUID REFERENCES users(id),content TEXT,ai_provider_id UUID,generated_at TIMESTAMPTZ)`,
`INSERT INTO users(id) VALUES('00000000-0000-0000-0000-000000000001')`,
`INSERT INTO sources(id,name,type,enabled) VALUES('00000000-0000-0000-0000-000000000002','Fixture','fixture',true)`,
`INSERT INTO sources(id,name,type,enabled,source_key) VALUES('00000000-0000-0000-0000-000000000002','Fixture','fixture',true,'yahoo_finance')`,
`CREATE TABLE summary_generations(id UUID PRIMARY KEY,user_id UUID,summary_id UUID REFERENCES summaries(id),outcome JSONB NOT NULL,created_at TIMESTAMPTZ)`,
} {
if _, err := db.Exec(statement); err != nil {
@ -48,7 +48,7 @@ func TestGenerationSucceedsWithoutArticleTablesAndRollsBackSummaryPostgres(t *te
}
}
repo := models.NewRepository(db)
uc := generation.NewUseCase(generation.Dependencies{Repository: generation.RepositoryAdapter{Repo: repo}, Scrapers: map[string]scraper.Scraper{"fixture": memoryFeed{}}, Ranker: passRanker{}, Summarizer: safeSummarizer{}})
uc := generation.NewUseCase(generation.Dependencies{Repository: generation.RepositoryAdapter{Repo: repo}, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: memoryFeed{}}, Ranker: passRanker{}, Summarizer: safeSummarizer{}})
result, err := uc.Generate(context.Background(), "00000000-0000-0000-0000-000000000001")
if err != nil || result.Summary == nil || result.Outcome.Status != "succeeded" {
t.Fatalf("result=%+v err=%v", result, err)

View File

@ -233,7 +233,16 @@ func (h *Handler) ListSources(c *gin.Context) {
httputil.InternalError(c, err)
return
}
httputil.OK(c, sources)
type sourceResponse struct {
models.Source
Supported bool `json:"supported"`
Operational bool `json:"operational"`
}
result := make([]sourceResponse, 0, len(sources))
for _, source := range sources {
result = append(result, sourceResponse{Source: source, Supported: source.Supported(), Operational: source.Operational()})
}
httputil.OK(c, result)
}
type updateSourceRequest struct {
@ -248,6 +257,14 @@ func (h *Handler) UpdateSource(c *gin.Context) {
return
}
if err := h.repo.UpdateSource(c.Param("id"), req.Enabled, req.ArticleLimit); err != nil {
if errors.Is(err, models.ErrSourceNotSupported) {
c.JSON(http.StatusConflict, gin.H{"error": "source_not_supported"})
return
}
if errors.Is(err, sql.ErrNoRows) {
httputil.NotFound(c)
return
}
httputil.InternalError(c, err)
return
}

View File

@ -0,0 +1,3 @@
-- Historical rows stay preserved and disabled; rollback must not reactivate
-- sources for which the previous enabled state is no longer known.
ALTER TABLE sources DROP COLUMN source_key;

View File

@ -0,0 +1,30 @@
-- One SQL statement: validation, DDL and backfill share a transaction even when
-- executed without a caller-owned transaction. Never merge historical sources.
DO $migration$
BEGIN
LOCK TABLE sources IN ACCESS EXCLUSIVE MODE;
IF (SELECT count(*) FROM sources WHERE type = 'stocktwits'
AND lower(btrim(regexp_replace(name, '[[:space:]]+', ' ', 'g'))) = 'yahoo finance') <> 1 THEN
RAISE EXCEPTION 'source_identity_invalid: expected exactly one Yahoo Finance';
END IF;
IF (SELECT count(*) FROM sources WHERE type = 'bloomberg'
AND lower(btrim(regexp_replace(name, '[[:space:]]+', ' ', 'g'))) = 'bloomberg') <> 1 THEN
RAISE EXCEPTION 'source_identity_invalid: expected exactly one Bloomberg';
END IF;
IF (SELECT count(*) FROM sources WHERE type = 'watcherguru'
AND lower(btrim(regexp_replace(name, '[[:space:]]+', ' ', 'g'))) = 'watcher.guru') <> 1 THEN
RAISE EXCEPTION 'source_identity_invalid: expected exactly one Watcher.Guru';
END IF;
ALTER TABLE sources ADD COLUMN source_key TEXT NULL
CONSTRAINT sources_source_key_check CHECK (source_key IN ('yahoo_finance', 'bloomberg', 'watcher_guru'));
CREATE UNIQUE INDEX sources_source_key_unique ON sources(source_key) WHERE source_key IS NOT NULL;
UPDATE sources SET source_key = CASE
WHEN type = 'stocktwits' AND lower(btrim(regexp_replace(name, '[[:space:]]+', ' ', 'g'))) = 'yahoo finance' THEN 'yahoo_finance'
WHEN type = 'bloomberg' AND lower(btrim(regexp_replace(name, '[[:space:]]+', ' ', 'g'))) = 'bloomberg' THEN 'bloomberg'
WHEN type = 'watcherguru' AND lower(btrim(regexp_replace(name, '[[:space:]]+', ' ', 'g'))) = 'watcher.guru' THEN 'watcher_guru'
ELSE NULL END;
UPDATE sources SET enabled = false WHERE source_key IS NULL;
END
$migration$;

View File

@ -0,0 +1,81 @@
package migrations
import (
"os"
"reflect"
"testing"
)
func TestSourceMigrationDirectExecFailureLeavesSchemaAndRowsUnchangedPostgres(t *testing.T) {
db, cleanup := ticket13Database(t)
defer cleanup()
// Caller intentionally supplies no transaction. The migration must own its
// atomicity, as when a migration driver submits a single SQL statement.
for _, row := range ticket13HistoricalRows() {
if row.typ == "bloomberg" {
continue
}
if _, err := db.Exec(`INSERT INTO sources(id,name,type,enabled,article_limit) VALUES($1,$2,$3,$4,$5)`, row.id, row.name, row.typ, row.enabled, row.cap); err != nil {
t.Fatal(err)
}
}
beforeSchema := ticket13SchemaSnapshot(t, db)
beforeRows := ticket13ReadSources(t, db)
up, err := os.ReadFile("000015_source_allowlist.up.sql")
if err != nil {
t.Fatal(err)
}
if _, err = db.Exec(string(up)); err == nil {
t.Fatal("missing exact Bloomberg identity accepted")
}
if after := ticket13SchemaSnapshot(t, db); after != beforeSchema {
t.Fatal("direct Exec changed schema on failure")
}
if after := ticket13ReadSources(t, db); !reflect.DeepEqual(after, beforeRows) {
t.Fatal("direct Exec changed rows on failure")
}
}
func TestSourceMigrationNormalizesNamesWithoutFuzzyMatchingOrRewritingOutcomesPostgres(t *testing.T) {
db, cleanup := ticket13Database(t)
defer cleanup()
for _, row := range []ticket13SourceRow{
{"y", "\tYaHoO \n Finance \t", "stocktwits", true, 83},
{"b", " Bloomberg ", "bloomberg", false, 77},
{"w", " watcher.guru ", "watcherguru", true, 64},
{"fake-y", "Yahoo Finance Daily", "stocktwits", true, 42},
{"wrong-type", "Yahoo Finance", "reuters", true, 31},
{"wrong-name", "StockTwits", "stocktwits", true, 32},
{"no-dot", "Watcher Guru", "watcherguru", true, 33},
} {
if _, err := db.Exec(`INSERT INTO sources(id,name,type,enabled,article_limit) VALUES($1,$2,$3,$4,$5)`, row.id, row.name, row.typ, row.enabled, row.cap); err != nil {
t.Fatal(err)
}
}
if _, err := db.Exec(`CREATE TABLE summary_generations(id TEXT PRIMARY KEY,outcome JSONB); INSERT INTO summary_generations VALUES('old','{"source_stats":[{"source_id":"wrong-name","source_type":"stocktwits","selected":4}],"status":"succeeded"}')`); err != nil {
t.Fatal(err)
}
var before, after string
if err := db.QueryRow(`SELECT outcome::text FROM summary_generations WHERE id='old'`).Scan(&before); err != nil {
t.Fatal(err)
}
applyTicket13(t, db)
var targets, unsupported int
if err := db.QueryRow(`SELECT count(*) FROM sources WHERE source_key IS NOT NULL`).Scan(&targets); err != nil || targets != 3 {
t.Fatalf("target count=%d err=%v", targets, err)
}
if err := db.QueryRow(`SELECT count(*) FROM sources WHERE source_key IS NULL AND enabled=false`).Scan(&unsupported); err != nil || unsupported != 4 {
t.Fatalf("unsupported count=%d err=%v", unsupported, err)
}
var enabled bool
var cap int
if err := db.QueryRow(`SELECT enabled,article_limit FROM sources WHERE id='b'`).Scan(&enabled, &cap); err != nil || enabled || cap != 77 {
t.Fatalf("recognized disabled/cap state changed: %v %d %v", enabled, cap, err)
}
if err := db.QueryRow(`SELECT outcome::text FROM summary_generations WHERE id='old'`).Scan(&after); err != nil || after != before {
t.Fatal("historical outcome rewritten", err)
}
if _, err := db.Exec(`INSERT INTO sources(id,name,type,enabled,article_limit,source_key) VALUES('duplicate-key','x','x',true,20,'yahoo_finance')`); err == nil {
t.Fatal("duplicate source_key accepted")
}
}

View File

@ -0,0 +1,267 @@
package migrations
import (
"database/sql"
"fmt"
"os"
"reflect"
"strings"
"testing"
"time"
"github.com/lib/pq"
)
// These cases intentionally exercise the historical source identity pairs:
// Yahoo's type is stocktwits, while the actual StockTwits row has a different name.
func TestSourceAllowlistMigrationBackfillsOnlyExactTargetsPostgres(t *testing.T) {
db, cleanup := ticket13Database(t)
defer cleanup()
for _, row := range []struct {
id, name, typ string
enabled bool
cap int
}{
{"yahoo-id", "Yahoo Finance", "stocktwits", true, 83},
{"bloomberg-id", "Bloomberg", "bloomberg", false, 77},
{"watcher-id", "Watcher.Guru", "watcherguru", true, 64},
{"stocktwits-id", "StockTwits", "stocktwits", true, 31},
{"reuters-id", "Reuters", "reuters", true, 42},
} {
if _, err := db.Exec(`INSERT INTO sources(id,name,type,enabled,article_limit) VALUES($1,$2,$3,$4,$5)`, row.id, row.name, row.typ, row.enabled, row.cap); err != nil {
t.Fatal(err)
}
}
if _, err := db.Exec(`INSERT INTO articles(id,source_id,title,url) VALUES('article-yahoo','yahoo-id','historic','https://fixture.invalid/yahoo'),('article-stocktwits','stocktwits-id','historic','https://fixture.invalid/stocktwits')`); err != nil {
t.Fatal(err)
}
applyTicket13(t, db)
want := map[string]struct {
key string
enabled bool
cap int
}{
"yahoo-id": {"yahoo_finance", true, 83}, "bloomberg-id": {"bloomberg", false, 77}, "watcher-id": {"watcher_guru", true, 64},
"stocktwits-id": {"", false, 31}, "reuters-id": {"", false, 42},
}
for id, expected := range want {
var key sql.NullString
var enabled bool
var cap int
if err := db.QueryRow(`SELECT source_key,enabled,article_limit FROM sources WHERE id=$1`, id).Scan(&key, &enabled, &cap); err != nil {
t.Fatal(err)
}
actualKey := ""
if key.Valid {
actualKey = key.String
}
if actualKey != expected.key || enabled != expected.enabled || cap != expected.cap {
t.Errorf("%s => key=%q enabled=%v cap=%d, want key=%q enabled=%v cap=%d", id, actualKey, enabled, cap, expected.key, expected.enabled, expected.cap)
}
}
for _, id := range []string{"article-yahoo", "article-stocktwits"} {
var count int
if err := db.QueryRow(`SELECT count(*) FROM articles WHERE id=$1`, id).Scan(&count); err != nil || count != 1 {
t.Errorf("historical FK article %s count=%d err=%v", id, count, err)
}
}
}
func TestSourceAllowlistMigrationFailsAtomicallyForMissingOrAmbiguousTargetPostgres(t *testing.T) {
targets := []ticket13SourceRow{{"yahoo-id", "Yahoo Finance", "stocktwits", true, 83}, {"bloomberg-id", "Bloomberg", "bloomberg", false, 77}, {"watcher-id", "Watcher.Guru", "watcherguru", true, 64}}
cases := []struct {
name string
mutate func([]ticket13SourceRow) []ticket13SourceRow
}{}
for i, target := range targets {
missingID := target.id
cases = append(cases, struct {
name string
mutate func([]ticket13SourceRow) []ticket13SourceRow
}{
name: "missing required " + target.name,
mutate: func(rows []ticket13SourceRow) []ticket13SourceRow {
out := []ticket13SourceRow{}
for _, row := range rows {
if row.id != missingID {
out = append(out, row)
}
}
return out
},
})
duplicate := target
duplicate.id = fmt.Sprintf("duplicate-%d", i)
duplicate.enabled, duplicate.cap = false, 19
cases = append(cases, struct {
name string
mutate func([]ticket13SourceRow) []ticket13SourceRow
}{
name: "duplicate exact identity " + target.name,
mutate: func(rows []ticket13SourceRow) []ticket13SourceRow { return append(rows, duplicate) },
})
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
db, cleanup := ticket13Database(t)
defer cleanup()
rows := tc.mutate(ticket13HistoricalRows())
for _, row := range rows {
if _, err := db.Exec(`INSERT INTO sources(id,name,type,enabled,article_limit) VALUES($1,$2,$3,$4,$5)`, row.id, row.name, row.typ, row.enabled, row.cap); err != nil {
t.Fatal(err)
}
}
if _, err := db.Exec(`INSERT INTO articles(id,source_id,title,url) SELECT 'article-'||id,id,'fixture','https://fixture.invalid/'||id FROM sources`); err != nil {
t.Fatal(err)
}
beforeSchema := ticket13SchemaSnapshot(t, db)
beforeRows := ticket13ReadSources(t, db)
beforeFKs := ticket13ReadArticleSources(t, db)
err := applyTicket13Err(db)
if err == nil {
t.Fatal("migration succeeded without exactly one target source")
}
if strings.Contains(err.Error(), "read migration 000015") {
t.Errorf("%s: atomic rollback cannot be exercised because migration 000015 is absent: %v", tc.name, err)
}
if after := ticket13SchemaSnapshot(t, db); after != beforeSchema {
t.Errorf("failed migration changed schema\nbefore: %s\nafter: %s", beforeSchema, after)
}
if after := ticket13ReadSources(t, db); !reflect.DeepEqual(after, beforeRows) {
t.Errorf("failed migration changed source data\nbefore: %#v\nafter: %#v", beforeRows, after)
}
if after := ticket13ReadArticleSources(t, db); !reflect.DeepEqual(after, beforeFKs) {
t.Errorf("failed migration changed article/source FK rows\nbefore: %#v\nafter: %#v", beforeFKs, after)
}
})
}
}
type ticket13SourceRow struct {
id, name, typ string
enabled bool
cap int
}
func ticket13HistoricalRows() []ticket13SourceRow {
return []ticket13SourceRow{{"yahoo-id", "Yahoo Finance", "stocktwits", true, 83}, {"bloomberg-id", "Bloomberg", "bloomberg", false, 77}, {"watcher-id", "Watcher.Guru", "watcherguru", true, 64}, {"stocktwits-id", "StockTwits", "stocktwits", true, 31}, {"reuters-id", "Reuters", "reuters", true, 42}}
}
func ticket13SchemaSnapshot(t *testing.T, db *sql.DB) string {
t.Helper()
parts := []string{}
for _, q := range []string{`SELECT column_name||':'||data_type||':'||is_nullable||':'||COALESCE(column_default,'') FROM information_schema.columns WHERE table_schema=current_schema() AND table_name='sources' ORDER BY ordinal_position`, `SELECT conname||':'||pg_get_constraintdef(oid) FROM pg_constraint WHERE conrelid='sources'::regclass ORDER BY conname`, `SELECT indexname||':'||indexdef FROM pg_indexes WHERE schemaname=current_schema() AND tablename='sources' ORDER BY indexname`} {
rows, err := db.Query(q)
if err != nil {
t.Fatal(err)
}
for rows.Next() {
var value string
if err := rows.Scan(&value); err != nil {
rows.Close()
t.Fatal(err)
}
parts = append(parts, value)
}
if err := rows.Err(); err != nil {
rows.Close()
t.Fatal(err)
}
rows.Close()
}
return strings.Join(parts, "\n")
}
func ticket13ReadSources(t *testing.T, db *sql.DB) []ticket13SourceRow {
t.Helper()
rows, err := db.Query(`SELECT id,name,type,enabled,article_limit FROM sources ORDER BY id`)
if err != nil {
t.Fatal(err)
}
defer rows.Close()
result := []ticket13SourceRow{}
for rows.Next() {
var row ticket13SourceRow
if err := rows.Scan(&row.id, &row.name, &row.typ, &row.enabled, &row.cap); err != nil {
t.Fatal(err)
}
result = append(result, row)
}
if err := rows.Err(); err != nil {
t.Fatal(err)
}
return result
}
func ticket13ReadArticleSources(t *testing.T, db *sql.DB) []string {
t.Helper()
rows, err := db.Query(`SELECT id||':'||source_id FROM articles ORDER BY id`)
if err != nil {
t.Fatal(err)
}
defer rows.Close()
result := []string{}
for rows.Next() {
var value string
if err := rows.Scan(&value); err != nil {
t.Fatal(err)
}
result = append(result, value)
}
if err := rows.Err(); err != nil {
t.Fatal(err)
}
return result
}
func ticket13Database(t *testing.T) (*sql.DB, func()) {
t.Helper()
dsn := os.Getenv("TEST_DATABASE_URL")
if dsn == "" {
if os.Getenv("TEST_DATABASE_REQUIRED") == "1" {
t.Fatal("TEST_DATABASE_REQUIRED=1 but TEST_DATABASE_URL is empty")
}
t.Skip("TEST_DATABASE_URL absent: isolated PostgreSQL required")
}
db, err := sql.Open("postgres", dsn)
if err != nil {
t.Fatal(err)
}
db.SetMaxOpenConns(1)
schema := fmt.Sprintf("ticket13_sources_%d", time.Now().UnixNano())
if _, err = db.Exec(`CREATE SCHEMA ` + pq.QuoteIdentifier(schema)); err != nil {
_ = db.Close()
t.Fatal(err)
}
if _, err = db.Exec(`SET search_path TO ` + pq.QuoteIdentifier(schema)); err != nil {
_, _ = db.Exec(`DROP SCHEMA ` + pq.QuoteIdentifier(schema) + ` CASCADE`)
_ = db.Close()
t.Fatal(err)
}
for _, q := range []string{`CREATE TABLE sources(id TEXT PRIMARY KEY,name TEXT NOT NULL,type TEXT NOT NULL,enabled BOOLEAN NOT NULL,article_limit INTEGER NOT NULL DEFAULT 20)`, `CREATE TABLE articles(id TEXT PRIMARY KEY,source_id TEXT NOT NULL REFERENCES sources(id),title TEXT NOT NULL,url TEXT NOT NULL UNIQUE)`} {
if _, err = db.Exec(q); err != nil {
_, _ = db.Exec(`DROP SCHEMA ` + pq.QuoteIdentifier(schema) + ` CASCADE`)
_ = db.Close()
t.Fatal(err)
}
}
return db, func() { _, _ = db.Exec(`DROP SCHEMA ` + pq.QuoteIdentifier(schema) + ` CASCADE`); _ = db.Close() }
}
func applyTicket13(t *testing.T, db *sql.DB) {
t.Helper()
if err := applyTicket13Err(db); err != nil {
t.Fatalf("apply source allowlist migration: %v", err)
}
}
func applyTicket13Err(db *sql.DB) error {
up, err := os.ReadFile("000015_source_allowlist.up.sql")
if err != nil {
return fmt.Errorf("read migration 000015: %w", err)
}
tx, err := db.Begin()
if err != nil {
return err
}
if _, err = tx.Exec(string(up)); err != nil {
_ = tx.Rollback()
return err
}
return tx.Commit()
}

View File

@ -117,14 +117,14 @@ func (u *useCase) Generate(ctx context.Context, userID string) (Result, error) {
stats := map[string]int{}
partial := false
for _, source := range input.Sources {
if !source.Enabled {
if !source.Operational() {
continue
}
stat := SourceStat{SourceID: source.ID, SourceType: source.Type, ArticleLimit: source.ArticleLimit, Status: "ok"}
if stat.ArticleLimit <= 0 {
stat.ArticleLimit = 20
}
feed := u.Scrapers[source.Type]
feed := u.Scrapers[*source.SourceKey]
var articles []scraper.Article
if feed == nil {
err = fmt.Errorf("unavailable")

View File

@ -92,9 +92,9 @@ func (s *contractSummarizer) Summarize(_ context.Context, language string, _ []m
func TestUseCaseIsolatesTwoUsersAndUsesOnlyEnabledSourcesAndUserInputs(t *testing.T) {
alphaID, betaID := "user-alpha", "user-beta"
alphaSource := models.Source{ID: "alpha-feed", Type: "alpha", Enabled: true, ArticleLimit: 5}
betaSource := models.Source{ID: "beta-feed", Type: "beta", Enabled: true, ArticleLimit: 5}
disabled := models.Source{ID: "disabled-feed", Type: "disabled", Enabled: false, ArticleLimit: 5}
alphaSource := models.Source{ID: "alpha-feed", Type: "alpha", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 5}
betaSource := models.Source{ID: "beta-feed", Type: "beta", SourceKey: testSourceKey(models.SourceBloomberg), Enabled: true, ArticleLimit: 5}
disabled := models.Source{ID: "disabled-feed", Type: "disabled", SourceKey: testSourceKey(models.SourceWatcherGuru), Enabled: false, ArticleLimit: 5}
alphaScraper := &contractScraper{name: "alpha", articles: []scraper.Article{{Title: "alpha-only", URL: "https://private.test/alpha", Content: "alpha-secret"}}}
betaScraper := &contractScraper{name: "beta", articles: []scraper.Article{{Title: "beta-only", URL: "https://private.test/beta", Content: "beta-secret"}}}
disabledScraper := &contractScraper{name: "disabled"}
@ -107,7 +107,7 @@ func TestUseCaseIsolatesTwoUsersAndUsesOnlyEnabledSourcesAndUserInputs(t *testin
},
saved: map[string][]GenerationRecord{},
}
useCase := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{"alpha": alphaScraper, "beta": betaScraper, "disabled": disabledScraper}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC) }})
useCase := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: alphaScraper, models.SourceBloomberg: betaScraper, models.SourceWatcherGuru: disabledScraper}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Date(2026, 11, 20, 12, 0, 0, 0, time.UTC) }})
alpha, err := useCase.Generate(context.Background(), alphaID)
if err != nil || alpha.Summary == nil {
@ -148,8 +148,8 @@ func TestUseCasePreservesLayaOrderThenAppliesPerSourceAndGlobalCaps(t *testing.T
feedB := &contractScraper{name: "b", articles: articles[2:]}
ranker := &contractRanker{order: []string{"a2", "b1", "a1", "b2", "a3"}}
summarizer := &contractSummarizer{}
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 3, Assets: []models.UserAsset{{Symbol: "IDX"}}, Sources: []models.Source{{ID: "a", Type: "a", Enabled: true, ArticleLimit: 1}, {ID: "b", Type: "b", Enabled: true, ArticleLimit: 2}}}}, saved: map[string][]GenerationRecord{}}
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{"a": feedA, "b": feedB}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 3, Assets: []models.UserAsset{{Symbol: "IDX"}}, Sources: []models.Source{{ID: "a", Type: "a", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 1}, {ID: "b", Type: "b", SourceKey: testSourceKey(models.SourceBloomberg), Enabled: true, ArticleLimit: 2}}}}, saved: map[string][]GenerationRecord{}}
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: feedA, models.SourceBloomberg: feedB}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
if _, err := uc.Generate(context.Background(), "u"); err != nil {
t.Fatal(err)
}
@ -176,10 +176,10 @@ func TestUseCaseNoResultsInvalidLayaAndSummaryFailurePersistNoSummary(t *testing
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 10, Sources: []models.Source{{ID: "s", Type: "s", Enabled: true, ArticleLimit: 10}}}}, saved: map[string][]GenerationRecord{}}
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title", GlobalLimit: 10, Sources: []models.Source{{ID: "s", Type: "s", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 10}}}}, saved: map[string][]GenerationRecord{}}
ranker := &contractRanker{err: tt.rankErr}
summarizer := &contractSummarizer{err: tt.summaryErr}
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{"s": &contractScraper{name: "s", articles: tt.articles}}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: &contractScraper{name: "s", articles: tt.articles}}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
result, err := uc.Generate(context.Background(), "u")
if err != nil {
t.Fatalf("expected aggregate failure outcome, got error: %v", err)
@ -199,8 +199,8 @@ func TestUseCasePartialSourceFailureCanSummarizeRemainingSources(t *testing.T) {
bad := &contractScraper{name: "bad", err: errors.New("private error with URL https://private.test/article")}
ranker := &contractRanker{order: []string{"good-result"}}
summarizer := &contractSummarizer{}
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title_content", GlobalLimit: 10, Sources: []models.Source{{ID: "good", Type: "good", Enabled: true, ArticleLimit: 5}, {ID: "bad", Type: "bad", Enabled: true, ArticleLimit: 5}}}}, saved: map[string][]GenerationRecord{}}
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{"good": good, "bad": bad}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title_content", GlobalLimit: 10, Sources: []models.Source{{ID: "good", Type: "good", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 5}, {ID: "bad", Type: "bad", SourceKey: testSourceKey(models.SourceBloomberg), Enabled: true, ArticleLimit: 5}}}}, saved: map[string][]GenerationRecord{}}
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: good, models.SourceBloomberg: bad}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
result, err := uc.Generate(context.Background(), "u")
if err != nil || result.Summary == nil || result.Outcome.Status != "partial" {
t.Fatalf("partial source failure result=%+v err=%v", result, err)
@ -221,8 +221,8 @@ func TestUseCaseOutcomeContainsAggregateCountsWithoutArticleIdentifiers(t *testi
feed := &contractScraper{name: "source", articles: []scraper.Article{{Title: "candidate-title-secret", URL: "https://private.test/x", Content: "candidate-content-secret"}}}
ranker := &contractRanker{order: []string{"candidate-title-secret"}}
summarizer := &contractSummarizer{}
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title_content", GlobalLimit: 10, Sources: []models.Source{{ID: "source-id", Type: "source", Enabled: true, ArticleLimit: 5}}}}, saved: map[string][]GenerationRecord{}}
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{"source": feed}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "fr", RankingMode: "title_content", GlobalLimit: 10, Sources: []models.Source{{ID: "source-id", Type: "source", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 5}}}}, saved: map[string][]GenerationRecord{}}
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: feed}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
result, err := uc.Generate(context.Background(), "u")
if err != nil {
t.Fatal(err)
@ -245,8 +245,8 @@ func TestUseCaseCountsTitleOnlyFallbackWhenContentIsUnavailable(t *testing.T) {
feed := &contractScraper{name: "source", articles: []scraper.Article{{Title: "title-without-content", Content: ""}}}
ranker := &contractRanker{}
summarizer := &contractSummarizer{}
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "en", RankingMode: "title_content", GlobalLimit: 4, Sources: []models.Source{{ID: "source", Type: "source", Enabled: true, ArticleLimit: 4}}}}, saved: map[string][]GenerationRecord{}}
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{"source": feed}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
repo := &contractRepository{inputs: map[string]UserInput{"u": {Language: "en", RankingMode: "title_content", GlobalLimit: 4, Sources: []models.Source{{ID: "source", Type: "source", SourceKey: testSourceKey(models.SourceYahooFinance), Enabled: true, ArticleLimit: 4}}}}, saved: map[string][]GenerationRecord{}}
uc := NewUseCase(Dependencies{Repository: repo, Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: feed}, Ranker: ranker, Summarizer: summarizer, Clock: func() time.Time { return time.Unix(1, 0) }})
result, err := uc.Generate(context.Background(), "u")
if err != nil || result.Summary == nil {
t.Fatalf("content fallback should permit generation: result=%+v err=%v", result, err)
@ -267,3 +267,5 @@ func candidateTitles(candidates []Candidate) []string {
func contains(value, needle string) bool {
return len(needle) > 0 && strings.Contains(value, needle)
}
func testSourceKey(key string) *string { return &key }

View File

@ -52,11 +52,12 @@ func TestLegacyNullFIGIAssetStillContributesToGenerationPostgres(t *testing.T) {
for _, statement := range []string{
`CREATE TABLE users (id UUID PRIMARY KEY, language TEXT NOT NULL DEFAULT 'fr', ranking_mode TEXT NOT NULL DEFAULT 'title')`,
`CREATE TABLE user_assets (id UUID PRIMARY KEY, user_id UUID NOT NULL, symbol VARCHAR(20) NOT NULL, name TEXT NOT NULL DEFAULT '', figi TEXT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
`CREATE TABLE sources (id UUID PRIMARY KEY, name TEXT NOT NULL, type TEXT NOT NULL, enabled BOOLEAN NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), article_limit INT NOT NULL DEFAULT 20)`,
`CREATE TABLE sources (id UUID PRIMARY KEY, name TEXT NOT NULL, type TEXT NOT NULL, enabled BOOLEAN NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), article_limit INT NOT NULL DEFAULT 20, source_key TEXT)`,
`CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT NOT NULL)`,
`INSERT INTO users(id,language,ranking_mode) VALUES ('` + userID + `','fr','title')`,
`INSERT INTO user_assets(id,user_id,symbol,name,figi) VALUES ('00000000-0000-0000-0000-000000000411','` + userID + `','LEGACY','Historic asset',NULL)`,
`INSERT INTO sources(id,name,type,enabled,article_limit) VALUES ('00000000-0000-0000-0000-000000000421','test source','ticket4',TRUE,20)`,
`INSERT INTO sources(id,name,type,enabled,article_limit,source_key) VALUES ('00000000-0000-0000-0000-000000000421','test source','ticket4',TRUE,20,'yahoo_finance')`,
`INSERT INTO sources(id,name,type,enabled,article_limit,source_key) VALUES ('00000000-0000-0000-0000-000000000422','Historic enabled','reuters',TRUE,42,NULL),('00000000-0000-0000-0000-000000000423','Disabled target','bloomberg',FALSE,77,'bloomberg')`,
`INSERT INTO settings(key,value) VALUES ('summary_max_articles','50')`,
} {
if _, err := db.Exec(statement); err != nil {
@ -68,6 +69,9 @@ func TestLegacyNullFIGIAssetStillContributesToGenerationPostgres(t *testing.T) {
if err != nil {
t.Fatalf("load legacy generation input from PostgreSQL: %v", err)
}
if len(input.Sources) != 1 || input.Sources[0].SourceKey == nil || *input.Sources[0].SourceKey != models.SourceYahooFinance || input.Sources[0].ArticleLimit != 20 {
t.Fatalf("LoadUserInput must exclude unsupported/disabled sources, preserving target caps: %+v", input.Sources)
}
if len(input.Assets) != 1 || input.Assets[0].Symbol != "LEGACY" || input.Assets[0].Name != "Historic asset" {
t.Fatalf("loaded legacy asset=%+v, want symbol/name preserved", input.Assets)
}
@ -84,7 +88,7 @@ func TestLegacyNullFIGIAssetStillContributesToGenerationPostgres(t *testing.T) {
fakeRepository := &contractRepository{inputs: map[string]UserInput{userID: input}, saved: map[string][]GenerationRecord{}}
uc := NewUseCase(Dependencies{
Repository: fakeRepository,
Scrapers: map[string]scraper.Scraper{"ticket4": feed},
Scrapers: map[string]scraper.Scraper{models.SourceYahooFinance: feed},
Ranker: ranker,
Summarizer: summarizer,
Clock: func() time.Time { return time.Unix(1, 0).UTC() },

View File

@ -33,7 +33,7 @@ func (r RepositoryAdapter) LoadUserInput(ctx context.Context, id string) (UserIn
if value == "" {
limit = 50
}
return UserInput{Language: p.Language, RankingMode: p.RankingMode, GlobalLimit: limit, Assets: assets, Sources: sources}, nil
return UserInput{Language: p.Language, RankingMode: p.RankingMode, GlobalLimit: limit, Assets: assets, Sources: models.OperationalSources(sources)}, nil
}
func (r RepositoryAdapter) SaveGeneration(ctx context.Context, id string, record GenerationRecord) error {
payload, err := json.Marshal(record.Outcome)

View File

@ -0,0 +1,49 @@
package generation
import (
"context"
"encoding/json"
"testing"
"github.com/tradarr/backend/internal/models"
"github.com/tradarr/backend/internal/scraper"
)
func TestGenerationRoutesOnlyAllowlistedSourceKeysEvenWhenLegacyRowsAreEnabled(t *testing.T) {
var sources []models.Source
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":"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}
]`), &sources); err != nil {
t.Fatal(err)
}
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"} {
feeds[key] = &contractScraper{name: key, articles: []scraper.Article{{Title: key}}}
}
scrapers := map[string]scraper.Scraper{}
for key, feed := range feeds {
scrapers[key] = feed
}
result, err := NewUseCase(Dependencies{Repository: repo, Scrapers: scrapers, Ranker: &contractRanker{}, Summarizer: &contractSummarizer{}}).Generate(context.Background(), "user")
if err != nil || result.Summary == nil {
t.Fatalf("generation result=%+v err=%v", result, err)
}
for _, key := range []string{"yahoo_finance", "bloomberg", "watcher_guru"} {
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"} {
if len(feeds[key].calls) != 0 {
t.Errorf("unsupported enabled source %s was invoked %d times", key, len(feeds[key].calls))
}
}
if result.Outcome.TotalCandidates != 3 {
t.Errorf("target candidate count=%d, want 3", result.Outcome.TotalCandidates)
}
}

View File

@ -31,6 +31,7 @@ type UserAsset struct {
}
type Source struct {
SourceKey *string `json:"source_key"`
ArticleLimit int `json:"article_limit"`
ID string `json:"id"`
Name string `json:"name"`

View File

@ -130,7 +130,7 @@ func (r *Repository) CountAdmins() (int, error) {
// ── Sources ────────────────────────────────────────────────────────────────
func (r *Repository) ListSources() ([]Source, error) {
rows, err := r.db.Query(`SELECT id, name, type, enabled, created_at, article_limit FROM sources ORDER BY name`)
rows, err := r.db.Query(`SELECT id, name, type, enabled, created_at, article_limit, source_key FROM sources ORDER BY name`)
if err != nil {
return nil, err
}
@ -138,35 +138,44 @@ func (r *Repository) ListSources() ([]Source, error) {
var sources []Source
for rows.Next() {
var s Source
if err := rows.Scan(&s.ID, &s.Name, &s.Type, &s.Enabled, &s.CreatedAt, &s.ArticleLimit); err != nil {
if err := rows.Scan(&s.ID, &s.Name, &s.Type, &s.Enabled, &s.CreatedAt, &s.ArticleLimit, &s.SourceKey); err != nil {
return nil, err
}
sources = append(sources, s)
}
return sources, nil
return sources, rows.Err()
}
func (r *Repository) GetSourceByType(sourceType string) (*Source, error) {
s := &Source{}
err := r.db.QueryRow(`
SELECT id, name, type, enabled, created_at, article_limit FROM sources WHERE type=$1`, sourceType,
).Scan(&s.ID, &s.Name, &s.Type, &s.Enabled, &s.CreatedAt, &s.ArticleLimit)
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,
).Scan(&s.ID, &s.Name, &s.Type, &s.Enabled, &s.CreatedAt, &s.ArticleLimit, &s.SourceKey)
if err == sql.ErrNoRows {
return nil, nil
}
return s, err
}
var ErrSourceNotSupported = errors.New("source_not_supported")
func (r *Repository) UpdateSource(id string, enabled bool, articleLimit *int) error {
result, err := r.db.Exec(`UPDATE sources SET enabled=$1, article_limit=COALESCE($2,article_limit) WHERE id=$3`, enabled, articleLimit, id)
tx, err := r.db.Begin()
if err != nil {
return err
}
count, err := result.RowsAffected()
if err == nil && count == 0 {
return sql.ErrNoRows
defer tx.Rollback()
var key *string
if err = tx.QueryRow(`SELECT source_key FROM sources WHERE id=$1 FOR UPDATE`, id).Scan(&key); err != nil {
return err
}
return err
if key == nil || !SupportedSourceKey(*key) {
return ErrSourceNotSupported
}
if _, err = tx.Exec(`UPDATE sources SET enabled=$1,article_limit=COALESCE($2,article_limit) WHERE id=$3`, enabled, articleLimit, id); err != nil {
return err
}
return tx.Commit()
}
// ── Scrape Credentials ─────────────────────────────────────────────────────

View File

@ -0,0 +1,26 @@
package models
const (
SourceYahooFinance = "yahoo_finance"
SourceBloomberg = "bloomberg"
SourceWatcherGuru = "watcher_guru"
)
func SupportedSourceKey(key string) bool {
switch key {
case SourceYahooFinance, SourceBloomberg, SourceWatcherGuru:
return true
}
return false
}
func (s Source) Supported() bool { return s.SourceKey != nil && SupportedSourceKey(*s.SourceKey) }
func (s Source) Operational() bool { return s.Enabled && s.Supported() }
func OperationalSources(sources []Source) []Source {
result := []Source{}
for _, source := range sources {
if source.Operational() {
result = append(result, source)
}
}
return result
}

View File

@ -0,0 +1,24 @@
package models
import "testing"
func TestSourceSupportUsesOnlyCanonicalKeyAndPersistedEnabled(t *testing.T) {
yahoo := SourceYahooFinance
unknown := "reuters"
sources := []Source{
{ID: "supported", Type: "stocktwits", SourceKey: &yahoo, Enabled: true, ArticleLimit: 83},
{ID: "disabled", SourceKey: &yahoo, Enabled: false, ArticleLimit: 77},
{ID: "legacy", Type: "stocktwits", Name: "Yahoo Finance", Enabled: true, ArticleLimit: 42},
{ID: "unknown", SourceKey: &unknown, Enabled: true, ArticleLimit: 31},
}
filtered := OperationalSources(sources)
if len(filtered) != 1 || filtered[0].ID != "supported" || filtered[0].ArticleLimit != 83 {
t.Fatalf("filtered=%v", filtered)
}
if !sources[2].Enabled || sources[2].Supported() || sources[2].Operational() {
t.Fatal("legacy enabled must remain persisted, without operational support")
}
if !sources[1].Supported() || sources[1].Operational() {
t.Fatal("disabled target support/operational mismatch")
}
}

View File

@ -0,0 +1,74 @@
package scheduler
import (
"context"
"encoding/json"
"testing"
"github.com/tradarr/backend/internal/generation"
"github.com/tradarr/backend/internal/models"
"github.com/tradarr/backend/internal/scraper"
)
type ticket13Repository struct{ input generation.UserInput }
type ticket13Users struct{}
func (ticket13Users) ListUsers() ([]models.User, error) { return []models.User{{ID: "one-user"}}, nil }
func (r ticket13Repository) LoadUserInput(context.Context, string) (generation.UserInput, error) {
return r.input, nil
}
func (ticket13Repository) SaveGeneration(context.Context, string, generation.GenerationRecord) error {
return nil
}
type ticket13Ranker struct{}
func (ticket13Ranker) Rank(_ context.Context, _ string, _ []models.UserAsset, c []generation.Candidate) ([]generation.Candidate, error) {
return c, nil
}
type ticket13Summary struct{}
func (ticket13Summary) Summarize(context.Context, string, []models.UserAsset, []generation.Candidate) (string, error) {
return "safe aggregate", nil
}
type ticket13Feed struct{ calls int }
func (f *ticket13Feed) Name() string { return "fake" }
func (f *ticket13Feed) Scrape(context.Context, []string) ([]scraper.Article, error) {
f.calls++
return []scraper.Article{{Title: "fixture"}}, nil
}
func TestScheduledGenerationUsesSameThreeSourceAllowlistForEnabledLegacyRows(t *testing.T) {
var sources []models.Source
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":"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"} {
f := &ticket13Feed{}
feeds[key] = f
scrapers[key] = f
}
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"} {
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"} {
if feeds[key].calls != 0 {
t.Errorf("scheduled legacy source %s was called %d times", key, feeds[key].calls)
}
}
}