328 lines
12 KiB
Go
328 lines
12 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/companycatalog"
|
|
"github.com/tradarr/backend/internal/generation"
|
|
"github.com/tradarr/backend/internal/models"
|
|
"github.com/tradarr/backend/internal/rankingcapability"
|
|
"github.com/tradarr/backend/internal/scraper"
|
|
"github.com/tradarr/backend/internal/summarybudget"
|
|
)
|
|
|
|
type Fixtures struct {
|
|
RankingModelID string `json:"rankingModelID"`
|
|
RankingModelName string `json:"rankingModelName"`
|
|
RankingCapability rankingcapability.Capability `json:"rankingCapability"`
|
|
SummaryModelID string `json:"summaryModelID"`
|
|
CompanyQuery string `json:"companyQuery"`
|
|
CompanyID string `json:"companyID"`
|
|
CompanyName string `json:"companyName"`
|
|
CompanySymbol string `json:"companySymbol"`
|
|
CompanyFIGI string `json:"companyFIGI"`
|
|
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{
|
|
SummaryModelID: "00000000-0000-0000-0000-000000001203",
|
|
RankingModelID: "00000000-0000-0000-0000-000000001204",
|
|
RankingModelName: "llama3",
|
|
RankingCapability: rankingcapability.Lookup("ollama", "llama3", ""),
|
|
CompanyQuery: "E2E Company", CompanyID: "isin:US0000000001", CompanyName: "E2E Company Inc.", CompanySymbol: "E2ECO", CompanyFIGI: "BBG000E2E001",
|
|
SummarySentinel: "E2E synthesized financial summary", ArticleTitle: "E2E private article title", ArticleURL: "https://fixture.invalid/private-article", ArticleContent: "E2E private article body", CandidateID: "pending-candidate-id",
|
|
}
|
|
}
|
|
|
|
type Event struct {
|
|
Model string `json:"model,omitempty"`
|
|
Kind string `json:"kind"`
|
|
Query string `json:"query,omitempty"`
|
|
CompanyID string `json:"company_id,omitempty"`
|
|
Symbols []string `json:"symbols,omitempty"`
|
|
CandidateID string `json:"candidate_id,omitempty"`
|
|
}
|
|
|
|
// FakeCompanyCatalog keeps the browser journey deterministic and entirely
|
|
// local. It exercises the production catalog port without OpenFIGI traffic.
|
|
type FakeCompanyCatalog struct{ Fakes *Fakes }
|
|
|
|
func (c FakeCompanyCatalog) SearchCompanies(query string, limit int) ([]companycatalog.Company, error) {
|
|
company := c.Fakes.company()
|
|
c.Fakes.record(Event{Kind: "companySearches", Query: query})
|
|
if limit < 1 || !strings.Contains(strings.ToLower(company.Name), strings.ToLower(strings.TrimSpace(query))) {
|
|
return []companycatalog.Company{}, nil
|
|
}
|
|
return []companycatalog.Company{company}, nil
|
|
}
|
|
|
|
func (c FakeCompanyCatalog) ResolveCompany(companyID string) (companycatalog.Company, error) {
|
|
company := c.Fakes.company()
|
|
c.Fakes.record(Event{Kind: "companyResolutions", CompanyID: companyID})
|
|
if companyID != company.CompanyID {
|
|
return companycatalog.Company{}, companycatalog.ErrUnknownCompany
|
|
}
|
|
return company, nil
|
|
}
|
|
|
|
func (f *Fakes) company() companycatalog.Company {
|
|
return companycatalog.Company{CompanyID: f.Fixture.CompanyID, Name: f.Fixture.CompanyName, YahooSymbol: f.Fixture.CompanySymbol, FIGI: f.Fixture.CompanyFIGI, Exchange: "E2E Exchange", MIC: "XEEE", Country: "E2E Country"}
|
|
}
|
|
|
|
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"], "companySearches": f.counts["companySearches"], "companyResolutions": f.counts["companyResolutions"], "scraperCalls": f.counts["scraperCalls"], "relevanceScoringCalls": f.counts["relevanceScoringCalls"], "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.CompanyName, "ticker": f.Fixture.CompanySymbol, "figi": f.Fixture.CompanyFIGI, "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{{ContentState: scraper.ContentComplete, 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 json.RawMessage `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 len(req.Format) > 0 && req.Format[0] == '{' {
|
|
if req.Model != f.Fixture.RankingModelName {
|
|
http.Error(w, "invalid scoring model", 400)
|
|
return
|
|
}
|
|
start := strings.LastIndex(req.Prompt, "\n{")
|
|
if start < 0 {
|
|
http.Error(w, "scoring payload missing", 400)
|
|
return
|
|
}
|
|
var payload generation.TitleScoreRequest
|
|
if json.Unmarshal([]byte(req.Prompt[start+1:]), &payload) != nil || len(payload.Titles) == 0 {
|
|
http.Error(w, "scoring titles missing", 400)
|
|
return
|
|
}
|
|
rows := []map[string]any{}
|
|
for i, title := range payload.Titles {
|
|
if title.Index != i {
|
|
http.Error(w, "invalid scoring index", 400)
|
|
return
|
|
}
|
|
rows = append(rows, map[string]any{"index": title.Index, "score": 80})
|
|
}
|
|
encoded, _ := json.Marshal(map[string]any{"scores": rows})
|
|
response = string(encoded)
|
|
f.record(Event{Kind: "relevanceScoringCalls", Model: req.Model})
|
|
} else if string(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]any{"response": response, "done": true, "done_reason": "stop"})
|
|
})
|
|
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"
|
|
}
|
|
if len(opts.JSONSchema) > 0 {
|
|
body["format"] = opts.JSONSchema
|
|
}
|
|
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 {
|
|
Done bool `json:"done"`
|
|
DoneReason string `json:"done_reason"`
|
|
Response string `json:"response"`
|
|
}
|
|
err = json.NewDecoder(resp.Body).Decode(&result)
|
|
if err == nil && opts.RequireComplete && (!result.Done || result.DoneReason != "stop") {
|
|
return "", fmt.Errorf("fake provider incomplete")
|
|
}
|
|
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
|
|
}
|
|
|
|
// Binary test seam: the loopback fixture's selected IDs represent yes decisions.
|
|
func (f FakeLayaRanker) DecideMentions(ctx context.Context, mode, pass string, assets []models.UserAsset, candidates []generation.Candidate) ([]generation.Candidate, error) {
|
|
return f.Rank(ctx, mode, assets, candidates)
|
|
}
|
|
func (c FakeCompanyCatalog) MentionNames(id string) ([]string, error) {
|
|
company, err := c.ResolveCompany(id)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return []string{company.Name}, nil
|
|
}
|
|
|
|
// FixtureSummaryProfile belongs only to the isolated browser stack. It is never
|
|
// registered globally or used by the production server's composition.
|
|
func FixtureSummaryProfile(provider, model string) (summarybudget.Profile, bool) {
|
|
if provider != "ollama" || model != "fake-summary" {
|
|
return summarybudget.Profile{}, false
|
|
}
|
|
return summarybudget.Profile{ContextWindowTokens: 8192, InputLimitTokens: 8192, OutputReserveTokens: 1024, Counter: summarybudget.UTF8UpperBound, FramingTokens: 1024}, true
|
|
}
|