This commit is contained in:
2026-11-12 17:28:28 +03:00
parent 276dbdad8a
commit 4fae7d7e87
103 changed files with 10742 additions and 54 deletions
+254
View File
@@ -0,0 +1,254 @@
package jobs
import (
"context"
"encoding/json"
"errors"
"fmt"
"math/rand/v2"
"time"
"mtusi2026/internal/idgen"
"mtusi2026/internal/model"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
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"`
}
type Repo struct {
Pool *pgxpool.Pool
MaxAttempts int
Lease time.Duration
}
type Work struct {
Job
Token, StagingKey, ObjectKey, SHA256, ContentType string
Size int64
}
func Enqueue(ctx context.Context, tx pgx.Tx, attachmentID string) error {
id := idgen.GenerateUUIDv4()
_, err := tx.Exec(ctx, `INSERT INTO attachment_jobs(id,attachment_id) VALUES($1,$2)`, id, attachmentID)
if err != nil {
return err
}
_, err = tx.Exec(ctx, `INSERT INTO attachment_outbox(job_id,attempt) VALUES($1,1)`, id)
return err
}
func (r Repo) Claim(ctx context.Context, j Job) (*Work, error) {
tx, err := r.Pool.Begin(ctx)
if err != nil {
return nil, err
}
defer tx.Rollback(ctx)
w := &Work{Job: j, Token: idgen.GenerateUUIDv4()}
err = tx.QueryRow(ctx, `UPDATE attachment_jobs SET status='processing',attempt=attempt+1,
lease_token=$3,lease_until=now()+$4::interval,updated_at=now()
WHERE id=$1 AND attachment_id=$2 AND pipeline_version=$5 AND status='queued'
AND next_attempt_at<=now() AND attempt=$6-1
RETURNING attempt`, j.ID, j.AttachmentID, w.Token, r.Lease.String(), j.PipelineVersion, j.Attempt).Scan(&w.Attempt)
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
err = tx.QueryRow(ctx, `UPDATE attachments SET status='processing',updated_at=now()
WHERE id=$1 RETURNING staging_key,object_key,sha256,content_type,size_bytes`, j.AttachmentID).
Scan(&w.StagingKey, &w.ObjectKey, &w.SHA256, &w.ContentType, &w.Size)
if err != nil {
return nil, err
}
if err = tx.Commit(ctx); err != nil {
return nil, err
}
return w, nil
}
func (r Repo) Complete(ctx context.Context, w *Work, variants []model.Variant) (bool, error) {
tx, err := r.Pool.Begin(ctx)
if err != nil {
return false, err
}
defer tx.Rollback(ctx)
tag, err := tx.Exec(ctx, `UPDATE attachment_jobs SET status='ready',error_code=NULL,
lease_token=NULL,lease_until=NULL,updated_at=now() WHERE id=$1 AND status='processing'
AND lease_token=$2 AND lease_until>now()`, w.ID, w.Token)
if err != nil || tag.RowsAffected() == 0 {
return false, err
}
b, err := json.Marshal(variants)
if err != nil {
return false, err
}
_, err = tx.Exec(ctx, `UPDATE attachments SET status='ready',variants=$2,error_code=NULL,updated_at=now() WHERE id=$1`, w.AttachmentID, b)
if err != nil {
return false, err
}
return true, tx.Commit(ctx)
}
func RetryDelay(attempt int) time.Duration {
base := time.Second
for i := 1; i < attempt && base < 60*time.Second; i++ {
base *= 2
}
if base > 60*time.Second {
base = 60 * time.Second
}
return base/2 + time.Duration(rand.Int64N(int64(base/2)+1))
}
func (r Repo) Fail(ctx context.Context, w *Work, code string, permanent bool) error {
tx, err := r.Pool.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
var attempt, replayBase int
err = tx.QueryRow(ctx, `SELECT attempt FROM attachment_jobs WHERE id=$1 AND status='processing'
AND lease_token=$2 FOR UPDATE`, w.ID, w.Token).Scan(&attempt)
if errors.Is(err, pgx.ErrNoRows) {
return nil
}
if err != nil {
return err
}
if err = tx.QueryRow(ctx, `SELECT COALESCE(max(previous_attempt),0) FROM job_replays WHERE job_id=$1`, w.ID).Scan(&replayBase); err != nil {
return err
}
state := "queued"
if permanent || attempt-replayBase >= r.MaxAttempts {
state = "failed"
if !permanent {
code = "retry_exhausted"
}
}
delay := RetryDelay(attempt)
_, err = tx.Exec(ctx, `UPDATE attachment_jobs SET status=$2,error_code=$3,lease_until=NULL,lease_token=NULL,
next_attempt_at=now()+$4::interval,updated_at=now() WHERE id=$1`, w.ID, state, code, delay.String())
if err != nil {
return err
}
_, err = tx.Exec(ctx, `UPDATE attachments SET status=$2,error_code=$3,updated_at=now() WHERE id=$1`, w.AttachmentID, state, code)
if err != nil {
return err
}
if state == "queued" {
_, err = tx.Exec(ctx, `INSERT INTO attachment_outbox(job_id,attempt,available_at)
SELECT id,attempt+1,next_attempt_at FROM attachment_jobs WHERE id=$1`, w.ID)
if err != nil {
return err
}
}
return tx.Commit(ctx)
}
func (r Repo) Recover(ctx context.Context) error {
rows, err := r.Pool.Query(ctx, `SELECT id,attachment_id,lease_token FROM attachment_jobs
WHERE status='processing' AND lease_until<now() LIMIT 100`)
if err != nil {
return err
}
var ws []Work
for rows.Next() {
var w Work
if err = rows.Scan(&w.ID, &w.AttachmentID, &w.Token); err != nil {
rows.Close()
return err
}
ws = append(ws, w)
}
rows.Close()
if err = rows.Err(); err != nil {
return err
}
for i := range ws {
if err = r.Fail(ctx, &ws[i], "lease_expired", false); err != nil {
return err
}
}
return nil
}
func (r Repo) Replay(ctx context.Context, id, reason string) error {
if !idgen.IsValidUUID(id) || len(reason) < 1 || len(reason) > 200 {
return errors.New("provide job UUID and reason (1..200 bytes)")
}
tx, err := r.Pool.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
var attempt int
var aid string
err = tx.QueryRow(ctx, `SELECT attempt,attachment_id FROM attachment_jobs WHERE id=$1 AND status='failed' FOR UPDATE`, id).Scan(&attempt, &aid)
if errors.Is(err, pgx.ErrNoRows) {
return errors.New("replay allowed only for failed jobs; ready is never replayed")
}
if err != nil {
return err
}
var staging *string
if err = tx.QueryRow(ctx, `SELECT staging_key FROM attachments WHERE id=$1 FOR UPDATE`, aid).Scan(&staging); err != nil {
return err
}
if staging == nil {
return errors.New("staging retention expired; original must be uploaded again")
}
_, err = tx.Exec(ctx, `INSERT INTO job_replays(job_id,reason,previous_attempt) VALUES($1,$2,$3)`, id, reason, attempt)
if err != nil {
return err
}
_, err = tx.Exec(ctx, `UPDATE attachment_jobs SET status='queued',error_code=NULL,next_attempt_at=now(),updated_at=now() WHERE id=$1`, id)
if err != nil {
return err
}
_, err = tx.Exec(ctx, `UPDATE attachments SET status='queued',error_code=NULL,updated_at=now() WHERE id=$1`, aid)
if err != nil {
return err
}
_, err = tx.Exec(ctx, `INSERT INTO attachment_outbox(job_id,attempt) VALUES($1,$2)`, id, attempt+1)
if err != nil {
return err
}
return tx.Commit(ctx)
}
func VariantKey(original, name string) string { return original + "/v1/" + name }
func (r Repo) Failed(ctx context.Context) ([]map[string]any, error) {
rows, err := r.Pool.Query(ctx, `SELECT id,attachment_id,attempt,error_code FROM attachment_jobs WHERE status='failed' ORDER BY updated_at`)
if err != nil {
return nil, err
}
defer rows.Close()
result := []map[string]any{}
for rows.Next() {
var id, aid, code string
var n int
if err = rows.Scan(&id, &aid, &n, &code); err != nil {
return nil, err
}
result = append(result, map[string]any{"job_id": id, "attachment_id": aid, "attempt": n, "error_code": code})
}
return result, rows.Err()
}
func (j Job) Validate() error {
if j.SchemaVersion != 1 || j.Type != "attachment.process.v1" || j.PipelineVersion != 1 || j.Attempt < 1 || !idgen.IsValidUUID(j.ID) || !idgen.IsValidUUID(j.AttachmentID) || j.CreatedAt.IsZero() {
return fmt.Errorf("invalid job envelope")
}
return nil
}
+29
View File
@@ -0,0 +1,29 @@
package jobs
import (
"testing"
"time"
)
func TestRetryBackoffJitterAndCap(t *testing.T) {
for attempt := 1; attempt <= 12; attempt++ {
base := time.Second
for i := 1; i < attempt && base < 60*time.Second; i++ {
base *= 2
}
if base > 60*time.Second {
base = 60 * time.Second
}
values := map[time.Duration]bool{}
for i := 0; i < 50; i++ {
d := RetryDelay(attempt)
if d < base/2 || d > base {
t.Fatalf("attempt=%d delay=%s", attempt, d)
}
values[d] = true
}
if len(values) < 2 {
t.Fatal("jitter absent")
}
}
}
+367
View File
@@ -0,0 +1,367 @@
package jobs
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"io"
"log"
"os"
"path/filepath"
"strings"
"sync"
"time"
"mtusi2026/internal/blobstore"
"mtusi2026/internal/images"
"mtusi2026/internal/model"
"github.com/jackc/pgx/v5"
"github.com/redis/go-redis/v9"
)
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
}
func (r *Runtime) PublishOne(ctx context.Context) (bool, error) {
tx, err := r.Repo.Pool.Begin(ctx)
if err != nil {
return false, err
}
defer tx.Rollback(ctx)
var oid int64
j := Job{SchemaVersion: 1, Type: "attachment.process.v1"}
err = tx.QueryRow(ctx, `SELECT o.id,j.id,j.attachment_id,j.pipeline_version,o.attempt,j.created_at
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)
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
}
pubCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
_, err = r.Broker.XAdd(pubCtx, &redis.XAddArgs{Stream: Stream, Values: map[string]any{"payload": string(payload)}}).Result()
cancel()
if err != nil {
return false, err
}
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 (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
}
w, err := r.Repo.Claim(ctx, j)
if err != nil {
log.Printf("claim job=%s: %v", j.ID, err)
return
}
if w != nil {
err = r.process(ctx, w)
if err != nil {
log.Printf("process job=%s attempt=%d: %v", j.ID, w.Attempt, err)
return
}
}
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 {
log.Printf("ack job=%s: %v", j.ID, err)
}
}
func (r *Runtime) process(ctx context.Context, w *Work) 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
}
log.Printf("job=%s attempt=%d error_code=%s", w.ID, w.Attempt, code)
return r.Repo.Fail(dbCtx, w, code, permanent)
}
ok, err := r.Repo.Complete(dbCtx, w, variants)
if err != nil {
return err
}
if !ok {
return errors.New("completion lease expired or replaced; delivery left pending")
}
if ok {
log.Printf("job=%s attempt=%d ready variants=%d", w.ID, w.Attempt, len(variants))
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 {
log.Printf("defer staging cleanup job=%s", w.ID)
}
}
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<now()-$1::interval AND a.staging_key IS NOT NULL
LIMIT 100 FOR UPDATE OF j,a SKIP LOCKED`, r.Retention.String())
if err != nil {
return err
}
type expired struct{ id, key string }
var old []expired
for failed.Next() {
var e expired
if err = failed.Scan(&e.id, &e.key); err != nil {
failed.Close()
return err
}
old = append(old, e)
}
failed.Close()
if err = failed.Err(); err != nil {
return err
}
for _, e := range old {
if err = r.Blobs.Delete(ctx, e.key); err != nil {
return err
}
if _, err = tx.Exec(ctx, `UPDATE attachments SET staging_key=NULL WHERE id=$1`, e.id); err != nil {
return err
}
}
if err = tx.Commit(ctx); err != nil {
return err
}
rows, err := r.Repo.Pool.Query(ctx, `SELECT id,staging_key FROM attachments WHERE status='ready' AND staging_key IS NOT NULL LIMIT 100`)
if err != nil {
return err
}
type rec struct{ id, key string }
var ready []rec
for rows.Next() {
var v rec
if err = rows.Scan(&v.id, &v.key); err != nil {
rows.Close()
return err
}
ready = append(ready, v)
}
rows.Close()
if err = rows.Err(); err != nil {
return err
}
for _, v := range ready {
if err = r.Blobs.Delete(ctx, v.key); err != nil {
return err
}
if _, err = r.Repo.Pool.Exec(ctx, `UPDATE attachments SET staging_key=NULL WHERE id=$1 AND status='ready'`, v.id); err != nil {
return err
}
}
return r.Blobs.List(ctx, "staging/", func(key string, modified time.Time) error {
if time.Since(modified) < r.Retention {
return nil
}
var exists bool
if err := r.Repo.Pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM attachments WHERE staging_key=$1)`, key).Scan(&exists); err != nil {
return err
}
if !exists {
return r.Blobs.Delete(ctx, key)
}
return nil
})
}