package store import ( "context" "encoding/json" "errors" "time" "gitflic.ru/project/bulla-max/mtusi2026lab/internal/common" "gitflic.ru/project/bulla-max/mtusi2026lab/internal/model" "github.com/google/uuid" "github.com/jackc/pgx/v5" ) // Job state machine. Every transition is a compare-and-set on // (job_id, attempt, status), so broker duplicates and stale workers are // harmless. // // queued --ClaimJob--> processing --CompleteJob--> ready // | // +--ScheduleRetry--> queued (future available_at) // +--FailJob--------> failed // +--attempt >= max-> failed/retry_exhausted // processing with an expired lease --RecoverExpiredLeases--> queued/failed // failed --ReplayFailed--> queued (attempt=0, replay_count+1) // // ClaimResult tells the consumer whether this delivery owns the work. type ClaimResult struct { Job model.JobRecord Attachment model.Attachment // Terminal means the logical work is already ready/failed. Ack it. Terminal bool // Busy means another attempt owns an active lease, or a retry is not due. // The publisher/lease sweeper will make the job visible again. Busy bool } // ClaimJob acquires or renews the logical job lease in one transaction. // A broker redelivery of the same job_id therefore cannot become two workers // writing results at the same time. func (s *Store) ClaimJob(ctx context.Context, jobID uuid.UUID, lease time.Duration) (ClaimResult, error) { ctx, cancel := s.withTimeout(ctx) defer cancel() tx, err := s.pool.Begin(ctx) if err != nil { return ClaimResult{}, dbError(err) } defer rollback(tx) job, err := scanJob(tx.QueryRow(ctx, ` SELECT job_id, attachment_id, type, pipeline_version, attempt, max_attempts, status, error_code, created_at, available_at, published_at, lease_until, processing_started_at, finished_at, replay_count FROM attachment_jobs WHERE job_id = $1 FOR UPDATE`, jobID)) if err != nil { return ClaimResult{}, err } att, err := scanAttachment(tx.QueryRow(ctx, attachmentSelect+` WHERE a.id = $1 FOR UPDATE`, job.AttachmentID)) if err != nil { return ClaimResult{}, err } now := time.Now().UTC() if job.Status == model.JobStatusReady || job.Status == model.JobStatusFailed || att.Status == "ready" { if err = tx.Commit(ctx); err != nil { return ClaimResult{}, dbError(err) } return ClaimResult{Job: job, Attachment: att, Terminal: true}, nil } if att.Status == "failed" { if err = tx.Commit(ctx); err != nil { return ClaimResult{}, dbError(err) } return ClaimResult{Job: job, Attachment: att, Terminal: true}, nil } if job.Status == model.JobStatusProcessing && job.LeaseUntil != nil && job.LeaseUntil.After(now) { if err = tx.Commit(ctx); err != nil { return ClaimResult{}, dbError(err) } return ClaimResult{Job: job, Attachment: att, Busy: true}, nil } if job.Status == model.JobStatusQueued && job.AvailableAt.After(now) { if err = tx.Commit(ctx); err != nil { return ClaimResult{}, dbError(err) } return ClaimResult{Job: job, Attachment: att, Busy: true}, nil } if job.Attempt >= job.MaxAttempts { _, failErr := tx.Exec(ctx, ` UPDATE attachment_jobs SET status = 'failed', error_code = 'retry_exhausted', finished_at = $2, lease_until = NULL, updated_at = $2 WHERE job_id = $1`, jobID, now) if failErr != nil { return ClaimResult{}, dbError(failErr) } _, failErr = tx.Exec(ctx, ` UPDATE attachments SET status = 'failed', error_code = 'retry_exhausted', updated_at = $2 WHERE id = $1 AND status <> 'ready'`, job.AttachmentID, now) if failErr != nil { return ClaimResult{}, dbError(failErr) } if err = tx.Commit(ctx); err != nil { return ClaimResult{}, dbError(err) } return ClaimResult{Job: job, Attachment: att, Terminal: true}, nil } attempt := job.Attempt + 1 leaseUntil := now.Add(lease) _, err = tx.Exec(ctx, ` UPDATE attachment_jobs SET status = 'processing', attempt = $2, error_code = NULL, lease_until = $3, processing_started_at = COALESCE(processing_started_at, $4), published_at = COALESCE(published_at, $4), updated_at = $4 WHERE job_id = $1`, jobID, attempt, leaseUntil, now) if err != nil { return ClaimResult{}, dbError(err) } _, err = tx.Exec(ctx, ` UPDATE attachments SET status = 'processing', error_code = NULL, updated_at = $2 WHERE id = $1 AND status IN ('queued', 'processing')`, job.AttachmentID, now) if err != nil { return ClaimResult{}, dbError(err) } if err = tx.Commit(ctx); err != nil { return ClaimResult{}, dbError(err) } job.Attempt = attempt job.Status = model.JobStatusProcessing job.ErrorCode = nil job.LeaseUntil = &leaseUntil if job.ProcessingStartedAt == nil { job.ProcessingStartedAt = &now } att.Status = "processing" att.ErrorCode = nil att.UpdatedAt = common.RFCFormTime(now) return ClaimResult{Job: job, Attachment: att}, nil } // CompleteJob commits the ready snapshot only for the attempt/version that // still owns the lease. An older duplicate can therefore never roll a newer // result back or overwrite it. func (s *Store) CompleteJob(ctx context.Context, jobID uuid.UUID, attempt int, variants []model.Variant) (bool, error) { ctx, cancel := s.withTimeout(ctx) defer cancel() if variants == nil { variants = []model.Variant{} } encoded, err := json.Marshal(variants) if err != nil { return false, common.Internal() } tx, err := s.pool.Begin(ctx) if err != nil { return false, dbError(err) } defer rollback(tx) var attachmentID uuid.UUID var pipelineVersion int var status string err = tx.QueryRow(ctx, ` SELECT attachment_id, pipeline_version, status FROM attachment_jobs WHERE job_id = $1 FOR UPDATE`, jobID). Scan(&attachmentID, &pipelineVersion, &status) if errors.Is(err, pgx.ErrNoRows) { return false, common.NotFound("job not found") } if err != nil { return false, dbError(err) } if status != model.JobStatusProcessing { return false, nil } att, err := scanAttachment(tx.QueryRow(ctx, attachmentSelect+` WHERE a.id = $1 FOR UPDATE`, attachmentID)) if err != nil { return false, err } if att.PipelineVersion != pipelineVersion || att.Status == "ready" || att.Status == "failed" { return false, nil } now := time.Now().UTC() tag, err := tx.Exec(ctx, ` UPDATE attachment_jobs SET status = 'ready', error_code = NULL, finished_at = $3, lease_until = NULL, updated_at = $3 WHERE job_id = $1 AND attempt = $2 AND status = 'processing'`, jobID, attempt, now) if err != nil { return false, dbError(err) } if tag.RowsAffected() == 0 { return false, nil } _, err = tx.Exec(ctx, ` UPDATE attachments SET status = 'ready', variants = $2, error_code = NULL, ready_at = $3, updated_at = $3 WHERE id = $1 AND pipeline_version = $4 AND status IN ('queued', 'processing')`, attachmentID, encoded, now, pipelineVersion) if err != nil { return false, dbError(err) } if err = tx.Commit(ctx); err != nil { return false, dbError(err) } return true, nil } // ScheduleRetry keeps the job in the durable outbox with a jittered delay. // The caller acks the broker only after this commit, so the retry intent is // never lost between "try later" and ack. func (s *Store) ScheduleRetry(ctx context.Context, jobID uuid.UUID, attempt int, code string, delay time.Duration) (bool, error) { ctx, cancel := s.withTimeout(ctx) defer cancel() tx, err := s.pool.Begin(ctx) if err != nil { return false, dbError(err) } defer rollback(tx) now := time.Now().UTC() tag, err := tx.Exec(ctx, ` UPDATE attachment_jobs SET status = 'queued', error_code = $3, available_at = $4, published_at = NULL, lease_until = NULL, updated_at = $5 WHERE job_id = $1 AND status = 'processing' AND attempt = $2`, jobID, attempt, code, now.Add(delay), now) if err != nil { return false, dbError(err) } if tag.RowsAffected() == 0 { return false, nil } _, err = tx.Exec(ctx, ` UPDATE attachments SET status = 'queued', error_code = NULL, updated_at = $2 WHERE id = (SELECT attachment_id FROM attachment_jobs WHERE job_id = $1) AND status <> 'ready'`, jobID, now) if err != nil { return false, dbError(err) } return true, dbError(tx.Commit(ctx)) } // FailJob records a terminal reason. It is idempotent: a later stale attempt // that no longer matches the current attempt is ignored. func (s *Store) FailJob(ctx context.Context, jobID uuid.UUID, attempt int, code string) error { ctx, cancel := s.withTimeout(ctx) defer cancel() tx, err := s.pool.Begin(ctx) if err != nil { return dbError(err) } defer rollback(tx) now := time.Now().UTC() tag, err := tx.Exec(ctx, ` UPDATE attachment_jobs SET status = 'failed', error_code = $3, finished_at = $4, lease_until = NULL, updated_at = $4 WHERE job_id = $1 AND status = 'processing' AND attempt = $2`, jobID, attempt, code, now) if err != nil { return dbError(err) } if tag.RowsAffected() == 0 { return nil } _, err = tx.Exec(ctx, ` UPDATE attachments SET status = 'failed', error_code = $2, updated_at = $3 WHERE id = (SELECT attachment_id FROM attachment_jobs WHERE job_id = $1) AND status <> 'ready'`, jobID, code, now) if err != nil { return dbError(err) } return dbError(tx.Commit(ctx)) } // RecoverExpiredLeases is the stuck-processing guard. A dead worker leaves a // processing row whose lease expires; the sweeper requeues it or marks it // retry_exhausted. It never touches ready work. func (s *Store) RecoverExpiredLeases(ctx context.Context) (int, error) { ctx, cancel := s.withTimeout(ctx) defer cancel() tag, err := s.pool.Exec(ctx, ` WITH expired AS ( UPDATE attachment_jobs j SET status = CASE WHEN j.attempt >= j.max_attempts THEN 'failed' ELSE 'queued' END, error_code = CASE WHEN j.attempt >= j.max_attempts THEN 'retry_exhausted' ELSE NULL END, available_at = now(), published_at = NULL, lease_until = NULL, finished_at = CASE WHEN j.attempt >= j.max_attempts THEN now() ELSE NULL END, updated_at = now() WHERE j.status = 'processing' AND j.lease_until IS NOT NULL AND j.lease_until < now() RETURNING j.attachment_id, j.status, j.error_code ) UPDATE attachments a SET status = CASE WHEN e.status = 'failed' THEN 'failed' ELSE 'queued' END, error_code = CASE WHEN e.status = 'failed' THEN e.error_code ELSE NULL END, updated_at = now() FROM expired e WHERE a.id = e.attachment_id AND a.status <> 'ready'`) if err != nil { return 0, dbError(err) } return int(tag.RowsAffected()), nil } // ListPublishableJobs is the outbox read side. It intentionally does not lock // rows: two API replicas may publish the same message, and the idempotent // claim/effect makes that duplicate harmless. func (s *Store) ListPublishableJobs(ctx context.Context, limit int) ([]model.JobRecord, error) { ctx, cancel := s.withTimeout(ctx) defer cancel() rows, err := s.pool.Query(ctx, ` SELECT job_id, attachment_id, type, pipeline_version, attempt, max_attempts, status, error_code, created_at, available_at, published_at, lease_until, processing_started_at, finished_at, replay_count FROM attachment_jobs WHERE published_at IS NULL AND status = 'queued' AND available_at <= now() ORDER BY available_at, created_at LIMIT $1`, limit) if err != nil { return nil, dbError(err) } defer rows.Close() var jobs []model.JobRecord for rows.Next() { job, scanErr := scanJob(rows) if scanErr != nil { return nil, scanErr } jobs = append(jobs, job) } if err = rows.Err(); err != nil { return nil, dbError(err) } return jobs, nil } // MarkJobPublished uses status+attempt as a compare-and-set. If a worker has // already claimed the job, or a retry has superseded this publish, the update // is a no-op and the outbox will publish the current intent later. func (s *Store) MarkJobPublished(ctx context.Context, jobID uuid.UUID, attempt int, at time.Time) error { ctx, cancel := s.withTimeout(ctx) defer cancel() _, err := s.pool.Exec(ctx, ` UPDATE attachment_jobs SET published_at = $3, updated_at = $3 WHERE job_id = $1 AND attempt = $2 AND status = 'queued' AND published_at IS NULL`, jobID, attempt, at.UTC()) return dbError(err) } // ReplayFailed is the explicit operator action. The status guard means a // second click, or a replay after success, cannot duplicate a ready effect. func (s *Store) ReplayFailed(ctx context.Context, attachmentID uuid.UUID) (bool, error) { ctx, cancel := s.withTimeout(ctx) defer cancel() tx, err := s.pool.Begin(ctx) if err != nil { return false, dbError(err) } defer rollback(tx) now := time.Now().UTC() tag, err := tx.Exec(ctx, ` UPDATE attachment_jobs SET status = 'queued', attempt = 0, error_code = NULL, available_at = $2, published_at = NULL, lease_until = NULL, processing_started_at = NULL, finished_at = NULL, replay_count = replay_count + 1, last_replay_at = $2, updated_at = $2 WHERE attachment_id = $1 AND status = 'failed' AND EXISTS (SELECT 1 FROM attachments WHERE id = $1 AND status = 'failed')`, attachmentID, now) if err != nil { return false, dbError(err) } if tag.RowsAffected() == 0 { return false, nil } _, err = tx.Exec(ctx, ` UPDATE attachments SET status = 'queued', error_code = NULL, updated_at = $2 WHERE id = $1 AND status = 'failed'`, attachmentID, now) if err != nil { return false, dbError(err) } if err = tx.Commit(ctx); err != nil { return false, dbError(err) } return true, nil } func scanJob(row rowScanner) (model.JobRecord, error) { var ( job model.JobRecord created time.Time errCode *string ) if err := row.Scan( &job.JobID, &job.AttachmentID, &job.Type, &job.PipelineVersion, &job.Attempt, &job.MaxAttempts, &job.Status, &errCode, &created, &job.AvailableAt, &job.PublishedAt, &job.LeaseUntil, &job.ProcessingStartedAt, &job.FinishedAt, &job.ReplayCount, ); err != nil { if errors.Is(err, pgx.ErrNoRows) { return model.JobRecord{}, common.NotFound("job not found") } return model.JobRecord{}, dbError(err) } job.SchemaVersion = 1 job.CreatedAt = common.RFCFormTime(created.UTC()) job.ErrorCode = errCode return job, nil }