Files
mtusi2026lab6/internal/pipeline/worker.go
T

178 lines
5.1 KiB
Go

package pipeline
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"math/rand/v2"
"time"
"go.uber.org/zap"
"gitea.privcloud.tech/vlad_marlo/mtusi2026lab6/internal/model/dto"
)
// ErrInvalidImage identifies a permanent decode/checksum failure.
var ErrInvalidImage = errors.New("invalid image")
const sourceLimit = 10 * 1024 * 1024
const maxAttempts = 5
const claimDuration = 2 * time.Minute
const processingTimeout = 45 * time.Second
const outboxBatch = 100
// Worker processes one job at a time, independently of API admission.
type Worker struct {
observer Observer
store Store
queue Queue
objects Objects
processor Processor
log *zap.Logger
}
// New validates all side-effect boundaries at composition time.
func New(store Store, queue Queue, objects Objects, processor Processor, log *zap.Logger) (*Worker, error) {
if store == nil || queue == nil || objects == nil || processor == nil || log == nil {
return nil, fmt.Errorf("worker dependencies are required")
}
return &Worker{store: store, queue: queue, objects: objects, processor: processor, log: log}, nil
}
// Dispatch republishes durable intents whose notification or consumer was lost.
func (w *Worker) Dispatch(ctx context.Context) error {
jobs, err := w.store.Due(ctx, outboxBatch)
if err != nil {
return err
}
for _, job := range jobs {
if err := w.publish(ctx, job); err != nil {
return err
}
if err := w.store.Published(ctx, job); err != nil {
return err
}
}
return nil
}
// Run owns a bounded serial processing loop and observes cancellation between operations.
func (w *Worker) Run(ctx context.Context) {
for ctx.Err() == nil {
if err := w.Dispatch(ctx); err != nil {
w.log.Warn("job dispatch unavailable")
}
delivery, err := w.queue.Receive(ctx)
if err != nil {
w.log.Warn("job broker unavailable")
wait(ctx, time.Second)
continue
}
if delivery == nil {
continue
}
if err := w.Handle(ctx, *delivery); err != nil {
w.log.Warn("job transition unavailable")
}
}
}
// Handle acknowledges only a durable completion, retry, terminal result or fenced no-op.
func (w *Worker) Handle(ctx context.Context, delivery Delivery) (result error) {
var processingError error
if w.observer != nil {
ctx = w.observer.Extract(ctx, delivery.Job.Traceparent, delivery.Job.Tracestate)
var finish func(error)
ctx, finish = w.observer.Start(ctx, "attachment.process", "consumer")
defer func() { finish(errors.Join(result, processingError)) }()
}
lease, err := w.store.Claim(ctx, delivery.Job, claimDuration, maxAttempts)
if err != nil {
return err
}
if lease == nil {
return w.queue.Ack(ctx, delivery.Receipt)
}
started := time.Now()
if w.observer != nil {
w.observer.JobStarted()
}
operation, cancel := context.WithTimeout(ctx, processingTimeout)
err = w.process(operation, *lease)
processingError = err
if w.observer != nil {
w.observer.JobFinished(ctx, time.Since(started), err)
}
cancel()
if err != nil {
code := "processing_failed"
if errors.Is(err, ErrInvalidImage) {
code = "invalid_image"
}
delay := time.Duration(1<<min(lease.Job.Attempt, maxAttempts))*time.Second + time.Duration(rand.IntN(1000))*time.Millisecond
if failErr := w.store.Fail(ctx, *lease, code, delay, maxAttempts); failErr != nil {
return failErr
}
}
return w.queue.Ack(ctx, delivery.Receipt)
}
// process writes attempt-isolated objects before atomically publishing their metadata.
func (w *Worker) process(ctx context.Context, lease Lease) error {
reader, err := w.objects.Get(ctx, lease.StagingKey)
if err != nil {
return err
}
source, readErr := io.ReadAll(io.LimitReader(reader, sourceLimit+1))
closeErr := reader.Close()
if readErr != nil {
return readErr
}
if closeErr != nil {
return closeErr
}
sum := sha256.Sum256(source)
if len(source) > sourceLimit || int64(len(source)) != lease.Attachment.SizeBytes || hex.EncodeToString(sum[:]) != lease.Attachment.SHA256 {
return ErrInvalidImage
}
outputs, err := w.processor.Process(ctx, source)
if err != nil {
return err
}
prefix := fmt.Sprintf("results/%s/v%d/%s/", lease.Job.AttachmentID, lease.Job.Version, lease.Token)
original := prefix + "original"
if err := w.objects.Put(ctx, original, lease.Attachment.ContentType, bytes.NewReader(source), int64(len(source))); err != nil {
return err
}
variants := make([]dto.Variant, 0, len(outputs))
for _, output := range outputs {
if err := ctx.Err(); err != nil {
return err
}
output.Metadata.ObjectKey = prefix + output.Metadata.Name
if err := w.objects.Put(ctx, output.Metadata.ObjectKey, output.Metadata.ContentType, bytes.NewReader(output.Bytes), int64(len(output.Bytes))); err != nil {
return err
}
variants = append(variants, output.Metadata)
}
published, err := w.store.Complete(ctx, lease, original, variants)
if err == nil && published && w.observer != nil {
w.observer.Ready(ctx, lease.Job.CreatedAt)
}
return err
}
// wait backs off broker failures without delaying shutdown.
func wait(ctx context.Context, duration time.Duration) {
timer := time.NewTimer(duration)
defer timer.Stop()
select {
case <-ctx.Done():
case <-timer.C:
}
}