Files
TradarrV2/backend/internal/generation/generation.go

303 lines
9.6 KiB
Go

package generation
import (
"context"
"crypto/rand"
"errors"
"fmt"
"strings"
"time"
"github.com/tradarr/backend/internal/models"
"github.com/tradarr/backend/internal/scraper"
)
type UserInput struct {
SummaryModelID *string
Language, RankingMode string
GlobalLimit int
Assets []models.UserAsset
Sources []models.Source
}
type Candidate struct {
ID, SourceID string
Article scraper.Article
orderDate *time.Time
orderFrozen bool
}
type SourceStat struct {
SourceID string `json:"source_id"`
SourceType string `json:"source_type"`
Status string `json:"status"`
Candidates int `json:"candidates"`
LayaSelected int `json:"laya_selected"`
Selected int `json:"selected"`
ArticleLimit int `json:"article_limit"`
ContentFallbacks int `json:"content_fallbacks"`
FailureCode string `json:"failure_code,omitempty"`
}
type GenerationOutcome struct {
ID string `json:"id"`
Status string `json:"status"`
Language string `json:"language"`
RankingMode string `json:"ranking_mode"`
TotalCandidates int `json:"total_candidates"`
ContentFallbacks int `json:"content_fallbacks"`
LayaSelected int `json:"laya_selected"`
Selected int `json:"selected"`
GlobalLimit int `json:"global_limit"`
SourceStats []SourceStat `json:"source_stats"`
FailureCode string `json:"failure_code,omitempty"`
CreatedAt time.Time `json:"created_at"`
}
type Result struct {
Summary *models.Summary `json:"summary"`
Outcome GenerationOutcome `json:"outcome"`
}
type GenerationRecord = Result
type Repository interface {
LoadUserInput(context.Context, string) (UserInput, error)
SaveGeneration(context.Context, string, GenerationRecord) error
}
// LayaRanker is a dedicated engine port, never a generic provider role.
type LayaRanker interface {
Rank(context.Context, string, []models.UserAsset, []Candidate) ([]Candidate, error)
}
type Ranker = LayaRanker
type Summarizer interface {
Summarize(context.Context, string, []models.UserAsset, []Candidate) (string, error)
}
type ResolvedSummary struct {
Summarizer Summarizer
CatalogID, ProviderID, Provider, Model string
}
type SummaryResolver interface {
Resolve(context.Context, string, *string) (ResolvedSummary, error)
}
type UseCase interface {
Generate(context.Context, string) (Result, error)
}
type Dependencies struct {
Decider MentionDecider
Names MentionNameResolver
Repository Repository
SummaryResolver SummaryResolver
LayaRanker LayaRanker
Scrapers map[string]scraper.Scraper
Ranker Ranker
Summarizer Summarizer
Clock func() time.Time
}
type useCase struct{ Dependencies }
func NewUseCase(d Dependencies) UseCase {
if d.LayaRanker != nil {
d.Ranker = d.LayaRanker
}
if d.Decider == nil {
d.Decider, _ = d.Ranker.(MentionDecider)
}
if d.Clock == nil {
d.Clock = time.Now
}
return &useCase{d}
}
func NewID() string {
var b [16]byte
if _, err := rand.Read(b[:]); err != nil {
panic(err)
}
b[6] = (b[6] & 15) | 64
b[8] = (b[8] & 63) | 128
return fmt.Sprintf("%x-%x-%x-%x-%x", b[:4], b[4:6], b[6:8], b[8:10], b[10:])
}
func (u *useCase) Generate(ctx context.Context, userID string) (Result, error) {
input, err := u.Repository.LoadUserInput(ctx, userID)
if err != nil {
return Result{}, fmt.Errorf("load generation input: %w", err)
}
id := models.GenerationJobID(ctx)
if id == "" {
id = NewID()
}
out := GenerationOutcome{ID: id, Language: input.Language, RankingMode: input.RankingMode, GlobalLimit: input.GlobalLimit, CreatedAt: u.Clock(), SourceStats: []SourceStat{}}
resolved := ResolvedSummary{Summarizer: u.Summarizer}
finish := func(status, code, content string) (Result, error) {
out.Status = status
out.FailureCode = code
result := Result{Outcome: out}
if content != "" {
result.Summary = &models.Summary{ID: NewID(), UserID: userID, Content: content, GeneratedAt: out.CreatedAt}
if resolved.CatalogID != "" {
result.Summary.SummaryModelID = &resolved.CatalogID
result.Summary.AIProviderID = &resolved.ProviderID
result.Summary.ProviderName = &resolved.Provider
result.Summary.ModelName = &resolved.Model
}
}
saveCtx := ctx
// Terminal metadata must survive a canceled provider/worker context.
// Preserve the job identity for the existing atomic finalization path.
if status == "failed" && ctx.Err() != nil {
var cancel context.CancelFunc
saveCtx, cancel = context.WithTimeout(context.WithoutCancel(ctx), 10*time.Second)
defer cancel()
}
if err := u.Repository.SaveGeneration(saveCtx, userID, result); err != nil {
return Result{}, fmt.Errorf("save generation: %w", err)
}
return result, nil
}
if (input.Language != "fr" && input.Language != "en") || (input.RankingMode != "title" && input.RankingMode != "title_content") || input.GlobalLimit <= 0 {
return finish("failed", "invalid_preferences", "")
}
// Explicit Summarizer is a test/injected port. Production always resolves
// the selected catalogue ID before touching any source or Laya.
if u.SummaryResolver != nil {
resolved, err = u.SummaryResolver.Resolve(ctx, userID, input.SummaryModelID)
if err != nil {
return finish("failed", "summary_model_unavailable", "")
}
}
if resolved.Summarizer == nil {
return finish("failed", "summary_model_unavailable", "")
}
if u.Decider == nil {
return finish("failed", "laya_unavailable", "")
}
symbols := []string{}
for _, a := range input.Assets {
symbols = append(symbols, a.Symbol)
}
candidates := []Candidate{}
stats := map[string]int{}
partial := false
for _, source := range input.Sources {
if !source.Operational() {
continue
}
stat := SourceStat{SourceID: source.ID, SourceType: source.Type, ArticleLimit: source.ArticleLimit, Status: "ok"}
if stat.ArticleLimit <= 0 {
stat.ArticleLimit = 20
}
feed := u.Scrapers[*source.SourceKey]
var articles []scraper.Article
if feed == nil {
err = fmt.Errorf("unavailable")
} else {
sourceSymbols := symbols
if *source.SourceKey == models.SourceYahooFinance {
sourceSymbols = yahooSymbols(input.Assets)
}
articles, err = feed.Scrape(ctx, append([]string(nil), sourceSymbols...))
}
if err != nil {
stat.Status = "failed"
stat.FailureCode = "source_unavailable"
partial = true
} else {
articles = recentArticles(articles)
if len(articles) > stat.ArticleLimit {
articles = articles[:stat.ArticleLimit]
}
orderDates := make([]*time.Time, len(articles))
for i, a := range articles {
if a.PublishedAt != nil {
date := *a.PublishedAt
orderDates[i] = &date
}
}
if input.RankingMode == "title_content" && *source.SourceKey == models.SourceBloomberg {
if enricher, ok := feed.(scraper.ArticleEnricher); ok {
enriched, enrichErr := enricher.Enrich(ctx, append([]scraper.Article(nil), articles...))
valid := enrichErr == nil && len(enriched) == len(articles)
if valid {
for i, a := range enriched {
if a.URL != articles[i].URL || a.Title != articles[i].Title {
valid = false
break
}
}
}
if valid {
for i, a := range enriched {
articles[i].Content = a.Content
articles[i].ContentTruncated = a.ContentTruncated
if a.PublishedAt != nil {
articles[i].PublishedAt = a.PublishedAt
}
}
}
}
}
for i, article := range articles {
stat.Candidates++
out.TotalCandidates++
if input.RankingMode == "title_content" && (strings.TrimSpace(article.Content) == "" || strings.TrimSpace(article.Content) == strings.TrimSpace(article.Title)) {
stat.ContentFallbacks++
out.ContentFallbacks++
article.Content = ""
article.ContentTruncated = false
}
if input.RankingMode == "title" {
article.Content = ""
article.ContentTruncated = false
}
candidates = append(candidates, Candidate{ID: NewID(), SourceID: source.ID, Article: article, orderDate: orderDates[i], orderFrozen: true})
}
}
stats[source.ID] = len(out.SourceStats)
out.SourceStats = append(out.SourceStats, stat)
}
if len(candidates) == 0 {
if partial {
return finish("failed", "sources_unavailable", "")
}
return finish("no_results", "", "")
}
selected, layaAccepted, err := u.selectThreePass(ctx, input, candidates)
if err != nil {
return finish("failed", err.Error(), "")
}
for source, n := range layaAccepted {
out.SourceStats[stats[source]].LayaSelected = n
out.LayaSelected += n
}
for _, c := range selected {
out.SourceStats[stats[c.SourceID]].Selected++
}
out.Selected = len(selected)
if len(selected) == 0 {
return finish("no_results", "", "")
}
content, err := resolved.Summarizer.Summarize(ctx, input.Language, input.Assets, selected)
if err != nil || ctx.Err() != nil {
return finish("failed", summaryFailureCode(ctx, err), "")
}
if strings.TrimSpace(content) == "" {
return finish("failed", "summary_failed", "")
}
if partial {
return finish("partial", "source_unavailable", content)
}
return finish("succeeded", "", content)
}
func summaryFailureCode(ctx context.Context, err error) string {
if errors.Is(ctx.Err(), context.DeadlineExceeded) || errors.Is(err, context.DeadlineExceeded) {
return "summary_timeout"
}
if errors.Is(ctx.Err(), context.Canceled) || errors.Is(err, context.Canceled) {
return "summary_canceled"
}
var timeout interface{ Timeout() bool }
if errors.As(err, &timeout) && timeout.Timeout() {
return "summary_timeout"
}
return "summary_failed"
}