test(e2e): add isolated browser journey and cleanup supervision

Add a fake-only end-to-end stack, Firefox journey, and bounded process cleanup for normal, failed, and interrupted runs.

Refs #12

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-11-20 23:39:02 +01:00
parent 8f42c30ec6
commit 4459a81206
28 changed files with 1647 additions and 51 deletions

View File

@ -11,10 +11,17 @@ import (
"github.com/tradarr/backend/internal/scraper"
)
type generationRanker struct{ p *Pipeline }
type generationRanker struct {
p *Pipeline
provider Provider
}
func (a generationRanker) Rank(ctx context.Context, mode string, assets []models.UserAsset, candidates []generation.Candidate) ([]generation.Candidate, error) {
provider, _, err := a.p.buildProviderForRole("filter")
provider := a.provider
var err error
if provider == nil {
provider, _, err = a.p.buildProviderForRole("filter")
}
if err != nil {
return nil, err
}
@ -44,10 +51,17 @@ func (a generationRanker) Rank(ctx context.Context, mode string, assets []models
return result, nil
}
type generationSummarizer struct{ p *Pipeline }
type generationSummarizer struct {
p *Pipeline
provider Provider
}
func (a generationSummarizer) Summarize(ctx context.Context, language string, assets []models.UserAsset, candidates []generation.Candidate) (string, error) {
provider, _, err := a.p.buildProviderForRole("summary")
provider := a.provider
var err error
if provider == nil {
provider, _, err = a.p.buildProviderForRole("summary")
}
if err != nil {
return "", err
}
@ -75,7 +89,18 @@ func (a generationSummarizer) Summarize(ctx context.Context, language string, as
return provider.Summarize(ctx, prompt, GenOptions{NumCtx: 32768})
}
func (p *Pipeline) NewGenerationUseCase(feeds map[string]scraper.Scraper) generation.UseCase {
uc := generation.NewUseCase(generation.Dependencies{Repository: generation.RepositoryAdapter{Repo: p.repo}, Scrapers: feeds, Ranker: generationRanker{p}, Summarizer: generationSummarizer{p}})
uc := generation.NewUseCase(generation.Dependencies{Repository: generation.RepositoryAdapter{Repo: p.repo}, Scrapers: feeds, Ranker: generationRanker{p: p}, Summarizer: generationSummarizer{p: p}})
p.generationUseCase = uc
return uc
}
// NewGenerationUseCaseWithProviders keeps provider selection explicit for isolated
// compositions. It never resolves a provider from database configuration.
func (p *Pipeline) NewGenerationUseCaseWithProviders(feeds map[string]scraper.Scraper, ranker, summary Provider) generation.UseCase {
if ranker == nil || summary == nil {
panic("explicit generation providers required")
}
uc := generation.NewUseCase(generation.Dependencies{Repository: generation.RepositoryAdapter{Repo: p.repo}, Scrapers: feeds, Ranker: generationRanker{p: p, provider: ranker}, Summarizer: generationSummarizer{p: p, provider: summary}})
p.generationUseCase = uc
return uc
}

View File

@ -0,0 +1,193 @@
package e2estack
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net"
"net/http"
"strings"
"sync"
"github.com/tradarr/backend/internal/ai"
"github.com/tradarr/backend/internal/scraper"
)
type Fixtures struct {
IndexQuery string `json:"indexQuery"`
IndexName string `json:"indexName"`
IndexSymbol string `json:"indexSymbol"`
IndexFIGI string `json:"indexFIGI"`
SummarySentinel string `json:"summarySentinel"`
ArticleTitle string `json:"articleTitle"`
ArticleURL string `json:"articleURL"`
ArticleContent string `json:"articleContent"`
CandidateID string `json:"candidateID"`
}
func DefaultFixtures() Fixtures {
return Fixtures{"E2E index", "E2E Financial Index", "E2EIDX", "BBG000E2E001", "E2E synthesized financial summary", "E2E private article title", "https://fixture.invalid/private-article", "E2E private article body", "pending-candidate-id"}
}
type Event struct {
Kind string `json:"kind"`
Symbols []string `json:"symbols,omitempty"`
CandidateID string `json:"candidate_id,omitempty"`
}
type Fakes struct {
mu sync.Mutex
Fixture Fixtures
Events []Event
counts map[string]int
}
func NewFakes() *Fakes {
return &Fakes{Fixture: DefaultFixtures(), Events: []Event{}, counts: map[string]int{}}
}
func (f *Fakes) record(event Event) {
f.mu.Lock()
defer f.mu.Unlock()
f.Events = append(f.Events, event)
f.counts[event.Kind]++
}
func (f *Fakes) Handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("/audit", func(w http.ResponseWriter, r *http.Request) {
f.mu.Lock()
defer f.mu.Unlock()
_ = json.NewEncoder(w).Encode(map[string]any{"openfigiSearches": f.counts["openfigiSearches"], "scraperCalls": f.counts["scraperCalls"], "layaRankingCalls": f.counts["layaRankingCalls"], "layaSummaryCalls": f.counts["layaSummaryCalls"], "events": f.Events})
})
mux.HandleFunc("/v3/search", func(w http.ResponseWriter, r *http.Request) {
var req struct {
Query string `json:"query"`
Market string `json:"marketSecDes"`
}
if r.Method != "POST" || json.NewDecoder(r.Body).Decode(&req) != nil || req.Market != "Index" {
http.Error(w, "invalid fixture search", 400)
return
}
f.record(Event{Kind: "openfigiSearches"})
_ = json.NewEncoder(w).Encode(map[string]any{"data": []map[string]string{{"name": f.Fixture.IndexName, "ticker": f.Fixture.IndexSymbol, "figi": f.Fixture.IndexFIGI, "marketSector": "Index"}}})
})
mux.HandleFunc("/scrape", func(w http.ResponseWriter, r *http.Request) {
var symbols []string
if r.Method != "POST" || json.NewDecoder(r.Body).Decode(&symbols) != nil {
http.Error(w, "invalid fixture scrape", 400)
return
}
f.record(Event{Kind: "scraperCalls", Symbols: symbols})
_ = json.NewEncoder(w).Encode([]scraper.Article{{Title: f.Fixture.ArticleTitle, Content: f.Fixture.ArticleContent, URL: f.Fixture.ArticleURL}})
})
mux.HandleFunc("/api/generate", func(w http.ResponseWriter, r *http.Request) {
var req struct {
Prompt string `json:"prompt"`
Format string `json:"format"`
}
if r.Method != "POST" || json.NewDecoder(r.Body).Decode(&req) != nil {
http.Error(w, "invalid fixture provider", 400)
return
}
response := f.Fixture.SummarySentinel
if req.Format == "json" {
// The candidate UUID is generated by the real use case; never hard-code it.
start := strings.LastIndex(req.Prompt, "\n{")
if start < 0 {
http.Error(w, "ranking payload missing", 400)
return
}
var payload struct {
Articles []struct {
ID string `json:"id"`
} `json:"articles"`
}
if json.Unmarshal([]byte(req.Prompt[start+1:]), &payload) != nil || len(payload.Articles) != 1 {
http.Error(w, "ranking candidate missing", 400)
return
}
id := payload.Articles[0].ID
f.mu.Lock()
f.Fixture.CandidateID = id
f.mu.Unlock()
f.record(Event{Kind: "layaRankingCalls", CandidateID: id})
encoded, _ := json.Marshal(map[string]any{"ranked_article_ids": []string{id}})
response = string(encoded)
} else {
f.record(Event{Kind: "layaSummaryCalls"})
}
_ = json.NewEncoder(w).Encode(map[string]string{"response": response})
})
return mux
}
func Listen(handler http.Handler) (string, func(), error) {
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return "", nil, err
}
server := &http.Server{Handler: handler}
go server.Serve(listener)
return "http://" + listener.Addr().String(), func() { _ = server.Close() }, nil
}
type FakeScraper struct {
URL string
Client *http.Client
}
func (FakeScraper) Name() string { return "e2e" }
func (s FakeScraper) Scrape(ctx context.Context, symbols []string) ([]scraper.Article, error) {
if err := ValidateURL(s.URL, false); err != nil {
return nil, err
}
raw, _ := json.Marshal(symbols)
req, err := http.NewRequestWithContext(ctx, "POST", s.URL+"/scrape", bytes.NewReader(raw))
if err != nil {
return nil, err
}
resp, err := s.Client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, fmt.Errorf("fake scraper failed")
}
var articles []scraper.Article
err = json.NewDecoder(resp.Body).Decode(&articles)
return articles, err
}
type FakeProvider struct {
URL string
Client *http.Client
}
func (FakeProvider) Name() string { return "fake-laya" }
func (FakeProvider) ListModels(context.Context) ([]string, error) { return []string{"fake-laya"}, nil }
func (p FakeProvider) Summarize(ctx context.Context, prompt string, opts ai.GenOptions) (string, error) {
if err := ValidateURL(p.URL, false); err != nil {
return "", err
}
body := map[string]any{"prompt": prompt, "model": "fake-laya", "stream": false}
if opts.JSONMode {
body["format"] = "json"
}
raw, _ := json.Marshal(body)
req, err := http.NewRequestWithContext(ctx, "POST", p.URL+"/api/generate", bytes.NewReader(raw))
if err != nil {
return "", err
}
resp, err := p.Client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return "", fmt.Errorf("fake provider failed")
}
var result struct {
Response string `json:"response"`
}
err = json.NewDecoder(resp.Body).Decode(&result)
return result.Response, err
}

