package main import ( "context" "encoding/json" "errors" "fmt" "math/rand/v2" "os" "time" "github.com/jackc/pgx/v5" ) type imageJob struct { SchemaVersion int `json:"schema_version"` JobID 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"` } type imageSource struct { contentType string size int64 sha256 string } func enqueueImage(ctx context.Context, tx pgx.Tx, attachment string, version int) error { _, err := tx.Exec(ctx, "INSERT INTO image_jobs(id,attachment_id,version) VALUES($1,$2,$3)", uuid(), attachment, version) return err } func stagingKey(id string) string { return "staging/" + id } func resultKey(id string, version int, variant string) string { if version == 0 { return "original/" + id } return fmt.Sprintf("%s/%s/v%d", variant, id, version) } func (a *App) claimImage(ctx context.Context, j imageJob, lease time.Duration) (imageSource, bool, error) { var src imageSource tx, err := a.db.Begin(ctx) if err != nil { return src, false, err } defer rollbackAttachment(tx) if err = attachmentLock(ctx, tx, j.AttachmentID); err != nil { return src, false, err } tag, err := tx.Exec(ctx, `UPDATE image_jobs j SET state='processing', lease_until=clock_timestamp()+$5::bigint*interval '1 second', updated_at=clock_timestamp() FROM attachments a WHERE a.id=j.attachment_id AND a.active_version=j.version AND j.id=$1 AND j.attachment_id=$2 AND j.version=$3 AND j.attempt=$4 AND j.state='queued' AND j.next_at<=clock_timestamp()`, j.JobID, j.AttachmentID, j.Version, j.Attempt, int64(lease.Seconds())) if err != nil || tag.RowsAffected() == 0 { return src, false, err } if _, err = tx.Exec(ctx, `UPDATE attachments SET status='processing',updated_at=clock_timestamp() WHERE id=$1 AND result_version=0`, j.AttachmentID); err != nil { return src, false, err } err = tx.QueryRow(ctx, "SELECT content_type,size_bytes,sha256 FROM attachments WHERE id=$1", j.AttachmentID). Scan(&src.contentType, &src.size, &src.sha256) if err != nil { return src, false, err } return src, true, tx.Commit(ctx) } func (a *App) completeImage(ctx context.Context, j imageJob, variants []Variant) error { tx, err := a.db.Begin(ctx) if err != nil { return err } defer rollbackAttachment(tx) if err = attachmentLock(ctx, tx, j.AttachmentID); err != nil { return err } tag, err := tx.Exec(ctx, `UPDATE image_jobs SET state='ready',lease_until=NULL,error_code=NULL,updated_at=clock_timestamp() WHERE id=$1 AND attempt=$2 AND state='processing' AND lease_until>clock_timestamp()`, j.JobID, j.Attempt) if err != nil || tag.RowsAffected() == 0 { return err // A lost lease is recovered by the dispatcher. } tag, err = tx.Exec(ctx, `UPDATE attachments SET status='ready',error_code=NULL,result_version=$2, variants=$3,updated_at=clock_timestamp() WHERE id=$1 AND active_version=$2 AND result_version<$2`, j.AttachmentID, j.Version, variants) if err != nil { return err } if tag.RowsAffected() != 1 { return errors.New("image result fence rejected") } return tx.Commit(ctx) } func (a *App) failImage(ctx context.Context, j imageJob, code string, permanent, expired bool, maxAttempts int) error { tx, err := a.db.Begin(ctx) if err != nil { return err } defer rollbackAttachment(tx) if err = attachmentLock(ctx, tx, j.AttachmentID); err != nil { return err } var cycleStart int err = tx.QueryRow(ctx, `SELECT cycle_start FROM image_jobs WHERE id=$1 AND attempt=$2 AND state='processing' AND (lease_until<=clock_timestamp())=$3 FOR UPDATE`, j.JobID, j.Attempt, expired).Scan(&cycleStart) if errors.Is(err, pgx.ErrNoRows) { return nil } if err != nil { return err } used := j.Attempt - cycleStart + 1 state := "failed" if !permanent { if used >= maxAttempts { code = "retry_exhausted" } else { state = "queued" } } attempt := j.Attempt var delay int64 if state == "queued" { attempt++ base := int64(1000) << min(used-1, 5) delay = base + rand.Int64N(base) } _, err = tx.Exec(ctx, `UPDATE image_jobs SET state=$2,error_code=$3,lease_until=NULL,attempt=$4, published=false,next_at=clock_timestamp()+$5::bigint*interval '1 millisecond',updated_at=clock_timestamp() WHERE id=$1`, j.JobID, state, code, attempt, delay) if err != nil { return err } var publicCode *string if state == "failed" { publicCode = &code } if _, err = tx.Exec(ctx, `UPDATE attachments SET status=$2,error_code=$3,updated_at=clock_timestamp() WHERE id=$1 AND active_version=$4 AND result_version=0`, j.AttachmentID, state, publicCode, j.Version); err != nil { return err } return tx.Commit(ctx) } func (a *App) recoverImage(ctx context.Context, maxAttempts int) error { var j imageJob err := a.db.QueryRow(ctx, `SELECT id::text,attachment_id::text,version,attempt FROM image_jobs WHERE state='processing' AND lease_until<=clock_timestamp() ORDER BY lease_until LIMIT 1`). Scan(&j.JobID, &j.AttachmentID, &j.Version, &j.Attempt) if errors.Is(err, pgx.ErrNoRows) { return nil } if err != nil { return err } return a.failImage(ctx, j, "lease_expired", false, true, maxAttempts) } func (a *App) upgradeImage(ctx context.Context, id string) error { tx, err := a.db.Begin(ctx) if err != nil { return err } defer rollbackAttachment(tx) if err = attachmentLock(ctx, tx, id); err != nil { return err } tag, err := tx.Exec(ctx, `UPDATE attachments SET active_version=2 WHERE id=$1 AND active_version=1 AND result_version=1 AND status='ready'`, id) if err != nil { return err } if tag.RowsAffected() != 1 { return errors.New("attachment is not eligible for upgrade") } if err = enqueueImage(ctx, tx, id, 2); err != nil { return err } return tx.Commit(ctx) } func (a *App) replayImage(ctx context.Context, id string, retention int) error { var attachment string if err := a.db.QueryRow(ctx, "SELECT attachment_id::text FROM image_jobs WHERE id=$1", id).Scan(&attachment); err != nil { return errors.New("job lookup failed") } tx, err := a.db.Begin(ctx) if err != nil { return err } defer rollbackAttachment(tx) if err = attachmentLock(ctx, tx, attachment); err != nil { return err } var attempt int var code string err = tx.QueryRow(ctx, `SELECT j.attempt,j.error_code FROM image_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE j.id=$1 AND j.state='failed' AND a.active_version=j.version AND a.result_versionclock_timestamp()-$2::bigint*interval '1 second')`, id, retention).Scan(&attempt, &code) if errors.Is(err, pgx.ErrNoRows) { return errors.New("job is not eligible for replay") } if err != nil { return err } attempt++ if _, err = tx.Exec(ctx, "INSERT INTO image_job_replays(job_id,attempt,previous_error) VALUES($1,$2,$3)", id, attempt, code); err != nil { return err } if _, err = tx.Exec(ctx, `UPDATE image_jobs SET state='queued',attempt=$2,cycle_start=$2,error_code=NULL, published=false,next_at=clock_timestamp(),updated_at=clock_timestamp() WHERE id=$1`, id, attempt); err != nil { return err } if _, err = tx.Exec(ctx, `UPDATE attachments SET status='queued',error_code=NULL,updated_at=clock_timestamp() WHERE id=$1 AND result_version=0`, attachment); err != nil { return err } return tx.Commit(ctx) } func (a *App) listFailedImages(ctx context.Context) error { rows, err := a.db.Query(ctx, `SELECT id::text,attachment_id::text,version,attempt,error_code,updated_at FROM image_jobs WHERE state='failed' ORDER BY updated_at DESC,id LIMIT 100`) if err != nil { return err } defer rows.Close() out := json.NewEncoder(os.Stdout) for rows.Next() { var j imageJob var code string var updated time.Time if err = rows.Scan(&j.JobID, &j.AttachmentID, &j.Version, &j.Attempt, &code, &updated); err != nil { return err } if err = out.Encode(map[string]any{"job_id": j.JobID, "attachment_id": j.AttachmentID, "pipeline_version": j.Version, "attempt": j.Attempt, "error_code": code, "updated_at": stamp(updated)}); err != nil { return err } } return rows.Err() }