442 lines
15 KiB
Go
442 lines
15 KiB
Go
package messenger
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
"github.com/minio/minio-go/v7"
|
|
"github.com/redis/go-redis/v9"
|
|
"go.opentelemetry.io/otel/attribute"
|
|
"go.opentelemetry.io/otel/trace"
|
|
"io"
|
|
"log/slog"
|
|
"math/rand/v2"
|
|
"mtusi/messenger/internal/telemetry"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"strconv"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
)
|
|
|
|
const stream = "attachment.jobs.v1"
|
|
const group = "image-workers"
|
|
const maxAttempts = 5
|
|
const leaseSeconds = 45
|
|
|
|
type Job struct {
|
|
SchemaVersion int `json:"schema_version"`
|
|
ID 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"`
|
|
Traceparent string `json:"traceparent,omitempty"`
|
|
Tracestate string `json:"tracestate,omitempty"`
|
|
}
|
|
type Pipeline struct {
|
|
DB *pgxpool.Pool
|
|
Broker *redis.Client
|
|
Objects *ObjectStore
|
|
Log *slog.Logger
|
|
}
|
|
|
|
func NewPipeline(db *pgxpool.Pool, broker *redis.Client, o *ObjectStore, log *slog.Logger) *Pipeline {
|
|
return &Pipeline{db, broker, o, log}
|
|
}
|
|
func wait(ctx context.Context, d time.Duration) bool {
|
|
t := time.NewTimer(d)
|
|
defer t.Stop()
|
|
select {
|
|
case <-ctx.Done():
|
|
return false
|
|
case <-t.C:
|
|
return true
|
|
}
|
|
}
|
|
func (p *Pipeline) RunDispatcher(ctx context.Context) error {
|
|
for ctx.Err() == nil {
|
|
if e := p.dispatch(ctx); e != nil {
|
|
p.Log.Warn("outbox_retry", "event", "outbox_retry")
|
|
}
|
|
if !wait(ctx, 500*time.Millisecond) {
|
|
break
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
func (p *Pipeline) dispatch(ctx context.Context) error {
|
|
// Small per-row transaction + SKIP LOCKED allows multiple dispatchers. A crash
|
|
// after XADD before COMMIT gives a duplicate, never a missing durable intent.
|
|
for i := 0; i < 32; i++ {
|
|
tx, e := p.DB.Begin(ctx)
|
|
if e != nil {
|
|
return e
|
|
}
|
|
var j Job
|
|
var created time.Time
|
|
e = tx.QueryRow(ctx, `SELECT job_id::text,attachment_id::text,pipeline_version,attempt+1,created_at,traceparent,tracestate FROM pipeline_jobs WHERE finished_at IS NULL AND next_attempt_at<=clock_timestamp() AND (lease_until IS NULL OR lease_until<clock_timestamp()) AND (published_at IS NULL OR published_at<clock_timestamp()-interval '60 seconds') ORDER BY next_attempt_at FOR UPDATE SKIP LOCKED LIMIT 1`).Scan(&j.ID, &j.AttachmentID, &j.Version, &j.Attempt, &created, &j.Traceparent, &j.Tracestate)
|
|
if errors.Is(e, pgx.ErrNoRows) {
|
|
tx.Rollback(ctx)
|
|
return nil
|
|
}
|
|
if e != nil {
|
|
tx.Rollback(ctx)
|
|
return e
|
|
}
|
|
j.SchemaVersion = 1
|
|
j.Type = "attachment.process.v1"
|
|
j.CreatedAt = stamp(created)
|
|
publishCtx, span := telemetry.Start(telemetry.Extract(ctx, j.Traceparent, j.Tracestate), "queue.publish", trace.SpanKindProducer)
|
|
span.SetAttributes(attribute.String("messaging.system", "valkey"), attribute.String("messaging.destination.name", stream))
|
|
j.Traceparent, j.Tracestate = telemetry.Inject(publishCtx)
|
|
payload, _ := json.Marshal(j)
|
|
_, e = p.Broker.XAdd(publishCtx, &redis.XAddArgs{Stream: stream, Values: map[string]any{"payload": string(payload)}}).Result()
|
|
telemetry.Failure(span, e)
|
|
span.End()
|
|
if e == nil {
|
|
_, e = tx.Exec(ctx, "UPDATE pipeline_jobs SET published_at=clock_timestamp() WHERE job_id=$1", j.ID)
|
|
}
|
|
if e != nil {
|
|
tx.Rollback(ctx)
|
|
return e
|
|
}
|
|
if e = tx.Commit(ctx); e != nil {
|
|
return e
|
|
}
|
|
p.Log.InfoContext(publishCtx, "job_published", "event", "job_published", "job_id", j.ID, "pipeline_version", j.Version)
|
|
}
|
|
return nil
|
|
}
|
|
func (p *Pipeline) RunWorker(ctx context.Context, concurrency int) error {
|
|
if concurrency < 1 || concurrency > 4 {
|
|
return fmt.Errorf("WORKER_CONCURRENCY must be 1..4")
|
|
}
|
|
for ctx.Err() == nil {
|
|
e := p.Broker.XGroupCreateMkStream(ctx, stream, group, "0").Err()
|
|
if e == nil || strings.Contains(e.Error(), "BUSYGROUP") {
|
|
break
|
|
}
|
|
if !wait(ctx, time.Second) {
|
|
return nil
|
|
}
|
|
}
|
|
telemetry.WorkerCapacity(concurrency)
|
|
var wg sync.WaitGroup
|
|
for i := 0; i < concurrency; i++ {
|
|
wg.Add(1)
|
|
go func() { defer wg.Done(); p.consume(ctx, uuid()) }()
|
|
}
|
|
wg.Wait()
|
|
return nil
|
|
}
|
|
func (p *Pipeline) consume(ctx context.Context, consumer string) {
|
|
cursor := "0-0"
|
|
for ctx.Err() == nil {
|
|
claimed, next, e := p.Broker.XAutoClaim(ctx, &redis.XAutoClaimArgs{Stream: stream, Group: group, Consumer: consumer, MinIdle: time.Minute, Start: cursor, Count: 1}).Result()
|
|
cursor = next
|
|
if e == nil && len(claimed) > 0 {
|
|
p.handle(ctx, claimed[0])
|
|
continue
|
|
}
|
|
entries, e := p.Broker.XReadGroup(ctx, &redis.XReadGroupArgs{Group: group, Consumer: consumer, Streams: []string{stream, ">"}, Count: 1, Block: time.Second}).Result()
|
|
if e != nil {
|
|
if e != redis.Nil {
|
|
wait(ctx, time.Second)
|
|
}
|
|
continue
|
|
}
|
|
for _, entry := range entries {
|
|
for _, m := range entry.Messages {
|
|
p.handle(ctx, m)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
func (p *Pipeline) handle(ctx context.Context, m redis.XMessage) {
|
|
raw, _ := m.Values["payload"].(string)
|
|
var j Job
|
|
d := json.NewDecoder(strings.NewReader(raw))
|
|
d.DisallowUnknownFields()
|
|
if len(raw) > 4096 || d.Decode(&j) != nil || j.SchemaVersion != 1 || j.Type != "attachment.process.v1" || !uuidRE.MatchString(j.ID) || !uuidRE.MatchString(j.AttachmentID) || j.Version < 1 || j.Attempt < 1 {
|
|
p.Log.Warn("invalid_job", "event", "invalid_job")
|
|
p.ack(ctx, m.ID)
|
|
return
|
|
}
|
|
// The authoritative attempt and storage locations come from PostgreSQL, never
|
|
// from untrusted broker payload fields. A terminal/stale delivery is a no-op.
|
|
ctx, span := telemetry.Start(telemetry.Extract(ctx, j.Traceparent, j.Tracestate), "queue.consume", trace.SpanKindConsumer)
|
|
defer span.End()
|
|
done, e := p.process(ctx, j)
|
|
telemetry.Failure(span, e)
|
|
if e != nil {
|
|
p.Log.WarnContext(ctx, "job_deferred", "event", "job_deferred", "job_id", j.ID)
|
|
}
|
|
if done {
|
|
p.ack(ctx, m.ID)
|
|
}
|
|
}
|
|
func (p *Pipeline) ack(ctx context.Context, id string) {
|
|
// Do not delete an entry unless ACK succeeded; the only consumer group is ours.
|
|
if p.Broker.XAck(ctx, stream, group, id).Err() == nil {
|
|
p.Broker.XDel(ctx, stream, id)
|
|
}
|
|
}
|
|
func (p *Pipeline) process(parent context.Context, j Job) (bool, error) {
|
|
ctx, cancel := context.WithTimeout(parent, 30*time.Second)
|
|
defer cancel()
|
|
tx, e := p.DB.Begin(ctx)
|
|
if e != nil {
|
|
return false, e
|
|
}
|
|
defer tx.Rollback(context.Background())
|
|
var status, key, sha, contentType string
|
|
var version, attempt int
|
|
var size int64
|
|
var lease *time.Time
|
|
e = tx.QueryRow(ctx, `SELECT a.status,a.pipeline_version,a.staging_key,a.sha256,a.content_type,a.size_bytes,j.attempt,j.lease_until FROM pipeline_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE j.job_id=$1 AND j.attachment_id=$2 AND j.pipeline_version=$3 FOR UPDATE OF j,a`, j.ID, j.AttachmentID, j.Version).Scan(&status, &version, &key, &sha, &contentType, &size, &attempt, &lease)
|
|
if errors.Is(e, pgx.ErrNoRows) {
|
|
return true, nil
|
|
}
|
|
if e != nil {
|
|
return false, e
|
|
}
|
|
if version != j.Version || status == "ready" || status == "failed" {
|
|
return true, nil
|
|
}
|
|
var now time.Time
|
|
if e = tx.QueryRow(ctx, "SELECT clock_timestamp()").Scan(&now); e != nil {
|
|
return false, e
|
|
}
|
|
if lease != nil && lease.After(now) {
|
|
return true, nil
|
|
} // live attempt; DB recovery remains durable
|
|
if attempt >= maxAttempts {
|
|
_, e = tx.Exec(ctx, `UPDATE attachments SET status='failed',error_code='retry_exhausted',updated_at=clock_timestamp() WHERE id=$1;`, j.AttachmentID)
|
|
if e == nil {
|
|
_, e = tx.Exec(ctx, "UPDATE pipeline_jobs SET finished_at=clock_timestamp(),lease_until=NULL WHERE job_id=$1", j.ID)
|
|
}
|
|
if e != nil {
|
|
return false, e
|
|
}
|
|
return true, tx.Commit(ctx)
|
|
}
|
|
token := uuid()
|
|
attempt++
|
|
if _, e = tx.Exec(ctx, `UPDATE pipeline_jobs SET attempt=$2,lease_token=$3,lease_until=clock_timestamp()+interval '45 seconds' WHERE job_id=$1`, j.ID, attempt, token); e != nil {
|
|
return false, e
|
|
}
|
|
if _, e = tx.Exec(ctx, `UPDATE attachments SET status='processing',error_code=NULL,updated_at=clock_timestamp() WHERE id=$1`, j.AttachmentID); e != nil {
|
|
return false, e
|
|
}
|
|
if _, e = tx.Exec(ctx, `INSERT INTO pipeline_audit(job_id,event,attempt) VALUES($1,'claimed',$2)`, j.ID, attempt); e != nil {
|
|
return false, e
|
|
}
|
|
if e = tx.Commit(ctx); e != nil {
|
|
return false, e
|
|
}
|
|
trace.SpanFromContext(ctx).SetAttributes(attribute.Int("job.attempt", attempt), attribute.Int("pipeline.version", j.Version))
|
|
attemptStart := time.Now()
|
|
outcome := "failure"
|
|
defer func() {
|
|
trace.SpanFromContext(ctx).SetAttributes(attribute.String("job.outcome", outcome))
|
|
telemetry.Job(ctx, outcome, time.Since(attemptStart).Seconds())
|
|
}()
|
|
p.Log.InfoContext(ctx, "job_started", "event", "job_started", "job_id", j.ID, "attempt", attempt, "pipeline_version", j.Version)
|
|
faultPoint("before_objects")
|
|
telemetry.Busy.Add(1)
|
|
variants, processErr := p.perform(ctx, j, key, sha, contentType, size)
|
|
telemetry.Busy.Add(-1)
|
|
telemetry.Failure(trace.SpanFromContext(ctx), processErr)
|
|
if processErr == nil {
|
|
faultPoint("after_objects")
|
|
}
|
|
// A short independent commit budget allows recording a timed-out attempt;
|
|
// a cancelled/killed process instead recovers via the persisted lease.
|
|
finish, stop := context.WithTimeout(context.WithoutCancel(ctx), 3*time.Second)
|
|
defer stop()
|
|
tx, e = p.DB.Begin(finish)
|
|
if e != nil {
|
|
return false, e
|
|
}
|
|
defer tx.Rollback(context.Background())
|
|
var currentToken *string
|
|
var currentVersion int
|
|
e = tx.QueryRow(finish, `SELECT j.lease_token::text,a.pipeline_version FROM pipeline_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE j.job_id=$1 FOR UPDATE OF j,a`, j.ID).Scan(¤tToken, ¤tVersion)
|
|
if e != nil {
|
|
return false, e
|
|
}
|
|
if currentToken == nil || *currentToken != token || currentVersion != j.Version {
|
|
return true, nil
|
|
}
|
|
if processErr == nil {
|
|
encoded, _ := json.Marshal(variants)
|
|
_, e = tx.Exec(finish, `UPDATE attachments SET status='ready',error_code=NULL,variants=$2,object_key=$3,updated_at=clock_timestamp() WHERE id=$1`, j.AttachmentID, encoded, resultPrefix(j)+"original")
|
|
if e == nil {
|
|
_, e = tx.Exec(finish, `UPDATE pipeline_jobs SET finished_at=clock_timestamp(),ready_at=clock_timestamp(),lease_until=NULL WHERE job_id=$1`, j.ID)
|
|
}
|
|
} else {
|
|
permanent := errors.Is(processErr, errInvalidImage)
|
|
if permanent || attempt >= maxAttempts {
|
|
code := "retry_exhausted"
|
|
if permanent {
|
|
code = "invalid_image"
|
|
}
|
|
_, e = tx.Exec(finish, `UPDATE attachments SET status='failed',error_code=$2,updated_at=clock_timestamp() WHERE id=$1`, j.AttachmentID, code)
|
|
if e == nil {
|
|
_, e = tx.Exec(finish, `UPDATE pipeline_jobs SET finished_at=clock_timestamp(),lease_until=NULL WHERE job_id=$1`, j.ID)
|
|
}
|
|
} else {
|
|
_, e = tx.Exec(finish, `UPDATE attachments SET status='queued',updated_at=clock_timestamp() WHERE id=$1`, j.AttachmentID)
|
|
delay := time.Duration(1<<attempt)*time.Second + time.Duration(rand.IntN(1000))*time.Millisecond
|
|
if e == nil {
|
|
_, e = tx.Exec(finish, `UPDATE pipeline_jobs SET lease_until=NULL,published_at=NULL,next_attempt_at=clock_timestamp()+$2::interval WHERE job_id=$1`, j.ID, fmt.Sprintf("%f seconds", delay.Seconds()))
|
|
}
|
|
}
|
|
}
|
|
if e != nil {
|
|
return false, e
|
|
}
|
|
event := "ready"
|
|
if processErr != nil {
|
|
event = "processing_error"
|
|
}
|
|
if _, e = tx.Exec(finish, `INSERT INTO pipeline_audit(job_id,event,attempt) VALUES($1,$2,$3)`, j.ID, event, attempt); e != nil {
|
|
return false, e
|
|
}
|
|
if e = tx.Commit(finish); e != nil {
|
|
return false, e
|
|
}
|
|
var since float64
|
|
if processErr == nil && p.DB.QueryRow(finish, "SELECT EXTRACT(EPOCH FROM ready_at-created_at)::float8 FROM pipeline_jobs WHERE job_id=$1", j.ID).Scan(&since) == nil {
|
|
telemetry.Ready(ctx, since)
|
|
}
|
|
p.Log.InfoContext(ctx, "job_completed", "event", "job_completed", "job_id", j.ID, "outcome", event, "attempt", attempt)
|
|
if processErr == nil {
|
|
outcome = "success"
|
|
faultPoint("after_commit")
|
|
// Committed ready points only at final objects. Cleanup failure is retried
|
|
// by the housekeeping pass; staging is never deleted before ready COMMIT.
|
|
if strings.HasPrefix(key, "staging/") {
|
|
_ = p.Objects.Client.RemoveObject(finish, p.Objects.Bucket, key, minio.RemoveObjectOptions{})
|
|
}
|
|
}
|
|
return true, nil
|
|
}
|
|
|
|
var ErrInvalidImage = errors.New("invalid_image")
|
|
var errInvalidImage = ErrInvalidImage
|
|
|
|
func resultPrefix(j Job) string {
|
|
return "originals/" + j.AttachmentID + "/v" + strconv.Itoa(j.Version) + "/"
|
|
}
|
|
func (p *Pipeline) perform(ctx context.Context, j Job, key, sha, contentType string, size int64) ([]Variant, error) {
|
|
dir, e := os.MkdirTemp("", "messenger-job-*")
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
defer os.RemoveAll(dir)
|
|
object, e := p.Objects.Client.GetObject(ctx, p.Objects.Bucket, key, minio.GetObjectOptions{})
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
defer object.Close()
|
|
f, e := os.Create(filepath.Join(dir, "input"))
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
h := sha256.New()
|
|
n, e := io.Copy(io.MultiWriter(f, h), io.LimitReader(object, maxUpload+1))
|
|
f.Close()
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
if n != size || hex.EncodeToString(h.Sum(nil)) != sha {
|
|
return nil, errInvalidImage
|
|
}
|
|
executable, e := os.Executable()
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
transformCtx, cancel := context.WithTimeout(ctx, 20*time.Second)
|
|
defer cancel()
|
|
cmd := exec.CommandContext(transformCtx, executable, "transform", filepath.Join(dir, "input"), dir, strconv.Itoa(j.Version))
|
|
// Descendant cwebp inherits the process group; negative-PGID kill prevents
|
|
// an orphan encoder outliving the transform deadline (Linux container only).
|
|
configureChild(cmd)
|
|
transformCtx, transformSpan := telemetry.Start(transformCtx, "image.transform", trace.SpanKindInternal)
|
|
_ = transformCtx
|
|
e = cmd.Run()
|
|
telemetry.Failure(transformSpan, e)
|
|
transformSpan.End()
|
|
if e != nil {
|
|
return nil, classifyTransformFailure(transformCtx.Err(), e)
|
|
}
|
|
raw, e := os.ReadFile(filepath.Join(dir, "variants.json"))
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
var variants []Variant
|
|
if e = json.Unmarshal(raw, &variants); e != nil {
|
|
return nil, e
|
|
}
|
|
input, e := os.Open(filepath.Join(dir, "input"))
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
defer input.Close()
|
|
faultPoint("before_write")
|
|
if _, e = p.Objects.Client.PutObject(ctx, p.Objects.Bucket, resultPrefix(j)+"original", input, size, minio.PutObjectOptions{ContentType: contentType, DisableMultipart: true}); e != nil {
|
|
return nil, e
|
|
}
|
|
for i, v := range variants {
|
|
b, e := os.ReadFile(filepath.Join(dir, v.Name))
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
digest := sha256.Sum256(b)
|
|
variants[i].SHA256 = hex.EncodeToString(digest[:])
|
|
variants[i].Size = int64(len(b))
|
|
_, e = p.Objects.Client.PutObject(ctx, p.Objects.Bucket, resultPrefix(j)+v.Name, bytes.NewReader(b), int64(len(b)), minio.PutObjectOptions{ContentType: v.ContentType, DisableMultipart: true})
|
|
if e != nil {
|
|
return nil, e
|
|
}
|
|
}
|
|
return variants, nil
|
|
}
|
|
|
|
// Opt-in local fault injection is absent from the normal Compose environment.
|
|
// A marker allows tests to observe the real boundary before killing the worker.
|
|
func faultPoint(point string) {
|
|
if os.Getenv("LAB_FAULT_POINT") == point {
|
|
_ = os.WriteFile("/tmp/fault-reached", []byte(point), 0600)
|
|
for {
|
|
if _, e := os.Stat("/tmp/fault-release"); e == nil {
|
|
return
|
|
}
|
|
time.Sleep(100 * time.Millisecond)
|
|
}
|
|
}
|
|
}
|
|
|
|
// A killed/crashed encoder is not evidence of an invalid source image.
|
|
func classifyTransformFailure(deadline, errorResult error) error {
|
|
if deadline != nil {
|
|
return deadline
|
|
}
|
|
var exited *exec.ExitError
|
|
if errors.As(errorResult, &exited) && exited.ExitCode() == 65 {
|
|
return ErrInvalidImage
|
|
}
|
|
return fmt.Errorf("transform temporarily unavailable")
|
|
}
|