package pipeline import ( "context" "errors" "regexp" "github.com/google/uuid" "github.com/jackc/pgx/v5" ) var errorCodePattern = regexp.MustCompile("^[a-z][a-z0-9_]{0,63}$") func (s *Store) Fail(ctx context.Context, c *Claim, code string, permanent bool, policy RetryPolicy) (bool, error) { if err := policy.validate(); err != nil { return false, err } if !errorCodePattern.MatchString(code) { return false, errors.New("invalid failure code") } var changed bool err := pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error { var budget int err := tx.QueryRow(ctx, `SELECT budget_attempt FROM attachment_jobs WHERE job_id=$1 AND attachment_id=$2 AND pipeline_version=$3 AND attempt=$4 AND state='processing' AND lease_token=$5 AND lease_until>clock_timestamp() FOR UPDATE`, c.JobID, c.AttachmentID, c.PipelineVersion, c.Attempt, c.Token).Scan(&budget) if errors.Is(err, pgx.ErrNoRows) { return nil } if err != nil { return err } changed, err = finishAttempt(ctx, tx, c.JobID, budget, code, permanent, false, policy) return err }) return changed && err == nil, err } func (s *Store) RecoverOne(ctx context.Context, policy RetryPolicy) (bool, error) { if err := policy.validate(); err != nil { return false, err } var changed bool err := pgx.BeginFunc(ctx, s.pool, func(tx pgx.Tx) error { var id uuid.UUID var budget int err := tx.QueryRow(ctx, `SELECT job_id,budget_attempt FROM attachment_jobs WHERE state='processing' AND lease_until<=clock_timestamp() ORDER BY lease_until,job_id LIMIT 1 FOR UPDATE SKIP LOCKED`).Scan(&id, &budget) if errors.Is(err, pgx.ErrNoRows) { return nil } if err != nil { return err } changed, err = finishAttempt(ctx, tx, id, budget, "lease_expired", false, true, policy) return err }) return changed && err == nil, err } // The caller holds the job row. Only the recovery path may advance an expired // attempt. A worker whose lease elapsed during its SQL call has lost ownership. func finishAttempt(ctx context.Context, tx pgx.Tx, id uuid.UUID, budget int, code string, permanent, expired bool, p RetryPolicy) (bool, error) { retry := !permanent && budget < p.MaxAttempts tag, err := tx.Exec(ctx, `UPDATE attachment_jobs SET state=CASE WHEN $3 THEN 'queued' ELSE 'failed' END, attempt=attempt+$3::boolean::int, budget_attempt=budget_attempt+$3::boolean::int, available_at=clock_timestamp()+$4::bigint*interval '1 microsecond', published_at=NULL, lease_token=NULL, lease_until=NULL, error_code=$2, updated_at=clock_timestamp() WHERE job_id=$1 AND (lease_until<=clock_timestamp())=$5`, id, code, retry, p.delay(budget).Microseconds(), expired) return tag.RowsAffected() == 1, err }