package pipeline import ( "context" "encoding/json" "github.com/jackc/pgx/v5/pgxpool" "github.com/redis/go-redis/v9" "os" "time" ) const Pending = "attachments:pending" const Active = "attachments:active" type Job 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"` } func Client() *redis.Client { addr := os.Getenv("BROKER_ADDR") if addr == "" { addr = "broker:6379" } return redis.NewClient(&redis.Options{Addr: addr}) } func Publish(ctx context.Context, id string, attempt int, created time.Time) error { c := Client() defer c.Close() b, err := json.Marshal(Job{1, id, "attachment.process.v1", id, 1, attempt, created.UTC()}) if err != nil { return err } return c.LPush(ctx, Pending, string(b)).Err() } // Dispatch republishes unfinished intentions. Duplicate messages are expected. func Dispatch(ctx context.Context, p *pgxpool.Pool) { for ctx.Err() == nil { func() { tx, err := p.Begin(ctx) if err != nil { return } defer tx.Rollback(ctx) rows, err := tx.Query(ctx, `SELECT o.attachment_id::text,a.attempts+1,a.created_at FROM attachment_outbox o JOIN attachments a ON a.id=o.attachment_id WHERE o.next_publish_at<=now() AND ((a.status='queued' AND a.next_attempt_at<=now()) OR (a.status='processing' AND a.lease_until