forked from mtusi2026/mtusi2026lab5
500 lines
17 KiB
Go
500 lines
17 KiB
Go
// Package pipeline implements durable intent, at-least-once delivery and fenced effects.
|
|
package pipeline
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"io"
|
|
"log"
|
|
"math/rand/v2"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"strconv"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
"github.com/redis/go-redis/v9"
|
|
"mtusi-messenger/internal/objectstore"
|
|
)
|
|
|
|
const Stream = "attachment.jobs.v1"
|
|
const Group = "image-workers"
|
|
|
|
type Pipeline struct {
|
|
DB *pgxpool.Pool
|
|
Broker *redis.Client
|
|
Objects *objectstore.Store
|
|
Timeout time.Duration
|
|
Retention time.Duration
|
|
Logger *log.Logger
|
|
}
|
|
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"`
|
|
Created string `json:"created_at"`
|
|
}
|
|
type Variant struct {
|
|
Name string `json:"name"`
|
|
ContentType string `json:"content_type"`
|
|
Size int64 `json:"size_bytes"`
|
|
Width int `json:"width"`
|
|
Height int `json:"height"`
|
|
SHA string `json:"sha256"`
|
|
}
|
|
|
|
func (p *Pipeline) Checkpoint(ctx context.Context, point string) {
|
|
var armed bool
|
|
err := p.DB.QueryRow(ctx, `UPDATE pipeline_faults SET armed=false,hit_at=clock_timestamp() WHERE point=$1 AND armed RETURNING true`, point).Scan(&armed)
|
|
if err == nil && armed {
|
|
p.Logger.Printf("injected crash: %s", point)
|
|
os.Exit(86)
|
|
}
|
|
}
|
|
func pause(ctx context.Context, d time.Duration) {
|
|
select {
|
|
case <-ctx.Done():
|
|
case <-time.After(d):
|
|
}
|
|
}
|
|
|
|
// Dispatch re-publishes unfinished intents if a broker confirmation/connection is lost.
|
|
// Publication is deliberately outside the PostgreSQL transaction; duplicates are safe.
|
|
func (p *Pipeline) Dispatch(ctx context.Context) {
|
|
for ctx.Err() == nil {
|
|
if err := p.dispatchOnce(ctx); err != nil {
|
|
p.Logger.Print("dispatcher unavailable; intent retained")
|
|
}
|
|
sweepctx, cancelSweep := context.WithTimeout(ctx, 5*time.Second)
|
|
if err := p.Sweep(sweepctx); err != nil {
|
|
p.Logger.Print("staging sweep deferred")
|
|
}
|
|
cancelSweep()
|
|
pause(ctx, time.Second)
|
|
}
|
|
}
|
|
func (p *Pipeline) dispatchOnce(ctx context.Context) error {
|
|
rows, err := p.DB.Query(ctx, `SELECT j.id::text,j.attachment_id::text,j.pipeline_version,j.attempts+1,j.created_at
|
|
FROM attachment_jobs j JOIN attachment_outbox o ON o.job_id=j.id
|
|
WHERE ((j.state='queued' AND j.next_at<=clock_timestamp()) OR (j.state='processing' AND j.lease_until<clock_timestamp()))
|
|
AND (o.published_at IS NULL OR o.published_at<clock_timestamp()-interval '5 seconds') ORDER BY j.created_at LIMIT 50`)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
jobs := []Job{}
|
|
for rows.Next() {
|
|
j := Job{SchemaVersion: 1, Type: "attachment.process.v1"}
|
|
var created time.Time
|
|
if err = rows.Scan(&j.ID, &j.AttachmentID, &j.Version, &j.Attempt, &created); err != nil {
|
|
rows.Close()
|
|
return err
|
|
}
|
|
j.Created = created.UTC().Format(time.RFC3339Nano)
|
|
jobs = append(jobs, j)
|
|
}
|
|
err = rows.Err()
|
|
rows.Close()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, j := range jobs {
|
|
p.Checkpoint(ctx, "dispatcher_before_publish")
|
|
b, _ := json.Marshal(j)
|
|
if err = p.Broker.XAdd(ctx, &redis.XAddArgs{Stream: Stream, Values: map[string]any{"job": string(b)}}).Err(); err != nil {
|
|
return err
|
|
}
|
|
p.Checkpoint(ctx, "dispatcher_after_publish")
|
|
if _, err = p.DB.Exec(ctx, `UPDATE attachment_outbox SET published_at=clock_timestamp(),publications=publications+1 WHERE job_id=$1`, j.ID); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
func (p *Pipeline) ack(ctx context.Context, id string) {
|
|
// Stream belongs to one group. Delete only after acknowledged; PG remains recovery authority.
|
|
if p.Broker.XAck(ctx, Stream, Group, id).Err() == nil {
|
|
_ = p.Broker.XDel(ctx, Stream, id).Err()
|
|
}
|
|
}
|
|
func (p *Pipeline) Worker(ctx context.Context, concurrency int) error {
|
|
if concurrency < 1 || concurrency > 4 {
|
|
return fmt.Errorf("WORKER_CONCURRENCY must be 1..4")
|
|
}
|
|
// One message at a time per consumer: prefetch=1.
|
|
done := make(chan struct{}, concurrency)
|
|
for i := 0; i < concurrency; i++ {
|
|
go func() { defer func() { done <- struct{}{} }(); p.consume(ctx, uuid.NewString()) }()
|
|
}
|
|
for i := 0; i < concurrency; i++ {
|
|
<-done
|
|
}
|
|
return nil
|
|
}
|
|
func (p *Pipeline) consume(ctx context.Context, consumer string) {
|
|
reclaimIdle := p.Timeout + 10*time.Second
|
|
for ctx.Err() == nil {
|
|
_ = p.Broker.XGroupCreateMkStream(ctx, Stream, Group, "0").Err()
|
|
pending, _, err := p.Broker.XAutoClaim(ctx, &redis.XAutoClaimArgs{Stream: Stream, Group: Group, Consumer: consumer, MinIdle: reclaimIdle, Start: "0-0", Count: 1}).Result()
|
|
if err == nil && len(pending) > 0 {
|
|
p.handle(ctx, pending[0])
|
|
continue
|
|
}
|
|
messages, err := p.Broker.XReadGroup(ctx, &redis.XReadGroupArgs{Group: Group, Consumer: consumer, Streams: []string{Stream, ">"}, Count: 1, Block: time.Second}).Result()
|
|
if err != nil {
|
|
pause(ctx, 200*time.Millisecond)
|
|
continue
|
|
}
|
|
for _, stream := range messages {
|
|
for _, m := range stream.Messages {
|
|
p.handle(ctx, m)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
func (p *Pipeline) handle(ctx context.Context, m redis.XMessage) {
|
|
raw, ok := m.Values["job"].(string)
|
|
var j Job
|
|
if !ok || json.Unmarshal([]byte(raw), &j) != nil || j.SchemaVersion != 1 || j.Version != 1 || j.Type != "attachment.process.v1" || uuid.Validate(j.ID) != nil || uuid.Validate(j.AttachmentID) != nil {
|
|
// Malformed envelopes go to a diagnostic dead-letter stream, never interpreted as storage paths.
|
|
if p.Broker.XAdd(ctx, &redis.XAddArgs{Stream: "attachment.invalid.dlq", Values: map[string]any{"stream_id": m.ID, "error_code": "invalid_envelope"}}).Err() == nil {
|
|
p.ack(ctx, m.ID)
|
|
}
|
|
return
|
|
}
|
|
jobctx, cancel := context.WithTimeout(ctx, p.Timeout)
|
|
defer cancel()
|
|
conn, err := p.DB.Acquire(jobctx)
|
|
if err != nil {
|
|
return
|
|
}
|
|
defer conn.Release()
|
|
var locked bool
|
|
if err = conn.QueryRow(jobctx, `SELECT pg_try_advisory_lock(hashtextextended($1,5))`, j.ID).Scan(&locked); err != nil || !locked {
|
|
return
|
|
}
|
|
defer func() {
|
|
unlockctx, done := context.WithTimeout(context.Background(), 3*time.Second)
|
|
defer done()
|
|
_, e := conn.Exec(unlockctx, `SELECT pg_advisory_unlock(hashtextextended($1,5))`, j.ID)
|
|
if e != nil {
|
|
_ = conn.Conn().Close(unlockctx)
|
|
}
|
|
}()
|
|
tx, err := conn.Begin(jobctx)
|
|
if err != nil {
|
|
return
|
|
}
|
|
defer tx.Rollback(context.Background())
|
|
var state, staging, attachment string
|
|
var attempt, maxAttempts int
|
|
var due bool
|
|
err = tx.QueryRow(jobctx, `SELECT state,staging_key,attachment_id::text,attempts,max_attempts,
|
|
(state='queued' AND next_at<=clock_timestamp()) OR (state='processing' AND lease_until<clock_timestamp())
|
|
FROM attachment_jobs WHERE id=$1 FOR UPDATE`, j.ID).Scan(&state, &staging, &attachment, &attempt, &maxAttempts, &due)
|
|
if errors.Is(err, pgx.ErrNoRows) {
|
|
p.ack(ctx, m.ID)
|
|
return
|
|
}
|
|
if err != nil {
|
|
return
|
|
}
|
|
if attachment != j.AttachmentID {
|
|
return
|
|
}
|
|
if state == "ready" || state == "failed" {
|
|
_ = tx.Rollback(jobctx)
|
|
p.ack(ctx, m.ID)
|
|
return
|
|
}
|
|
if !due {
|
|
_ = tx.Rollback(jobctx)
|
|
p.ack(ctx, m.ID)
|
|
return
|
|
}
|
|
if attempt >= maxAttempts {
|
|
if p.failTx(jobctx, tx, j.ID, attachment, "retry_exhausted") == nil && tx.Commit(jobctx) == nil {
|
|
p.ack(ctx, m.ID)
|
|
}
|
|
return
|
|
}
|
|
token := uuid.NewString()
|
|
attempt++
|
|
_, err = tx.Exec(jobctx, `UPDATE attachment_jobs SET state='processing',attempts=$2,lease_token=$3,lease_until=clock_timestamp()+($4*interval '1 second'),updated_at=clock_timestamp() WHERE id=$1`, j.ID, attempt, token, int(p.Timeout/time.Second)+5)
|
|
if err != nil {
|
|
return
|
|
}
|
|
if _, err = tx.Exec(jobctx, `UPDATE attachments SET status='processing',updated_at=clock_timestamp() WHERE id=$1`, attachment); err != nil {
|
|
return
|
|
}
|
|
if tx.Commit(jobctx) != nil {
|
|
return
|
|
}
|
|
p.Checkpoint(jobctx, "worker_after_claim")
|
|
variants, code := p.process(jobctx, attachment, staging)
|
|
p.Checkpoint(jobctx, "worker_after_objects")
|
|
// A separate connection completes after job timeout/cancel; token fences stale attempts.
|
|
finishctx, finishcancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
defer finishcancel()
|
|
finish, err := conn.Begin(finishctx)
|
|
if err != nil {
|
|
return
|
|
}
|
|
defer finish.Rollback(context.Background())
|
|
var current string
|
|
if err = finish.QueryRow(finishctx, `SELECT lease_token::text FROM attachment_jobs WHERE id=$1 AND state='processing' FOR UPDATE`, j.ID).Scan(¤t); err != nil || current != token {
|
|
return
|
|
}
|
|
if code == "" {
|
|
encoded, _ := json.Marshal(variants)
|
|
_, err = finish.Exec(finishctx, `UPDATE attachments SET status='ready',object_key=$2,variants=$3,error_code=NULL,updated_at=clock_timestamp() WHERE id=$1`, attachment, "originals/"+attachment, encoded)
|
|
if err == nil {
|
|
_, err = finish.Exec(finishctx, `UPDATE attachment_jobs SET state='ready',lease_until=NULL,lease_token=NULL,error_code=NULL,updated_at=clock_timestamp() WHERE id=$1`, j.ID)
|
|
}
|
|
} else if code == "invalid_image" || attempt >= maxAttempts {
|
|
if code != "invalid_image" {
|
|
code = "retry_exhausted"
|
|
}
|
|
err = p.failTx(finishctx, finish, j.ID, attachment, code)
|
|
} else {
|
|
delay := RetryDelay(attempt)
|
|
_, err = finish.Exec(finishctx, `UPDATE attachment_jobs SET state='queued',error_code=$2,next_at=clock_timestamp()+($3*interval '1 millisecond'),lease_until=NULL,lease_token=NULL,updated_at=clock_timestamp() WHERE id=$1`, j.ID, code, delay.Milliseconds())
|
|
if err == nil {
|
|
_, err = finish.Exec(finishctx, `UPDATE attachments SET status='queued',updated_at=clock_timestamp() WHERE id=$1`, attachment)
|
|
}
|
|
}
|
|
if err != nil || finish.Commit(finishctx) != nil {
|
|
return
|
|
}
|
|
p.Checkpoint(finishctx, "worker_before_ack")
|
|
p.ack(finishctx, m.ID)
|
|
}
|
|
func RetryDelay(attempt int) time.Duration {
|
|
if attempt > 6 {
|
|
attempt = 6
|
|
}
|
|
base := time.Second * time.Duration(1<<uint(attempt-1))
|
|
return base + time.Duration(rand.Int64N(int64(base/2)+1))
|
|
}
|
|
func (p *Pipeline) failTx(ctx context.Context, tx pgx.Tx, id, attachment, code string) error {
|
|
_, err := tx.Exec(ctx, `UPDATE attachment_jobs SET state='failed',error_code=$2,lease_until=NULL,lease_token=NULL,updated_at=clock_timestamp() WHERE id=$1`, id, code)
|
|
if err == nil {
|
|
_, err = tx.Exec(ctx, `UPDATE attachments SET status='failed',error_code=$2,updated_at=clock_timestamp() WHERE id=$1`, attachment, code)
|
|
}
|
|
return err
|
|
}
|
|
func (p *Pipeline) process(ctx context.Context, id, key string) ([]Variant, string) {
|
|
dir, err := os.MkdirTemp("", "job-*")
|
|
if err != nil {
|
|
return nil, "storage_unavailable"
|
|
}
|
|
defer os.RemoveAll(dir)
|
|
object, err := p.Objects.Get(ctx, key)
|
|
if err != nil {
|
|
return nil, "storage_unavailable"
|
|
}
|
|
file, err := os.Create(filepath.Join(dir, "source"))
|
|
if err != nil {
|
|
object.Close()
|
|
return nil, "storage_unavailable"
|
|
}
|
|
hash := sha256.New()
|
|
n, copyErr := io.Copy(io.MultiWriter(file, hash), io.LimitReader(object, 10485761))
|
|
object.Close()
|
|
file.Close()
|
|
if copyErr != nil {
|
|
return nil, "storage_unavailable"
|
|
}
|
|
if n > 10485760 {
|
|
return nil, "invalid_image"
|
|
}
|
|
var expected string
|
|
if p.DB.QueryRow(ctx, `SELECT sha256 FROM attachments WHERE id=$1`, id).Scan(&expected) != nil {
|
|
return nil, "storage_unavailable"
|
|
}
|
|
if hex.EncodeToString(hash.Sum(nil)) != expected {
|
|
return nil, "invalid_image"
|
|
}
|
|
cmd := exec.CommandContext(ctx, "python3", "/opt/process_image.py", filepath.Join(dir, "source"), dir)
|
|
output, err := cmd.Output()
|
|
if err != nil {
|
|
if ctx.Err() != nil {
|
|
return nil, "processing_timeout"
|
|
}
|
|
var exit *exec.ExitError
|
|
if errors.As(err, &exit) && exit.ExitCode() == 2 {
|
|
return nil, "invalid_image"
|
|
}
|
|
return nil, "processing_failed"
|
|
}
|
|
variants := []Variant{}
|
|
if json.Unmarshal(output, &variants) != nil || len(variants) != 3 {
|
|
return nil, "processing_failed"
|
|
}
|
|
var kind string
|
|
if p.DB.QueryRow(ctx, `SELECT content_type FROM attachments WHERE id=$1`, id).Scan(&kind) != nil {
|
|
return nil, "storage_unavailable"
|
|
}
|
|
source, err := os.Open(filepath.Join(dir, "source"))
|
|
if err != nil {
|
|
return nil, "storage_unavailable"
|
|
}
|
|
err = p.Objects.Put(ctx, "originals/"+id, source, n, kind)
|
|
source.Close()
|
|
if err != nil {
|
|
return nil, "storage_unavailable"
|
|
}
|
|
for _, v := range variants {
|
|
f, err := os.Open(filepath.Join(dir, v.Name))
|
|
if err != nil {
|
|
return nil, "processing_failed"
|
|
}
|
|
err = p.Objects.Put(ctx, "variants/"+id+"/v1/"+v.Name, f, v.Size, v.ContentType)
|
|
f.Close()
|
|
if err != nil {
|
|
return nil, "storage_unavailable"
|
|
}
|
|
}
|
|
return variants, ""
|
|
}
|
|
|
|
// Failed registry is PostgreSQL; explicit replay is audited and refuses successful jobs.
|
|
func (p *Pipeline) Replay(ctx context.Context, id string) error {
|
|
if uuid.Validate(id) != nil {
|
|
return fmt.Errorf("invalid job id")
|
|
}
|
|
conn, err := p.DB.Acquire(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer conn.Release()
|
|
tx, err := conn.Begin(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer tx.Rollback(ctx)
|
|
var attachment, state, code string
|
|
var retained bool
|
|
err = tx.QueryRow(ctx, `SELECT attachment_id::text,state,COALESCE(error_code,''),staging_deleted_at IS NULL FROM attachment_jobs WHERE id=$1 FOR UPDATE`, id).Scan(&attachment, &state, &code, &retained)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if state != "failed" || !retained {
|
|
return fmt.Errorf("only failed jobs with retained staging can be replayed")
|
|
}
|
|
var key string
|
|
if err = tx.QueryRow(ctx, `SELECT staging_key FROM attachment_jobs WHERE id=$1`, id).Scan(&key); err != nil {
|
|
return err
|
|
}
|
|
object, err := p.Objects.Get(ctx, key)
|
|
if err != nil {
|
|
return fmt.Errorf("staging unavailable")
|
|
}
|
|
object.Close()
|
|
if _, err = tx.Exec(ctx, `INSERT INTO attachment_replays(job_id,previous_error) VALUES($1,$2)`, id, code); err != nil {
|
|
return err
|
|
}
|
|
if _, err = tx.Exec(ctx, `UPDATE attachment_jobs SET state='queued',attempts=0,error_code=NULL,next_at=clock_timestamp(),lease_until=NULL,lease_token=NULL,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`, attachment); err != nil {
|
|
return err
|
|
}
|
|
if _, err = tx.Exec(ctx, `UPDATE attachment_outbox SET published_at=NULL WHERE job_id=$1`, id); err != nil {
|
|
return err
|
|
}
|
|
return tx.Commit(ctx)
|
|
}
|
|
|
|
func (p *Pipeline) Sweep(ctx context.Context) error {
|
|
rows, err := p.DB.Query(ctx, `SELECT id::text,staging_key FROM attachment_jobs WHERE staging_deleted_at IS NULL AND (state='ready' OR (state='failed' AND updated_at<clock_timestamp()-($1*interval '1 second'))) LIMIT 20`, int64(p.Retention/time.Second))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
type item struct{ id, key string }
|
|
items := []item{}
|
|
for rows.Next() {
|
|
var i item
|
|
if err = rows.Scan(&i.id, &i.key); err != nil {
|
|
rows.Close()
|
|
return err
|
|
}
|
|
items = append(items, i)
|
|
}
|
|
err = rows.Err()
|
|
rows.Close()
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for _, i := range items {
|
|
tx, err := p.DB.Begin(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
// Replay and retention serialize on this row. Never delete a newly queued job.
|
|
var allowed bool
|
|
err = tx.QueryRow(ctx, `SELECT state='ready' OR (state='failed' AND updated_at<clock_timestamp()-($2*interval '1 second')) FROM attachment_jobs WHERE id=$1 FOR UPDATE`, i.id, int64(p.Retention/time.Second)).Scan(&allowed)
|
|
if err != nil || !allowed {
|
|
_ = tx.Rollback(ctx)
|
|
continue
|
|
}
|
|
err = p.Objects.Delete(ctx, i.key)
|
|
if err == nil {
|
|
_, err = tx.Exec(ctx, `UPDATE attachment_jobs SET staging_deleted_at=clock_timestamp() WHERE id=$1`, i.id)
|
|
}
|
|
if err != nil {
|
|
_ = tx.Rollback(ctx)
|
|
return err
|
|
}
|
|
if err = tx.Commit(ctx); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Operator commands are available only through docker exec, not through HTTP.
|
|
func (p *Pipeline) Command(ctx context.Context, args []string) error {
|
|
if len(args) == 2 && args[0] == "replay" {
|
|
return p.Replay(ctx, args[1])
|
|
}
|
|
if len(args) == 1 && args[0] == "failed-jobs" {
|
|
rows, err := p.DB.Query(ctx, `SELECT id::text,error_code,attempts FROM attachment_jobs WHERE state='failed' ORDER BY created_at`)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer rows.Close()
|
|
for rows.Next() {
|
|
var id, code string
|
|
var attempts int
|
|
if err = rows.Scan(&id, &code, &attempts); err != nil {
|
|
return err
|
|
}
|
|
_ = json.NewEncoder(os.Stdout).Encode(map[string]any{"job_id": id, "error_code": code, "attempts": attempts})
|
|
}
|
|
return rows.Err()
|
|
}
|
|
if len(args) == 3 && args[0] == "fault" && (args[1] == "arm" || args[1] == "clear") {
|
|
allowed := map[string]bool{"dispatcher_before_publish": true, "dispatcher_after_publish": true, "worker_after_claim": true, "worker_after_objects": true, "worker_before_ack": true}
|
|
if !allowed[args[2]] {
|
|
return fmt.Errorf("unknown fault point")
|
|
}
|
|
if args[1] == "clear" {
|
|
_, err := p.DB.Exec(ctx, `DELETE FROM pipeline_faults WHERE point=$1`, args[2])
|
|
return err
|
|
}
|
|
_, err := p.DB.Exec(ctx, `INSERT INTO pipeline_faults(point) VALUES($1) ON CONFLICT(point) DO UPDATE SET armed=true,hit_at=NULL`, args[2])
|
|
return err
|
|
}
|
|
return fmt.Errorf("unknown pipeline command: %s", strconv.Itoa(len(args)))
|
|
}
|