package jobs import ( "bytes" "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "io" "log" "os" "path/filepath" "strings" "sync" "sync/atomic" "time" "mtusi2026/internal/blobstore" "mtusi2026/internal/images" "mtusi2026/internal/model" "mtusi2026/internal/telemetry" "github.com/jackc/pgx/v5" "github.com/redis/go-redis/v9" "go.opentelemetry.io/otel/attribute" otellog "go.opentelemetry.io/otel/log" "go.opentelemetry.io/otel/metric" "go.opentelemetry.io/otel/propagation" "go.opentelemetry.io/otel/trace" ) const Stream = "attachment-jobs-v1" const Group = "image-workers-v1" type Runtime struct { Repo Repo Broker *redis.Client Blobs blobstore.Store Timeout time.Duration Concurrency int Fault string Retention time.Duration busy atomic.Int64 } func (r *Runtime) PublishOne(ctx context.Context) (_ bool, err error) { tx, err := r.Repo.Pool.Begin(ctx) if err != nil { return false, err } defer tx.Rollback(ctx) var oid int64 var parent, state string j := Job{SchemaVersion: 1, Type: JobType} err = tx.QueryRow(ctx, `SELECT o.id,j.id,j.attachment_id,j.pipeline_version,o.attempt,j.created_at, COALESCE(j.traceparent,''),COALESCE(j.tracestate,'') FROM attachment_outbox o JOIN attachment_jobs j ON j.id=o.job_id WHERE o.published_at IS NULL AND o.available_at<=now() ORDER BY o.id LIMIT 1 FOR UPDATE OF o SKIP LOCKED`). Scan(&oid, &j.ID, &j.AttachmentID, &j.PipelineVersion, &j.Attempt, &j.CreatedAt, &parent, &state) if err != nil { if errors.Is(err, pgx.ErrNoRows) { return false, nil } return false, err } if r.Fault == "before_publish" { log.Print("FAULT before_publish: committed outbox remains pending") os.Exit(86) } payload, err := json.Marshal(j) if err != nil { return false, err } ctx = telemetry.Extract(ctx, propagation.MapCarrier{"traceparent": parent, "tracestate": state}) ctx, span := telemetry.Tracer.Start(ctx, "attachment.publish", trace.WithSpanKind(trace.SpanKindProducer), messagingAttributes("send", j)) defer func() { telemetry.Finish(span, err) }() values := map[string]any{"payload": string(payload)} for key, value := range telemetry.Inject(ctx) { values[key] = value } pubCtx, cancel := context.WithTimeout(ctx, 3*time.Second) _, err = r.Broker.XAdd(pubCtx, &redis.XAddArgs{Stream: Stream, Values: values}).Result() cancel() if err != nil { telemetry.Warn(ctx, "attachment.publish_failed", otellog.Int("job.attempt", j.Attempt)) return false, err } telemetry.Info(ctx, "attachment.published", otellog.Int("job.attempt", j.Attempt)) if r.Fault == "after_publish" { log.Print("FAULT after_publish: duplicate publication expected") os.Exit(86) } _, err = tx.Exec(ctx, `UPDATE attachment_outbox SET published_at=now() WHERE id=$1`, oid) if err != nil { return false, err } return true, tx.Commit(ctx) } func messagingAttributes(operation string, j Job) trace.SpanStartOption { return trace.WithAttributes( attribute.String("messaging.system", "redis"), attribute.String("messaging.destination.name", Stream), attribute.String("messaging.operation.type", operation), attribute.String("job.type", j.Type), attribute.Int("job.attempt", j.Attempt), ) } func (r *Runtime) Relay(ctx context.Context) { tick := time.NewTicker(300 * time.Millisecond) defer tick.Stop() lastClean := time.Time{} for ctx.Err() == nil { if err := r.Repo.Recover(ctx); err != nil && ctx.Err() == nil { log.Printf("lease recovery: %v", err) } for i := 0; i < 100 && ctx.Err() == nil; i++ { ok, err := r.PublishOne(ctx) if err != nil { log.Printf("outbox publish: %v", err) break } if !ok { break } } if time.Since(lastClean) > time.Minute { if err := r.Cleanup(ctx); err != nil { log.Printf("staging cleanup: %v", err) } lastClean = time.Now() } select { case <-ctx.Done(): return case <-tick.C: } } } func (r *Runtime) Workers(ctx context.Context) error { err := r.Broker.XGroupCreateMkStream(ctx, Stream, Group, "0").Err() if err != nil && !strings.Contains(err.Error(), "BUSYGROUP") { return err } var wg sync.WaitGroup for i := 0; i < r.Concurrency; i++ { wg.Add(1) go func() { defer wg.Done(); r.consume(ctx) }() } wg.Wait() return nil } func (r *Runtime) consume(ctx context.Context) { host, _ := os.Hostname() consumer := host + "-" + time.Now().Format("150405.000000000") for ctx.Err() == nil { msgs, _, err := r.Broker.XAutoClaim(ctx, &redis.XAutoClaimArgs{Stream: Stream, Group: Group, Consumer: consumer, MinIdle: r.Repo.Lease, Start: "0-0", Count: 1}).Result() if err == nil && len(msgs) > 0 { r.deliver(ctx, msgs[0]) continue } streams, err := r.Broker.XReadGroup(ctx, &redis.XReadGroupArgs{Group: Group, Consumer: consumer, Streams: []string{Stream, ">"}, Count: 1, Block: time.Second}).Result() if err != nil { if !errors.Is(err, redis.Nil) && ctx.Err() == nil { log.Printf("broker read: %v", err) select { case <-ctx.Done(): return case <-time.After(time.Second): } } continue } for _, s := range streams { for _, m := range s.Messages { r.deliver(ctx, m) } } } } func (r *Runtime) deliver(ctx context.Context, m redis.XMessage) { var j Job payload, _ := m.Values["payload"].(string) if json.Unmarshal([]byte(payload), &j) != nil || j.Validate() != nil { if r.Broker.XAdd(ctx, &redis.XAddArgs{Stream: Stream + "-invalid", Values: map[string]any{"message_id": m.ID, "error_code": "invalid_job"}}).Err() == nil { r.Broker.XAck(ctx, Stream, Group, m.ID) } return } parent, _ := m.Values["traceparent"].(string) state, _ := m.Values["tracestate"].(string) ctx = telemetry.Extract(ctx, propagation.MapCarrier{"traceparent": parent, "tracestate": state}) ctx, span := telemetry.Tracer.Start(ctx, "attachment.consume", trace.WithSpanKind(trace.SpanKindConsumer), messagingAttributes("process", j)) defer span.End() w, err := r.Repo.Claim(ctx, j) if err != nil { telemetry.SetError(span, "claim_failed") telemetry.Error(ctx, "attachment.claim_failed", otellog.Int("job.attempt", j.Attempt)) return } if w != nil { started := time.Now() r.busy.Add(1) code, err := r.process(ctx, w) r.busy.Add(-1) outcome := "success" logFields := []otellog.KeyValue{otellog.String("job.type", j.Type), otellog.Int("job.attempt", j.Attempt)} if code != "" { outcome = "error" telemetry.SetError(span, code) telemetry.Error(ctx, "attachment.attempt_failed", append(logFields, otellog.String("error.type", code))...) } else { telemetry.Info(ctx, "attachment.ready", logFields...) } span.SetAttributes(attribute.String("job.outcome", outcome)) attrs := metric.WithAttributes(attribute.String("job_type", j.Type), attribute.String("outcome", outcome)) jobAttempts.Add(ctx, 1, attrs) jobDuration.Record(ctx, time.Since(started).Seconds(), attrs) if err != nil { return } } else { span.SetAttributes(attribute.String("job.outcome", "duplicate")) } if r.Fault == "before_ack" { log.Print("FAULT before_ack: durable DB result, pending broker delivery") os.Exit(86) } if err = r.Broker.XAck(ctx, Stream, Group, m.ID).Err(); err != nil { telemetry.SetError(span, "ack_failed") telemetry.Warn(ctx, "attachment.ack_failed", otellog.Int("job.attempt", j.Attempt)) } } func (r *Runtime) process(ctx context.Context, w *Work) (string, error) { workCtx, cancel := context.WithTimeout(ctx, r.Timeout) defer cancel() variants, err := r.effects(workCtx, w) dbCtx, dbCancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) defer dbCancel() if err != nil { code, permanent := "storage_unavailable", false switch { case errors.Is(err, images.ErrInvalid): code, permanent = "invalid_image", true case errors.Is(err, images.ErrLimit): code, permanent = "image_resource_limit", true case errors.Is(err, context.DeadlineExceeded): code = "processing_timeout" case errors.Is(err, blobstore.ErrNotFound): code, permanent = "staging_missing", true } return code, r.Repo.Fail(dbCtx, w, code, permanent) } ok, err := r.Repo.Complete(dbCtx, w, variants) if err != nil { return "complete_failed", err } if !ok { return "lease_lost", errors.New("completion lease expired or replaced; delivery left pending") } timeToReady.Record(ctx, max(0, time.Since(w.CreatedAt).Seconds()), metric.WithAttributes(attribute.String("job_type", w.Type))) if r.Fault == "after_commit" { log.Print("FAULT after_commit") os.Exit(86) } if err = r.Blobs.Delete(dbCtx, w.StagingKey); err == nil { _, err = r.Repo.Pool.Exec(dbCtx, `UPDATE attachments SET staging_key=NULL WHERE id=$1 AND status='ready'`, w.AttachmentID) } if err != nil { telemetry.Warn(ctx, "attachment.staging.cleanup_deferred") } return "", nil } func (r *Runtime) effects(ctx context.Context, w *Work) ([]model.Variant, error) { dir, err := os.MkdirTemp("", "pipeline-*") if err != nil { return nil, err } defer os.RemoveAll(dir) body, err := r.Blobs.Get(ctx, w.StagingKey) if err != nil { return nil, err } raw, err := io.ReadAll(io.LimitReader(body, (10<<20)+1)) body.Close() if err != nil { return nil, err } sum := sha256.Sum256(raw) if int64(len(raw)) != w.Size || hex.EncodeToString(sum[:]) != w.SHA256 { return nil, images.ErrInvalid } source := filepath.Join(dir, "source") if err = os.WriteFile(source, raw, 0600); err != nil { return nil, err } out, err := images.Run(ctx, "process", source, dir) if err != nil { return nil, err } var variants []model.Variant if err = json.Unmarshal(out, &variants); err != nil { return nil, err } if len(variants) != 3 { return nil, images.ErrInvalid } if err = r.Blobs.Put(ctx, w.ObjectKey, bytes.NewReader(raw), w.Size, w.ContentType); err != nil { return nil, err } if r.Fault == "after_object" { log.Print("FAULT after_object: original persisted, no DB commit or ack") os.Exit(86) } for i := range variants { v := &variants[i] if v.Name != "thumbnail" && v.Name != "crop" && v.Name != "optimized" { return nil, images.ErrInvalid } b, err := os.ReadFile(filepath.Join(dir, v.Name)) if err != nil { return nil, err } sum := sha256.Sum256(b) v.SHA256 = hex.EncodeToString(sum[:]) v.SizeBytes = int64(len(b)) if err = r.Blobs.Put(ctx, VariantKey(w.ObjectKey, v.Name), bytes.NewReader(b), v.SizeBytes, v.ContentType); err != nil { return nil, err } } return variants, nil } func (r *Runtime) Cleanup(ctx context.Context) error { tx, err := r.Repo.Pool.Begin(ctx) if err != nil { return err } defer tx.Rollback(ctx) failed, err := tx.Query(ctx, `SELECT a.id,a.staging_key FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE j.status='failed' AND j.updated_at