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 } } }