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:
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)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user