Files
mtusi2026lab5-fork/src/backend/repositories/jobs.go
T

214 lines
8.7 KiB
Go

package repositories
import (
"context"
"crypto/rand"
"encoding/json"
"errors"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"math/big"
"time"
)
type Variant struct {
Name string `json:"name"`
ContentType string `json:"content_type"`
SizeBytes int64 `json:"size_bytes"`
Width int `json:"width"`
Height int `json:"height"`
SHA256 string `json:"sha256"`
}
type Job struct {
SchemaVersion int `json:"schema_version"`
ID string `json:"job_id"`
Type string `json:"type"`
AttachmentID string `json:"attachment_id"`
PipelineVersion int `json:"pipeline_version"`
Attempt int `json:"attempt"`
CreatedAt time.Time `json:"created_at"`
}
// QueuedJobs is also the recovery source when publish/confirm is uncertain.
// Re-publication is intentional: a durable intent is never removed by publish.
func (s *AttachmentStore) QueuedJobs(ctx context.Context) ([]Job, error) {
rows, err := s.db.Query(ctx, `SELECT j.id,j.attachment_id,j.pipeline_version,j.attempts+1,j.created_at FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE j.superseded_at IS NULL AND j.pipeline_version=a.pipeline_version AND a.status IN ('queued','processing') AND j.next_attempt_at<=now() AND (j.lease_until IS NULL OR j.lease_until<now()) AND (j.published_at IS NULL OR j.published_at<now()-interval '30 seconds') ORDER BY j.created_at LIMIT 100`)
if err != nil {
return nil, err
}
defer rows.Close()
jobs := []Job{}
for rows.Next() {
j := Job{SchemaVersion: 1, Type: "attachment.process.v1"}
if err = rows.Scan(&j.ID, &j.AttachmentID, &j.PipelineVersion, &j.Attempt, &j.CreatedAt); err != nil {
return nil, err
}
j.CreatedAt = j.CreatedAt.UTC()
jobs = append(jobs, j)
}
return jobs, rows.Err()
}
func (s *AttachmentStore) MarkPublished(ctx context.Context, id string) error {
_, err := s.db.Exec(ctx, `UPDATE attachment_jobs SET published_at=now() WHERE id=$1`, id)
return err
}
// StartAttempt commits the lease and attempt before decoding. A token fences a
// consumer that was paused between claim and processing past its lease deadline.
func (s *AttachmentStore) StartAttempt(ctx context.Context, j Job, timeout time.Duration, maxAttempts int) (string, error) {
tx, err := s.db.Begin(ctx)
if err != nil {
return "", err
}
defer tx.Rollback(context.Background())
var status string
var attempts, generation int
var available bool
err = tx.QueryRow(ctx, `SELECT a.status,j.attempts,j.generation,j.next_attempt_at<=now() AND (j.lease_until IS NULL OR j.lease_until<now()) FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE j.id=$1 AND j.attachment_id=$2 AND j.pipeline_version=$3 AND j.superseded_at IS NULL AND a.pipeline_version=j.pipeline_version FOR UPDATE OF j,a SKIP LOCKED`, j.ID, j.AttachmentID, j.PipelineVersion).Scan(&status, &attempts, &generation, &available)
if errors.Is(err, pgx.ErrNoRows) {
return "", nil
}
if err != nil {
return "", err
}
if status == "ready" || status == "failed" || !available {
return "", nil
}
// A crashed attempt remains visible in the audit trail.
if _, err = tx.Exec(ctx, `UPDATE attachment_job_attempts SET finished_at=clock_timestamp(),error_code='processing_timeout' WHERE job_id=$1 AND finished_at IS NULL`, j.ID); err != nil {
return "", err
}
if attempts >= maxAttempts {
if err = failJob(ctx, tx, j, "retry_exhausted", attempts); err != nil {
return "", err
}
return "", tx.Commit(ctx)
}
token := uuid.NewString()
_, err = tx.Exec(ctx, `UPDATE attachment_jobs SET attempts=attempts+1,lease_token=$2,lease_until=now()+$3*interval '1 second' WHERE id=$1`, j.ID, token, timeout.Seconds()+5)
if err != nil {
return "", err
}
if _, err = tx.Exec(ctx, `UPDATE attachments SET status='processing',updated_at=now() WHERE id=$1`, j.AttachmentID); err != nil {
return "", err
}
if _, err = tx.Exec(ctx, `INSERT INTO attachment_job_attempts(job_id,generation,attempt) VALUES($1,$2,$3)`, j.ID, generation, attempts+1); err != nil {
return "", err
}
return token, tx.Commit(ctx)
}
var ErrStaleJob = errors.New("stale job lease or version")
var ErrProcessingTimeout = errors.New("processing timeout")
// ProcessJob holds the row lock across deterministic object writes. The lock and
// token check prevent overlapping/stale attempts from publishing metadata.
func (s *AttachmentStore) ProcessJob(ctx context.Context, j Job, token string, maxAttempts int, process func(Attachment, string) ([]Variant, string, error)) error {
tx, err := s.db.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(context.Background())
var staging string
var attempts, generation int
var a Attachment
err = tx.QueryRow(ctx, `SELECT a.id,a.object_key,a.content_type,a.size_bytes,a.sha256,a.status,j.staging_key,j.attempts,j.generation FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE j.id=$1 AND j.attachment_id=$2 AND j.pipeline_version=$3 AND j.lease_token=$4 AND j.lease_until>now() AND j.superseded_at IS NULL AND a.pipeline_version=j.pipeline_version FOR UPDATE OF j,a`, j.ID, j.AttachmentID, j.PipelineVersion, token).Scan(&a.ID, &a.ObjectKey, &a.ContentType, &a.SizeBytes, &a.SHA256, &a.Status, &staging, &attempts, &generation)
if errors.Is(err, pgx.ErrNoRows) {
return ErrStaleJob
}
if err != nil {
return err
}
if a.Status != "processing" {
return errors.New("job is not processing")
}
a.PipelineVersion = j.PipelineVersion
variants, code, workErr := process(a, staging)
var next *time.Time
var auditCode *string
if workErr == nil {
data, e := json.Marshal(variants)
if e != nil {
return e
}
_, err = tx.Exec(ctx, `UPDATE attachments SET status='ready',variants=$2,published_pipeline_version=$3,error_code=NULL,updated_at=now() WHERE id=$1 AND pipeline_version=$3`, a.ID, data, j.PipelineVersion)
if err == nil {
_, err = tx.Exec(ctx, `INSERT INTO attachment_publications(attachment_id,job_id,pipeline_version,variants) VALUES($1,$2,$3,$4)`, a.ID, j.ID, j.PipelineVersion, data)
}
} else {
reason := "temporary_failure"
if errors.Is(workErr, ErrProcessingTimeout) {
reason = "processing_timeout"
}
if code != "" {
reason = code
}
auditCode = &reason
if code != "" || attempts >= maxAttempts {
if code == "" {
code = "retry_exhausted"
}
err = failJob(ctx, tx, j, code, attempts)
} else {
due := time.Now().UTC().Add(RetryDelay(attempts))
next = &due
_, err = tx.Exec(ctx, `UPDATE attachments SET status='queued',error_code=NULL,updated_at=now() WHERE id=$1`, a.ID)
}
}
if err != nil {
return err
}
_, err = tx.Exec(ctx, `UPDATE attachment_job_attempts SET finished_at=clock_timestamp(),error_code=$4,next_attempt_at=$5 WHERE job_id=$1 AND generation=$2 AND attempt=$3`, j.ID, generation, attempts, auditCode, next)
if err != nil {
return err
}
_, err = tx.Exec(ctx, `UPDATE attachment_jobs SET lease_until=NULL,lease_token=NULL,published_at=NULL,next_attempt_at=COALESCE($2,now()) WHERE id=$1`, j.ID, next)
if err != nil {
return err
}
return tx.Commit(ctx)
}
func failJob(ctx context.Context, tx pgx.Tx, j Job, code string, attempts int) error {
if _, err := tx.Exec(ctx, `UPDATE attachments SET status='failed',error_code=$2,updated_at=now() WHERE id=$1`, j.AttachmentID, code); err != nil {
return err
}
if _, err := tx.Exec(ctx, `UPDATE attachment_jobs SET lease_token=NULL,lease_until=NULL WHERE id=$1`, j.ID); err != nil {
return err
}
_, err := tx.Exec(ctx, `INSERT INTO attachment_job_failures(job_id,error_code,attempts) VALUES($1,$2,$3) ON CONFLICT(job_id) DO UPDATE SET error_code=EXCLUDED.error_code,attempts=EXCLUDED.attempts,failed_at=clock_timestamp()`, j.ID, code, attempts)
return err
}
// Equal jitter: exponential ceiling 2,4,8,...,30 seconds; delay in [ceiling/2,ceiling).
func RetryDelay(attempt int) time.Duration {
ceiling := 2 * time.Second
for i := 1; i < attempt && ceiling < 30*time.Second; i++ {
ceiling *= 2
}
if ceiling > 30*time.Second {
ceiling = 30 * time.Second
}
n, err := rand.Int(rand.Reader, big.NewInt(int64(ceiling/2)))
if err != nil {
return ceiling
}
return ceiling/2 + time.Duration(n.Int64())
}
func enqueueJob(ctx context.Context, tx pgx.Tx, a Attachment, staging string) error {
_, err := tx.Exec(ctx, `UPDATE attachments SET status='queued' WHERE id=$1`, a.ID)
if err != nil {
return err
}
_, err = tx.Exec(ctx, `INSERT INTO attachment_jobs(id,attachment_id,staging_key) VALUES($1,$2,$3)`, uuid.NewString(), a.ID, staging)
return err
}
func (s *AttachmentStore) JobTerminal(ctx context.Context, id string) (bool, error) {
var done bool
err := s.db.QueryRow(ctx, `SELECT j.superseded_at IS NOT NULL OR j.pipeline_version<a.pipeline_version OR a.status IN ('ready','failed') FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE j.id=$1`, id).Scan(&done)
return done, err
}