View File

@ -0,0 +1,49 @@
// Package e2estack contains test-only loopback adapters. Production does not import it.
package e2estack
import (
"context"
"errors"
"net"
"net/http"
"net/url"
)
func ValidateURL(raw string, database bool) error {
u, err := url.Parse(raw)
if err != nil {
return errors.New("invalid E2E URL")
}
scheme := u.Scheme == "http" || u.Scheme == "https"
if database {
scheme = u.Scheme == "postgres" || u.Scheme == "postgresql"
}
ip := net.ParseIP(u.Hostname())
if !scheme || ip == nil || !ip.IsLoopback() || u.Port() == "" {
return errors.New("E2E URL must use a literal loopback IP and explicit port")
}
return nil
}
type loopbackTransport struct{ base *http.Transport }
func (t loopbackTransport) RoundTrip(r *http.Request) (*http.Response, error) {
if err := ValidateURL(r.URL.String(), false); err != nil {
return nil, err
}
return t.base.RoundTrip(r)
}
func LoopbackClient() *http.Client {
transport := &http.Transport{Proxy: nil, DialContext: func(ctx context.Context, network, address string) (net.Conn, error) {
host, _, err := net.SplitHostPort(address)
if err != nil {
return nil, err
}
ip := net.ParseIP(host)
if ip == nil || !ip.IsLoopback() {
return nil, errors.New("E2E external egress forbidden")
}
return (&net.Dialer{}).DialContext(ctx, network, address)
}}
return &http.Client{Transport: loopbackTransport{transport}, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }}
}

