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:
237
backend/cmd/e2e/main.go
Normal file
237
backend/cmd/e2e/main.go
Normal file
@ -0,0 +1,237 @@
|
||||
// The dedicated E2E executable never imports concrete article scraper adapters.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"database/sql"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"os/signal"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/tradarr/backend/internal/ai"
|
||||
"github.com/tradarr/backend/internal/config"
|
||||
"github.com/tradarr/backend/internal/database"
|
||||
"github.com/tradarr/backend/internal/e2estack"
|
||||
"github.com/tradarr/backend/internal/generation"
|
||||
"github.com/tradarr/backend/internal/indices/openfigi"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
"github.com/tradarr/backend/internal/server"
|
||||
)
|
||||
|
||||
func secret() string {
|
||||
var b [32]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return hex.EncodeToString(b[:])
|
||||
}
|
||||
func main() {
|
||||
// Linux parent-death signals follow the creating thread; keep it alive until
|
||||
// all managed child processes have been stopped and reaped.
|
||||
runtime.LockOSThread()
|
||||
defer runtime.UnlockOSThread()
|
||||
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
|
||||
defer stop()
|
||||
if err := guardParentDeath(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "E2E parent guard:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
if err := run(ctx); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "E2E:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
func run(ctx context.Context) error {
|
||||
work := flag.String("work", "", "private disposable directory")
|
||||
psql := flag.String("psql", "", "cached PostgreSQL psql path")
|
||||
flag.Parse()
|
||||
if *work == "" || *psql == "" || !filepath.IsAbs(*work) || !filepath.IsAbs(*psql) {
|
||||
return errors.New("E2E requires absolute private workspace and psql paths")
|
||||
}
|
||||
dsn := os.Getenv("DATABASE_URL")
|
||||
if err := e2estack.ValidateURL(dsn, true); err != nil {
|
||||
return err
|
||||
}
|
||||
parsed, _ := url.Parse(dsn)
|
||||
if strings.TrimPrefix(parsed.Path, "/") != "tradarr_e2e" {
|
||||
return errors.New("E2E database must be the dedicated tradarr_e2e database")
|
||||
}
|
||||
// Block external Go HTTP egress even if a future code path accidentally uses
|
||||
// a default client. Explicit fake clients use the same restricted transport.
|
||||
client := e2estack.LoopbackClient()
|
||||
http.DefaultTransport = client.Transport
|
||||
http.DefaultClient = client
|
||||
db, err := database.Connect(dsn)
|
||||
if err != nil {
|
||||
return errors.New("cannot connect disposable E2E database")
|
||||
}
|
||||
defer db.Close()
|
||||
var tables int
|
||||
if err = db.QueryRow(`SELECT count(*) FROM information_schema.tables WHERE table_schema='public' AND table_type='BASE TABLE'`).Scan(&tables); err != nil || tables != 0 {
|
||||
return errors.New("refusing to migrate a nonempty E2E database")
|
||||
}
|
||||
if err = database.RunMigrations(db); err != nil {
|
||||
return fmt.Errorf("E2E migrations: %w", err)
|
||||
}
|
||||
fakes := e2estack.NewFakes()
|
||||
fakeURL, closeFakes, err := e2estack.Listen(fakes.Handler())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer closeFakes()
|
||||
if err = e2estack.ValidateURL(fakeURL, false); err != nil {
|
||||
return err
|
||||
}
|
||||
// Keep every migration's historical tables, but choose exactly one enabled
|
||||
// fixture source. Do not seed candidate data into any historical table.
|
||||
if err = seed(db, fakeURL); err != nil {
|
||||
return err
|
||||
}
|
||||
cfg := &config.Config{JWTSecret: secret(), EncryptionKey: []byte(secret()[:32]), AdminEmail: "bootstrap-e2e@example.test", AdminPassword: secret()}
|
||||
repo := models.NewRepository(db)
|
||||
if err = server.EnsureAdmin(repo, cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
feeds := map[string]scraper.Scraper{"stocktwits": e2estack.FakeScraper{URL: fakeURL, Client: client}}
|
||||
provider := e2estack.FakeProvider{URL: fakeURL, Client: client}
|
||||
gin.SetMode(gin.TestMode)
|
||||
gin.DefaultWriter = io.Discard
|
||||
app := server.New(repo, cfg, server.Dependencies{Feeds: feeds, IndexSearcher: openfigi.New(openfigi.Config{BaseURL: fakeURL}, client), EnableScheduler: false, GenerationFactory: func(p *ai.Pipeline) generation.UseCase {
|
||||
return p.NewGenerationUseCaseWithProviders(feeds, provider, provider)
|
||||
}})
|
||||
defer app.Close()
|
||||
apiURL, closeAPI, err := e2estack.Listen(app.Router)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer closeAPI()
|
||||
frontend, err := filepath.Abs("../frontend")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
port := listener.Addr().(*net.TCPAddr).Port
|
||||
listener.Close()
|
||||
frontendURL := fmt.Sprintf("http://127.0.0.1:%d", port)
|
||||
baseConfig, _ := json.Marshal(filepath.Join(frontend, "vite.config.ts"))
|
||||
root, _ := json.Marshal(frontend)
|
||||
target, _ := json.Marshal(apiURL)
|
||||
viteConfig := filepath.Join(*work, "vite.e2e.config.mjs")
|
||||
content := fmt.Sprintf(`import base from %s; export default {...base,root:%s,plugins:[...base.plugins,{name:'e2e-no-external-links',transformIndexHtml(html){return html.replace(/<link[^>]*https?:[^>]*>/g,'')}}],server:{headers:{'Content-Security-Policy':"default-src 'self' blob: data:; connect-src 'self' ws://127.0.0.1:*; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; img-src 'self' data:"},host:'127.0.0.1',port:%d,strictPort:true,proxy:{'/api':{target:%s,changeOrigin:true}}}};`, baseConfig, root, port, target)
|
||||
if err = os.WriteFile(viteConfig, []byte(content), 0600); err != nil {
|
||||
return err
|
||||
}
|
||||
logFile, err := os.OpenFile(filepath.Join(*work, "frontend.log"), os.O_CREATE|os.O_WRONLY, 0600)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer logFile.Close()
|
||||
vite := exec.Command("node", filepath.Join(frontend, "node_modules/vite/bin/vite.js"), "--config", viteConfig)
|
||||
vite.Dir = frontend
|
||||
vite.Stdout = logFile
|
||||
vite.Stderr = logFile
|
||||
vite.SysProcAttr = e2estack.ChildProcessAttrs()
|
||||
if err = vite.Start(); err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = syscall.Kill(-vite.Process.Pid, syscall.SIGKILL); _ = vite.Wait() }()
|
||||
readyCtx, cancel := context.WithTimeout(ctx, 45*time.Second)
|
||||
defer cancel()
|
||||
if err = waitReady(readyCtx, client, frontendURL); err != nil {
|
||||
data, _ := os.ReadFile(filepath.Join(*work, "frontend.log"))
|
||||
fmt.Fprintln(os.Stderr, string(data))
|
||||
return err
|
||||
}
|
||||
manifest := map[string]any{"networkPolicy": "loopback-only", "generationProvider": "fake-laya", "frontendUrl": frontendURL, "apiUrl": apiURL, "databaseUrl": dsn, "openFigiFakeUrl": fakeURL, "scraperFakeUrl": fakeURL, "layaFakeUrl": fakeURL, "fakeControlUrl": fakeURL, "psqlPath": *psql, "fakeAuditPath": "/audit", "bootstrapAdmin": map[string]string{"email": cfg.AdminEmail, "password": cfg.AdminPassword}, "fixtures": fakes.Fixture}
|
||||
path := filepath.Join(*work, "stack.json")
|
||||
encoded, _ := json.Marshal(manifest)
|
||||
if err = os.WriteFile(path, encoded, 0600); err != nil {
|
||||
return err
|
||||
}
|
||||
defer os.Remove(path)
|
||||
pw := exec.CommandContext(ctx, "node", filepath.Join(frontend, "node_modules/@playwright/test/cli.js"), "test", "--config=playwright.e2e.config.mjs", "--output", filepath.Join(*work, "playwright"))
|
||||
pw.Dir = frontend
|
||||
pw.Env = append(os.Environ(), "TRADARR_E2E_STACK_MANIFEST="+path)
|
||||
pw.Stdout = os.Stdout
|
||||
pw.Stderr = os.Stderr
|
||||
pw.SysProcAttr = e2estack.ChildProcessAttrs()
|
||||
if err = pw.Start(); err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = syscall.Kill(-pw.Process.Pid, syscall.SIGKILL) }()
|
||||
err = pw.Wait()
|
||||
audit, _ := os.OpenFile(filepath.Join(*work, "fake-audit.json"), os.O_CREATE|os.O_WRONLY, 0600)
|
||||
if audit != nil {
|
||||
fakes.Handler().ServeHTTP(auditWriter{audit}, mustRequest(fakeURL+"/audit"))
|
||||
audit.Close()
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
type auditWriter struct{ io.Writer }
|
||||
|
||||
func (a auditWriter) Header() http.Header { return http.Header{} }
|
||||
func (a auditWriter) WriteHeader(int) {}
|
||||
func mustRequest(u string) *http.Request { r, _ := http.NewRequest("GET", u, nil); return r }
|
||||
func waitReady(ctx context.Context, client *http.Client, address string) error {
|
||||
for {
|
||||
attempt, cancel := context.WithTimeout(ctx, time.Second)
|
||||
req, _ := http.NewRequestWithContext(attempt, "GET", address, nil)
|
||||
resp, err := client.Do(req)
|
||||
if err == nil {
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode == 200 {
|
||||
cancel()
|
||||
return nil
|
||||
}
|
||||
}
|
||||
cancel()
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return errors.New("E2E frontend readiness timed out")
|
||||
case <-time.After(100 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
}
|
||||
func seed(db *sql.DB, fakeURL string) error {
|
||||
tx, err := db.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
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 {
|
||||
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 {
|
||||
return err
|
||||
}
|
||||
for _, role := range []string{"filter", "summary", "report"} {
|
||||
if _, err = tx.Exec(`INSERT INTO settings(key,value) VALUES($1,'00000000-0000-0000-0000-000000001202') ON CONFLICT(key) DO UPDATE SET value=EXCLUDED.value`, "ai_role_"+role+"_provider"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
23
backend/cmd/e2e/parent_death_linux.go
Normal file
23
backend/cmd/e2e/parent_death_linux.go
Normal file
@ -0,0 +1,23 @@
|
||||
//go:build linux
|
||||
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// Arm the signal after NotifyContext, before creating any resources. Unlike a
|
||||
// shell trap, Linux delivers it even when the CLI parent is killed with SIGKILL.
|
||||
func guardParentDeath() error {
|
||||
parent := os.Getppid()
|
||||
_, _, errno := syscall.RawSyscall6(syscall.SYS_PRCTL, 1, uintptr(syscall.SIGTERM), 0, 0, 0, 0)
|
||||
if errno != 0 {
|
||||
return errno
|
||||
}
|
||||
if os.Getppid() != parent {
|
||||
return errors.New("E2E parent exited during setup")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
7
backend/cmd/e2e/parent_death_other.go
Normal file
7
backend/cmd/e2e/parent_death_other.go
Normal file
@ -0,0 +1,7 @@
|
||||
//go:build !linux
|
||||
|
||||
package main
|
||||
|
||||
import "errors"
|
||||
|
||||
func guardParentDeath() error { return errors.New("E2E supervision requires Linux") }
|
||||
@ -4,21 +4,17 @@ import (
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"github.com/tradarr/backend/internal/ai"
|
||||
"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/crypto"
|
||||
"github.com/tradarr/backend/internal/database"
|
||||
"github.com/tradarr/backend/internal/indices/openfigi"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
"github.com/tradarr/backend/internal/scheduler"
|
||||
"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"
|
||||
)
|
||||
|
||||
func main() {
|
||||
@ -39,34 +35,22 @@ func main() {
|
||||
|
||||
repo := models.NewRepository(db)
|
||||
enc := crypto.New(cfg.EncryptionKey)
|
||||
pipeline := ai.NewPipeline(repo, enc)
|
||||
|
||||
if err := ensureAdmin(repo, cfg); err != nil {
|
||||
log.Printf("ensure admin: %v", err)
|
||||
}
|
||||
|
||||
registry := scraper.NewRegistry(repo)
|
||||
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
|
||||
}
|
||||
useCase := pipeline.NewGenerationUseCase(feeds)
|
||||
|
||||
sched := scheduler.New(registry, pipeline, repo)
|
||||
sched.SetGenerationUseCase(useCase)
|
||||
if err := sched.Start(); err != nil {
|
||||
log.Printf("scheduler: %v", err)
|
||||
}
|
||||
defer sched.Stop()
|
||||
|
||||
h := handlers.New(repo, cfg, enc, registry, pipeline, sched)
|
||||
h.SetGenerationUseCase(useCase)
|
||||
h.SetIndexSearcher(openfigi.New(openfigi.Config{APIKey: cfg.OpenFIGIAPIKey, Timeout: cfg.OpenFIGITimeout}, nil))
|
||||
r := api.SetupRouter(h, cfg.JWTSecret)
|
||||
app := server.New(repo, cfg, server.Dependencies{Feeds: feeds, IndexSearcher: openfigi.New(openfigi.Config{APIKey: cfg.OpenFIGIAPIKey, Timeout: cfg.OpenFIGITimeout}, nil), EnableScheduler: true})
|
||||
defer app.Close()
|
||||
|
||||
addr := fmt.Sprintf(":%s", cfg.Port)
|
||||
log.Printf("server listening on %s", addr)
|
||||
if err := r.Run(addr); err != nil {
|
||||
if err := app.Router.Run(addr); err != nil {
|
||||
log.Fatalf("server: %v", err)
|
||||
}
|
||||
}
|
||||
@ -77,27 +61,5 @@ type adminRepository interface {
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
_, err = repo.CreateUser(cfg.AdminEmail, hash, models.RoleAdmin)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
log.Printf("admin account created: %s", cfg.AdminEmail)
|
||||
return nil
|
||||
return server.EnsureAdmin(repo, cfg)
|
||||
}
|
||||
|
||||
@ -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
|
||||
}
|
||||
|
||||
193
backend/internal/e2estack/fakes.go
Normal file
193
backend/internal/e2estack/fakes.go
Normal 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
|
||||
}
|
||||
49
backend/internal/e2estack/network.go
Normal file
49
backend/internal/e2estack/network.go
Normal 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 }}
|
||||
}
|
||||
11
backend/internal/e2estack/process_linux.go
Normal file
11
backend/internal/e2estack/process_linux.go
Normal 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}
|
||||
}
|
||||
7
backend/internal/e2estack/process_other.go
Normal file
7
backend/internal/e2estack/process_other.go
Normal file
@ -0,0 +1,7 @@
|
||||
//go:build !linux
|
||||
|
||||
package e2estack
|
||||
|
||||
import "syscall"
|
||||
|
||||
func ChildProcessAttrs() *syscall.SysProcAttr { return &syscall.SysProcAttr{Setpgid: true} }
|
||||
50
backend/internal/e2estack/safety_test.go
Normal file
50
backend/internal/e2estack/safety_test.go
Normal 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")
|
||||
}
|
||||
}
|
||||
39
backend/internal/server/bootstrap.go
Normal file
39
backend/internal/server/bootstrap.go
Normal 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
|
||||
}
|
||||
51
backend/internal/server/server.go
Normal file
51
backend/internal/server/server.go
Normal 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() }
|
||||
40
backend/internal/server/server_test.go
Normal file
40
backend/internal/server/server_test.go
Normal 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)
|
||||
}
|
||||
}
|
||||
270
backend/scripts/e2e-supervisor.py
Normal file
270
backend/scripts/e2e-supervisor.py
Normal file
@ -0,0 +1,270 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Linux-only E2E lifecycle owner, independent of make's signal disposition.
|
||||
|
||||
The detached watcher outlives a killed launcher/make, acts as child subreaper,
|
||||
then terminates and reaps the whole descendant tree before removing its workspace.
|
||||
Never scans/kills by executable name and never removes shared caches.
|
||||
"""
|
||||
import ctypes
|
||||
import json
|
||||
import os
|
||||
import math
|
||||
import re
|
||||
from pathlib import Path
|
||||
import select
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
PR_SET_CHILD_SUBREAPER = 36
|
||||
PR_SET_PDEATHSIG = 1
|
||||
|
||||
|
||||
def process(pid):
|
||||
"""Identity includes start ticks to avoid acting on a recycled PID."""
|
||||
try:
|
||||
fields = Path(f"/proc/{pid}/stat").read_text().rsplit(")", 1)[1].split()
|
||||
return int(fields[1]), fields[19], fields[0] # ppid, starttime, state
|
||||
except (OSError, ValueError, IndexError):
|
||||
return None
|
||||
|
||||
|
||||
def same_process(pid, identity):
|
||||
current = process(pid)
|
||||
return current is not None and current[1] == identity[1] and current[2] != "Z"
|
||||
|
||||
|
||||
def descendants(root):
|
||||
records = {}
|
||||
for item in Path("/proc").iterdir():
|
||||
if item.name.isdigit():
|
||||
identity = process(int(item.name))
|
||||
if identity is not None:
|
||||
records[int(item.name)] = identity
|
||||
owned = {root}
|
||||
while True:
|
||||
found = {pid for pid, identity in records.items() if identity[0] in owned}
|
||||
if found <= owned:
|
||||
break
|
||||
owned |= found
|
||||
return {pid: records[pid] for pid in owned if pid != root and pid in records}
|
||||
|
||||
|
||||
def direct_children(root):
|
||||
# Unlike a cross-process ancestry scan, these lists come from the kernel's
|
||||
# actual child ownership. Include every thread, not just the group leader.
|
||||
records = {}
|
||||
for entry in Path(f"/proc/{root}/task").glob("*/children"):
|
||||
for value in entry.read_text().split():
|
||||
pid = int(value)
|
||||
identity = process(pid)
|
||||
if identity is not None and identity[0] == root:
|
||||
records[pid] = identity
|
||||
return records
|
||||
|
||||
|
||||
def reap():
|
||||
"""Return True while the kernel still owns a live child, False on ECHILD."""
|
||||
while True:
|
||||
try:
|
||||
pid, _ = os.waitpid(-1, os.WNOHANG)
|
||||
if pid == 0:
|
||||
return True
|
||||
except ChildProcessError:
|
||||
return False
|
||||
|
||||
|
||||
def stop_tree(worker):
|
||||
root = os.getpid()
|
||||
known = {}
|
||||
identity = process(worker.pid)
|
||||
if identity is not None:
|
||||
known[worker.pid] = identity
|
||||
signalled = set()
|
||||
grace = time.monotonic() + 1.5
|
||||
deadline = grace + 3
|
||||
empty_confirmations = 0
|
||||
while time.monotonic() < deadline:
|
||||
# Never forget previously observed live identities when an ancestry
|
||||
# snapshot temporarily loses a parent during exit/adoption.
|
||||
known.update(descendants(root))
|
||||
known.update(direct_children(root))
|
||||
force = time.monotonic() >= grace
|
||||
for pid, identity in known.items():
|
||||
if same_process(pid, identity):
|
||||
key = (pid, identity[1])
|
||||
if force or key not in signalled:
|
||||
try:
|
||||
os.kill(pid, signal.SIGKILL if force else signal.SIGTERM)
|
||||
signalled.add(key)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
worker.poll()
|
||||
has_children = reap()
|
||||
alive = any(same_process(pid, identity) for pid, identity in known.items())
|
||||
if not has_children and not alive:
|
||||
empty_confirmations += 1
|
||||
if empty_confirmations >= 2:
|
||||
return
|
||||
else:
|
||||
empty_confirmations = 0
|
||||
time.sleep(0.03)
|
||||
raise RuntimeError("E2E kernel-owned descendants failed to terminate; workspace retained")
|
||||
|
||||
|
||||
def timeout_duration(arguments):
|
||||
"""Read a GNU timeout soft duration; never extend an enclosing deadline."""
|
||||
position = 1
|
||||
while position < len(arguments):
|
||||
value = arguments[position]
|
||||
if value == "--":
|
||||
position += 1
|
||||
break
|
||||
if value in ("-k", "--kill-after", "-s", "--signal"):
|
||||
position += 2
|
||||
elif value in ("--foreground", "--preserve-status", "--verbose", "-v") or value.startswith(("--signal=", "--kill-after=")):
|
||||
position += 1
|
||||
elif value.startswith("-"):
|
||||
return None
|
||||
else:
|
||||
break
|
||||
if position >= len(arguments):
|
||||
return None
|
||||
match = re.fullmatch(r"([0-9]+(?:\.[0-9]+)?)([smhd]?)", arguments[position])
|
||||
if not match:
|
||||
return None
|
||||
duration = float(match[1]) * {"": 1, "s": 1, "m": 60, "h": 3600, "d": 86400}[match[2]]
|
||||
return duration if duration > 0 and math.isfinite(duration) else None
|
||||
|
||||
|
||||
def enclosing_deadline(pid):
|
||||
deadlines = []
|
||||
for _ in range(64):
|
||||
identity = process(pid)
|
||||
if identity is None:
|
||||
break
|
||||
try:
|
||||
executable = Path(os.readlink(f"/proc/{pid}/exe")).name
|
||||
if executable == "timeout":
|
||||
arguments = Path(f"/proc/{pid}/cmdline").read_bytes().decode().strip("\0").split("\0")
|
||||
duration = timeout_duration(arguments)
|
||||
if duration is not None:
|
||||
boot_now = time.clock_gettime(time.CLOCK_BOOTTIME)
|
||||
started = int(identity[1]) / os.sysconf("SC_CLK_TCK")
|
||||
remaining = max(0, duration - (boot_now - started))
|
||||
deadlines.append(time.monotonic() + remaining)
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
if identity[0] <= 0 or identity[0] == pid:
|
||||
break
|
||||
pid = identity[0]
|
||||
return min(deadlines) if deadlines else None
|
||||
|
||||
|
||||
def watcher(project, owner_pid, owner_start, life_fd, deadline=None):
|
||||
libc = ctypes.CDLL(None, use_errno=True)
|
||||
if libc.prctl(PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0) != 0:
|
||||
raise OSError(ctypes.get_errno(), "E2E subreaper setup failed")
|
||||
interrupted = []
|
||||
for sig in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP):
|
||||
signal.signal(sig, lambda received, _frame: interrupted.append(received))
|
||||
base = os.environ.get("TMPDIR") or os.environ.get("IDEA_MANAGED_TMP") or "/tmp"
|
||||
work = Path(tempfile.mkdtemp(prefix="tradarr-e2e.", dir=base))
|
||||
worker = None
|
||||
expected_parent = os.getpid()
|
||||
|
||||
def parent_death_guard():
|
||||
if libc.prctl(PR_SET_PDEATHSIG, signal.SIGTERM, 0, 0, 0) != 0:
|
||||
os._exit(125)
|
||||
if os.getppid() != expected_parent:
|
||||
os._exit(125)
|
||||
|
||||
try:
|
||||
env = dict(os.environ, TRADARR_E2E_RUN_DIR=str(work))
|
||||
worker = subprocess.Popen(
|
||||
["bash", str(project / "backend/scripts/test-e2e-worker.sh")],
|
||||
cwd=project, env=env, start_new_session=True, preexec_fn=parent_death_guard,
|
||||
)
|
||||
# Diagnostic process identities only; never credentials or DSNs.
|
||||
(work / "supervisor.json").write_text(json.dumps({
|
||||
"watcher": os.getpid(), "worker": worker.pid, "owner": owner_pid,
|
||||
}))
|
||||
while True:
|
||||
result = worker.poll()
|
||||
if result is not None:
|
||||
return result if result >= 0 else 128 - result
|
||||
ready, _, _ = select.select([life_fd], [], [], 0.05)
|
||||
alive = process(owner_pid)
|
||||
if (deadline is not None and time.monotonic() >= deadline) or interrupted or alive is None or alive[1] != owner_start or alive[2] == "Z":
|
||||
return 130
|
||||
if ready and os.read(life_fd, 1) == b"":
|
||||
return 130
|
||||
finally:
|
||||
if worker is not None:
|
||||
stop_tree(worker)
|
||||
shutil.rmtree(work)
|
||||
os.close(life_fd)
|
||||
|
||||
|
||||
def launch(project):
|
||||
if sys.platform != "linux" or not Path("/proc/self/stat").exists():
|
||||
raise RuntimeError("E2E supervision requires Linux /proc and child-subreaper support")
|
||||
owner_pid = os.getppid()
|
||||
owner = process(owner_pid)
|
||||
if owner is None:
|
||||
raise RuntimeError("E2E owner disappeared before supervision")
|
||||
read_fd, write_fd = os.pipe()
|
||||
watch = None
|
||||
pending = []
|
||||
|
||||
def forward(received, _frame):
|
||||
pending.append(received)
|
||||
if watch is not None:
|
||||
try:
|
||||
os.kill(watch.pid, signal.SIGTERM)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
|
||||
for sig in (signal.SIGINT, signal.SIGTERM, signal.SIGHUP):
|
||||
signal.signal(sig, forward)
|
||||
# Kernel notification complements polling when make itself is SIGKILLed.
|
||||
# Install handlers first, then close the setup race by rechecking the parent.
|
||||
libc = ctypes.CDLL(None, use_errno=True)
|
||||
if libc.prctl(PR_SET_PDEATHSIG, signal.SIGTERM, 0, 0, 0) != 0:
|
||||
raise OSError(ctypes.get_errno(), "E2E launcher parent-death guard failed")
|
||||
if os.getppid() != owner_pid:
|
||||
os.close(read_fd)
|
||||
os.close(write_fd)
|
||||
raise RuntimeError("E2E owner disappeared during launcher setup")
|
||||
try:
|
||||
watch = subprocess.Popen(
|
||||
[sys.executable, "-E", __file__, "--watch", str(project),
|
||||
str(owner_pid), owner[1], str(read_fd), str(enclosing_deadline(owner_pid) or 0)],
|
||||
pass_fds=(read_fd,), start_new_session=True,
|
||||
)
|
||||
os.close(read_fd)
|
||||
if pending:
|
||||
os.kill(watch.pid, signal.SIGTERM)
|
||||
return watch.wait()
|
||||
finally:
|
||||
os.close(write_fd) # abrupt launcher death closes it in the kernel too
|
||||
if watch is not None and watch.poll() is None:
|
||||
os.kill(watch.pid, signal.SIGTERM)
|
||||
watch.wait(timeout=6)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
if len(sys.argv) == 7 and sys.argv[1] == "--watch":
|
||||
code = watcher(Path(sys.argv[2]), int(sys.argv[3]), sys.argv[4], int(sys.argv[5]), float(sys.argv[6]) or None)
|
||||
elif len(sys.argv) == 2:
|
||||
code = launch(Path(sys.argv[1]))
|
||||
else:
|
||||
raise RuntimeError("invalid E2E supervisor invocation")
|
||||
sys.exit(code)
|
||||
except Exception as error:
|
||||
print(f"E2E supervisor: {error}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
126
backend/scripts/test-e2e-supervisor.py
Normal file
126
backend/scripts/test-e2e-supervisor.py
Normal file
@ -0,0 +1,126 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Offline lifecycle regression: kill the owner/launcher, not their process group."""
|
||||
import importlib.util
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
import json
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
|
||||
SUPERVISOR = Path(__file__).with_name("e2e-supervisor.py")
|
||||
spec = importlib.util.spec_from_file_location("e2e_supervisor", SUPERVISOR)
|
||||
supervision = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(supervision)
|
||||
|
||||
|
||||
@unittest.skipUnless(sys.platform == "linux", "Linux /proc supervision")
|
||||
class Lifecycle(unittest.TestCase):
|
||||
def run_case(self, victim, normal_exit=False):
|
||||
with tempfile.TemporaryDirectory(prefix="e2e-supervisor-test-", dir=os.environ.get("TMPDIR")) as temporary:
|
||||
root = Path(temporary)
|
||||
project = root / "project"
|
||||
scripts = project / "backend/scripts"
|
||||
scripts.mkdir(parents=True)
|
||||
sleeper = "import signal,time;signal.signal(signal.SIGTERM,signal.SIG_IGN);time.sleep(60)"
|
||||
code = (
|
||||
"import subprocess,sys,signal,time;"
|
||||
f"subprocess.Popen([sys.executable,'-E','-c',{sleeper!r}],start_new_session=True);"
|
||||
"signal.signal(signal.SIGTERM,signal.SIG_IGN);"
|
||||
+ ("time.sleep(.2)" if normal_exit else "time.sleep(60)")
|
||||
)
|
||||
(scripts / "test-e2e-worker.sh").write_text(
|
||||
"#!/bin/sh\nexec " + shlex.quote(sys.executable) + " -E -c " + shlex.quote(code) + "\n"
|
||||
)
|
||||
owner_code = (
|
||||
"import subprocess,sys,time;"
|
||||
f"p=subprocess.Popen([sys.executable,'-E',{str(SUPERVISOR)!r},{str(project)!r}]);"
|
||||
"p.wait();time.sleep(60)"
|
||||
)
|
||||
with (root / "output.log").open("w") as output:
|
||||
owner = subprocess.Popen([sys.executable, "-E", "-c", owner_code], env=dict(os.environ, TMPDIR=str(root)), stdout=output, stderr=output)
|
||||
identities = {}
|
||||
try:
|
||||
deadline = time.monotonic() + 5
|
||||
info = None
|
||||
while time.monotonic() < deadline:
|
||||
files = list(root.glob("tradarr-e2e.*/supervisor.json"))
|
||||
if files:
|
||||
try:
|
||||
info = json.loads(files[0].read_text())
|
||||
identities = supervision.descendants(info["watcher"])
|
||||
if len(identities) >= 2:
|
||||
workspace = files[0].parent
|
||||
break
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
time.sleep(.02)
|
||||
else:
|
||||
self.fail("supervised descendants did not start")
|
||||
if not normal_exit:
|
||||
if victim == "owner":
|
||||
os.kill(owner.pid, signal.SIGKILL)
|
||||
else:
|
||||
launcher = supervision.process(info["watcher"])[0]
|
||||
os.kill(launcher, signal.SIGKILL)
|
||||
deadline = time.monotonic() + 7
|
||||
while time.monotonic() < deadline:
|
||||
alive = [pid for pid, identity in identities.items() if supervision.same_process(pid, identity)]
|
||||
if not alive and not workspace.exists():
|
||||
break
|
||||
time.sleep(.02)
|
||||
self.assertFalse(alive, f"surviving descendants: {alive}")
|
||||
self.assertFalse(workspace.exists(), "workspace leaked")
|
||||
if victim == "launcher":
|
||||
self.assertIsNone(owner.poll(), "owner should remain alive for broken-pipe case")
|
||||
finally:
|
||||
# Tests never kill by a name/shared group, even on failure.
|
||||
for pid, identity in identities.items():
|
||||
if supervision.same_process(pid, identity):
|
||||
os.kill(pid, signal.SIGKILL)
|
||||
if owner.poll() is None:
|
||||
owner.kill()
|
||||
owner.wait(timeout=5)
|
||||
|
||||
def test_empty_proc_snapshot_is_not_cleanup_confirmation(self):
|
||||
# /proc traversal is not atomic during exit/reparenting. Even an empty
|
||||
# ancestry snapshot must not override the kernel's live-child state.
|
||||
code = "import signal,time;signal.signal(signal.SIGTERM,signal.SIG_IGN);print('ready',flush=True);time.sleep(60)"
|
||||
child = subprocess.Popen([sys.executable, "-E", "-c", code], stdout=subprocess.PIPE, text=True)
|
||||
original = supervision.descendants
|
||||
try:
|
||||
self.assertEqual(child.stdout.readline().strip(), "ready")
|
||||
supervision.descendants = lambda _root: {}
|
||||
supervision.stop_tree(child)
|
||||
self.assertIsNotNone(child.poll(), "empty /proc snapshot left a live child")
|
||||
finally:
|
||||
supervision.descendants = original
|
||||
if child.poll() is None:
|
||||
child.kill()
|
||||
child.wait()
|
||||
child.stdout.close()
|
||||
|
||||
def test_gnu_timeout_duration_parsing(self):
|
||||
self.assertEqual(supervision.timeout_duration(["timeout", "--foreground", "--preserve-status", "--signal=INT", "--kill-after=8s", "8s", "make", "test-e2e"]), 8)
|
||||
self.assertEqual(supervision.timeout_duration(["timeout", "-k", "8s", "-s", "INT", "1.5m", "make"]), 90)
|
||||
self.assertIsNone(supervision.timeout_duration(["timeout", "0", "make"]))
|
||||
self.assertIsNone(supervision.timeout_duration(["timeout", "--unknown", "8s", "make"]))
|
||||
|
||||
def test_sigkill_owner_only(self):
|
||||
self.run_case("owner")
|
||||
|
||||
def test_sigkill_launcher_broken_liveness_pipe(self):
|
||||
self.run_case("launcher")
|
||||
|
||||
def test_normal_worker_exit_reaps_detached_grandchildren(self):
|
||||
self.run_case("normal", normal_exit=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
123
backend/scripts/test-e2e-timeout.py
Normal file
123
backend/scripts/test-e2e-timeout.py
Normal file
@ -0,0 +1,123 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Integration regression: real make/embedded PG/E2E runner, single-PID timeout.
|
||||
|
||||
Pass --wrapper-dir to use QA's exact node wrapper. Without it, Playwright is
|
||||
blocked before execution, after the real Vite server has started.
|
||||
"""
|
||||
import argparse
|
||||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shlex
|
||||
import shutil
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
sys.dont_write_bytecode = True
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
spec = importlib.util.spec_from_file_location("supervisor", Path(__file__).with_name("e2e-supervisor.py"))
|
||||
supervision = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(supervision)
|
||||
|
||||
|
||||
def run(wrapper_dir):
|
||||
base = Path(os.environ.get("TMPDIR") or os.environ.get("IDEA_MANAGED_TMP") or "/tmp")
|
||||
with tempfile.TemporaryDirectory(prefix="ticket12-timeout-integration.", dir=base) as temporary:
|
||||
evidence = Path(temporary)
|
||||
if wrapper_dir:
|
||||
wrapper = Path(wrapper_dir).resolve()
|
||||
if not (wrapper / "node").is_file():
|
||||
raise RuntimeError("QA wrapper node is absent; exact reproduction refused")
|
||||
else:
|
||||
wrapper = evidence / "wrapper"
|
||||
wrapper.mkdir()
|
||||
node = shutil.which("node")
|
||||
(wrapper / "node").write_text(
|
||||
'#!/bin/bash\nif [[ "$*" == *playwright* ]]; then\n'
|
||||
' exec sleep 60\nelse\n exec ' + shlex.quote(node) + ' "$@"\nfi\n'
|
||||
)
|
||||
(wrapper / "node").chmod(0o755)
|
||||
command = ["timeout", "--foreground", "--preserve-status", "--signal=INT", "--kill-after=8s", "8s", "make", "test-e2e"]
|
||||
known = {}
|
||||
workspace = None
|
||||
process = None
|
||||
watcher = None
|
||||
names = set()
|
||||
real_ready = False
|
||||
try:
|
||||
with (evidence / "runner.log").open("w") as log:
|
||||
process = subprocess.Popen(command, cwd=ROOT, env=dict(os.environ, PATH=str(wrapper) + ":" + os.environ["PATH"]), stdout=log, stderr=log)
|
||||
deadline = time.monotonic() + 35
|
||||
while process.poll() is None and time.monotonic() < deadline:
|
||||
if workspace is None:
|
||||
for metadata in base.glob("tradarr-e2e.*/supervisor.json"):
|
||||
try:
|
||||
info = json.loads(metadata.read_text())
|
||||
owner = supervision.process(info["owner"])
|
||||
if owner is not None and owner[0] == process.pid:
|
||||
workspace = metadata.parent
|
||||
watcher = info["watcher"]
|
||||
identity = supervision.process(watcher)
|
||||
if identity:
|
||||
known[watcher] = identity
|
||||
break
|
||||
except (OSError, ValueError, KeyError):
|
||||
pass
|
||||
if watcher:
|
||||
known.update(supervision.descendants(watcher))
|
||||
if workspace is not None and (workspace / "stack.json").exists():
|
||||
real_ready = True
|
||||
for pid in known:
|
||||
try:
|
||||
names.add(Path(f"/proc/{pid}/comm").read_text().strip())
|
||||
except OSError:
|
||||
pass
|
||||
time.sleep(.03)
|
||||
code = process.wait(timeout=2)
|
||||
if workspace is None:
|
||||
raise RuntimeError("real runner did not create a supervised workspace")
|
||||
if not real_ready or not {"postgres", "e2e-stack", "sleep"}.issubset(names):
|
||||
raise RuntimeError(f"real stack incomplete: ready={real_ready}, observed process names={sorted(names)}")
|
||||
# This assertion is deliberately immediate. Waiting after timeout
|
||||
# returns keeps the test supervisor alive and masked the QA leak.
|
||||
if watcher:
|
||||
known.update(supervision.descendants(watcher))
|
||||
survivors = [pid for pid, identity in known.items() if supervision.same_process(pid, identity)]
|
||||
if survivors or workspace.exists():
|
||||
raise RuntimeError(f"timeout returned before cleanup: {len(survivors)} survivors; workspace remains={workspace.exists()}")
|
||||
if code not in (130, 2):
|
||||
raise RuntimeError(f"runner failed to clean during timeout grace period: exit={code}")
|
||||
print(f"PASS real runner + exact timeout flags: exit={code}, observed={len(known)}, no survivor/workspace when timeout returns")
|
||||
except Exception:
|
||||
print((evidence / "runner.log").read_text()[-5000:] if (evidence / "runner.log").exists() else "", file=sys.stderr)
|
||||
raise
|
||||
finally:
|
||||
# Independent fallback so a red regression does not itself leak.
|
||||
if watcher:
|
||||
known.update(supervision.descendants(watcher))
|
||||
for pid, identity in known.items():
|
||||
if supervision.same_process(pid, identity):
|
||||
try:
|
||||
os.kill(pid, signal.SIGKILL)
|
||||
except ProcessLookupError:
|
||||
pass
|
||||
if process is not None and process.poll() is None:
|
||||
process.kill()
|
||||
process.wait()
|
||||
if workspace is not None and workspace.exists():
|
||||
shutil.rmtree(workspace)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--wrapper-dir")
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
run(args.wrapper_dir)
|
||||
except Exception as error:
|
||||
print(f"FAIL E2E timeout integration: {error}", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
28
backend/scripts/test-e2e-worker.sh
Executable file
28
backend/scripts/test-e2e-worker.sh
Executable file
@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
project_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
managed_tmp="${TMPDIR:-${IDEA_MANAGED_TMP:-/tmp}}"
|
||||
pg_home="$managed_tmp/tradarr-embedded-postgres"
|
||||
cli="$pg_home/bin/embedded-postgres"
|
||||
if [[ ! -x "$cli" ]] || [[ "$("$cli" version)" != *'"version":"v2.0.1"'* ]]; then
|
||||
echo 'E2E requires cached embedded-postgres v2.0.1; prepare with make test-postgres.' >&2
|
||||
exit 2
|
||||
fi
|
||||
psql_path="$(find "$pg_home/cache" -type f -path '*/postgresql-16.15.1-*/bin/psql' -print -quit)"
|
||||
if [[ -z "$psql_path" ]]; then
|
||||
echo 'E2E requires cached PostgreSQL 16.15.1; prepare with make test-postgres.' >&2
|
||||
exit 2
|
||||
fi
|
||||
# The independent supervisor owns this directory and every process below us.
|
||||
: "${TRADARR_E2E_RUN_DIR:?invoke make test-e2e through its supervisor}"
|
||||
run_dir="$TRADARR_E2E_RUN_DIR"
|
||||
export GOCACHE="${GOCACHE:-$managed_tmp/go-build}"
|
||||
export GOMODCACHE="${GOMODCACHE:-$managed_tmp/gomodcache}"
|
||||
# No dependency installation/network downloads during an E2E run.
|
||||
export GOPROXY=off GOSUMDB=off npm_config_update_notifier=false
|
||||
unset DATABASE_URL TEST_DATABASE_URL PGHOST PGPORT PGUSER PGPASSWORD PGDATABASE PGSSLMODE TRADARR_E2E_STACK_MANIFEST NO_COLOR FORCE_COLOR
|
||||
cd "$project_root/backend"
|
||||
go build -o "$run_dir/e2e-stack" ./cmd/e2e
|
||||
exec "$cli" exec --offline --postgres-version 16.15.1 --database tradarr_e2e \
|
||||
--cache-dir "$pg_home/cache" --work-dir "$run_dir/db" \
|
||||
-- "$run_dir/e2e-stack" -work "$run_dir" -psql "$psql_path"
|
||||
6
backend/scripts/test-e2e.sh
Executable file
6
backend/scripts/test-e2e.sh
Executable file
@ -0,0 +1,6 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
project_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||
# exec preserves our parent (make) identity; Python -E ignores bundled-app
|
||||
# PYTHONHOME/PYTHONPATH without altering the caller's environment.
|
||||
exec python3 -E -B "$project_root/backend/scripts/e2e-supervisor.py" "$project_root"
|
||||
Reference in New Issue
Block a user