feat(generation): resume manual summary jobs
This commit is contained in:
@ -3,108 +3,55 @@ 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"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const generationHTTPSecret = "ticket-7-http-contract-secret"
|
||||
const generationHTTPSecret = "ticket-27-http-contract-secret"
|
||||
|
||||
type fakeGenerationUseCase struct {
|
||||
result generation.Result
|
||||
err error
|
||||
userID string
|
||||
calls int
|
||||
type fakeJobStarter struct{ user string }
|
||||
|
||||
func (f *fakeJobStarter) Start(_ context.Context, user string) (models.GenerationJob, error) {
|
||||
f.user = user
|
||||
return models.GenerationJob{ID: "job-id", Status: "running"}, nil
|
||||
}
|
||||
|
||||
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 {
|
||||
func TestGenerateSummaryHTTPAcceptsJobUsingJWTUser(t *testing.T) {
|
||||
h := handlers.New(nil, &config.Config{JWTSecret: generationHTTPSecret}, nil, nil, nil, nil)
|
||||
starter := &fakeJobStarter{}
|
||||
h.SetGenerationJobs(starter)
|
||||
router := api.SetupRouter(h, generationHTTPSecret)
|
||||
token, _ := auth.GenerateToken("jwt-owner", "owner@example.test", "user", generationHTTPSecret)
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/summaries/generate", strings.NewReader(`{"user_id":"attacker","content":"candidate-secret"}`))
|
||||
request.Header.Set("Authorization", "Bearer "+token)
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, request)
|
||||
if response.Code != 202 || starter.user != "jwt-owner" {
|
||||
t.Fatalf("status=%d user=%s body=%s", response.Code, starter.user, response.Body)
|
||||
}
|
||||
if response.Header().Get("Location") != "/api/summaries/generation-jobs/job-id" {
|
||||
t.Fatal("missing poll location")
|
||||
}
|
||||
var envelope struct {
|
||||
Data models.GenerationJob `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &envelope); 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},
|
||||
if envelope.Data.Status != "running" || strings.Contains(response.Body.String(), "candidate-secret") {
|
||||
t.Fatal(response.Body)
|
||||
}
|
||||
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)
|
||||
}
|
||||
}
|
||||
})
|
||||
for _, path := range []string{"/api/summaries/generation-jobs/recent", "/api/summaries/generation-jobs/id"} {
|
||||
response = httptest.NewRecorder()
|
||||
router.ServeHTTP(response, httptest.NewRequest("GET", path, nil))
|
||||
if response.Code != 401 {
|
||||
t.Fatalf("%s: %d", path, response.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -1,6 +1,7 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/tradarr/backend/internal/ai"
|
||||
"github.com/tradarr/backend/internal/auth"
|
||||
@ -15,16 +16,18 @@ import (
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
companyCatalog CompanyCatalog
|
||||
indexSearcher indices.IndexSearcher
|
||||
generationUseCase generation.UseCase
|
||||
repo *models.Repository
|
||||
cfg *config.Config
|
||||
enc *crypto.Encryptor
|
||||
registry *scraper.Registry
|
||||
pipeline *ai.Pipeline
|
||||
scheduler *scheduler.Scheduler
|
||||
reportManager *ai.ReportManager
|
||||
companyCatalog CompanyCatalog
|
||||
indexSearcher indices.IndexSearcher
|
||||
generationJobs interface {
|
||||
Start(context.Context, string) (models.GenerationJob, error)
|
||||
}
|
||||
repo *models.Repository
|
||||
cfg *config.Config
|
||||
enc *crypto.Encryptor
|
||||
registry *scraper.Registry
|
||||
pipeline *ai.Pipeline
|
||||
scheduler *scheduler.Scheduler
|
||||
reportManager *ai.ReportManager
|
||||
}
|
||||
|
||||
func New(
|
||||
@ -51,6 +54,13 @@ func New(
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) SetGenerationUseCase(uc generation.UseCase) { h.generationUseCase = uc }
|
||||
func (h *Handler) SetGenerationUseCase(uc generation.UseCase) {
|
||||
if h.repo != nil && uc != nil {
|
||||
h.generationJobs = generation.NewJobs(h.repo, uc)
|
||||
}
|
||||
}
|
||||
func (h *Handler) SetGenerationJobs(jobs interface {
|
||||
Start(context.Context, string) (models.GenerationJob, error)
|
||||
}) { h.generationJobs = jobs }
|
||||
|
||||
func (h *Handler) AdminOnly() gin.HandlerFunc { return auth.AdminOnly(h.repo) }
|
||||
|
||||
@ -1,10 +1,9 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/tradarr/backend/internal/httputil"
|
||||
@ -22,27 +21,45 @@ func (h *Handler) ListSummaries(c *gin.Context) {
|
||||
}
|
||||
|
||||
func (h *Handler) GenerateSummary(c *gin.Context) {
|
||||
if h.generationUseCase == nil {
|
||||
if h.generationJobs == nil {
|
||||
c.JSON(http.StatusServiceUnavailable, gin.H{"error": "generation unavailable"})
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(c.Request.Context(), 2*time.Hour)
|
||||
defer cancel()
|
||||
result, err := h.generationUseCase.Generate(ctx, c.GetString("userID"))
|
||||
job, err := h.generationJobs.Start(c.Request.Context(), 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"})
|
||||
c.Header("Location", "/api/summaries/generation-jobs/"+job.ID)
|
||||
c.JSON(http.StatusAccepted, gin.H{"data": job})
|
||||
}
|
||||
func (h *Handler) RecentGenerationJob(c *gin.Context) {
|
||||
job, err := h.repo.RecentGenerationJob(c.Request.Context(), c.GetString("userID"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "generation unavailable"})
|
||||
return
|
||||
}
|
||||
httputil.OK(c, job)
|
||||
}
|
||||
|
||||
var generationJobUUID = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`)
|
||||
|
||||
func (h *Handler) GetGenerationJob(c *gin.Context) {
|
||||
id := c.Param("id")
|
||||
if !generationJobUUID.MatchString(id) {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "generation not found"})
|
||||
return
|
||||
}
|
||||
job, err := h.repo.GetGenerationJob(c.Request.Context(), c.GetString("userID"), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "generation unavailable"})
|
||||
return
|
||||
}
|
||||
if job == nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "generation not found"})
|
||||
return
|
||||
}
|
||||
httputil.OK(c, job)
|
||||
}
|
||||
func (h *Handler) ListGenerations(c *gin.Context) {
|
||||
limit, err := strconv.Atoi(c.DefaultQuery("limit", "10"))
|
||||
|
||||
Reference in New Issue
Block a user