View File

@ -0,0 +1,11 @@
//go:build linux
package e2estack
import "syscall"
// ChildProcessAttrs prevents a Vite/Playwright launcher surviving e2e-stack.
// The subreaper separately owns and cleans their detached descendants.
func ChildProcessAttrs() *syscall.SysProcAttr {
return &syscall.SysProcAttr{Setpgid: true, Pdeathsig: syscall.SIGKILL}
}

View File

@ -0,0 +1,7 @@
//go:build !linux
package e2estack
import "syscall"
func ChildProcessAttrs() *syscall.SysProcAttr { return &syscall.SysProcAttr{Setpgid: true} }

View File

@ -0,0 +1,50 @@
package e2estack
import (
"context"
"net/http"
"strings"
"testing"
"github.com/tradarr/backend/internal/ai"
"github.com/tradarr/backend/internal/models"
)
func TestRejectNonLoopbackDestinationsWithoutEgress(t *testing.T) {
for _, destination := range []string{"https://api.openfigi.com:443", "http://203.0.113.10:80", "http://localhost:8080", "http://127.0.0.1.evil.test:80", "file:///tmp/fixture"} {
if ValidateURL(destination, false) == nil {
t.Fatalf("unsafe base URL accepted: %s", destination)
}
request, err := http.NewRequest("GET", destination, nil)
if err == nil {
if _, err = LoopbackClient().Do(request); err == nil {
t.Fatal("external request accepted")
}
}
}
if ValidateURL("postgres://127.0.0.1:5432/tradarr_e2e", true) != nil {
t.Fatal("loopback DB rejected")
}
}
func TestFakesRankActualCandidateIDAndJournalCalls(t *testing.T) {
fake := NewFakes()
base, closeServer, err := Listen(fake.Handler())
if err != nil {
t.Fatal(err)
}
defer closeServer()
provider := FakeProvider{URL: base, Client: LoopbackClient()}
articles := []models.Article{{ID: "runtime-candidate-uuid", Title: fake.Fixture.ArticleTitle, Content: fake.Fixture.ArticleContent}}
ranked, err := ai.RankArticles(context.Background(), provider, []string{"Index (IDX)"}, articles, 20, "title_content")
if err != nil || len(ranked) != 1 || ranked[0].ID != articles[0].ID {
t.Fatalf("ranking=%v err=%v", ranked, err)
}
fake.mu.Lock()
defer fake.mu.Unlock()
if fake.counts["layaRankingCalls"] != 1 || fake.Events[0].CandidateID != "runtime-candidate-uuid" {
t.Fatal("ranking call not journaled")
}
if strings.Contains(fake.Fixture.SummarySentinel, fake.Fixture.ArticleTitle) {
t.Fatal("unsafe summary fixture")
}
}

View File

