feat(generation): resume manual summary jobs

This commit is contained in:
2026-11-23 17:42:30 +01:00
parent 6afe2bdee0
commit 61cc906e0a
22 changed files with 851 additions and 173 deletions

View File

@ -111,7 +111,11 @@ func (u *useCase) Generate(ctx context.Context, userID string) (Result, error) {
if err != nil {
return Result{}, fmt.Errorf("load generation input: %w", err)
}
out := GenerationOutcome{ID: NewID(), Language: input.Language, RankingMode: input.RankingMode, GlobalLimit: input.GlobalLimit, CreatedAt: u.Clock(), SourceStats: []SourceStat{}}
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

View File

@ -0,0 +1,52 @@
package generation
import (
"context"
"github.com/tradarr/backend/internal/models"
"log"
"time"
)
// JobStore keeps lifecycle metadata only. Generate persists the aggregate result.
type JobStore interface {
CreateGenerationJob(context.Context, models.GenerationJob) (models.GenerationJob, bool, error)
FinishGenerationJob(context.Context, string, string, string, string) error
}
type Jobs struct {
store JobStore
useCase UseCase
}
func NewJobs(store JobStore, uc UseCase) *Jobs { return &Jobs{store, uc} }
func (j *Jobs) Start(ctx context.Context, user string) (models.GenerationJob, error) {
job, created, err := j.store.CreateGenerationJob(ctx, models.GenerationJob{ID: NewID(), UserID: user, Status: "running", CreatedAt: time.Now().UTC()})
if err != nil || !created {
return job, err
}
go j.run(job)
return job, nil
}
func (j *Jobs) run(job models.GenerationJob) {
// No HTTP request values, credentials or cancellation escape into this worker.
ctx, cancel := context.WithTimeout(models.WithGenerationJob(context.Background(), job.ID), 2*time.Hour)
defer cancel()
status, code := "failed", "generation_unavailable"
defer func() {
if recover() != nil {
status, code = "failed", "generation_unavailable"
}
// Finalization must survive a timed-out generation context.
finishCtx, finishCancel := context.WithTimeout(context.Background(), 10*time.Second)
defer finishCancel()
if err := j.store.FinishGenerationJob(finishCtx, job.ID, job.UserID, status, code); err != nil {
log.Print("generation job finalization failed")
}
}()
result, err := j.useCase.Generate(ctx, job.UserID)
if err == nil {
switch result.Outcome.Status {
case "succeeded", "partial", "no_results", "failed":
status, code = result.Outcome.Status, result.Outcome.FailureCode
}
}
}

View File

@ -0,0 +1,136 @@
package generation
import (
"context"
"fmt"
"github.com/tradarr/backend/internal/models"
"sync"
"testing"
"time"
)
type jobMemory struct {
sync.Mutex
job models.GenerationJob
finished chan struct{}
}
func (m *jobMemory) CreateGenerationJob(_ context.Context, j models.GenerationJob) (models.GenerationJob, bool, error) {
m.Lock()
defer m.Unlock()
if m.job.Status == "running" {
return m.job, false, nil
}
m.job = j
return j, true, nil
}
func (m *jobMemory) FinishGenerationJob(_ context.Context, id, user, status, code string) error {
m.Lock()
defer m.Unlock()
m.job.Status = status
m.job.FailureCode = code
close(m.finished)
return nil
}
type blockedGeneration struct {
started chan context.Context
release chan struct{}
}
func (b blockedGeneration) Generate(ctx context.Context, user string) (Result, error) {
b.started <- ctx
<-b.release
return Result{Outcome: GenerationOutcome{Status: "no_results"}}, nil
}
func TestJobSurvivesRequestCancellationAndDeduplicates(t *testing.T) {
store := &jobMemory{finished: make(chan struct{})}
uc := blockedGeneration{make(chan context.Context, 1), make(chan struct{})}
jobs := NewJobs(store, uc)
ctx, cancel := context.WithCancel(context.Background())
job, err := jobs.Start(ctx, "owner")
if err != nil || job.Status != "running" {
t.Fatalf("job=%+v err=%v", job, err)
}
worker := <-uc.started
cancel()
if worker.Err() != nil {
t.Fatal("request canceled worker")
}
if models.GenerationJobID(worker) != job.ID {
t.Fatal("job identity not propagated")
}
other, err := jobs.Start(context.Background(), "owner")
if err != nil || other.ID != job.ID {
t.Fatal("duplicate job")
}
close(uc.release)
select {
case <-store.finished:
case <-time.After(time.Second):
t.Fatal("job not finished")
}
store.Lock()
defer store.Unlock()
if store.job.Status != "no_results" {
t.Fatalf("%+v", store.job)
}
}
type terminalGeneration struct {
status string
panic bool
}
func (u terminalGeneration) Generate(context.Context, string) (Result, error) {
if u.panic {
panic("private-provider-secret")
}
return Result{Outcome: GenerationOutcome{Status: u.status}}, nil
}
func TestJobsKeepTerminalStatesAndSanitizePanics(t *testing.T) {
for _, status := range []string{"succeeded", "partial", "no_results", "failed", "invalid", "panic"} {
t.Run(status, func(t *testing.T) {
store := &jobMemory{finished: make(chan struct{})}
jobs := NewJobs(store, terminalGeneration{status: status, panic: status == "panic"})
if _, err := jobs.Start(context.Background(), "owner"); err != nil {
t.Fatal(err)
}
select {
case <-store.finished:
case <-time.After(time.Second):
t.Fatal("not finalized")
}
store.Lock()
defer store.Unlock()
expected := status
if status == "invalid" || status == "panic" {
expected = "failed"
if store.job.FailureCode != "generation_unavailable" {
t.Fatal(store.job)
}
}
if store.job.Status != expected {
t.Fatal(store.job)
}
})
}
}
type unavailableJobStore struct{ jobMemory }
func (unavailableJobStore) CreateGenerationJob(context.Context, models.GenerationJob) (models.GenerationJob, bool, error) {
return models.GenerationJob{}, false, fmt.Errorf("storage unavailable")
}
func TestJobsDoNotStartBeforeDurableAcceptance(t *testing.T) {
started := make(chan context.Context, 1)
jobs := NewJobs(&unavailableJobStore{}, blockedGeneration{started: started, release: make(chan struct{})})
if _, err := jobs.Start(context.Background(), "owner"); err == nil {
t.Fatal("accepted without persistence")
}
select {
case <-started:
t.Fatal("started without persistence")
default:
}
}