package pipeline import ( "context" "errors" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgxpool" "messenger/internal/attachment" ) type Store struct{ pool *pgxpool.Pool } func NewStore(pool *pgxpool.Pool) *Store { return &Store{pool: pool} } // The callback waits for a routed publisher confirm with a finite timeout. // Losing that confirm or the SQL commit leaves the same envelope deliverable. // NO KEY UPDATE excludes other publishers but allows messages to link a queued attachment. func (s *Store) PublishOne(ctx context.Context, publish func(context.Context, Job) error) (bool, error) { var found bool err := pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error { j := Job{SchemaVersion: 1, Type: "attachment.process.v1"} err := tx.QueryRow(ctx, `SELECT job_id,attachment_id,pipeline_version,attempt,created_at FROM attachment_jobs WHERE state='queued' AND published_at IS NULL AND available_at<=clock_timestamp() ORDER BY available_at,job_id LIMIT 1 FOR NO KEY UPDATE SKIP LOCKED`). Scan(&j.JobID, &j.AttachmentID, &j.PipelineVersion, &j.Attempt, &j.CreatedAt) if errors.Is(err, pgx.ErrNoRows) { return nil } if err != nil { return err } found = true if err := publish(ctx, j); err != nil { return err } _, err = tx.Exec(ctx, `UPDATE attachment_jobs SET published_at=clock_timestamp() WHERE job_id=$1 AND attempt=$2 AND state='queued'`, j.JobID, j.Attempt) return err }) return found, err } // Claim checks the envelope against SQL and sources all object metadata from SQL. // A processing duplicate can be acknowledged: lease recovery is independent // of broker redelivery and persists a fresh outbox intent after worker death. func (s *Store) Claim(ctx context.Context, j Job, lease time.Duration) (*Claim, error) { if !j.Valid() || lease < time.Microsecond { return nil, errors.New("invalid pipeline job or lease") } c := Claim{Job: j, Token: uuid.New()} err := s.pool.QueryRow(ctx, `UPDATE attachment_jobs j SET state='processing', lease_token=$6, lease_until=clock_timestamp()+$7::bigint*interval '1 microsecond', updated_at=clock_timestamp() FROM attachments a JOIN files f ON f.hash=a.file_hash WHERE j.job_id=$1 AND j.attachment_id=$2 AND j.pipeline_version=$3 AND j.attempt=$4 AND j.created_at=$5 AND a.id=j.attachment_id AND a.target_version=j.pipeline_version AND j.state='queued' AND j.available_at<=clock_timestamp() RETURNING j.source_key,f.hash,f.size_bytes,f.mime_type`, j.JobID, j.AttachmentID, j.PipelineVersion, j.Attempt, j.CreatedAt, c.Token, lease.Microseconds()). Scan(&c.SourceKey, &c.Hash, &c.SizeBytes, &c.MIMEType) if err == nil { return &c, nil } if !errors.Is(err, pgx.ErrNoRows) { return nil, err } var incomplete bool err = s.pool.QueryRow(ctx, `SELECT EXISTS ( SELECT 1 FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id WHERE j.job_id=$1 AND j.state='ready' AND (coalesce(a.published_version,0)( SELECT count(*) FROM attachment_variants v WHERE v.attachment_id=a.id AND v.pipeline_version=j.pipeline_version)) )`, j.JobID).Scan(&incomplete) if err != nil { return nil, err } if incomplete { return nil, errors.New("ready job has incomplete durable result") } return nil, nil } var errLostClaim = errors.New("claim expired or superseded") func (s *Store) Complete(ctx context.Context, c *Claim, variants []Variant) (bool, error) { if err := validateVariants(c, variants); err != nil { return false, err } err := pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error { if err := attachment.LockHash(ctx, tx, c.Hash); err != nil { return err } // Lock the attachment before the job, in the same order as operator commands. tag, err := tx.Exec(ctx, `SELECT 1 FROM attachments WHERE id=$1 AND target_version=$2 FOR UPDATE`, c.AttachmentID, c.PipelineVersion) if err != nil { return err } if tag.RowsAffected() != 1 { return errLostClaim } tag, err = tx.Exec(ctx, `SELECT 1 FROM attachment_jobs WHERE job_id=$1 AND attachment_id=$2 AND pipeline_version=$3 AND state='processing' AND lease_token=$4 AND lease_until>clock_timestamp() FOR UPDATE`, c.JobID, c.AttachmentID, c.PipelineVersion, c.Token) if err != nil { return err } if tag.RowsAffected() != 1 { return errLostClaim } for _, v := range variants { _, err := tx.Exec(ctx, `INSERT INTO attachment_variants (attachment_id,pipeline_version,variant,object_key,mime_type,width,height,size_bytes,sha256) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)`, c.AttachmentID, c.PipelineVersion, v.Name, v.Key, v.MIMEType, v.Width, v.Height, v.SizeBytes, v.SHA256) if err != nil { return err } } if _, err = tx.Exec(ctx, `UPDATE files SET status='ready' WHERE hash=(SELECT file_hash FROM attachments WHERE id=$1)`, c.AttachmentID); err != nil { return err } if _, err = tx.Exec(ctx, `UPDATE attachments SET published_version=$2 WHERE id=$1`, c.AttachmentID, c.PipelineVersion); err != nil { return err } // Recheck DB time after every operation that could have waited on a lock. tag, err = tx.Exec(ctx, `UPDATE attachment_jobs SET state='ready',lease_until=NULL,lease_token=NULL, error_code=NULL,updated_at=clock_timestamp() WHERE job_id=$1 AND lease_until>clock_timestamp()`, c.JobID) if err != nil { return err } if tag.RowsAffected() != 1 { return errLostClaim } return nil }) if errors.Is(err, errLostClaim) { return false, nil } return err == nil, err }