Files

160 lines
4.2 KiB
Go

package usecase
import (
"backend/internal/domain/model"
"backend/internal/domain/port"
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"github.com/google/uuid"
"io"
"math/rand/v2"
"time"
)
type Pipeline struct {
store port.PipelineStore
objects port.Objects
transform port.Transformer
MaxAttempts int32
Fault func(string) error
OnResult func(context.Context, model.Job, string, time.Duration)
}
func NewPipeline(s port.PipelineStore, o port.Objects, t port.Transformer, max int32) *Pipeline {
return &Pipeline{store: s, objects: o, transform: t, MaxAttempts: max, Fault: func(string) error { return nil }}
}
func VariantKey(id uuid.UUID, version int32, name string) string {
return fmt.Sprintf("variants/%s/v%d/%s", id, version, name)
}
func (p *Pipeline) Process(ctx context.Context, j model.Job) error {
lease := uuid.New()
owned, a, ok, e := p.store.AcquireJob(ctx, j, lease, 30*time.Second)
if e != nil {
return e
}
if !ok {
return p.Cleanup(ctx)
}
j = owned
started := time.Now()
outcome := "retry"
if j.Attempt >= p.MaxAttempts {
outcome = "failed"
}
reported := false
defer func() {
if !reported && p.OnResult != nil {
p.OnResult(ctx, j, outcome, time.Since(started))
}
}()
if j.Attempt > p.MaxAttempts {
return p.store.RetryJob(ctx, j, lease, "retry_exhausted", 0, true)
}
// Reprocessing uses the immutable original after staging was safely removed.
key := "staging/" + a.ID.String()
r, e := p.objects.Get(ctx, key)
if errors.Is(e, model.ErrNotFound) {
r, e = p.objects.Get(ctx, ObjectKey(a.ID))
}
if e != nil {
return p.retry(ctx, j, lease, e)
}
original, e := io.ReadAll(io.LimitReader(r, model.MaxImageBytes+1))
_ = r.Close()
if e != nil || int64(len(original)) != a.SizeBytes {
return p.retry(ctx, j, lease, model.ErrUnavailable)
}
sum := sha256.Sum256(original)
if hex.EncodeToString(sum[:]) != a.SHA256 {
outcome = "failed"
return p.retry(ctx, j, lease, model.ErrInvalidImage)
}
if e = p.objects.Put(ctx, ObjectKey(a.ID), bytes.NewReader(original), a.SizeBytes, a.ContentType); e != nil {
return p.retry(ctx, j, lease, e)
}
if e = p.Fault("after_original"); e != nil {
return e
}
variants, e := p.transform.Transform(ctx, bytes.NewReader(original))
if e != nil {
if errors.Is(e, model.ErrInvalidImage) {
outcome = "failed"
}
return p.retry(ctx, j, lease, e)
}
result := make([]model.Variant, 0, len(variants))
for _, v := range variants {
if e = p.objects.Put(ctx, VariantKey(a.ID, j.PipelineVersion, v.Metadata.Name), bytes.NewReader(v.Bytes), int64(len(v.Bytes)), v.Metadata.ContentType); e != nil {
return p.retry(ctx, j, lease, e)
}
result = append(result, v.Metadata)
}
if e = p.Fault("after_objects"); e != nil {
return e
}
ok, e = p.store.CompleteJob(ctx, j, lease, result)
if e != nil {
return e
}
if !ok {
outcome = "stale"
return nil
}
outcome = "ready"
if p.OnResult != nil {
p.OnResult(ctx, j, outcome, time.Since(started))
}
reported = true
if e = p.Fault("after_commit"); e != nil {
return e
}
return p.Cleanup(ctx)
}
func (p *Pipeline) retry(ctx context.Context, j model.Job, lease uuid.UUID, cause error) error {
failed := j.Attempt >= p.MaxAttempts
code := "processing_failed"
if failed {
code = "retry_exhausted"
}
if errors.Is(cause, model.ErrInvalidImage) {
failed = true
code = "invalid_image"
}
delay := time.Duration((1<<min(j.Attempt, 5))*100+rand.IntN(100)) * time.Millisecond
if e := p.store.RetryJob(ctx, j, lease, code, delay, failed); e != nil {
return e
}
// This delivery has durably recorded its retry/failed effect. Ack it; the
// transactional outbox schedules the next attempt instead of retaining a PEL entry.
return nil
}
func (p *Pipeline) Cleanup(ctx context.Context) error {
rows, e := p.store.StagingCleanup(ctx)
if e != nil {
return e
}
for _, a := range rows {
if a.Status == "ready" {
info, e := p.objects.Stat(ctx, ObjectKey(a.ID))
if e != nil {
return e
}
if info.Size != a.SizeBytes {
return model.ErrUnavailable
}
}
if e = p.objects.Remove(ctx, "staging/"+a.ID.String()); e != nil {
return e
}
if e = p.store.StagingCleaned(ctx, a.ID); e != nil {
return e
}
}
return nil
}