package messenger import ( "bytes" "context" "crypto/sha256" "encoding/hex" "encoding/json" "errors" "fmt" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" "github.com/minio/minio-go/v7" "github.com/redis/go-redis/v9" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/trace" "io" "log/slog" "math/rand/v2" "mtusi/messenger/internal/telemetry" "os" "os/exec" "path/filepath" "strconv" "strings" "sync" "time" ) const stream = "attachment.jobs.v1" const group = "image-workers" const maxAttempts = 5 const leaseSeconds = 45 type Job struct { SchemaVersion int `json:"schema_version"` ID string `json:"job_id"` Type string `json:"type"` AttachmentID string `json:"attachment_id"` Version int `json:"pipeline_version"` Attempt int `json:"attempt"` CreatedAt string `json:"created_at"` Traceparent string `json:"traceparent,omitempty"` Tracestate string `json:"tracestate,omitempty"` } type Pipeline struct { DB *pgxpool.Pool Broker *redis.Client Objects *ObjectStore Log *slog.Logger } func NewPipeline(db *pgxpool.Pool, broker *redis.Client, o *ObjectStore, log *slog.Logger) *Pipeline { return &Pipeline{db, broker, o, log} } func wait(ctx context.Context, d time.Duration) bool { t := time.NewTimer(d) defer t.Stop() select { case <-ctx.Done(): return false case <-t.C: return true } } func (p *Pipeline) RunDispatcher(ctx context.Context) error { for ctx.Err() == nil { if e := p.dispatch(ctx); e != nil { p.Log.Warn("outbox_retry", "event", "outbox_retry") } if !wait(ctx, 500*time.Millisecond) { break } } return nil } func (p *Pipeline) dispatch(ctx context.Context) error { // Small per-row transaction + SKIP LOCKED allows multiple dispatchers. A crash // after XADD before COMMIT gives a duplicate, never a missing durable intent. for i := 0; i < 32; i++ { tx, e := p.DB.Begin(ctx) if e != nil { return e } var j Job var created time.Time e = tx.QueryRow(ctx, `SELECT job_id::text,attachment_id::text,pipeline_version,attempt+1,created_at,traceparent,tracestate FROM pipeline_jobs WHERE finished_at IS NULL AND next_attempt_at<=clock_timestamp() AND (lease_until IS NULL OR lease_until 4 { return fmt.Errorf("WORKER_CONCURRENCY must be 1..4") } for ctx.Err() == nil { e := p.Broker.XGroupCreateMkStream(ctx, stream, group, "0").Err() if e == nil || strings.Contains(e.Error(), "BUSYGROUP") { break } if !wait(ctx, time.Second) { return nil } } telemetry.WorkerCapacity(concurrency) var wg sync.WaitGroup for i := 0; i < concurrency; i++ { wg.Add(1) go func() { defer wg.Done(); p.consume(ctx, uuid()) }() } wg.Wait() return nil } func (p *Pipeline) consume(ctx context.Context, consumer string) { cursor := "0-0" for ctx.Err() == nil { claimed, next, e := p.Broker.XAutoClaim(ctx, &redis.XAutoClaimArgs{Stream: stream, Group: group, Consumer: consumer, MinIdle: time.Minute, Start: cursor, Count: 1}).Result() cursor = next if e == nil && len(claimed) > 0 { p.handle(ctx, claimed[0]) continue } entries, e := p.Broker.XReadGroup(ctx, &redis.XReadGroupArgs{Group: group, Consumer: consumer, Streams: []string{stream, ">"}, Count: 1, Block: time.Second}).Result() if e != nil { if e != redis.Nil { wait(ctx, time.Second) } continue } for _, entry := range entries { for _, m := range entry.Messages { p.handle(ctx, m) } } } } func (p *Pipeline) handle(ctx context.Context, m redis.XMessage) { raw, _ := m.Values["payload"].(string) var j Job d := json.NewDecoder(strings.NewReader(raw)) d.DisallowUnknownFields() if len(raw) > 4096 || d.Decode(&j) != nil || j.SchemaVersion != 1 || j.Type != "attachment.process.v1" || !uuidRE.MatchString(j.ID) || !uuidRE.MatchString(j.AttachmentID) || j.Version < 1 || j.Attempt < 1 { p.Log.Warn("invalid_job", "event", "invalid_job") p.ack(ctx, m.ID) return } // The authoritative attempt and storage locations come from PostgreSQL, never // from untrusted broker payload fields. A terminal/stale delivery is a no-op. ctx, span := telemetry.Start(telemetry.Extract(ctx, j.Traceparent, j.Tracestate), "queue.consume", trace.SpanKindConsumer) defer span.End() done, e := p.process(ctx, j) telemetry.Failure(span, e) if e != nil { p.Log.WarnContext(ctx, "job_deferred", "event", "job_deferred", "job_id", j.ID) } if done { p.ack(ctx, m.ID) } } func (p *Pipeline) ack(ctx context.Context, id string) { // Do not delete an entry unless ACK succeeded; the only consumer group is ours. if p.Broker.XAck(ctx, stream, group, id).Err() == nil { p.Broker.XDel(ctx, stream, id) } } func (p *Pipeline) process(parent context.Context, j Job) (bool, error) { ctx, cancel := context.WithTimeout(parent, 30*time.Second) defer cancel() tx, e := p.DB.Begin(ctx) if e != nil { return false, e } defer tx.Rollback(context.Background()) var status, key, sha, contentType string var version, attempt int var size int64 var lease *time.Time e = tx.QueryRow(ctx, `SELECT a.status,a.pipeline_version,a.staging_key,a.sha256,a.content_type,a.size_bytes,j.attempt,j.lease_until FROM pipeline_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE j.job_id=$1 AND j.attachment_id=$2 AND j.pipeline_version=$3 FOR UPDATE OF j,a`, j.ID, j.AttachmentID, j.Version).Scan(&status, &version, &key, &sha, &contentType, &size, &attempt, &lease) if errors.Is(e, pgx.ErrNoRows) { return true, nil } if e != nil { return false, e } if version != j.Version || status == "ready" || status == "failed" { return true, nil } var now time.Time if e = tx.QueryRow(ctx, "SELECT clock_timestamp()").Scan(&now); e != nil { return false, e } if lease != nil && lease.After(now) { return true, nil } // live attempt; DB recovery remains durable if attempt >= maxAttempts { _, e = tx.Exec(ctx, `UPDATE attachments SET status='failed',error_code='retry_exhausted',updated_at=clock_timestamp() WHERE id=$1;`, j.AttachmentID) if e == nil { _, e = tx.Exec(ctx, "UPDATE pipeline_jobs SET finished_at=clock_timestamp(),lease_until=NULL WHERE job_id=$1", j.ID) } if e != nil { return false, e } return true, tx.Commit(ctx) } token := uuid() attempt++ if _, e = tx.Exec(ctx, `UPDATE pipeline_jobs SET attempt=$2,lease_token=$3,lease_until=clock_timestamp()+interval '45 seconds' WHERE job_id=$1`, j.ID, attempt, token); e != nil { return false, e } if _, e = tx.Exec(ctx, `UPDATE attachments SET status='processing',error_code=NULL,updated_at=clock_timestamp() WHERE id=$1`, j.AttachmentID); e != nil { return false, e } if _, e = tx.Exec(ctx, `INSERT INTO pipeline_audit(job_id,event,attempt) VALUES($1,'claimed',$2)`, j.ID, attempt); e != nil { return false, e } if e = tx.Commit(ctx); e != nil { return false, e } trace.SpanFromContext(ctx).SetAttributes(attribute.Int("job.attempt", attempt), attribute.Int("pipeline.version", j.Version)) attemptStart := time.Now() outcome := "failure" defer func() { trace.SpanFromContext(ctx).SetAttributes(attribute.String("job.outcome", outcome)) telemetry.Job(ctx, outcome, time.Since(attemptStart).Seconds()) }() p.Log.InfoContext(ctx, "job_started", "event", "job_started", "job_id", j.ID, "attempt", attempt, "pipeline_version", j.Version) faultPoint("before_objects") telemetry.Busy.Add(1) variants, processErr := p.perform(ctx, j, key, sha, contentType, size) telemetry.Busy.Add(-1) telemetry.Failure(trace.SpanFromContext(ctx), processErr) if processErr == nil { faultPoint("after_objects") } // A short independent commit budget allows recording a timed-out attempt; // a cancelled/killed process instead recovers via the persisted lease. finish, stop := context.WithTimeout(context.WithoutCancel(ctx), 3*time.Second) defer stop() tx, e = p.DB.Begin(finish) if e != nil { return false, e } defer tx.Rollback(context.Background()) var currentToken *string var currentVersion int e = tx.QueryRow(finish, `SELECT j.lease_token::text,a.pipeline_version FROM pipeline_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE j.job_id=$1 FOR UPDATE OF j,a`, j.ID).Scan(¤tToken, ¤tVersion) if e != nil { return false, e } if currentToken == nil || *currentToken != token || currentVersion != j.Version { return true, nil } if processErr == nil { encoded, _ := json.Marshal(variants) _, e = tx.Exec(finish, `UPDATE attachments SET status='ready',error_code=NULL,variants=$2,object_key=$3,updated_at=clock_timestamp() WHERE id=$1`, j.AttachmentID, encoded, resultPrefix(j)+"original") if e == nil { _, e = tx.Exec(finish, `UPDATE pipeline_jobs SET finished_at=clock_timestamp(),ready_at=clock_timestamp(),lease_until=NULL WHERE job_id=$1`, j.ID) } } else { permanent := errors.Is(processErr, errInvalidImage) if permanent || attempt >= maxAttempts { code := "retry_exhausted" if permanent { code = "invalid_image" } _, e = tx.Exec(finish, `UPDATE attachments SET status='failed',error_code=$2,updated_at=clock_timestamp() WHERE id=$1`, j.AttachmentID, code) if e == nil { _, e = tx.Exec(finish, `UPDATE pipeline_jobs SET finished_at=clock_timestamp(),lease_until=NULL WHERE job_id=$1`, j.ID) } } else { _, e = tx.Exec(finish, `UPDATE attachments SET status='queued',updated_at=clock_timestamp() WHERE id=$1`, j.AttachmentID) delay := time.Duration(1<