@ -0,0 +1,39 @@
package server
import (
"fmt"
"github.com/tradarr/backend/internal/auth"
"github.com/tradarr/backend/internal/config"
"github.com/tradarr/backend/internal/models"
"log"
)
type AdminRepository interface {
GetUserByEmail(string) (*models.User, error)
CreateUser(string, string, models.Role) (*models.User, error)
}
func EnsureAdmin(repo AdminRepository, cfg *config.Config) error {
if cfg.AdminEmail == "" {
return nil
}
existing, err := repo.GetUserByEmail(cfg.AdminEmail)
if err != nil {
return err
}
if existing != nil {
return nil
}
if cfg.AdminPassword == "" {
return fmt.Errorf("ADMIN_PASSWORD is required to create the bootstrap admin")
}
hash, err := auth.HashPassword(cfg.AdminPassword)
if err != nil {
return err
}
if _, err = repo.CreateUser(cfg.AdminEmail, hash, models.RoleAdmin); err != nil {
return err
}
log.Printf("admin account created: %s", cfg.AdminEmail)
return nil
}

View File

@ -0,0 +1,51 @@
// Package server composes HTTP and optional scheduled application execution.
// Concrete retrieval/provider adapters belong to the executable's composition root.
package server
import (
"github.com/gin-gonic/gin"
"github.com/tradarr/backend/internal/ai"
"github.com/tradarr/backend/internal/api"
"github.com/tradarr/backend/internal/api/handlers"
"github.com/tradarr/backend/internal/config"
"github.com/tradarr/backend/internal/crypto"
"github.com/tradarr/backend/internal/generation"
"github.com/tradarr/backend/internal/indices"
"github.com/tradarr/backend/internal/models"
"github.com/tradarr/backend/internal/scheduler"
"github.com/tradarr/backend/internal/scraper"
"log"
)
type Dependencies struct {
Feeds map[string]scraper.Scraper
IndexSearcher indices.IndexSearcher
GenerationFactory func(*ai.Pipeline) generation.UseCase
EnableScheduler bool
}
type App struct {
Router *gin.Engine
scheduler *scheduler.Scheduler
}
func New(repo *models.Repository, cfg *config.Config, deps Dependencies) *App {
enc := crypto.New(cfg.EncryptionKey)
pipeline := ai.NewPipeline(repo, enc)
registry := scraper.NewRegistry(repo)
uc := pipeline.NewGenerationUseCase(deps.Feeds)
if deps.GenerationFactory != nil {
uc = deps.GenerationFactory(pipeline)
}
sched := scheduler.New(registry, pipeline, repo)
sched.SetGenerationUseCase(uc)
if deps.EnableScheduler {
if err := sched.Start(); err != nil {
log.Printf("scheduler: %v", err)
}
}
h := handlers.New(repo, cfg, enc, registry, pipeline, sched)
h.SetGenerationUseCase(uc)
h.SetIndexSearcher(deps.IndexSearcher)
return &App{Router: api.SetupRouter(h, cfg.JWTSecret), scheduler: sched}
}
func (a *App) Close() { a.scheduler.Stop() }

View File

@ -0,0 +1,40 @@
package server
import (
"context"
"net/http/httptest"
"testing"
"github.com/tradarr/backend/internal/ai"
"github.com/tradarr/backend/internal/auth"
"github.com/tradarr/backend/internal/config"
"github.com/tradarr/backend/internal/generation"
"github.com/tradarr/backend/internal/indices"
)
type fakeGeneration struct{}
func (fakeGeneration) Generate(context.Context, string) (generation.Result, error) {
return generation.Result{Outcome: generation.GenerationOutcome{Status: "no_results"}}, nil
}
type fakeSearch struct{ calls int }
func (f *fakeSearch) Search(context.Context, string, int) ([]indices.Index, error) {
f.calls++
return []indices.Index{}, nil
}
func TestInjectableCompositionDoesNotStartSchedulerOrNeedDatabase(t *testing.T) {
search := &fakeSearch{}
factoryCalls := 0
app := New(nil, &config.Config{JWTSecret: "composition-test"}, Dependencies{IndexSearcher: search, GenerationFactory: func(*ai.Pipeline) generation.UseCase { factoryCalls++; return fakeGeneration{} }, EnableScheduler: false})
defer app.Close()
token, _ := auth.GenerateToken("owner", "owner@example.test", "user", "composition-test")
request := httptest.NewRequest("GET", "/api/indices/search?q=test", nil)
request.Header.Set("Authorization", "Bearer "+token)
response := httptest.NewRecorder()
app.Router.ServeHTTP(response, request)
if response.Code != 200 || search.calls != 1 || factoryCalls != 1 {
t.Fatalf("status=%d search=%d factory=%d", response.Code, search.calls, factoryCalls)
}
}