Files
TradarrV2/backend/internal/e2estack/fakes.go
Blomios 989996fbd6 feat(ai): add personal summary models and retire Q&A
Add an admin-managed provider model catalog with per-user summary selection, migration backfill, and generation snapshots. Retire report creation and messaging while preserving owner-scoped history.

Refs #15 #16

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-11-21 20:45:21 +01:00

230 lines
7.4 KiB
Go

package e2estack
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net"
"net/http"
"strings"
"sync"
"github.com/tradarr/backend/internal/ai"
"github.com/tradarr/backend/internal/generation"
"github.com/tradarr/backend/internal/models"
"github.com/tradarr/backend/internal/scraper"
)
type Fixtures struct {
SummaryModelID string `json:"summaryModelID"`
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{"00000000-0000-0000-0000-000000001203", "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 {
Model string `json:"model,omitempty"`
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"`
Model string `json:"model"`
}
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", Model: req.Model})
}
_ = 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 {
Model string
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
}
model := p.Model
if model == "" {
model = "fake-laya"
}
body := map[string]any{"prompt": prompt, "model": model, "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
}
// FakeLayaRanker is explicitly test-only. No production Laya implementation is
// inferred from an Ollama/provider role; the real adapter remains unavailable.
type FakeLayaRanker struct{ Provider FakeProvider }
func (f FakeLayaRanker) Rank(ctx context.Context, mode string, assets []models.UserAsset, candidates []generation.Candidate) ([]generation.Candidate, error) {
articles := []models.Article{}
byID := map[string]generation.Candidate{}
labels := []string{}
for _, a := range assets {
labels = append(labels, a.Name+" ("+a.Symbol+")")
}
for _, c := range candidates {
articles = append(articles, models.Article{ID: c.ID, Title: c.Article.Title, Content: c.Article.Content})
byID[c.ID] = c
}
ranked, err := ai.RankArticles(ctx, f.Provider, labels, articles, 20, mode)
if err != nil {
return nil, err
}
result := []generation.Candidate{}
for _, a := range ranked {
result = append(result, byID[a.ID])
}
return result, nil
}