Files
mtusi2026lab5/internal/jobs/runtime.go
2026-11-12 17:28:28 +03:00

368 lines
9.8 KiB
Go

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
})
}