package postgres import ( "cmp" "context" "errors" "fmt" "math" "slices" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" "lincodex/backend/internal/adapter/secondary/postgres/sqlc" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" ) // Job status values that the worker side of the store writes or reads. const ( jobStatusFailed = "failed" jobStatusDead = "dead" jobStatusCancelled = "cancelled" ) // ScheduledJobStore implements outbound.JobStore with a pgx pool owned by // the caller. A claim, a failure, and a release are single statements; each // Run holds one connection and one transaction for the duration of the // handler. type ScheduledJobStore struct { pool *pgxpool.Pool // runTimeout is set as statement_timeout and // idle_in_transaction_session_timeout of every Run transaction. runTimeout time.Duration } var _ outbound.JobStore = (*ScheduledJobStore)(nil) // NewScheduledJobStore bounds each handler transaction on the server by // runTimeout, the lease duration. The worker's context already ends a live // handler with its lease; the server-side limits also end the transaction of // a worker that froze or lost the network, so the job row lock it holds is // released and the job can be claimed again once the lease expired. func NewScheduledJobStore(pool *pgxpool.Pool, runTimeout time.Duration) *ScheduledJobStore { return &ScheduledJobStore{pool: pool, runTimeout: runTimeout} } func (store *ScheduledJobStore) Claim(ctx context.Context, claim outbound.JobClaim) ([]outbound.ClaimedJob, error) { if claim.Limit <= 0 || claim.Limit > math.MaxInt32 { return nil, fmt.Errorf("ScheduledJobStore.Claim - limit must be between 1 and %d", math.MaxInt32) } if claim.DefaultMaxAttempts <= 0 || claim.DefaultMaxAttempts > domain.MaxScheduledJobAttempts { return nil, fmt.Errorf("ScheduledJobStore.Claim - default max attempts must be between 1 and %d", domain.MaxScheduledJobAttempts) } if len(claim.Kinds) == 0 || claim.Owner == uuid.Nil || claim.Lease <= 0 || claim.Now.IsZero() { return nil, errors.New("ScheduledJobStore.Claim - kinds, owner, lease, and now must be set") } expiresAt := claim.Now.Add(claim.Lease) rows, err := sqlc.New(store.pool).ClaimScheduledJobs(ctx, sqlc.ClaimScheduledJobsParams{ LeaseOwner: pgtype.UUID{Bytes: claim.Owner, Valid: true}, LeaseExpiresAt: timestamp(expiresAt), DefaultMaxAttempts: int32(claim.DefaultMaxAttempts), Kinds: claim.Kinds, Now: timestamp(claim.Now), BatchLimit: int32(claim.Limit), }) if err != nil { return nil, fmt.Errorf("ScheduledJobStore.Claim - claim due jobs: %w", sanitizedDatabaseError(err)) } jobs := make([]outbound.ClaimedJob, 0, len(rows)) for _, row := range rows { exhausted := row.Exhausted.Valid && row.Exhausted.Bool job := outbound.ClaimedJob{ ID: row.ID, Kind: row.Kind, Key: row.DedupKey, Payload: row.Payload, DueAt: row.DueAt.Time, Attempt: int(row.Attempts), MaxAttempts: int(row.MaxAttempts), Exhausted: exhausted, } if !exhausted { job.LeaseOwner = claim.Owner job.LeaseExpiresAt = expiresAt } jobs = append(jobs, job) } // UPDATE ... RETURNING does not keep the order of the locking scan. slices.SortFunc(jobs, func(left, right outbound.ClaimedJob) int { return cmp.Or(left.DueAt.Compare(right.DueAt), cmp.Compare(left.ID, right.ID)) }) return jobs, nil } func (store *ScheduledJobStore) Start(ctx context.Context, job outbound.ClaimedJob, now time.Time, lease time.Duration) (outbound.ClaimedJob, bool, error) { guard, err := leaseGuard(job) if err != nil { return outbound.ClaimedJob{}, false, err } if now.IsZero() || lease <= 0 { return outbound.ClaimedJob{}, false, errors.New("ScheduledJobStore.Start - now and lease must be set") } expiresAt := now.Add(lease) started, err := sqlc.New(store.pool).StartScheduledJob(ctx, sqlc.StartScheduledJobParams{ LeaseExpiresAt: timestamp(expiresAt), Now: timestamp(now), ID: guard.ID, LeaseOwner: guard.LeaseOwner, Attempt: guard.Attempt, }) if err != nil { return outbound.ClaimedJob{}, false, fmt.Errorf("ScheduledJobStore.Start - renew lease: %w", sanitizedDatabaseError(err)) } if started != 1 { return outbound.ClaimedJob{}, false, nil } job.LeaseExpiresAt = expiresAt return job, true, nil } func (store *ScheduledJobStore) Run(ctx context.Context, job outbound.ClaimedJob, apply outbound.ApplyJob) error { // PostgreSQL reads 0 as no limit, so a value below one millisecond would // silently remove the bound. if store.runTimeout < time.Millisecond { return errors.New("ScheduledJobStore.Run - transaction timeout must be at least 1ms") } guard, err := leaseGuard(job) if err != nil { return err } if ctx.Value(transactionContextKey{}) != nil { return fmt.Errorf("ScheduledJobStore.Run - begin transaction: %w", outbound.ErrNestedTransaction) } tx, err := store.pool.BeginTx(ctx, transactionOptions) if err != nil { return fmt.Errorf("ScheduledJobStore.Run - begin transaction: %w", sanitizeConnectError(err)) } finished := false defer func() { // Runs only when apply panics; the panic keeps its stack and the // rollback error cannot change that outcome. if !finished { _ = rollback(ctx, tx) } }() runErr := store.runInTransaction(ctx, tx, guard, apply) finished = true if runErr != nil { if rollbackErr := rollback(ctx, tx); rollbackErr != nil { return errors.Join(runErr, fmt.Errorf("ScheduledJobStore.Run - roll back transaction: %w", rollbackErr)) } return runErr } if err := tx.Commit(ctx); err != nil { return fmt.Errorf("ScheduledJobStore.Run - commit transaction: %w", classifyCommitRefusal(err, outbound.ErrJobEffectRejected)) } return nil } func (store *ScheduledJobStore) runInTransaction(ctx context.Context, tx pgx.Tx, guard jobLeaseGuard, apply outbound.ApplyJob) error { queries := sqlc.New(tx) timeout := milliseconds(store.runTimeout) err := queries.SetScheduledJobTransactionTimeouts(ctx, sqlc.SetScheduledJobTransactionTimeoutsParams{ StatementTimeoutMs: timeout, IdleTimeoutMs: timeout, }) if err != nil { return fmt.Errorf("postgres.runInTransaction - set transaction timeouts: %w", sanitizedDatabaseError(err)) } _, err = queries.LockClaimedScheduledJob(ctx, sqlc.LockClaimedScheduledJobParams(guard)) if errors.Is(err, pgx.ErrNoRows) { return fmt.Errorf("postgres.runInTransaction - lock job: %w", outbound.ErrJobLeaseLost) } if err != nil { return fmt.Errorf("postgres.runInTransaction - lock job: %w", sanitizedDatabaseError(err)) } unit := &UnitOfWork{tx: tx, queries: queries} // The error of apply is returned without a store location, so the // caller keeps its identity; only PostgreSQL text inside it is replaced. if err := apply(context.WithValue(ctx, transactionContextKey{}, true), unit); err != nil { return sanitizeApplyError(markTransactionConflict(err)) } completed, err := queries.CompleteScheduledJob(ctx, sqlc.CompleteScheduledJobParams(guard)) if err != nil { return fmt.Errorf("postgres.runInTransaction - complete job: %w", sanitizedDatabaseError(err)) } if completed == 1 { return nil } return completeChangedJob(ctx, queries, guard.ID) } // completeChangedJob decides a completion whose guard no longer matched. // The transaction holds the row lock, so only apply can have changed the // job. A handler that canceled its own job, for example an expiry that // also cancels the deadline it stands for, has finished it: its effect // commits. Any other change is a handler bug that would repeat on every // attempt, so it is a final failure rather than a database failure, which // would release the job and claim it first again on every pass. func completeChangedJob(ctx context.Context, queries *sqlc.Queries, id int64) error { status, err := queries.GetScheduledJobStatus(ctx, id) if err != nil { return fmt.Errorf("postgres.completeChangedJob - read job status: %w", sanitizedDatabaseError(err)) } if status == jobStatusCancelled { return nil } return fmt.Errorf("postgres.completeChangedJob - job is %s: %w", status, outbound.ErrJobCompletionConflict) } func (store *ScheduledJobStore) Fail(ctx context.Context, job outbound.ClaimedJob, failure outbound.JobFailure) (bool, error) { guard, err := leaseGuard(job) if err != nil { return false, err } if failure.Class == "" { return false, errors.New("ScheduledJobStore.Fail - failure class must be set") } status, retryAt := jobStatusFailed, timestamp(failure.RetryAt) if failure.Dead { // A dead job keeps the time it was last available. status, retryAt = jobStatusDead, pgtype.Timestamptz{} } else if failure.RetryAt.IsZero() { return false, errors.New("ScheduledJobStore.Fail - retry time must be set") } recorded, err := sqlc.New(store.pool).FailScheduledJob(ctx, sqlc.FailScheduledJobParams{ Status: status, RetryAt: retryAt, ErrorClass: pgtype.Text{String: string(failure.Class), Valid: true}, ID: guard.ID, LeaseOwner: guard.LeaseOwner, Attempt: guard.Attempt, }) if err != nil { return false, fmt.Errorf("ScheduledJobStore.Fail - record failure: %w", sanitizedDatabaseError(err)) } return recorded == 1, nil } func (store *ScheduledJobStore) Release(ctx context.Context, jobs []outbound.ClaimedJob) ([]int64, error) { if len(jobs) == 0 { return nil, nil } owner := jobs[0].LeaseOwner ids := make([]int64, 0, len(jobs)) attempts := make([]int32, 0, len(jobs)) for _, job := range jobs { guard, err := leaseGuard(job) if err != nil { return nil, err } if job.LeaseOwner != owner { return nil, errors.New("ScheduledJobStore.Release - jobs must share one lease owner") } ids = append(ids, guard.ID) attempts = append(attempts, guard.Attempt) } released, err := sqlc.New(store.pool).ReleaseScheduledJobs(ctx, sqlc.ReleaseScheduledJobsParams{ LeaseOwner: pgtype.UUID{Bytes: owner, Valid: true}, Ids: ids, Attempts: attempts, }) if err != nil { return nil, fmt.Errorf("ScheduledJobStore.Release - release jobs: %w", sanitizedDatabaseError(err)) } return released, nil } func (store *ScheduledJobStore) Backlog(ctx context.Context, now time.Time) (outbound.JobBacklog, error) { row, err := sqlc.New(store.pool).GetScheduledJobBacklog(ctx, timestamp(now)) if err != nil { return outbound.JobBacklog{}, fmt.Errorf("ScheduledJobStore.Backlog - read backlog: %w", sanitizedDatabaseError(err)) } return outbound.JobBacklog{ Due: row.DueJobs, OldestDueAge: time.Duration(row.OldestDueAgeSeconds * float64(time.Second)), Dead: row.DeadJobs, }, nil } // jobLeaseGuard has the field layout of the sqlc lock and completion // parameters, so one value converts to both. type jobLeaseGuard struct { ID int64 LeaseOwner pgtype.UUID Attempt int32 } func leaseGuard(job outbound.ClaimedJob) (jobLeaseGuard, error) { if job.Exhausted || job.LeaseOwner == uuid.Nil || job.Attempt < 1 || job.Attempt > math.MaxInt32 { return jobLeaseGuard{}, errors.New("postgres.leaseGuard - job is not held under a lease") } return jobLeaseGuard{ ID: job.ID, LeaseOwner: pgtype.UUID{Bytes: job.LeaseOwner, Valid: true}, Attempt: int32(job.Attempt), }, nil } func timestamp(value time.Time) pgtype.Timestamptz { return pgtype.Timestamptz{Time: value, Valid: true} } // scheduledJobWriter schedules jobs in the transaction of its unit of work. type scheduledJobWriter struct { queries *sqlc.Queries } func (unit *UnitOfWork) ScheduledJobs() outbound.JobScheduler { return scheduledJobWriter{queries: unit.queries} } func (writer scheduledJobWriter) Schedule(ctx context.Context, job domain.ScheduledJob) (bool, error) { if job.Kind() == "" { return false, fmt.Errorf("scheduledJobWriter.Schedule - job was not built by domain.NewScheduledJob: %w", domain.ErrInvalidScheduledJob) } maxAttempts := pgtype.Int4{} if limit := job.MaxAttempts(); limit > 0 && limit <= domain.MaxScheduledJobAttempts { maxAttempts = pgtype.Int4{Int32: int32(limit), Valid: true} } inserted, err := writer.queries.InsertScheduledJob(ctx, sqlc.InsertScheduledJobParams{ Kind: job.Kind(), DedupKey: job.Key(), Payload: job.Payload(), DueAt: timestamp(job.DueAt()), MaxAttempts: maxAttempts, }) if err != nil { return false, fmt.Errorf("scheduledJobWriter.Schedule - insert job: %w", sanitizedDatabaseError(err)) } return inserted == 1, nil } func (writer scheduledJobWriter) Cancel(ctx context.Context, kind, key string) (bool, error) { cancelled, err := writer.queries.CancelScheduledJob(ctx, sqlc.CancelScheduledJobParams{Kind: kind, DedupKey: key}) if err != nil { return false, fmt.Errorf("scheduledJobWriter.Cancel - cancel job: %w", sanitizedDatabaseError(err)) } return cancelled == 1, nil }