forked from mtusi2026/mtusi2026lab5
619 lines
20 KiB
Go
619 lines
20 KiB
Go
package attachment
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"math/rand/v2"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
"syscall"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/minio/minio-go/v7"
|
|
"github.com/redis/go-redis/v9"
|
|
"golang.org/x/sync/semaphore"
|
|
)
|
|
|
|
const Stream = "attachments:jobs:v1"
|
|
const Group = "image-workers-v1"
|
|
|
|
type JobMessage struct {
|
|
SchemaVersion int `json:"schema_version"`
|
|
JobID 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"`
|
|
Traceparent string `json:"traceparent,omitempty"`
|
|
Tracestate string `json:"tracestate,omitempty"`
|
|
}
|
|
type Variant struct {
|
|
Name string `json:"name"`
|
|
ContentType string `json:"content_type"`
|
|
Width int `json:"width"`
|
|
Height int `json:"height"`
|
|
Size int64 `json:"size_bytes"`
|
|
SHA256 string `json:"sha256"`
|
|
}
|
|
type claimed struct {
|
|
JobMessage
|
|
Fence int64
|
|
Stage, Original, MIME, SHA string
|
|
Width, Height int
|
|
Size int64
|
|
}
|
|
|
|
func (s *Service) put(ctx context.Context, key string, r io.Reader, size int64, mime string) error {
|
|
_, err := s.Store.Client.PutObject(ctx, s.Store.Bucket, key, r, size, minio.PutObjectOptions{ContentType: mime, DisableMultipart: true})
|
|
return err
|
|
}
|
|
func (s *Service) Publish(ctx context.Context, r *redis.Client) error {
|
|
tx, err := s.Pool.Begin(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback(context.Background())
|
|
rows, err := tx.Query(ctx, `SELECT j.id::text,j.attachment_id::text,j.pipeline_version,j.attempts+1,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<=clock_timestamp() AND j.state='queued' ORDER BY o.available_at LIMIT 32 FOR UPDATE OF o SKIP LOCKED`)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
messages := []JobMessage{}
|
|
for rows.Next() {
|
|
m := JobMessage{SchemaVersion: 1, Type: "attachment.process.v1"}
|
|
if err = rows.Scan(&m.JobID, &m.AttachmentID, &m.PipelineVersion, &m.Attempt, &m.CreatedAt); err != nil {
|
|
rows.Close()
|
|
return err
|
|
}
|
|
m.CreatedAt = m.CreatedAt.UTC()
|
|
messages = append(messages, m)
|
|
}
|
|
err = rows.Err()
|
|
rows.Close()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, m := range messages {
|
|
raw, _ := json.Marshal(m)
|
|
id, e := r.XAdd(ctx, &redis.XAddArgs{Stream: Stream, Values: map[string]interface{}{"job": string(raw)}}).Result()
|
|
if e != nil {
|
|
return e
|
|
}
|
|
if _, e = tx.Exec(ctx, `UPDATE attachment_outbox SET published_at=clock_timestamp(),stream_id=$2 WHERE job_id=$1`, m.JobID, id); e != nil {
|
|
return e
|
|
}
|
|
}
|
|
return tx.Commit(ctx)
|
|
}
|
|
func (s *Service) recover(ctx context.Context) error {
|
|
tx, err := s.Pool.Begin(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback(context.Background())
|
|
rows, err := tx.Query(ctx, `SELECT id::text,attachment_id::text,attempts,max_attempts FROM attachment_jobs WHERE state='processing' AND lease_until<clock_timestamp() FOR UPDATE SKIP LOCKED`)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
type lost struct {
|
|
id, att string
|
|
attempt, max int
|
|
}
|
|
all := []lost{}
|
|
for rows.Next() {
|
|
var l lost
|
|
if err = rows.Scan(&l.id, &l.att, &l.attempt, &l.max); err != nil {
|
|
rows.Close()
|
|
return err
|
|
}
|
|
all = append(all, l)
|
|
}
|
|
err = rows.Err()
|
|
rows.Close()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, l := range all {
|
|
state := "queued"
|
|
var code *string
|
|
if l.attempt >= l.max {
|
|
state = "failed"
|
|
v := "retry_exhausted"
|
|
code = &v
|
|
}
|
|
if _, err = tx.Exec(ctx, `UPDATE attachment_jobs SET state=$2,lease_until=NULL,available_at=clock_timestamp(),updated_at=clock_timestamp(),last_error='worker_lost' WHERE id=$1`, l.id, state); err != nil {
|
|
return err
|
|
}
|
|
if _, err = tx.Exec(ctx, `UPDATE attachments SET status=$2,error_code=$3,updated_at=clock_timestamp() WHERE id=$1`, l.att, state, code); err != nil {
|
|
return err
|
|
}
|
|
if state == "queued" {
|
|
if _, err = tx.Exec(ctx, `UPDATE attachment_outbox SET published_at=NULL,available_at=clock_timestamp() WHERE job_id=$1`, l.id); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
}
|
|
return tx.Commit(ctx)
|
|
}
|
|
func (s *Service) claim(ctx context.Context, m JobMessage) (claimed, bool, error) {
|
|
j := claimed{JobMessage: m}
|
|
tx, err := s.Pool.Begin(ctx)
|
|
if err != nil {
|
|
return j, false, err
|
|
}
|
|
defer tx.Rollback(context.Background())
|
|
var state string
|
|
var attempts, max, version int
|
|
var available time.Time
|
|
err = tx.QueryRow(ctx, `SELECT state,attempts,max_attempts,available_at,pipeline_version FROM attachment_jobs WHERE id=$1 AND attachment_id=$2 FOR UPDATE`, m.JobID, m.AttachmentID).Scan(&state, &attempts, &max, &available, &version)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return j, false, nil
|
|
}
|
|
if err != nil {
|
|
return j, false, err
|
|
}
|
|
if state == "ready" {
|
|
var key, mime string
|
|
var size int64
|
|
var raw []byte
|
|
if err = tx.QueryRow(ctx, `SELECT object_key,content_type,size_bytes,variants FROM attachments WHERE id=$1 AND status='ready' AND pipeline_version=$2`, m.AttachmentID, version).Scan(&key, &mime, &size, &raw); err != nil {
|
|
return j, false, err
|
|
}
|
|
var variants []Variant
|
|
if err = json.Unmarshal(raw, &variants); err != nil || len(variants) != 3 {
|
|
return j, false, fmt.Errorf("completed effect metadata incomplete")
|
|
}
|
|
objects := map[string]int64{key: size}
|
|
for _, v := range variants {
|
|
objects[effectKey(m.AttachmentID, version, v.Name)] = v.Size
|
|
}
|
|
for object, n := range objects {
|
|
info, e := s.Store.Client.StatObject(ctx, s.Store.Bucket, object, minio.StatObjectOptions{})
|
|
if e != nil {
|
|
return j, false, e
|
|
}
|
|
if info.Size != n {
|
|
return j, false, fmt.Errorf("completed effect size mismatch")
|
|
}
|
|
}
|
|
return j, false, nil
|
|
}
|
|
if state != "queued" || available.After(time.Now()) || m.Attempt != attempts+1 || version != m.PipelineVersion {
|
|
return j, false, nil
|
|
}
|
|
if attempts >= max {
|
|
return j, false, fmt.Errorf("attempt invariant violated")
|
|
}
|
|
err = tx.QueryRow(ctx, `UPDATE attachment_jobs SET state='processing',attempts=attempts+1,fence=fence+1,lease_until=clock_timestamp()+$2*interval '1 second',updated_at=clock_timestamp() WHERE id=$1 RETURNING fence`, m.JobID, s.Options.Lease.Seconds()).Scan(&j.Fence)
|
|
if err != nil {
|
|
return j, false, err
|
|
}
|
|
err = tx.QueryRow(ctx, `UPDATE attachments SET status='processing',updated_at=clock_timestamp() WHERE id=$1 AND pipeline_version=$2 AND status IN ('queued','processing') RETURNING staging_key,object_key,content_type,size_bytes,sha256,width,height`, m.AttachmentID, version).Scan(&j.Stage, &j.Original, &j.MIME, &j.Size, &j.SHA, &j.Width, &j.Height)
|
|
if err != nil {
|
|
return j, false, err
|
|
}
|
|
return j, true, tx.Commit(ctx)
|
|
}
|
|
|
|
// finish publishes metadata only for the current, unexpired fencing token.
|
|
func (s *Service) finish(ctx context.Context, j claimed, variants []Variant, code string, permanent bool) (bool, error) {
|
|
tx, err := s.Pool.Begin(ctx)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
defer tx.Rollback(context.Background())
|
|
var max int
|
|
err = tx.QueryRow(ctx, `SELECT max_attempts FROM attachment_jobs WHERE id=$1 AND fence=$2 AND state='processing' AND lease_until>clock_timestamp() AND pipeline_version=$3 FOR UPDATE`, j.JobID, j.Fence, j.PipelineVersion).Scan(&max)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
return false, nil
|
|
}
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
lastError := code
|
|
state := "ready"
|
|
var failure *string
|
|
available := time.Now()
|
|
if code != "" {
|
|
state = "queued"
|
|
if permanent || j.Attempt >= max {
|
|
state = "failed"
|
|
if !permanent {
|
|
code = "retry_exhausted"
|
|
}
|
|
failure = &code
|
|
}
|
|
delay := time.Duration(1<<min(j.Attempt, 5)) * time.Second
|
|
available = available.Add(delay + time.Duration(rand.IntN(500))*time.Millisecond)
|
|
}
|
|
raw := []byte("[]")
|
|
if state == "ready" {
|
|
raw, err = json.Marshal(variants)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
}
|
|
if _, err = tx.Exec(ctx, `UPDATE attachment_jobs SET state=$2,lease_until=NULL,available_at=$3,last_error=NULLIF($4,''),updated_at=clock_timestamp() WHERE id=$1`, j.JobID, state, available, lastError); err != nil {
|
|
return false, err
|
|
}
|
|
tag, updateErr := tx.Exec(ctx, `UPDATE attachments SET status=$2,error_code=$3,variants=$4,updated_at=clock_timestamp() WHERE id=$1 AND pipeline_version=$5 AND status='processing'`, j.AttachmentID, state, failure, raw, j.PipelineVersion)
|
|
if updateErr != nil {
|
|
return false, updateErr
|
|
}
|
|
if tag.RowsAffected() != 1 {
|
|
return false, fmt.Errorf("attachment version/state changed")
|
|
}
|
|
if state == "queued" {
|
|
if _, err = tx.Exec(ctx, `UPDATE attachment_outbox SET published_at=NULL,available_at=$2 WHERE job_id=$1`, j.JobID, available); err != nil {
|
|
return false, err
|
|
}
|
|
}
|
|
return true, tx.Commit(ctx)
|
|
}
|
|
func (s *Service) render(ctx context.Context, j claimed) ([]Variant, string, bool) {
|
|
if os.Getenv("PIPELINE_FAILPOINT") == "transient" {
|
|
return nil, "storage_unavailable", false
|
|
}
|
|
dir, err := os.MkdirTemp("", "pipeline-*")
|
|
if err != nil {
|
|
return nil, "processing_failed", false
|
|
}
|
|
defer os.RemoveAll(dir)
|
|
source := filepath.Join(dir, "source")
|
|
obj, err := s.Store.Client.GetObject(ctx, s.Store.Bucket, j.Stage, minio.GetObjectOptions{})
|
|
if err != nil {
|
|
return nil, "storage_unavailable", false
|
|
}
|
|
defer obj.Close()
|
|
f, err := os.Create(source)
|
|
if err != nil {
|
|
return nil, "processing_failed", false
|
|
}
|
|
n, err := io.Copy(f, io.LimitReader(&contextReader{ctx: ctx, r: obj}, MaxBytes+1))
|
|
f.Close()
|
|
if err != nil {
|
|
if IsMissing(err) {
|
|
return nil, "original_missing", true
|
|
}
|
|
return nil, "storage_unavailable", false
|
|
}
|
|
if n != j.Size {
|
|
return nil, "invalid_image", true
|
|
}
|
|
exe, err := os.Executable()
|
|
if err != nil {
|
|
return nil, "processing_failed", false
|
|
}
|
|
cmd := exec.CommandContext(ctx, exe, "render", source, dir, j.SHA)
|
|
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
|
|
cmd.Cancel = func() error {
|
|
if cmd.Process == nil {
|
|
return nil
|
|
}
|
|
return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
|
|
}
|
|
cmd.WaitDelay = time.Second
|
|
cmd.Env = append(os.Environ(), "GOMEMLIMIT=384MiB")
|
|
if err = cmd.Run(); err != nil {
|
|
if ctx.Err() != nil {
|
|
return nil, "processing_timeout", false
|
|
}
|
|
if cmd.ProcessState != nil && cmd.ProcessState.ExitCode() == 2 {
|
|
return nil, "invalid_image", true
|
|
}
|
|
return nil, "processing_failed", false
|
|
}
|
|
raw, err := os.ReadFile(filepath.Join(dir, "manifest.json"))
|
|
if err != nil {
|
|
return nil, "processing_failed", false
|
|
}
|
|
var variants []Variant
|
|
if json.Unmarshal(raw, &variants) != nil {
|
|
return nil, "processing_failed", false
|
|
}
|
|
f, err = os.Open(source)
|
|
if err != nil {
|
|
return nil, "processing_failed", false
|
|
}
|
|
err = s.put(ctx, j.Original, f, j.Size, j.MIME)
|
|
f.Close()
|
|
if err != nil {
|
|
return nil, "storage_unavailable", false
|
|
}
|
|
for _, v := range variants {
|
|
f, err = os.Open(filepath.Join(dir, v.Name))
|
|
if err != nil {
|
|
return nil, "processing_failed", false
|
|
}
|
|
err = s.put(ctx, effectKey(j.AttachmentID, j.PipelineVersion, v.Name), f, v.Size, v.ContentType)
|
|
f.Close()
|
|
if err != nil {
|
|
return nil, "storage_unavailable", false
|
|
}
|
|
}
|
|
if os.Getenv("PIPELINE_FAILPOINT") == "after_objects" {
|
|
log.Print("FAILPOINT after_objects reached")
|
|
os.Exit(86)
|
|
}
|
|
return variants, "", false
|
|
}
|
|
func (s *Service) RunWorker(ctx context.Context, r *redis.Client) error {
|
|
if err := r.XGroupCreateMkStream(ctx, Stream, Group, "0").Err(); err != nil && !strings.Contains(err.Error(), "BUSYGROUP") {
|
|
return err
|
|
}
|
|
consumer := uuid.NewString()
|
|
queue := make(chan redis.XMessage, s.Options.Prefetch)
|
|
pixels := semaphore.NewWeighted(int64(s.Options.PixelBudget))
|
|
var wg sync.WaitGroup
|
|
for i := 0; i < s.Options.Concurrency; i++ {
|
|
wg.Add(1)
|
|
go func() {
|
|
defer wg.Done()
|
|
for msg := range queue {
|
|
var m JobMessage
|
|
decoder := json.NewDecoder(strings.NewReader(fmt.Sprint(msg.Values["job"])))
|
|
decoder.DisallowUnknownFields()
|
|
err := decoder.Decode(&m)
|
|
if err != nil || m.SchemaVersion != 1 || m.Type != "attachment.process.v1" || m.Attempt < 1 || m.PipelineVersion < 1 || m.CreatedAt.IsZero() || uuid.Validate(m.JobID) != nil || uuid.Validate(m.AttachmentID) != nil {
|
|
log.Print("invalid stream envelope ignored")
|
|
ack(ctx, r, msg.ID)
|
|
continue
|
|
}
|
|
op, cancel := context.WithTimeout(ctx, 5*time.Second)
|
|
j, ok, err := s.claim(op, m)
|
|
cancel()
|
|
if err != nil {
|
|
log.Print("job claim/effect verification will retry")
|
|
continue
|
|
}
|
|
if !ok {
|
|
ack(ctx, r, msg.ID)
|
|
continue
|
|
}
|
|
weight := int64(j.Width) * int64(j.Height)
|
|
// The whole lease includes pixel admission, download, decoder and all S3 writes.
|
|
op, cancel = context.WithTimeout(ctx, s.Options.Timeout)
|
|
var variants []Variant
|
|
code := "processing_timeout"
|
|
permanent := false
|
|
if err = pixels.Acquire(op, weight); err == nil {
|
|
variants, code, permanent = s.render(op, j)
|
|
pixels.Release(weight)
|
|
}
|
|
cancel()
|
|
finishCtx, finishCancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
durable, e := s.finish(finishCtx, j, variants, code, permanent)
|
|
finishCancel()
|
|
if e == nil && durable {
|
|
if os.Getenv("PIPELINE_FAILPOINT") == "after_commit" && code == "" {
|
|
log.Print("FAILPOINT after_commit reached")
|
|
os.Exit(87)
|
|
}
|
|
ack(ctx, r, msg.ID)
|
|
}
|
|
}
|
|
}()
|
|
}
|
|
lastCleanup := time.Now()
|
|
ticker := time.NewTicker(250 * time.Millisecond)
|
|
defer ticker.Stop()
|
|
defer func() { close(queue); wg.Wait() }()
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return nil
|
|
case <-ticker.C:
|
|
}
|
|
op, cancel := context.WithTimeout(ctx, 5*time.Second)
|
|
if err := s.recover(op); err != nil {
|
|
log.Print("lease recovery will retry")
|
|
}
|
|
if os.Getenv("PIPELINE_PAUSE_PUBLISH") != "1" {
|
|
if err := s.Publish(op, r); err != nil {
|
|
log.Print("outbox publish will retry")
|
|
}
|
|
}
|
|
cancel()
|
|
// Claim PEL entries left by a dead consumer; PG leases remain the effect authority.
|
|
op, cancel = context.WithTimeout(ctx, 2*time.Second)
|
|
pending, _, _ := r.XAutoClaim(op, &redis.XAutoClaimArgs{Stream: Stream, Group: Group, Consumer: consumer, MinIdle: s.Options.Lease, Start: "0-0", Count: int64(s.Options.Prefetch)}).Result()
|
|
cancel()
|
|
for _, m := range pending {
|
|
select {
|
|
case queue <- m:
|
|
case <-ctx.Done():
|
|
return nil
|
|
}
|
|
}
|
|
// Never fetch beyond bounded prefetch capacity; no unbounded in-memory backlog.
|
|
room := cap(queue) - len(queue)
|
|
if room > 0 {
|
|
op, cancel = context.WithTimeout(ctx, time.Second)
|
|
streams, e := r.XReadGroup(op, &redis.XReadGroupArgs{Group: Group, Consumer: consumer, Streams: []string{Stream, ">"}, Count: int64(room), Block: 100 * time.Millisecond}).Result()
|
|
cancel()
|
|
if e == nil {
|
|
for _, stream := range streams {
|
|
for _, m := range stream.Messages {
|
|
select {
|
|
case queue <- m:
|
|
case <-ctx.Done():
|
|
return nil
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
if time.Since(lastCleanup) >= 5*time.Second {
|
|
lastCleanup = time.Now()
|
|
op, cancel = context.WithTimeout(ctx, 5*time.Second)
|
|
s.cleanStages(op)
|
|
cancel()
|
|
}
|
|
}
|
|
}
|
|
func ack(ctx context.Context, r *redis.Client, id string) {
|
|
if r.XAck(ctx, Stream, Group, id).Err() == nil {
|
|
r.XDel(ctx, Stream, id)
|
|
}
|
|
}
|
|
|
|
// Replay is an explicit operator action, serialized with admission and job claims.
|
|
// It preserves job/effect identity and refuses already successful work.
|
|
func (s *Service) Replay(ctx context.Context, id, operator, reason string) error {
|
|
if uuid.Validate(id) != nil || len(operator) < 1 || len(operator) > 100 || len(reason) < 1 || len(reason) > 300 {
|
|
return fmt.Errorf("job UUID, operator and reason are required")
|
|
}
|
|
tx, err := s.Pool.Begin(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback(context.Background())
|
|
if _, err = tx.Exec(ctx, `SELECT pg_advisory_xact_lock(578903551)`); err != nil {
|
|
return err
|
|
}
|
|
var pending int
|
|
if err = tx.QueryRow(ctx, `SELECT count(*) FROM attachment_jobs WHERE state IN ('queued','processing')`).Scan(&pending); err != nil {
|
|
return err
|
|
}
|
|
if pending >= s.Options.MaxOutstanding {
|
|
return fmt.Errorf("admission limit reached")
|
|
}
|
|
var att, state, previous string
|
|
err = tx.QueryRow(ctx, `SELECT attachment_id::text,state,coalesce(last_error,'processing_failed') FROM attachment_jobs WHERE id=$1 FOR UPDATE`, id).Scan(&att, &state, &previous)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if state != "failed" {
|
|
return fmt.Errorf("only failed jobs may be replayed")
|
|
}
|
|
var stage *string
|
|
if err = tx.QueryRow(ctx, `SELECT staging_key FROM attachments WHERE id=$1 FOR UPDATE`, att).Scan(&stage); err != nil {
|
|
return err
|
|
}
|
|
if stage == nil {
|
|
return fmt.Errorf("staging retention expired")
|
|
}
|
|
if _, err = s.Store.Client.StatObject(ctx, s.Store.Bucket, *stage, minio.StatObjectOptions{}); err != nil {
|
|
return fmt.Errorf("staging unavailable")
|
|
}
|
|
if _, err = tx.Exec(ctx, `INSERT INTO attachment_replays(job_id,operator,reason,previous_error) VALUES($1,$2,$3,$4)`, id, operator, reason, previous); err != nil {
|
|
return err
|
|
}
|
|
if _, err = tx.Exec(ctx, `UPDATE attachment_jobs SET state='queued',attempts=0,fence=fence+1,last_error=NULL,available_at=clock_timestamp(),updated_at=clock_timestamp() WHERE id=$1`, id); err != nil {
|
|
return err
|
|
}
|
|
if _, err = tx.Exec(ctx, `UPDATE attachments SET status='queued',error_code=NULL,updated_at=clock_timestamp() WHERE id=$1`, att); err != nil {
|
|
return err
|
|
}
|
|
if _, err = tx.Exec(ctx, `UPDATE attachment_outbox SET published_at=NULL,available_at=clock_timestamp() WHERE job_id=$1`, id); err != nil {
|
|
return err
|
|
}
|
|
return tx.Commit(ctx)
|
|
}
|
|
|
|
// Keep failed stages for seven days for explicit replay; ready stages are garbage.
|
|
func (s *Service) cleanStages(ctx context.Context) {
|
|
rows, err := s.Pool.Query(ctx, `SELECT id::text FROM attachments WHERE (status='ready' AND staging_key IS NOT NULL) OR (status='failed' AND updated_at<clock_timestamp()-interval '7 days' AND storage_cleaned_at IS NULL) LIMIT 100`)
|
|
if err != nil {
|
|
return
|
|
}
|
|
ids := []string{}
|
|
for rows.Next() {
|
|
var id string
|
|
if rows.Scan(&id) == nil {
|
|
ids = append(ids, id)
|
|
}
|
|
}
|
|
rows.Close()
|
|
for _, id := range ids {
|
|
tx, e := s.Pool.Begin(ctx)
|
|
if e != nil {
|
|
return
|
|
}
|
|
var stage *string
|
|
var state, original string
|
|
var version int
|
|
e = tx.QueryRow(ctx, `SELECT staging_key,status,object_key,pipeline_version FROM attachments WHERE id=$1 AND ((status='ready' AND staging_key IS NOT NULL) OR (status='failed' AND updated_at<clock_timestamp()-interval '7 days' AND storage_cleaned_at IS NULL)) FOR UPDATE`, id).Scan(&stage, &state, &original, &version)
|
|
if e == nil && state == "failed" {
|
|
for _, name := range []string{"original", "thumbnail", "crop", "optimized"} {
|
|
key := effectKey(id, version, name)
|
|
if name == "original" {
|
|
key = original
|
|
}
|
|
e = s.Store.Client.RemoveObject(ctx, s.Store.Bucket, key, minio.RemoveObjectOptions{})
|
|
if e != nil {
|
|
break
|
|
}
|
|
}
|
|
}
|
|
if e == nil && stage != nil {
|
|
e = s.Store.Client.RemoveObject(ctx, s.Store.Bucket, *stage, minio.RemoveObjectOptions{})
|
|
}
|
|
if e == nil {
|
|
if state == "failed" {
|
|
_, e = tx.Exec(ctx, `UPDATE attachments SET staging_key=NULL,variants='[]',storage_cleaned_at=clock_timestamp() WHERE id=$1`, id)
|
|
} else {
|
|
_, e = tx.Exec(ctx, `UPDATE attachments SET staging_key=NULL WHERE id=$1`, id)
|
|
}
|
|
}
|
|
if e == nil {
|
|
tx.Commit(ctx)
|
|
} else {
|
|
tx.Rollback(ctx)
|
|
}
|
|
}
|
|
|
|
// Unconfirmed stages (PUT succeeded, DB did not COMMIT) have a 90s grace and upload lock.
|
|
for obj := range s.Store.Client.ListObjects(ctx, s.Store.Bucket, minio.ListObjectsOptions{Prefix: "staging/", Recursive: true}) {
|
|
if obj.Err != nil {
|
|
return
|
|
}
|
|
if time.Since(obj.LastModified) < MinimumGrace {
|
|
continue
|
|
}
|
|
tx, e := s.Pool.Begin(ctx)
|
|
if e != nil {
|
|
return
|
|
}
|
|
var locked, exists bool
|
|
e = tx.QueryRow(ctx, `SELECT pg_try_advisory_xact_lock(hashtextextended($1,0))`, obj.Key).Scan(&locked)
|
|
if e == nil && locked {
|
|
e = tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM attachments WHERE staging_key=$1)`, obj.Key).Scan(&exists)
|
|
if e == nil && !exists {
|
|
e = s.Store.Client.RemoveObject(ctx, s.Store.Bucket, obj.Key, minio.RemoveObjectOptions{})
|
|
}
|
|
}
|
|
tx.Rollback(ctx)
|
|
}
|
|
}
|
|
|
|
// RunPublisher drains durable DB intentions independently of worker availability.
|
|
func (s *Service) RunPublisher(ctx context.Context, r *redis.Client) {
|
|
ticker := time.NewTicker(200 * time.Millisecond)
|
|
defer ticker.Stop()
|
|
for {
|
|
select {
|
|
case <-ctx.Done():
|
|
return
|
|
case <-ticker.C:
|
|
}
|
|
if os.Getenv("PIPELINE_PAUSE_PUBLISH") == "1" {
|
|
continue
|
|
}
|
|
op, cancel := context.WithTimeout(ctx, 5*time.Second)
|
|
if err := s.Publish(op, r); err != nil {
|
|
log.Print("outbox publisher will retry")
|
|
}
|
|
cancel()
|
|
}
|
|
}
|