feat(jobs): add durable due-time job runner with leases

This commit is contained in:
shira committed 2026-10-06 14:29:23 +03:00
1 parent 7e80c8ad2a
commit 008254e44a
39 files changed
+4909 -43

No files matched your search

@@ -103,17 +103,24 @@ func (store *EventConsumerStore) ApplyOnce(ctx context.Context, consumer string,
//
// Connection and network errors pass through as store failures.
func classifyCommitError(err error) error {
return classifyCommitRefusal(err, outbound.ErrEventEffectRejected)
}
// classifyCommitRefusal is classifyCommitError with the sentinel that a
// refused commit matches, so the scheduled job store applies the same rules
// with its own port error.
func classifyCommitRefusal(err, rejected error) error {
if errors.Is(err, pgx.ErrTxCommitRollback) {
return fmt.Errorf("postgres.classifyCommitError - transaction was aborted by a failed statement: %w", outbound.ErrEventEffectRejected)
return fmt.Errorf("postgres.classifyCommitRefusal - transaction was aborted by a failed statement: %w", rejected)
}
var pgError *pgconn.PgError
if errors.As(err, &pgError) && len(pgError.Code) == len(deadlockDetectedCode) {
safe := &databaseError{code: pgError.Code, constraint: pgError.ConstraintName}
switch pgError.Code[:sqlStateClassLength] {
case integrityConstraintClass:
return fmt.Errorf("postgres.classifyCommitError - %w: %w", outbound.ErrEventEffectRejected, safe)
return fmt.Errorf("postgres.classifyCommitRefusal - %w: %w", rejected, safe)
case transactionRollbackClass:
return fmt.Errorf("postgres.classifyCommitError - %w: %w", outbound.ErrTransactionConflict, safe)
return fmt.Errorf("postgres.classifyCommitRefusal - %w: %w", outbound.ErrTransactionConflict, safe)
}
}
return sanitizedDatabaseError(err)
@@ -0,0 +1,345 @@
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
}
@@ -138,6 +138,24 @@ type PolicyVersion struct {
CreatedAt pgtype.Timestamptz
}
type ScheduledJob struct {
ID int64
Kind string
DedupKey string
Payload []byte
DueAt pgtype.Timestamptz
AvailableAt pgtype.Timestamptz
Status string
Attempts int32
MaxAttempts pgtype.Int4
LeaseOwner pgtype.UUID
LeaseExpiresAt pgtype.Timestamptz
StartedAt pgtype.Timestamptz
LastErrorClass pgtype.Text
CreatedAt pgtype.Timestamptz
UpdatedAt pgtype.Timestamptz
}
type Session struct {
ID pgtype.UUID
UserID pgtype.UUID
@@ -14,6 +14,30 @@ type Querier interface {
// Adds recipients to the day and the month row. The caller holds their
// locks from LockMailQuotaRows and has checked both limits.
AddMailQuotaUsage(ctx context.Context, arg AddMailQuotaUsageParams) (int64, error)
// Cancels a job that has not finished. A job whose handler transaction is
// in progress holds its row lock, so the statement waits for it: after the
// handler committed the job is done and nothing is canceled; otherwise the
// worker finds its lease gone and does not run or complete the job.
CancelScheduledJob(ctx context.Context, arg CancelScheduledJobParams) (int64, error)
// Claims up to batch_limit jobs of the listed kinds in one statement: jobs
// whose available_at has passed, and running jobs whose lease expired
// because their worker stopped without finishing them. Rows that another
// worker locks are skipped without waiting. Each claimed job gets the lease
// of lease_owner and one more attempt, except a job whose expired attempt
// never started its handler: that attempt is reused, so a worker that was
// busy with other jobs of its batch costs the job nothing. A job whose
// started attempt was abandoned on its last allowed attempt becomes dead
// with lease_expired instead, so a job that keeps crashing its worker
// stops. now is the application clock.
//
// The kind filter applies after the index on available_at; when many waiting
// jobs belong to kinds without a handler in the claiming process, an index
// on (kind, available_at, id) is the next step.
ClaimScheduledJobs(ctx context.Context, arg ClaimScheduledJobsParams) ([]ClaimScheduledJobsRow, error)
// Completes a job in the transaction of its handler effect. The guard is
// the lease owner and the attempt, so a worker that lost its lease cannot
// complete the job.
CompleteScheduledJob(ctx context.Context, arg CompleteScheduledJobParams) (int64, error)
// Consumes a token in one statement. Concurrent callers queue on the token
// row lock; under READ COMMITTED each waiter re-checks the WHERE clause
// against the committed row, so exactly one of them updates it. The join
@@ -51,6 +75,11 @@ type Querier interface {
// for the first transaction and then inserts nothing. Existing rows are
// neither changed nor locked here.
EnsureMailQuotaRows(ctx context.Context, arg EnsureMailQuotaRowsParams) error
// Records a failed attempt after its handler transaction rolled back: the
// job waits for its retry at retry_at (status failed) or is dead, with a
// NULL retry_at. due_at keeps the deadline. The same guard as the
// completion applies.
FailScheduledJob(ctx context.Context, arg FailScheduledJobParams) (int64, error)
// Returns the newest open reservation of a delivery under a provider account
// made at or after reserved_since. A retry of the delivery inside the
// provider's idempotency window reuses it instead of counting again.
@@ -77,6 +106,16 @@ type Querier interface {
// clock that set occurred_at.
GetOutboxBacklog(ctx context.Context) (GetOutboxBacklogRow, error)
GetPolicyVersionByID(ctx context.Context, id pgtype.UUID) (PolicyVersion, error)
// Reads the backlog for metrics without locking: jobs that a worker may
// claim at now, how long the earliest of them has waited, and the dead
// jobs. The
// partial indexes keep the cost proportional to those rows. now is the
// application clock.
GetScheduledJobBacklog(ctx context.Context, now pgtype.Timestamptz) (GetScheduledJobBacklogRow, error)
// Reads the status of a job whose completion found it changed, inside
// the handler transaction that holds its row lock: only that transaction
// can have changed it, for example by canceling its own job.
GetScheduledJobStatus(ctx context.Context, id int64) (string, error)
GetUserByEmailNormalized(ctx context.Context, emailNormalized string) (User, error)
GetUserByID(ctx context.Context, id pgtype.UUID) (User, error)
// Stores a record that a consumer could not apply. A second delivery of the
@@ -106,6 +145,16 @@ type Querier interface {
// commit it returns 0, after a rollback it inserts. So a concurrent duplicate
// never runs the effect at the same time as the first delivery.
InsertProcessedEventMarker(ctx context.Context, arg InsertProcessedEventMarkerParams) (int64, error)
// Lock order. A job handler runs while its transaction holds the row lock
// of the job, and may then lock product rows. A business transaction that
// cancels a job should cancel it before it locks the product rows the
// handler touches, so both take the locks in the same order.
// Schedules a job in the caller's transaction. The first schedule of a
// (kind, dedup_key) wins: a repeat, also after the job finished or was
// canceled, inserts nothing and reports 0 rows, so a repeated command never
// moves a deadline. A concurrent insert of the same key waits for the first
// transaction and then inserts nothing, or inserts after its rollback.
InsertScheduledJob(ctx context.Context, arg InsertScheduledJobParams) (int64, error)
InsertSession(ctx context.Context, arg InsertSessionParams) error
InsertUser(ctx context.Context, arg InsertUserParams) error
InvalidateActiveEmailTokens(ctx context.Context, arg InvalidateActiveEmailTokensParams) (int64, error)
@@ -113,6 +162,11 @@ type Querier interface {
// Lists the other accounts of a provider that have usage in a month, so
// startup can warn about a renamed EMAIL_ACCOUNT.
ListOtherMailQuotaAccounts(ctx context.Context, arg ListOtherMailQuotaAccountsParams) ([]string, error)
// Locks a claimed job for its handler transaction and checks that the lease
// still belongs to this attempt. It returns no row when the job was
// canceled, or reclaimed after the lease expired. While the lock is held,
// other workers skip the row, so the handler never runs twice at once.
LockClaimedScheduledJob(ctx context.Context, arg LockClaimedScheduledJobParams) (int64, error)
// Locks the listed window rows until the transaction ends, in
// (period_kind, period_start) order, the same order for every caller, and
// returns their usage. Under READ COMMITTED a waiting caller reads the usage
@@ -168,6 +222,12 @@ type Querier interface {
// provider's answer outranks the local count until the window resets. The
// count never drops below zero.
ReleaseMailQuotaUsage(ctx context.Context, arg ReleaseMailQuotaUsageParams) (int64, error)
// Returns claimed jobs that did not finish, at shutdown or after a database
// failure outside the handler, so another worker can run them at once
// instead of after the lease expires. The attempt is not counted, because
// the job did not cause the failure. The same guard as the completion
// applies, one (id, attempt) pair per job. It returns the IDs it released.
ReleaseScheduledJobs(ctx context.Context, arg ReleaseScheduledJobsParams) ([]int64, error)
RevokeSession(ctx context.Context, arg RevokeSessionParams) (int64, error)
RevokeUserSessions(ctx context.Context, arg RevokeUserSessionsParams) (int64, error)
// Bounds a consumer transaction on the server, local to the transaction.
@@ -183,6 +243,19 @@ type Querier interface {
// froze or lost the network without closing the connection. Both settings
// are local to the transaction.
SetRelayTransactionTimeouts(ctx context.Context, arg SetRelayTransactionTimeoutsParams) error
// Bounds a handler transaction on the server, local to the transaction.
// statement_timeout stops a slow statement; idle_in_transaction_session_timeout
// ends the session of a worker that froze or lost the network inside the
// handler, which releases the job row lock so the job can be reclaimed once
// its lease expires.
SetScheduledJobTransactionTimeouts(ctx context.Context, arg SetScheduledJobTransactionTimeoutsParams) error
// Starts a claimed attempt right before its handler transaction: it renews
// the lease from now and records the start, committed on its own. It
// changes nothing when the lease already expired by now or no longer
// belongs to this attempt, so a job whose turn in the batch came too late is
// never started on a lease that another worker may take over. now is the
// application clock.
StartScheduledJob(ctx context.Context, arg StartScheduledJobParams) (int64, error)
// Records activity on an active session and reports whether it is active.
// The row is written only when last_seen_at is older than touch_cutoff, so
// frequent requests do not rewrite it. last_seen_at never moves back, and a
@@ -0,0 +1,532 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: scheduled_job.sql
package sqlc
import (
"context"
"github.com/jackc/pgx/v5/pgtype"
)
const cancelScheduledJob = `-- name: CancelScheduledJob :execrows
UPDATE scheduled_jobs
SET
status = 'cancelled',
lease_owner = NULL,
lease_expires_at = NULL,
started_at = NULL,
updated_at = clock_timestamp()
WHERE
kind = $1
AND dedup_key = $2
AND status IN ('pending', 'failed', 'running')
`
type CancelScheduledJobParams struct {
Kind string
DedupKey string
}
// Cancels a job that has not finished. A job whose handler transaction is
// in progress holds its row lock, so the statement waits for it: after the
// handler committed the job is done and nothing is canceled; otherwise the
// worker finds its lease gone and does not run or complete the job.
func (q *Queries) CancelScheduledJob(ctx context.Context, arg CancelScheduledJobParams) (int64, error) {
result, err := q.db.Exec(ctx, cancelScheduledJob, arg.Kind, arg.DedupKey)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const claimScheduledJobs = `-- name: ClaimScheduledJobs :many
WITH candidates AS (
SELECT
candidate.id,
(
candidate.status = 'running'
AND candidate.started_at IS NULL
) AS unstarted,
(
candidate.status = 'running'
AND candidate.started_at IS NOT NULL
AND candidate.attempts >= coalesce(
candidate.max_attempts,
$3::integer
)
) AS exhausted
FROM scheduled_jobs AS candidate
WHERE
candidate.kind = any($4::text [])
AND (
(
candidate.status IN ('pending', 'failed')
AND candidate.available_at <= $5::timestamptz
)
OR (
candidate.status = 'running'
AND candidate.lease_expires_at <= $5::timestamptz
)
)
ORDER BY candidate.available_at, candidate.id
LIMIT $6
FOR UPDATE SKIP LOCKED
)
UPDATE scheduled_jobs AS job
SET
status = CASE WHEN candidates.exhausted THEN 'dead' ELSE 'running' END,
attempts = CASE
WHEN candidates.exhausted OR candidates.unstarted THEN job.attempts
ELSE job.attempts + 1
END,
lease_owner = CASE
WHEN candidates.exhausted THEN NULL ELSE $1::uuid
END,
lease_expires_at = CASE
WHEN
candidates.exhausted
THEN NULL
ELSE $2::timestamptz
END,
started_at = NULL,
last_error_class = CASE
WHEN
job.status = 'running' AND NOT candidates.unstarted
THEN 'lease_expired'
ELSE job.last_error_class
END,
updated_at = clock_timestamp()
FROM candidates
WHERE job.id = candidates.id
RETURNING
job.id,
job.kind,
job.dedup_key,
job.payload,
job.due_at,
job.attempts,
coalesce(
job.max_attempts, $3::integer
)::integer AS max_attempts,
candidates.exhausted
`
type ClaimScheduledJobsParams struct {
LeaseOwner pgtype.UUID
LeaseExpiresAt pgtype.Timestamptz
DefaultMaxAttempts int32
Kinds []string
Now pgtype.Timestamptz
BatchLimit int32
}
type ClaimScheduledJobsRow struct {
ID int64
Kind string
DedupKey string
Payload []byte
DueAt pgtype.Timestamptz
Attempts int32
MaxAttempts int32
Exhausted pgtype.Bool
}
// Claims up to batch_limit jobs of the listed kinds in one statement: jobs
// whose available_at has passed, and running jobs whose lease expired
// because their worker stopped without finishing them. Rows that another
// worker locks are skipped without waiting. Each claimed job gets the lease
// of lease_owner and one more attempt, except a job whose expired attempt
// never started its handler: that attempt is reused, so a worker that was
// busy with other jobs of its batch costs the job nothing. A job whose
// started attempt was abandoned on its last allowed attempt becomes dead
// with lease_expired instead, so a job that keeps crashing its worker
// stops. now is the application clock.
//
// The kind filter applies after the index on available_at; when many waiting
// jobs belong to kinds without a handler in the claiming process, an index
// on (kind, available_at, id) is the next step.
func (q *Queries) ClaimScheduledJobs(ctx context.Context, arg ClaimScheduledJobsParams) ([]ClaimScheduledJobsRow, error) {
rows, err := q.db.Query(ctx, claimScheduledJobs,
arg.LeaseOwner,
arg.LeaseExpiresAt,
arg.DefaultMaxAttempts,
arg.Kinds,
arg.Now,
arg.BatchLimit,
)
if err != nil {
return nil, err
}
defer rows.Close()
var items []ClaimScheduledJobsRow
for rows.Next() {
var i ClaimScheduledJobsRow
if err := rows.Scan(
&i.ID,
&i.Kind,
&i.DedupKey,
&i.Payload,
&i.DueAt,
&i.Attempts,
&i.MaxAttempts,
&i.Exhausted,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const completeScheduledJob = `-- name: CompleteScheduledJob :execrows
UPDATE scheduled_jobs
SET
status = 'done',
lease_owner = NULL,
lease_expires_at = NULL,
started_at = NULL,
updated_at = clock_timestamp()
WHERE
id = $1
AND status = 'running'
AND lease_owner = $2
AND attempts = $3
`
type CompleteScheduledJobParams struct {
ID int64
LeaseOwner pgtype.UUID
Attempt int32
}
// Completes a job in the transaction of its handler effect. The guard is
// the lease owner and the attempt, so a worker that lost its lease cannot
// complete the job.
func (q *Queries) CompleteScheduledJob(ctx context.Context, arg CompleteScheduledJobParams) (int64, error) {
result, err := q.db.Exec(ctx, completeScheduledJob, arg.ID, arg.LeaseOwner, arg.Attempt)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const failScheduledJob = `-- name: FailScheduledJob :execrows
UPDATE scheduled_jobs
SET
status = $1,
available_at = coalesce($2, available_at),
last_error_class = $3,
lease_owner = NULL,
lease_expires_at = NULL,
started_at = NULL,
updated_at = clock_timestamp()
WHERE
id = $4
AND status = 'running'
AND lease_owner = $5
AND attempts = $6
`
type FailScheduledJobParams struct {
Status string
RetryAt pgtype.Timestamptz
ErrorClass pgtype.Text
ID int64
LeaseOwner pgtype.UUID
Attempt int32
}
// Records a failed attempt after its handler transaction rolled back: the
// job waits for its retry at retry_at (status failed) or is dead, with a
// NULL retry_at. due_at keeps the deadline. The same guard as the
// completion applies.
func (q *Queries) FailScheduledJob(ctx context.Context, arg FailScheduledJobParams) (int64, error) {
result, err := q.db.Exec(ctx, failScheduledJob,
arg.Status,
arg.RetryAt,
arg.ErrorClass,
arg.ID,
arg.LeaseOwner,
arg.Attempt,
)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const getScheduledJobBacklog = `-- name: GetScheduledJobBacklog :one
SELECT
(
SELECT count(*)
FROM scheduled_jobs AS due
WHERE
due.status IN ('pending', 'failed')
AND due.available_at <= $1::timestamptz
)::bigint AS due_jobs,
coalesce((
SELECT
extract(EPOCH FROM $1::timestamptz - oldest.available_at)
FROM scheduled_jobs AS oldest
WHERE
oldest.status IN ('pending', 'failed')
AND oldest.available_at <= $1::timestamptz
ORDER BY oldest.available_at
LIMIT 1
), 0)::float8 AS oldest_due_age_seconds,
(
SELECT count(*)
FROM scheduled_jobs AS dead
WHERE dead.status = 'dead'
)::bigint AS dead_jobs
`
type GetScheduledJobBacklogRow struct {
DueJobs int64
OldestDueAgeSeconds float64
DeadJobs int64
}
// Reads the backlog for metrics without locking: jobs that a worker may
// claim at now, how long the earliest of them has waited, and the dead
// jobs. The
// partial indexes keep the cost proportional to those rows. now is the
// application clock.
func (q *Queries) GetScheduledJobBacklog(ctx context.Context, now pgtype.Timestamptz) (GetScheduledJobBacklogRow, error) {
row := q.db.QueryRow(ctx, getScheduledJobBacklog, now)
var i GetScheduledJobBacklogRow
err := row.Scan(&i.DueJobs, &i.OldestDueAgeSeconds, &i.DeadJobs)
return i, err
}
const getScheduledJobStatus = `-- name: GetScheduledJobStatus :one
SELECT job.status
FROM scheduled_jobs AS job
WHERE job.id = $1
`
// Reads the status of a job whose completion found it changed, inside
// the handler transaction that holds its row lock: only that transaction
// can have changed it, for example by canceling its own job.
func (q *Queries) GetScheduledJobStatus(ctx context.Context, id int64) (string, error) {
row := q.db.QueryRow(ctx, getScheduledJobStatus, id)
var status string
err := row.Scan(&status)
return status, err
}
const insertScheduledJob = `-- name: InsertScheduledJob :execrows
INSERT INTO scheduled_jobs (
kind,
dedup_key,
payload,
due_at,
available_at,
status,
attempts,
max_attempts
) VALUES (
$1,
$2,
$3,
$4,
$4,
'pending',
0,
$5
)
ON CONFLICT (kind, dedup_key) DO NOTHING
`
type InsertScheduledJobParams struct {
Kind string
DedupKey string
Payload []byte
DueAt pgtype.Timestamptz
MaxAttempts pgtype.Int4
}
// Lock order. A job handler runs while its transaction holds the row lock
// of the job, and may then lock product rows. A business transaction that
// cancels a job should cancel it before it locks the product rows the
// handler touches, so both take the locks in the same order.
// Schedules a job in the caller's transaction. The first schedule of a
// (kind, dedup_key) wins: a repeat, also after the job finished or was
// canceled, inserts nothing and reports 0 rows, so a repeated command never
// moves a deadline. A concurrent insert of the same key waits for the first
// transaction and then inserts nothing, or inserts after its rollback.
func (q *Queries) InsertScheduledJob(ctx context.Context, arg InsertScheduledJobParams) (int64, error) {
result, err := q.db.Exec(ctx, insertScheduledJob,
arg.Kind,
arg.DedupKey,
arg.Payload,
arg.DueAt,
arg.MaxAttempts,
)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const lockClaimedScheduledJob = `-- name: LockClaimedScheduledJob :one
SELECT job.id
FROM scheduled_jobs AS job
WHERE
job.id = $1
AND job.status = 'running'
AND job.lease_owner = $2
AND job.attempts = $3
FOR UPDATE
`
type LockClaimedScheduledJobParams struct {
ID int64
LeaseOwner pgtype.UUID
Attempt int32
}
// Locks a claimed job for its handler transaction and checks that the lease
// still belongs to this attempt. It returns no row when the job was
// canceled, or reclaimed after the lease expired. While the lock is held,
// other workers skip the row, so the handler never runs twice at once.
func (q *Queries) LockClaimedScheduledJob(ctx context.Context, arg LockClaimedScheduledJobParams) (int64, error) {
row := q.db.QueryRow(ctx, lockClaimedScheduledJob, arg.ID, arg.LeaseOwner, arg.Attempt)
var id int64
err := row.Scan(&id)
return id, err
}
const releaseScheduledJobs = `-- name: ReleaseScheduledJobs :many
UPDATE scheduled_jobs AS job
SET
status = CASE
WHEN job.last_error_class IS NULL THEN 'pending' ELSE 'failed'
END,
attempts = job.attempts - 1,
lease_owner = NULL,
lease_expires_at = NULL,
started_at = NULL,
updated_at = clock_timestamp()
FROM (
-- Set-returning functions in one select list advance together, so the
-- arrays pair up by position. The two-argument unnest(ids, attempts)
-- would say the same, but the sqlc analyzer cannot type it, and
-- sqlfluff cannot parse ROWS FROM.
SELECT
unnest($2::bigint []) AS id,
unnest($3::integer []) AS attempt
) AS released
WHERE
job.id = released.id
AND job.attempts = released.attempt
AND job.status = 'running'
AND job.lease_owner = $1
RETURNING job.id
`
type ReleaseScheduledJobsParams struct {
LeaseOwner pgtype.UUID
Ids []int64
Attempts []int32
}
// Returns claimed jobs that did not finish, at shutdown or after a database
// failure outside the handler, so another worker can run them at once
// instead of after the lease expires. The attempt is not counted, because
// the job did not cause the failure. The same guard as the completion
// applies, one (id, attempt) pair per job. It returns the IDs it released.
func (q *Queries) ReleaseScheduledJobs(ctx context.Context, arg ReleaseScheduledJobsParams) ([]int64, error) {
rows, err := q.db.Query(ctx, releaseScheduledJobs, arg.LeaseOwner, arg.Ids, arg.Attempts)
if err != nil {
return nil, err
}
defer rows.Close()
var items []int64
for rows.Next() {
var id int64
if err := rows.Scan(&id); err != nil {
return nil, err
}
items = append(items, id)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const setScheduledJobTransactionTimeouts = `-- name: SetScheduledJobTransactionTimeouts :exec
SELECT
set_config('statement_timeout', $1::text, true),
set_config(
'idle_in_transaction_session_timeout',
$2::text,
true
)
`
type SetScheduledJobTransactionTimeoutsParams struct {
StatementTimeoutMs string
IdleTimeoutMs string
}
// Bounds a handler transaction on the server, local to the transaction.
// statement_timeout stops a slow statement; idle_in_transaction_session_timeout
// ends the session of a worker that froze or lost the network inside the
// handler, which releases the job row lock so the job can be reclaimed once
// its lease expires.
func (q *Queries) SetScheduledJobTransactionTimeouts(ctx context.Context, arg SetScheduledJobTransactionTimeoutsParams) error {
_, err := q.db.Exec(ctx, setScheduledJobTransactionTimeouts, arg.StatementTimeoutMs, arg.IdleTimeoutMs)
return err
}
const startScheduledJob = `-- name: StartScheduledJob :execrows
UPDATE scheduled_jobs
SET
lease_expires_at = $1,
started_at = $2,
updated_at = clock_timestamp()
WHERE
id = $3
AND status = 'running'
AND lease_owner = $4
AND attempts = $5
AND lease_expires_at > $2
`
type StartScheduledJobParams struct {
LeaseExpiresAt pgtype.Timestamptz
Now pgtype.Timestamptz
ID int64
LeaseOwner pgtype.UUID
Attempt int32
}
// Starts a claimed attempt right before its handler transaction: it renews
// the lease from now and records the start, committed on its own. It
// changes nothing when the lease already expired by now or no longer
// belongs to this attempt, so a job whose turn in the batch came too late is
// never started on a lease that another worker may take over. now is the
// application clock.
func (q *Queries) StartScheduledJob(ctx context.Context, arg StartScheduledJobParams) (int64, error) {
result, err := q.db.Exec(ctx, startScheduledJob,
arg.LeaseExpiresAt,
arg.Now,
arg.ID,
arg.LeaseOwner,
arg.Attempt,
)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
@@ -31,6 +31,15 @@ type Metrics struct {
// consumerFailures counts every failed consumer operation, including the
// last handler attempt before a dead letter, by the stage that failed.
consumerFailures *client.CounterVec
// scheduledJobs counts claimed scheduled jobs by kind and outcome:
// done, retry, dead, lease_lost, or released.
scheduledJobs *client.CounterVec
// scheduledJobsDue, scheduledJobsOldestDueAge, and scheduledJobsDead
// describe the waiting and dead jobs. Every backend instance reports the
// same database-wide values, so dashboards aggregate them with max.
scheduledJobsDue client.Gauge
scheduledJobsOldestDueAge client.Gauge
scheduledJobsDead client.Gauge
}
// Outbox relay outcome label values.
@@ -44,6 +53,8 @@ const (
var (
consumerOutcomes = []string{"applied", "duplicate", "ignored", "dead_lettered"}
consumerStages = []string{"handler", "store", "poll", "commit"}
// scheduledJobOutcomes mirror the jobrunner outcome constants.
scheduledJobOutcomes = []string{"done", "retry", "dead", "lease_lost", "released"}
)
func New() *Metrics {
@@ -77,11 +88,28 @@ func New() *Metrics {
Name: "lincodex_event_consumer_failures_total",
Help: "Failed event consumer operations, including the last handler attempt before a dead letter, by stage: handler, store, poll, or commit.",
}, []string{"consumer", "stage"})
scheduledJobs := client.NewCounterVec(client.CounterOpts{
Name: "lincodex_scheduled_jobs_total",
Help: "Claimed scheduled jobs by kind and outcome: done, retry, dead, lease_lost, or released.",
}, []string{"kind", "outcome"})
scheduledJobsDue := client.NewGauge(client.GaugeOpts{
Name: "lincodex_scheduled_jobs_due",
Help: "Scheduled jobs that fell due and wait for a worker, at the last backlog read.",
})
scheduledJobsOldestDueAge := client.NewGauge(client.GaugeOpts{
Name: "lincodex_scheduled_jobs_oldest_due_age_seconds",
Help: "How long the earliest waiting scheduled job has been due, by the application clock, at the last backlog read; 0 without due jobs.",
})
scheduledJobsDead := client.NewGauge(client.GaugeOpts{
Name: "lincodex_scheduled_jobs_dead",
Help: "Dead scheduled jobs, which need an operator, at the last backlog read.",
})
registry.MustRegister(
collectors.NewGoCollector(),
collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
requests, latency, relayEvents, relayPending, relayOldestAge,
consumerRecords, consumerFailures,
scheduledJobs, scheduledJobsDue, scheduledJobsOldestDueAge, scheduledJobsDead,
)
// Expose both series from the start so rate queries see zero, not absence.
relayEvents.WithLabelValues(relayOutcomePublished)
@@ -96,9 +124,34 @@ func New() *Metrics {
consumerRecords: consumerRecords,
consumerFailures: consumerFailures,
scheduledJobs: scheduledJobs,
scheduledJobsDue: scheduledJobsDue,
scheduledJobsOldestDueAge: scheduledJobsOldestDueAge,
scheduledJobsDead: scheduledJobsDead,
}
}
// PrepareScheduledJobKind exposes every outcome series of kind at zero, so
// an alert on the first dead job sees an increase instead of a new series.
func (metrics *Metrics) PrepareScheduledJobKind(kind string) {
for _, outcome := range scheduledJobOutcomes {
metrics.scheduledJobs.WithLabelValues(kind, outcome)
}
}
// ObserveScheduledJob counts the outcome of one claimed job.
func (metrics *Metrics) ObserveScheduledJob(kind, outcome string) {
metrics.scheduledJobs.WithLabelValues(kind, outcome).Inc()
}
// ObserveScheduledJobBacklog records the latest backlog read.
func (metrics *Metrics) ObserveScheduledJobBacklog(backlog outbound.JobBacklog) {
metrics.scheduledJobsDue.Set(float64(backlog.Due))
metrics.scheduledJobsOldestDueAge.Set(backlog.OldestDueAge.Seconds())
metrics.scheduledJobsDead.Set(float64(backlog.Dead))
}
// PrepareEventConsumer exposes every series of consumer at zero, so an alert
// on the first dead letter sees an increase instead of a new series.
func (metrics *Metrics) PrepareEventConsumer(consumer string) {
@@ -86,3 +86,27 @@ func TestMetricsHandlerExposesEventConsumerOutcomes(t *testing.T) {
}
}
}
func TestMetricsHandlerExposesScheduledJobs(t *testing.T) {
metrics := New()
metrics.PrepareScheduledJobKind("invitation.response_deadline")
metrics.ObserveScheduledJob("invitation.response_deadline", "done")
metrics.ObserveScheduledJob("invitation.response_deadline", "done")
metrics.ObserveScheduledJobBacklog(outbound.JobBacklog{Due: 7, OldestDueAge: 2 * time.Minute, Dead: 1})
response := httptest.NewRecorder()
metrics.Handler().ServeHTTP(response, httptest.NewRequest("GET", "/metrics", nil))
body := response.Body.String()
for _, want := range []string{
`lincodex_scheduled_jobs_total{kind="invitation.response_deadline",outcome="done"} 2`,
// Prepared at zero, so an alert sees the first dead job as an increase.
`lincodex_scheduled_jobs_total{kind="invitation.response_deadline",outcome="dead"} 0`,
"lincodex_scheduled_jobs_due 7",
"lincodex_scheduled_jobs_oldest_due_age_seconds 120",
"lincodex_scheduled_jobs_dead 1",
} {
if !strings.Contains(body, want) {
t.Fatalf("metrics output is missing %s:\n%s", want, body)
}
}
}