feat(generation): persist summary outcomes without articles
Record generation outcomes and summaries for history while keeping article content transient. Refs #7 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
76
backend/internal/api/generation_persistence_test.go
Normal file
76
backend/internal/api/generation_persistence_test.go
Normal file
@ -0,0 +1,76 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/tradarr/backend/internal/generation"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
)
|
||||
|
||||
type memoryFeed struct{}
|
||||
|
||||
func (memoryFeed) Name() string { return "fixture" }
|
||||
func (memoryFeed) Scrape(context.Context, []string) ([]scraper.Article, error) {
|
||||
return []scraper.Article{{Title: "private-candidate-title", Content: "private-candidate-content", URL: "https://private.invalid/candidate"}}, nil
|
||||
}
|
||||
|
||||
type passRanker struct{}
|
||||
|
||||
func (passRanker) Rank(_ context.Context, _ string, _ []models.UserAsset, c []generation.Candidate) ([]generation.Candidate, error) {
|
||||
return c, nil
|
||||
}
|
||||
|
||||
type safeSummarizer struct{}
|
||||
|
||||
func (safeSummarizer) Summarize(context.Context, string, []models.UserAsset, []generation.Candidate) (string, error) {
|
||||
return "Safe financial synthesis", nil
|
||||
}
|
||||
|
||||
func TestGenerationSucceedsWithoutArticleTablesAndRollsBackSummaryPostgres(t *testing.T) {
|
||||
db, _ := ticket7DB(t)
|
||||
for _, statement := range []string{
|
||||
`CREATE TABLE users(id UUID PRIMARY KEY,language TEXT DEFAULT 'fr',ranking_mode TEXT DEFAULT 'title')`,
|
||||
`CREATE TABLE user_assets(id UUID PRIMARY KEY,user_id UUID,symbol TEXT,name TEXT,created_at TIMESTAMPTZ DEFAULT NOW())`,
|
||||
`CREATE TABLE sources(id UUID PRIMARY KEY,name TEXT,type TEXT,enabled BOOLEAN,article_limit INTEGER DEFAULT 20,created_at TIMESTAMPTZ DEFAULT NOW())`,
|
||||
`CREATE TABLE settings(key TEXT PRIMARY KEY,value TEXT)`,
|
||||
`CREATE TABLE summaries(id UUID PRIMARY KEY,user_id UUID REFERENCES users(id),content TEXT,ai_provider_id UUID,generated_at TIMESTAMPTZ)`,
|
||||
`INSERT INTO users(id) VALUES('00000000-0000-0000-0000-000000000001')`,
|
||||
`INSERT INTO sources(id,name,type,enabled) VALUES('00000000-0000-0000-0000-000000000002','Fixture','fixture',true)`,
|
||||
`CREATE TABLE summary_generations(id UUID PRIMARY KEY,user_id UUID,summary_id UUID REFERENCES summaries(id),outcome JSONB NOT NULL,created_at TIMESTAMPTZ)`,
|
||||
} {
|
||||
if _, err := db.Exec(statement); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
repo := models.NewRepository(db)
|
||||
uc := generation.NewUseCase(generation.Dependencies{Repository: generation.RepositoryAdapter{Repo: repo}, Scrapers: map[string]scraper.Scraper{"fixture": memoryFeed{}}, Ranker: passRanker{}, Summarizer: safeSummarizer{}})
|
||||
result, err := uc.Generate(context.Background(), "00000000-0000-0000-0000-000000000001")
|
||||
if err != nil || result.Summary == nil || result.Outcome.Status != "succeeded" {
|
||||
t.Fatalf("result=%+v err=%v", result, err)
|
||||
}
|
||||
var payload string
|
||||
if err = db.QueryRow(`SELECT outcome::text FROM summary_generations`).Scan(&payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, secret := range []string{"private-candidate", "private.invalid"} {
|
||||
if strings.Contains(payload, secret) {
|
||||
t.Fatal("candidate data persisted", payload)
|
||||
}
|
||||
}
|
||||
// Force the second INSERT to fail; the first summary INSERT must roll back.
|
||||
id := generation.NewID()
|
||||
s := &models.Summary{ID: generation.NewID(), Content: "must roll back", GeneratedAt: time.Now()}
|
||||
err = repo.SaveGeneration(context.Background(), "00000000-0000-0000-0000-000000000001", id, s, json.RawMessage(`invalid-json`), time.Now())
|
||||
if err == nil {
|
||||
t.Fatal("expected aggregate insert failure")
|
||||
}
|
||||
var count int
|
||||
if err = db.QueryRow(`SELECT count(*) FROM summaries`).Scan(&count); err != nil || count != 1 {
|
||||
t.Fatalf("summary insert did not roll back: %d %v", count, err)
|
||||
}
|
||||
}
|
||||
236
backend/internal/api/generation_ticket7_test.go
Normal file
236
backend/internal/api/generation_ticket7_test.go
Normal file
@ -0,0 +1,236 @@
|
||||
package api_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/lib/pq"
|
||||
"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/models"
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
)
|
||||
|
||||
const ticket7JWTSecret = "ticket-7-test-secret"
|
||||
|
||||
func TestGenerationHistoryRouteExistsAndIsAuthenticated(t *testing.T) {
|
||||
router := api.SetupRouter(handlers.New(nil, &config.Config{JWTSecret: ticket7JWTSecret}, nil, nil, nil, nil), ticket7JWTSecret)
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/summaries/generations?limit=10", nil))
|
||||
if response.Code != http.StatusUnauthorized {
|
||||
t.Fatalf("GET /api/summaries/generations without a token: got %d, want 401; body=%s", response.Code, response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerationHistoryIsScopedToJWTUserPostgres(t *testing.T) {
|
||||
db, _ := ticket7DB(t)
|
||||
if _, err := db.Exec(`CREATE TABLE summary_generations (id UUID PRIMARY KEY, user_id UUID NOT NULL, summary_id UUID, outcome JSONB NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, row := range []struct{ id, user, marker string }{
|
||||
{"00000000-0000-0000-0000-000000000101", "00000000-0000-0000-0000-000000000001", "alpha-private-outcome"},
|
||||
{"00000000-0000-0000-0000-000000000202", "00000000-0000-0000-0000-000000000002", "beta-private-outcome"},
|
||||
} {
|
||||
if _, err := db.Exec(`INSERT INTO summary_generations (id,user_id,outcome) VALUES ($1,$2,$3)`, row.id, row.user, `{"marker":"`+row.marker+`"}`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
router := api.SetupRouter(handlers.New(models.NewRepository(db), &config.Config{JWTSecret: ticket7JWTSecret}, nil, nil, nil, nil), ticket7JWTSecret)
|
||||
for _, user := range []struct{ id, email, own, other string }{
|
||||
{"00000000-0000-0000-0000-000000000001", "alpha@example.test", "alpha-private-outcome", "beta-private-outcome"},
|
||||
{"00000000-0000-0000-0000-000000000002", "beta@example.test", "beta-private-outcome", "alpha-private-outcome"},
|
||||
} {
|
||||
token, err := auth.GenerateToken(user.id, user.email, "user", ticket7JWTSecret)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/summaries/generations?limit=10", nil)
|
||||
request.Header.Set("Authorization", "Bearer "+token)
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, request)
|
||||
if response.Code != http.StatusOK {
|
||||
t.Errorf("generation history for %s: got %d want 200: %s", user.email, response.Code, response.Body.String())
|
||||
continue
|
||||
}
|
||||
var body map[string]any
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
encoded, _ := json.Marshal(body["data"])
|
||||
if !strings.Contains(string(encoded), user.own) || strings.Contains(string(encoded), user.other) {
|
||||
t.Errorf("generation history crossed user scope for %s: %s", user.email, encoded)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenerationHistoryLimitContractPostgres(t *testing.T) {
|
||||
db, _ := ticket7DB(t)
|
||||
if _, err := db.Exec(`CREATE TABLE summary_generations (id UUID PRIMARY KEY, user_id UUID NOT NULL, summary_id UUID, outcome JSONB NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
router := api.SetupRouter(handlers.New(models.NewRepository(db), &config.Config{JWTSecret: ticket7JWTSecret}, nil, nil, nil, nil), ticket7JWTSecret)
|
||||
token, err := auth.GenerateToken("00000000-0000-0000-0000-000000000001", "limit@example.test", "user", ticket7JWTSecret)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
limit string
|
||||
want int
|
||||
}{{"50", http.StatusOK}, {"51", http.StatusBadRequest}} {
|
||||
t.Run("limit="+tc.limit, func(t *testing.T) {
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/summaries/generations?limit="+tc.limit, nil)
|
||||
request.Header.Set("Authorization", "Bearer "+token)
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, request)
|
||||
if response.Code != tc.want {
|
||||
t.Fatalf("GET /api/summaries/generations?limit=%s: got %d, want %d; body=%s", tc.limit, response.Code, tc.want, response.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPersistentScrapeTriggerRouteIsClosed(t *testing.T) {
|
||||
router := api.SetupRouter(handlers.New(nil, &config.Config{JWTSecret: ticket7JWTSecret}, nil, nil, nil, nil), ticket7JWTSecret)
|
||||
for _, route := range router.Routes() {
|
||||
if route.Method == http.MethodPost && route.Path == "/api/admin/scrape-jobs/trigger" {
|
||||
t.Fatalf("persistent scrape trigger route is still registered: %s %s", route.Method, route.Path)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSummaryGenerationOutcomesMigrationIsAggregateAndTransactionalPostgres(t *testing.T) {
|
||||
db, schema := ticket7DB(t)
|
||||
for _, statement := range []string{
|
||||
`CREATE TABLE users (id UUID PRIMARY KEY, email TEXT NOT NULL UNIQUE)`,
|
||||
`CREATE TABLE summaries (id UUID PRIMARY KEY, user_id UUID NOT NULL REFERENCES users(id), content TEXT NOT NULL)`,
|
||||
} {
|
||||
if _, err := db.Exec(statement); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
up, err := os.ReadFile("../database/migrations/000013_summary_generations.up.sql")
|
||||
if err != nil {
|
||||
t.Fatalf("read migration 000013 summary generations: %v", err)
|
||||
}
|
||||
tx, err := db.Begin()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = tx.Exec(string(up)); err != nil {
|
||||
t.Fatalf("apply migration 000013 in a transaction: %v", err)
|
||||
}
|
||||
var aggregateColumns int
|
||||
if err = tx.QueryRow(`SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=$1 AND table_name='summary_generations' AND column_name IN ('user_id','summary_id','outcome','created_at')`, schema).Scan(&aggregateColumns); err != nil || aggregateColumns != 4 {
|
||||
t.Fatalf("migration must persist user/summary references and aggregate outcome only: aggregate columns=%d err=%v", aggregateColumns, err)
|
||||
}
|
||||
var forbiddenColumns int
|
||||
if err = tx.QueryRow(`SELECT COUNT(*) FROM information_schema.columns WHERE table_schema=$1 AND table_name='summary_generations' AND column_name IN ('article_id','article_title','title','url','content','prompt')`, schema).Scan(&forbiddenColumns); err != nil || forbiddenColumns != 0 {
|
||||
t.Fatalf("generation outcome schema contains article/prompt data columns: count=%d err=%v", forbiddenColumns, err)
|
||||
}
|
||||
for _, relation := range []string{"articles", "article_symbols"} {
|
||||
var exists bool
|
||||
if err = tx.QueryRow(`SELECT to_regclass($1) IS NOT NULL`, schema+"."+relation).Scan(&exists); err != nil || exists {
|
||||
t.Fatalf("generation migration requires/persisted article relation %s: exists=%v err=%v", relation, exists, err)
|
||||
}
|
||||
}
|
||||
if err = tx.Rollback(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var exists bool
|
||||
if err = db.QueryRow(`SELECT to_regclass($1) IS NOT NULL`, schema+".summary_generations").Scan(&exists); err != nil || exists {
|
||||
t.Fatalf("migration DDL did not roll back atomically: exists=%v err=%v", exists, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReportRequiresOwnedSummaryAndExcerptFromThatSummaryPostgres(t *testing.T) {
|
||||
db, _ := ticket7DB(t)
|
||||
for _, statement := range []string{
|
||||
`CREATE TABLE users (id UUID PRIMARY KEY, email TEXT NOT NULL, password_hash TEXT NOT NULL, role TEXT NOT NULL DEFAULT 'user', created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
|
||||
`CREATE TABLE summaries (id UUID PRIMARY KEY, user_id UUID NOT NULL REFERENCES users(id), content TEXT NOT NULL, ai_provider_id UUID, generated_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
|
||||
`CREATE TABLE reports (id UUID PRIMARY KEY DEFAULT gen_random_uuid(), user_id UUID NOT NULL REFERENCES users(id), summary_id UUID REFERENCES summaries(id), context_excerpt TEXT NOT NULL, question TEXT NOT NULL, answer TEXT NOT NULL DEFAULT '', status TEXT NOT NULL DEFAULT 'generating', error_msg TEXT NOT NULL DEFAULT '', created_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
|
||||
`CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT NOT NULL DEFAULT '')`,
|
||||
`CREATE TABLE ai_providers (id UUID PRIMARY KEY, name TEXT NOT NULL, api_key_encrypted TEXT NOT NULL DEFAULT '', model TEXT NOT NULL DEFAULT '', endpoint TEXT NOT NULL DEFAULT '', is_active BOOLEAN NOT NULL DEFAULT FALSE, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW())`,
|
||||
`INSERT INTO users (id,email,password_hash) VALUES ('00000000-0000-0000-0000-000000000001','first@example.test','hash'), ('00000000-0000-0000-0000-000000000002','second@example.test','hash')`,
|
||||
`INSERT INTO summaries (id,user_id,content) VALUES ('00000000-0000-0000-0000-000000000011','00000000-0000-0000-0000-000000000001','FIRST USER SUMMARY: approved excerpt.'), ('00000000-0000-0000-0000-000000000022','00000000-0000-0000-0000-000000000002','SECOND USER SUMMARY: private excerpt.')`,
|
||||
} {
|
||||
if _, err := db.Exec(statement); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
token, err := auth.GenerateToken("00000000-0000-0000-0000-000000000001", "first@example.test", "user", ticket7JWTSecret)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := models.NewRepository(db)
|
||||
h := handlers.New(repo, &config.Config{JWTSecret: ticket7JWTSecret}, nil, nil, ai.NewPipeline(repo, nil), nil)
|
||||
router := api.SetupRouter(h, ticket7JWTSecret)
|
||||
for _, payload := range []string{
|
||||
`{"excerpts":["FIRST USER SUMMARY: approved excerpt."],"question":"Explain"}`,
|
||||
`{"summary_id":"00000000-0000-0000-0000-000000000022","excerpts":["SECOND USER SUMMARY: private excerpt."],"question":"Explain"}`,
|
||||
`{"summary_id":"00000000-0000-0000-0000-000000000011","excerpts":["article data not present in this summary"],"question":"Explain"}`,
|
||||
} {
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/reports", strings.NewReader(payload))
|
||||
request.Header.Set("Authorization", "Bearer "+token)
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, request)
|
||||
if response.Code < http.StatusBadRequest || response.Code >= http.StatusInternalServerError {
|
||||
t.Errorf("report must reject missing/foreign summary or unverified excerpt with a client error: status=%d", response.Code)
|
||||
}
|
||||
}
|
||||
deadline := time.Now().Add(time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
var pending int
|
||||
if err := db.QueryRow(`SELECT COUNT(*) FROM reports WHERE status='generating'`).Scan(&pending); err != nil || pending == 0 {
|
||||
break
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
var reports int
|
||||
if err := db.QueryRow(`SELECT COUNT(*) FROM reports`).Scan(&reports); err != nil || reports != 0 {
|
||||
t.Errorf("rejected report requests were persisted: count=%d err=%v", reports, err)
|
||||
}
|
||||
}
|
||||
|
||||
func ticket7DB(t *testing.T) (*sql.DB, string) {
|
||||
t.Helper()
|
||||
dsn := postgresTestURL(t)
|
||||
db, err := sql.Open("postgres", dsn)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
db.SetMaxOpenConns(1)
|
||||
schema := fmt.Sprintf("ticket7_%d", time.Now().UnixNano())
|
||||
if _, err = db.Exec(`CREATE SCHEMA ` + pq.QuoteIdentifier(schema)); err != nil {
|
||||
db.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = db.Exec(`SET search_path TO ` + pq.QuoteIdentifier(schema)); err != nil {
|
||||
db.Exec(`DROP SCHEMA ` + pq.QuoteIdentifier(schema) + ` CASCADE`)
|
||||
db.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_, _ = db.Exec(`DROP SCHEMA ` + pq.QuoteIdentifier(schema) + ` CASCADE`)
|
||||
_ = db.Close()
|
||||
})
|
||||
return db, schema
|
||||
}
|
||||
|
||||
type inertContractScraper struct{}
|
||||
|
||||
func (inertContractScraper) Name() string { return "bloomberg" }
|
||||
func (inertContractScraper) Scrape(context.Context, []string) ([]scraper.Article, error) {
|
||||
return nil, nil
|
||||
}
|
||||
110
backend/internal/api/handlers/generation_http_contract_test.go
Normal file
110
backend/internal/api/handlers/generation_http_contract_test.go
Normal file
@ -0,0 +1,110 @@
|
||||
package handlers_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"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/auth"
|
||||
"github.com/tradarr/backend/internal/config"
|
||||
"github.com/tradarr/backend/internal/generation"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
)
|
||||
|
||||
const generationHTTPSecret = "ticket-7-http-contract-secret"
|
||||
|
||||
type fakeGenerationUseCase struct {
|
||||
result generation.Result
|
||||
err error
|
||||
userID string
|
||||
calls int
|
||||
}
|
||||
|
||||
func (f *fakeGenerationUseCase) Generate(_ context.Context, userID string) (generation.Result, error) {
|
||||
f.calls++
|
||||
f.userID = userID
|
||||
return f.result, f.err
|
||||
}
|
||||
|
||||
func TestGenerateSummaryHTTPUsesJWTUserAndReturnsAggregateOnlyEnvelopes(t *testing.T) {
|
||||
previousMode := gin.Mode()
|
||||
gin.SetMode(gin.TestMode)
|
||||
t.Cleanup(func() { gin.SetMode(previousMode) })
|
||||
token, err := auth.GenerateToken("jwt-owner", "owner@example.test", "user", generationHTTPSecret)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
status string
|
||||
wantStatus int
|
||||
wantSummary bool
|
||||
}{
|
||||
{name: "success", status: "succeeded", wantStatus: http.StatusCreated, wantSummary: true},
|
||||
{name: "partial", status: "partial", wantStatus: http.StatusCreated, wantSummary: true},
|
||||
{name: "no results", status: "no_results", wantStatus: http.StatusOK, wantSummary: false},
|
||||
{name: "provider failure", status: "failed", wantStatus: http.StatusBadGateway, wantSummary: false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
fake := &fakeGenerationUseCase{result: generation.Result{
|
||||
Outcome: generation.GenerationOutcome{
|
||||
ID: "outcome-aggregate-id", Status: tt.status, Language: "fr", RankingMode: "title",
|
||||
TotalCandidates: 7, ContentFallbacks: 1, LayaSelected: 2,
|
||||
Selected: 2, SourceStats: []generation.SourceStat{{SourceID: "source-aggregate-id", SourceType: "fixture", Status: "ok", Candidates: 7, LayaSelected: 2}},
|
||||
},
|
||||
}}
|
||||
if tt.wantSummary {
|
||||
fake.result.Summary = &models.Summary{ID: "summary-id", UserID: "jwt-owner", Content: "Safe synthesized market summary"}
|
||||
}
|
||||
h := handlers.New(nil, &config.Config{JWTSecret: generationHTTPSecret}, nil, nil, ai.NewPipeline(nil, nil), nil)
|
||||
h.SetGenerationUseCase(fake)
|
||||
router := api.SetupRouter(h, generationHTTPSecret)
|
||||
body := `{"user_id":"attacker-user","title":"candidate-title-secret","url":"https://candidate.invalid/private","content":"candidate-content-secret","candidate_id":"candidate-id-secret"}`
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/summaries/generate", strings.NewReader(body))
|
||||
request.Header.Set("Authorization", "Bearer "+token)
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, request)
|
||||
if response.Code != tt.wantStatus {
|
||||
t.Fatalf("POST /api/summaries/generate status=%d, want %d: %s", response.Code, tt.wantStatus, response.Body.String())
|
||||
}
|
||||
if fake.calls != 1 || fake.userID != "jwt-owner" {
|
||||
t.Fatalf("use case identity came from client input: calls=%d userID=%q", fake.calls, fake.userID)
|
||||
}
|
||||
var envelope struct {
|
||||
Data struct {
|
||||
Summary *models.Summary `json:"summary"`
|
||||
Outcome generation.GenerationOutcome `json:"outcome"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &envelope); err != nil {
|
||||
t.Fatalf("decode generation envelope: %v; body=%s", err, response.Body.String())
|
||||
}
|
||||
if (envelope.Data.Summary != nil) != tt.wantSummary || envelope.Data.Outcome.Status != tt.status {
|
||||
t.Fatalf("unexpected summary/outcome envelope: %+v", envelope.Data)
|
||||
}
|
||||
for _, articleValue := range []string{"candidate-title-secret", "https://candidate.invalid/private", "candidate-content-secret", "candidate-id-secret"} {
|
||||
if strings.Contains(response.Body.String(), articleValue) {
|
||||
t.Errorf("article candidate data leaked in response: %q", articleValue)
|
||||
}
|
||||
}
|
||||
outcomeJSON, err := json.Marshal(envelope.Data.Outcome)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, articleField := range []string{`"title"`, `"url"`, `"content"`, `"prompt"`, `"candidate_id"`} {
|
||||
if strings.Contains(string(outcomeJSON), articleField+":") {
|
||||
t.Errorf("article field %s leaked into outcome: %s", articleField, outcomeJSON)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@ -4,19 +4,21 @@ import (
|
||||
"github.com/tradarr/backend/internal/ai"
|
||||
"github.com/tradarr/backend/internal/config"
|
||||
"github.com/tradarr/backend/internal/crypto"
|
||||
"github.com/tradarr/backend/internal/generation"
|
||||
"github.com/tradarr/backend/internal/models"
|
||||
"github.com/tradarr/backend/internal/scheduler"
|
||||
"github.com/tradarr/backend/internal/scraper"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
repo *models.Repository
|
||||
cfg *config.Config
|
||||
enc *crypto.Encryptor
|
||||
registry *scraper.Registry
|
||||
pipeline *ai.Pipeline
|
||||
scheduler *scheduler.Scheduler
|
||||
reportManager *ai.ReportManager
|
||||
generationUseCase generation.UseCase
|
||||
repo *models.Repository
|
||||
cfg *config.Config
|
||||
enc *crypto.Encryptor
|
||||
registry *scraper.Registry
|
||||
pipeline *ai.Pipeline
|
||||
scheduler *scheduler.Scheduler
|
||||
reportManager *ai.ReportManager
|
||||
}
|
||||
|
||||
func New(
|
||||
@ -37,3 +39,5 @@ func New(
|
||||
reportManager: ai.NewReportManager(),
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) SetGenerationUseCase(uc generation.UseCase) { h.generationUseCase = uc }
|
||||
|
||||
@ -9,7 +9,7 @@ import (
|
||||
)
|
||||
|
||||
type reportRequest struct {
|
||||
SummaryID string `json:"summary_id"`
|
||||
SummaryID string `json:"summary_id" binding:"required,uuid"`
|
||||
Excerpts []string `json:"excerpts" binding:"required,min=1"`
|
||||
Question string `json:"question" binding:"required"`
|
||||
}
|
||||
@ -22,10 +22,22 @@ func (h *Handler) CreateReport(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
var summaryID *string
|
||||
if req.SummaryID != "" {
|
||||
summaryID = &req.SummaryID
|
||||
summary, err := h.repo.GetOwnedSummary(req.SummaryID, userID)
|
||||
if err != nil {
|
||||
httputil.InternalError(c, err)
|
||||
return
|
||||
}
|
||||
if summary == nil {
|
||||
httputil.NotFound(c)
|
||||
return
|
||||
}
|
||||
for _, excerpt := range req.Excerpts {
|
||||
if strings.TrimSpace(excerpt) == "" || !strings.Contains(summary.Content, excerpt) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "excerpt must come from the summary"})
|
||||
return
|
||||
}
|
||||
}
|
||||
summaryID := &summary.ID
|
||||
|
||||
// Joindre les extraits avec un séparateur visuel
|
||||
excerpt := buildExcerptContext(req.Excerpts)
|
||||
|
||||
@ -2,6 +2,7 @@ package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
@ -21,13 +22,38 @@ func (h *Handler) ListSummaries(c *gin.Context) {
|
||||
}
|
||||
|
||||
func (h *Handler) GenerateSummary(c *gin.Context) {
|
||||
userID := c.GetString("userID")
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Hour)
|
||||
defer cancel()
|
||||
summary, err := h.pipeline.GenerateForUser(ctx, userID)
|
||||
if err != nil {
|
||||
httputil.InternalError(c, err)
|
||||
if h.generationUseCase == nil {
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "generation unavailable"})
|
||||
return
|
||||
}
|
||||
httputil.Created(c, summary)
|
||||
ctx, cancel := context.WithTimeout(c.Request.Context(), 2*time.Hour)
|
||||
defer cancel()
|
||||
result, err := h.generationUseCase.Generate(ctx, c.GetString("userID"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "generation unavailable"})
|
||||
return
|
||||
}
|
||||
switch result.Outcome.Status {
|
||||
case "succeeded", "partial":
|
||||
c.JSON(http.StatusCreated, gin.H{"data": result})
|
||||
case "no_results":
|
||||
httputil.OK(c, result)
|
||||
case "failed":
|
||||
c.JSON(http.StatusBadGateway, gin.H{"data": result})
|
||||
default:
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "invalid generation outcome"})
|
||||
}
|
||||
}
|
||||
func (h *Handler) ListGenerations(c *gin.Context) {
|
||||
limit, err := strconv.Atoi(c.DefaultQuery("limit", "10"))
|
||||
if err != nil || limit < 1 || limit > 50 {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "limit must be between 1 and 50"})
|
||||
return
|
||||
}
|
||||
rows, err := h.repo.ListGenerations(c.Request.Context(), c.GetString("userID"), limit)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "history unavailable"})
|
||||
return
|
||||
}
|
||||
httputil.OK(c, rows)
|
||||
}
|
||||
|
||||
@ -40,10 +40,8 @@ func SetupRouter(h *handlers.Handler, jwtSecret string) *gin.Engine {
|
||||
authed.POST("/me/assets", h.AddMyAsset)
|
||||
authed.DELETE("/me/assets/:symbol", h.RemoveMyAsset)
|
||||
|
||||
authed.GET("/articles", h.ListArticles)
|
||||
authed.GET("/articles/:id", h.GetArticle)
|
||||
|
||||
authed.GET("/summaries", h.ListSummaries)
|
||||
authed.GET("/summaries/generations", h.ListGenerations)
|
||||
authed.GET("/summaries/status", h.GetGeneratingStatus)
|
||||
authed.POST("/summaries/generate", h.GenerateSummary)
|
||||
|
||||
@ -71,9 +69,6 @@ func SetupRouter(h *handlers.Handler, jwtSecret string) *gin.Engine {
|
||||
admin.GET("/sources", h.ListSources)
|
||||
admin.PUT("/sources/:id", h.UpdateSource)
|
||||
|
||||
admin.GET("/scrape-jobs", h.ListScrapeJobs)
|
||||
admin.POST("/scrape-jobs/trigger", h.TriggerScrapeJob)
|
||||
|
||||
admin.GET("/settings", h.ListSettings)
|
||||
admin.PUT("/settings", h.UpdateSettings)
|
||||
admin.GET("/settings/default-prompt", h.GetDefaultSystemPrompt)
|
||||
|
||||
Reference in New Issue
Block a user