Files
mtusi2026lab7/internal/pipeline/pipeline.go
T
2026-11-24 12:20:21 +03:00

550 lines
19 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"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
"mtusi-messenger/internal/objectstore"
"mtusi-messenger/internal/telemetry"
)
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"`
Traceparent string `json:"traceparent,omitempty"`
Tracestate string `json:"tracestate,omitempty"`
}
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,j.traceparent,j.tracestate
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, &j.Traceparent, &j.Tracestate); 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")
parent := telemetry.Extract(ctx, j.Traceparent, j.Tracestate)
pubctx, pubspan := telemetry.Span(parent, "attachment.publish", trace.SpanKindProducer, attribute.String("messaging.system", "redis"), attribute.String("messaging.destination.name", Stream), attribute.Int("job.attempt", j.Attempt))
j.Traceparent, j.Tracestate = telemetry.Inject(pubctx)
b, _ := json.Marshal(j)
err = p.Broker.XAdd(pubctx, &redis.XAddArgs{Stream: Stream, Values: map[string]any{"job": string(b)}}).Err()
telemetry.Event(pubctx, "job.published", map[string]any{"job_id": j.ID, "attempt": j.Attempt, "success": err == nil})
telemetry.Result(pubspan, err)
if 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
}
ctx = telemetry.Extract(ctx, j.Traceparent, j.Tracestate)
ctx, consumer := telemetry.Span(ctx, "attachment.consume", trace.SpanKindConsumer, attribute.String("messaging.system", "redis"), attribute.String("messaging.destination.name", Stream), attribute.String("job.id", j.ID))
began := time.Now()
attempted := false
outcome := "abandoned"
defer func() {
consumer.SetAttributes(attribute.String("job.outcome", outcome))
if outcome == "retry" || outcome == "failed" || outcome == "abandoned" {
consumer.SetStatus(codes.Error, outcome)
}
if attempted {
telemetry.Busy.Add(-1)
telemetry.Job(ctx, outcome, time.Since(began))
}
telemetry.Event(ctx, "job.completed", map[string]any{"job_id": j.ID, "outcome": outcome, "duration_ms": time.Since(began).Milliseconds()})
consumer.End()
}()
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, requestID string
var accepted time.Time
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())
,created_at,request_id FROM attachment_jobs WHERE id=$1 FOR UPDATE`, j.ID).Scan(&state, &staging, &attachment, &attempt, &maxAttempts, &due, &accepted, &requestID)
if errors.Is(err, pgx.ErrNoRows) {
p.ack(ctx, m.ID)
return
}
if err != nil {
return
}
if attachment != j.AttachmentID {
return
}
ctx = telemetry.WithRequestID(ctx, requestID)
jobctx = telemetry.WithRequestID(jobctx, requestID)
if state == "ready" || state == "failed" {
outcome = "duplicate"
_ = tx.Rollback(jobctx)
p.ack(ctx, m.ID)
return
}
if !due {
outcome = "deferred"
_ = 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()
consumer.SetAttributes(attribute.Int("job.attempt", attempt+1))
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
}
attempted = true
telemetry.Busy.Add(1)
telemetry.Event(jobctx, "job.started", map[string]any{"job_id": j.ID, "attempt": attempt})
p.Checkpoint(jobctx, "worker_after_claim")
variants, code := p.process(jobctx, attachment, staging)
p.Checkpoint(jobctx, "worker_after_objects")
// A fresh transaction completes after job timeout/cancel; token fences stale attempts.
finishctx, finishcancel := context.WithTimeout(context.WithoutCancel(ctx), 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(&current); err != nil || current != token {
return
}
if code == "" {
outcome = "success"
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 {
outcome = "failed"
if code != "invalid_image" {
code = "retry_exhausted"
}
err = p.failTx(finishctx, finish, j.ID, attachment, code)
} else {
outcome = "retry"
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 {
outcome = "abandoned"
return
}
if outcome == "success" {
telemetry.Ready(ctx, time.Since(accepted))
}
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)
_, imagespan := telemetry.Span(ctx, "image.process", trace.SpanKindInternal)
output, err := cmd.Output()
telemetry.Result(imagespan, err)
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)))
}