package pipeline import ( "bytes" "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "io" "log/slog" "math/rand/v2" "os" "path/filepath" "time" "highload/internal/broker" "highload/internal/config" "highload/internal/fault" "highload/internal/imageproc" "highload/internal/model" "highload/internal/observability" "highload/internal/repository" "highload/internal/storage" "github.com/google/uuid" amqp "github.com/rabbitmq/amqp091-go" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/codes" "go.opentelemetry.io/otel/log" "go.opentelemetry.io/otel/trace" ) type WorkerRepository interface { ClaimJob(context.Context, string, time.Time) (*model.AttachmentJob, error) GetAttachmentJobState(context.Context, string) (*model.AttachmentJobState, error) GetAttachmentByID(context.Context, string) (*model.Attachment, error) CompleteJob(context.Context, string, int32, string, []model.AttachmentVariant) (bool, error) PublishedObjectKeys(context.Context, string, int32) ([]string, error) ScheduleRetry(context.Context, string, int32, string, time.Time) (bool, error) FailJob(context.Context, string, int32, string) (bool, error) } type WorkerObjects interface { storage.ObjectWriter Head(context.Context, string) error } type Worker struct { Repo WorkerRepository Objects WorkerObjects Config config.Pipeline } type message struct { SchemaVersion int `json:"schema_version"` Type string `json:"type"` JobID string `json:"job_id"` AttachmentID string `json:"attachment_id"` PipelineVersion int32 `json:"pipeline_version"` Attempt int `json:"attempt"` CreatedAt time.Time `json:"created_at"` Traceparent string `json:"traceparent,omitempty"` Tracestate string `json:"tracestate,omitempty"` } func decodeMessage(payload []byte) (message, error) { var msg message if len(payload) > 4096 { return msg, errors.New("oversize job") } d := json.NewDecoder(bytes.NewReader(payload)) d.DisallowUnknownFields() if err := d.Decode(&msg); err != nil { return msg, err } if err := d.Decode(new(any)); err != io.EOF { return msg, errors.New("trailing job data") } jobID, err1 := uuid.Parse(msg.JobID) attachmentID, err2 := uuid.Parse(msg.AttachmentID) if err1 != nil || err2 != nil || msg.SchemaVersion != 1 || msg.Type != "attachment.process.v1" || msg.PipelineVersion <= 0 || msg.Attempt <= 0 || msg.CreatedAt.IsZero() { return msg, errors.New("invalid job envelope") } msg.JobID, msg.AttachmentID = jobID.String(), attachmentID.String() return msg, nil } func (w Worker) Serve(ctx context.Context) { for ctx.Err() == nil { if err := w.consume(ctx); err != nil && ctx.Err() == nil { slog.Warn("worker consumer reconnecting", "error", err) } select { case <-ctx.Done(): case <-time.After(500 * time.Millisecond): } } } func (w Worker) consume(ctx context.Context) error { conn, ch, err := broker.Connect(w.Config.BrokerURL) if err != nil { return err } defer broker.Close(conn) if err := ch.Qos(w.Config.Prefetch, 0, false); err != nil { return err } deliveries, err := ch.ConsumeWithContext(ctx, broker.Queue, "", false, false, false, false, nil) if err != nil { return err } for { select { case <-ctx.Done(): return ctx.Err() case delivery, ok := <-deliveries: if !ok { return errors.New("broker delivery channel closed") } msg, err := decodeMessage(delivery.Body) if err != nil { slog.Warn("rejecting invalid job envelope") if err := delivery.Reject(false); err != nil { return err } continue } if err := w.consumeDelivery(ctx, delivery, msg); err != nil { // Closing the channel requeues an unacknowledged delivery. return err } } } } func (w Worker) consumeDelivery(ctx context.Context, delivery amqp.Delivery, msg message) (err error) { ctx = observability.JobContext(ctx, msg.Traceparent, msg.Tracestate) ctx, span := observability.Tracer.Start(ctx, "attachment.process", trace.WithSpanKind(trace.SpanKindConsumer), trace.WithAttributes( attribute.String("messaging.system", "rabbitmq"), attribute.String("messaging.destination.name", broker.Queue), attribute.String("messaging.operation.name", "process"), attribute.String("messaging.message.id", msg.JobID), )) defer func() { observability.End(span, err) }() observability.Log(ctx, "job.received", log.SeverityInfo, attribute.String("job_id", msg.JobID), attribute.Int("envelope_attempt", msg.Attempt)) reject, err := w.handle(ctx, msg) if err != nil { return err } if reject { span.SetAttributes(attribute.String("messaging.delivery.disposition", "rejected")) return delivery.Reject(false) } span.SetAttributes(attribute.String("messaging.delivery.disposition", "acked")) return delivery.Ack(false) } func (w Worker) handle(ctx context.Context, msg message) (bool, error) { state, err := w.Repo.GetAttachmentJobState(ctx, msg.JobID) if errors.Is(err, repository.ErrNotFound) { return true, nil } if err != nil { return false, err } if state.AttachmentID != msg.AttachmentID || state.PipelineVersion != msg.PipelineVersion { return true, nil } if state.Status == "superseded" { return false, nil } job, err := w.Repo.ClaimJob(ctx, msg.JobID, time.Now().Add(w.Config.Lease)) if err != nil { return false, err } if job == nil { return false, w.handleUnclaimed(ctx, msg) } slog.Info("job claimed", "job_id", job.ID, "attempt", job.AttemptsStarted, "lease_generation", job.LeaseGeneration) outcome, err := w.runAttempt(ctx, job, msg) if err != nil || outcome != "ready" { return false, err } pauseCtx, pauseCancel := context.WithTimeout(ctx, 30*time.Second) defer pauseCancel() return false, fault.Pause(pauseCtx, "before_ack", job.ID) } func (w Worker) runAttempt(ctx context.Context, job *model.AttachmentJob, msg message) (outcome string, err error) { started := time.Now() span := trace.SpanFromContext(ctx) span.SetAttributes(attribute.Int("job.attempt", int(job.AttemptsStarted))) done := observability.WorkerAttempt() defer func() { done() observability.ObserveJob(ctx, outcome, time.Since(started)) span.SetAttributes(attribute.String("job.outcome", outcome)) if outcome != "ready" { span.SetStatus(codes.Error, outcome) } observability.Log(ctx, "job.finished", log.SeverityInfo, attribute.String("job_id", job.ID), attribute.Int("attempt", int(job.AttemptsStarted)), attribute.String("outcome", outcome)) }() attemptCtx, cancel := context.WithTimeout(ctx, w.Config.Timeout) failure := w.process(attemptCtx, job) cancel() if ctx.Err() != nil { return "interrupted", ctx.Err() } if failure == nil { return "ready", nil } if errors.Is(failure, errLostLease) { return "lease_lost", w.handleUnclaimed(ctx, msg) } return w.saveFailure(ctx, job, failure) } func (w Worker) handleUnclaimed(ctx context.Context, msg message) error { state, err := w.Repo.GetAttachmentJobState(ctx, msg.JobID) if err != nil { return err } switch state.Status { case "ready": checkCtx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() keys, err := w.Repo.PublishedObjectKeys(checkCtx, state.AttachmentID, state.PipelineVersion) if err != nil { return err } for _, key := range keys { if err := w.Objects.Head(checkCtx, key); err != nil { return err } } return nil case "failed", "queued", "superseded": return nil // A queued retry is already in the transactionally durable outbox. case "processing": if state.AttemptsStarted >= state.MaxAttempts && state.LeaseExpired { _, err = w.Repo.FailJob(ctx, msg.JobID, state.LeaseGeneration, "retry_exhausted") return err } return nil // The recovery loop publishes one event for this expired lease. default: return errors.New("unrecognized job state") } } var ( errLostLease = errors.New("job lease lost") errOriginalMismatch = errors.New("staging hash or size differs") ) func (w Worker) process(ctx context.Context, job *model.AttachmentJob) error { att, err := w.Repo.GetAttachmentByID(ctx, job.AttachmentID) if err != nil { return err } if att.PipelineVersion != job.PipelineVersion { return errLostLease } if att.StagingKey == "" { return errOriginalMismatch } dir, err := os.MkdirTemp("", "attachment-job-") if err != nil { return err } defer os.RemoveAll(dir) source := filepath.Join(dir, "input") if err := w.download(ctx, att, source); err != nil { return err } files, err := imageproc.Generate(ctx, dir, source, att.ContentType, job.PipelineVersion) if err != nil { return err } if err := fault.Pause(ctx, "before_objects", job.ID); err != nil { return err } prefix := fmt.Sprintf("results/%s/v%d/%d/", job.AttachmentID, job.PipelineVersion, job.LeaseGeneration) originalKey := prefix + "original" if err := w.putFile(ctx, originalKey, att.ContentType, source, att.SizeBytes); err != nil { return err } variants := make([]model.AttachmentVariant, 0, len(files)) for _, f := range files { v := f.Variant v.ObjectKey = prefix + filepath.Base(f.Path) if err := w.putFile(ctx, v.ObjectKey, v.ContentType, f.Path, v.SizeBytes); err != nil { return err } variants = append(variants, v) } if err := fault.Pause(ctx, "after_objects", job.ID); err != nil { return err } done, err := w.Repo.CompleteJob(ctx, job.ID, job.LeaseGeneration, originalKey, variants) if err != nil { return err } if !done { slog.Info("job finalization rejected", "job_id", job.ID, "lease_generation", job.LeaseGeneration) return errLostLease } observability.ObserveReady(ctx, job.AcceptedAt) observability.Log(ctx, "job.ready", log.SeverityInfo, attribute.String("job_id", job.ID)) slog.Info("job ready", "job_id", job.ID, "lease_generation", job.LeaseGeneration) return nil } func (w Worker) download(ctx context.Context, att *model.Attachment, path string) error { if att.SizeBytes <= 0 || att.SizeBytes > imageproc.MaxBytes { return errOriginalMismatch } reader, err := w.Objects.Get(ctx, att.StagingKey) if err != nil { return err } defer reader.Close() f, err := os.Create(path) if err != nil { return err } sum := sha256.New() n, copyErr := io.Copy(io.MultiWriter(f, sum), io.LimitReader(reader, att.SizeBytes+1)) closeErr := f.Close() if copyErr != nil { return copyErr } if closeErr != nil { return closeErr } if n != att.SizeBytes || hex.EncodeToString(sum.Sum(nil)) != att.SHA256 { return errOriginalMismatch } return nil } func (w Worker) putFile(ctx context.Context, key, mime, path string, size int64) error { f, err := os.Open(path) if err != nil { return err } defer f.Close() return w.Objects.Put(ctx, key, mime, f, size) } func (w Worker) saveFailure(ctx context.Context, job *model.AttachmentJob, failure error) (string, error) { code := "processing_failed" permanent := false switch { case errors.Is(failure, errOriginalMismatch), errors.Is(failure, imageproc.ErrInvalidImage): code, permanent = "invalid_image", true case errors.Is(failure, imageproc.ErrResourceLimit): code, permanent = "resource_limit", true case errors.Is(failure, storage.ErrObjectNotFound): code, permanent = "original_missing", true case errors.Is(failure, storage.ErrServiceUnavailable): code = "s3_unavailable" case errors.Is(failure, context.DeadlineExceeded): code = "processing_timeout" } dbCtx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() if permanent || job.AttemptsStarted >= job.MaxAttempts { if !permanent { code = "retry_exhausted" } changed, err := w.Repo.FailJob(dbCtx, job.ID, job.LeaseGeneration, code) if err != nil { return "error", err } if !changed { return "lease_lost", nil } observability.Log(ctx, "job.failed", log.SeverityWarn, attribute.String("job_id", job.ID), attribute.String("error_code", code)) slog.Warn("job failed", "job_id", job.ID, "error_code", code) return "failed", nil } // The floor avoids immediate requeue loops. The upper bound grows with // each attempt and is capped to keep the lab recoverable. upper := min(30*time.Second, w.Config.RetryBase<