289 lines
10 KiB
SQL
289 lines
10 KiB
SQL
-- 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.
|
|
-- name: InsertScheduledJob :execrows
|
|
INSERT INTO scheduled_jobs (
|
|
kind,
|
|
dedup_key,
|
|
payload,
|
|
due_at,
|
|
available_at,
|
|
status,
|
|
attempts,
|
|
max_attempts
|
|
) VALUES (
|
|
sqlc.arg(kind),
|
|
sqlc.arg(dedup_key),
|
|
sqlc.arg(payload),
|
|
sqlc.arg(due_at),
|
|
sqlc.arg(due_at),
|
|
'pending',
|
|
0,
|
|
sqlc.narg(max_attempts)
|
|
)
|
|
ON CONFLICT (kind, dedup_key) DO NOTHING;
|
|
|
|
-- 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.
|
|
-- 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 = sqlc.arg(kind)
|
|
AND dedup_key = sqlc.arg(dedup_key)
|
|
AND status IN ('pending', 'failed', 'running');
|
|
|
|
-- 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.
|
|
-- 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,
|
|
sqlc.arg(default_max_attempts)::integer
|
|
)
|
|
) AS exhausted
|
|
FROM scheduled_jobs AS candidate
|
|
WHERE
|
|
candidate.kind = any(sqlc.arg(kinds)::text [])
|
|
AND (
|
|
(
|
|
candidate.status IN ('pending', 'failed')
|
|
AND candidate.available_at <= sqlc.arg(now)::timestamptz
|
|
)
|
|
OR (
|
|
candidate.status = 'running'
|
|
AND candidate.lease_expires_at <= sqlc.arg(now)::timestamptz
|
|
)
|
|
)
|
|
ORDER BY candidate.available_at, candidate.id
|
|
LIMIT sqlc.arg(batch_limit)
|
|
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 sqlc.arg(lease_owner)::uuid
|
|
END,
|
|
lease_expires_at = CASE
|
|
WHEN
|
|
candidates.exhausted
|
|
THEN NULL
|
|
ELSE sqlc.arg(lease_expires_at)::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, sqlc.arg(default_max_attempts)::integer
|
|
)::integer AS max_attempts,
|
|
candidates.exhausted;
|
|
|
|
-- 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.
|
|
-- name: StartScheduledJob :execrows
|
|
UPDATE scheduled_jobs
|
|
SET
|
|
lease_expires_at = sqlc.arg(lease_expires_at),
|
|
started_at = sqlc.arg(now),
|
|
updated_at = clock_timestamp()
|
|
WHERE
|
|
id = sqlc.arg(id)
|
|
AND status = 'running'
|
|
AND lease_owner = sqlc.arg(lease_owner)
|
|
AND attempts = sqlc.arg(attempt)
|
|
AND lease_expires_at > sqlc.arg(now);
|
|
|
|
-- 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.
|
|
-- name: LockClaimedScheduledJob :one
|
|
SELECT job.id
|
|
FROM scheduled_jobs AS job
|
|
WHERE
|
|
job.id = sqlc.arg(id)
|
|
AND job.status = 'running'
|
|
AND job.lease_owner = sqlc.arg(lease_owner)
|
|
AND job.attempts = sqlc.arg(attempt)
|
|
FOR UPDATE;
|
|
|
|
-- 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.
|
|
-- 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 = sqlc.arg(id)
|
|
AND status = 'running'
|
|
AND lease_owner = sqlc.arg(lease_owner)
|
|
AND attempts = sqlc.arg(attempt);
|
|
|
|
-- 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.
|
|
-- name: FailScheduledJob :execrows
|
|
UPDATE scheduled_jobs
|
|
SET
|
|
status = sqlc.arg(status),
|
|
available_at = coalesce(sqlc.narg(retry_at), available_at),
|
|
last_error_class = sqlc.arg(error_class),
|
|
lease_owner = NULL,
|
|
lease_expires_at = NULL,
|
|
started_at = NULL,
|
|
updated_at = clock_timestamp()
|
|
WHERE
|
|
id = sqlc.arg(id)
|
|
AND status = 'running'
|
|
AND lease_owner = sqlc.arg(lease_owner)
|
|
AND attempts = sqlc.arg(attempt);
|
|
|
|
-- 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.
|
|
-- 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(sqlc.arg(ids)::bigint []) AS id,
|
|
unnest(sqlc.arg(attempts)::integer []) AS attempt
|
|
) AS released
|
|
WHERE
|
|
job.id = released.id
|
|
AND job.attempts = released.attempt
|
|
AND job.status = 'running'
|
|
AND job.lease_owner = sqlc.arg(lease_owner)
|
|
RETURNING job.id;
|
|
|
|
-- 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.
|
|
-- name: GetScheduledJobStatus :one
|
|
SELECT job.status
|
|
FROM scheduled_jobs AS job
|
|
WHERE job.id = sqlc.arg(id);
|
|
|
|
-- 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.
|
|
-- name: GetScheduledJobBacklog :one
|
|
SELECT
|
|
(
|
|
SELECT count(*)
|
|
FROM scheduled_jobs AS due
|
|
WHERE
|
|
due.status IN ('pending', 'failed')
|
|
AND due.available_at <= sqlc.arg(now)::timestamptz
|
|
)::bigint AS due_jobs,
|
|
coalesce((
|
|
SELECT
|
|
extract(EPOCH FROM sqlc.arg(now)::timestamptz - oldest.available_at)
|
|
FROM scheduled_jobs AS oldest
|
|
WHERE
|
|
oldest.status IN ('pending', 'failed')
|
|
AND oldest.available_at <= sqlc.arg(now)::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;
|
|
|
|
-- 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.
|
|
-- name: SetScheduledJobTransactionTimeouts :exec
|
|
SELECT
|
|
set_config('statement_timeout', sqlc.arg(statement_timeout_ms)::text, true),
|
|
set_config(
|
|
'idle_in_transaction_session_timeout',
|
|
sqlc.arg(idle_timeout_ms)::text,
|
|
true
|
|
);
|