feat(jobs): add durable due-time job runner with leases
This commit is contained in:
1 parent
7e80c8ad2a
commit
008254e44a
39 files changed
+4909
-43
No files matched your search
@@ -0,0 +1,127 @@
|
||||
-- +goose Up
|
||||
-- Durable jobs that run when they fall due, such as a response deadline. A
|
||||
-- usecase schedules a job in its own business transaction, so the job exists
|
||||
-- exactly when the business change committed. The scheduled job worker
|
||||
-- claims due jobs under a lease and runs each handler in one transaction
|
||||
-- with the completion of its job, so a database-only effect happens once.
|
||||
--
|
||||
-- Every due and lease time comes from the application clock, never from the
|
||||
-- database clock, so tests can move time without waiting. created_at and
|
||||
-- updated_at are informational database times for operators.
|
||||
--
|
||||
-- The payload holds identifiers only. Rows are kept after they finish: the
|
||||
-- (kind, dedup_key) pair stays reserved, so a repeated schedule of a job
|
||||
-- that already ran or was canceled does nothing. Retention of finished rows
|
||||
-- is not implemented yet.
|
||||
CREATE TABLE scheduled_jobs (
|
||||
id bigint GENERATED ALWAYS AS IDENTITY,
|
||||
-- Handler name from the code, for example "invitation.response_deadline".
|
||||
kind text NOT NULL,
|
||||
-- Caller key of the logical job within its kind, for example an
|
||||
-- aggregate ID. It must not contain personal data.
|
||||
dedup_key text NOT NULL,
|
||||
-- Small JSON object of identifiers for the handler.
|
||||
payload jsonb NOT NULL,
|
||||
-- When the job falls due: the deadline it stands for. It never changes,
|
||||
-- so a handler that runs late or on a retry still sees the deadline.
|
||||
due_at timestamptz NOT NULL,
|
||||
-- When a worker may claim the job next: due_at at first, then the
|
||||
-- retry time after a failed attempt.
|
||||
available_at timestamptz NOT NULL,
|
||||
-- pending: waits for available_at and no attempt failed yet;
|
||||
-- failed: an attempt failed and the job waits for its retry at
|
||||
-- available_at;
|
||||
-- running: claimed under a lease; done, dead, cancelled: final.
|
||||
status text NOT NULL,
|
||||
-- Attempts counted so far, including a running one. A claim counts its
|
||||
-- attempt before the handler runs, so a job that crashes the process
|
||||
-- cannot loop forever; a claim whose attempt never started is reused
|
||||
-- by the next claim instead of counted twice.
|
||||
attempts integer NOT NULL,
|
||||
-- NULL means the worker default, JOBS_MAX_ATTEMPTS.
|
||||
max_attempts integer,
|
||||
-- Random ID of the worker instance that holds the lease.
|
||||
lease_owner uuid,
|
||||
lease_expires_at timestamptz,
|
||||
-- When the worker started the handler of the running attempt and
|
||||
-- renewed its lease, by the application clock. NULL while the job is
|
||||
-- claimed but not started, and whenever it is not running.
|
||||
started_at timestamptz,
|
||||
-- Bounded cause of the last failed or abandoned attempt; never text
|
||||
-- from the handler.
|
||||
last_error_class text,
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
updated_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
CONSTRAINT scheduled_jobs_pkey PRIMARY KEY (id),
|
||||
CONSTRAINT scheduled_jobs_kind_dedup_key_key UNIQUE (kind, dedup_key),
|
||||
CONSTRAINT scheduled_jobs_kind_format CHECK (
|
||||
char_length(kind) <= 64
|
||||
AND kind ~ '^[a-z][a-z0-9_]*(\.[a-z][a-z0-9_]*)*$'
|
||||
),
|
||||
CONSTRAINT scheduled_jobs_dedup_key_format CHECK (
|
||||
char_length(dedup_key) <= 128
|
||||
AND dedup_key ~ '^[A-Za-z0-9][A-Za-z0-9._:-]*$'
|
||||
),
|
||||
-- The application allows 2 KiB of compact JSON; the jsonb text form
|
||||
-- adds spaces, so this backstop is wider.
|
||||
CONSTRAINT scheduled_jobs_payload_object CHECK (
|
||||
jsonb_typeof(payload) = 'object'
|
||||
AND octet_length(payload::text) <= 4096
|
||||
),
|
||||
CONSTRAINT scheduled_jobs_status_known CHECK (
|
||||
status IN ('pending', 'failed', 'running', 'done', 'dead', 'cancelled')
|
||||
),
|
||||
CONSTRAINT scheduled_jobs_attempts_bounded CHECK (
|
||||
attempts >= 0
|
||||
AND (max_attempts IS NULL OR max_attempts BETWEEN 1 AND 100)
|
||||
),
|
||||
-- Only a running job holds a lease, and a running job always does.
|
||||
CONSTRAINT scheduled_jobs_lease_when_running CHECK (
|
||||
(status = 'running')
|
||||
= (lease_owner IS NOT NULL AND lease_expires_at IS NOT NULL)
|
||||
AND (lease_owner IS NULL) = (lease_expires_at IS NULL)
|
||||
),
|
||||
CONSTRAINT scheduled_jobs_running_counted CHECK (
|
||||
status <> 'running' OR attempts > 0
|
||||
),
|
||||
CONSTRAINT scheduled_jobs_started_when_running CHECK (
|
||||
status = 'running' OR started_at IS NULL
|
||||
),
|
||||
-- failed differs from pending only by the recorded cause, so an
|
||||
-- operator can tell a first wait from a retry.
|
||||
CONSTRAINT scheduled_jobs_failed_has_cause CHECK (
|
||||
(status <> 'pending' OR last_error_class IS NULL)
|
||||
AND (status <> 'failed' OR last_error_class IS NOT NULL)
|
||||
),
|
||||
CONSTRAINT scheduled_jobs_error_class_known CHECK (
|
||||
last_error_class IN (
|
||||
'handler_failed',
|
||||
'handler_rejected',
|
||||
'handler_panic',
|
||||
'timeout',
|
||||
'conflict',
|
||||
'effect_rejected',
|
||||
'lease_expired',
|
||||
'completion_conflict'
|
||||
)
|
||||
)
|
||||
);
|
||||
|
||||
-- Serves the claim of due jobs. It covers only waiting rows, so it stays
|
||||
-- small while finished rows accumulate.
|
||||
CREATE INDEX scheduled_jobs_available_idx
|
||||
ON scheduled_jobs (available_at, id)
|
||||
WHERE status IN ('pending', 'failed');
|
||||
|
||||
-- Serves the claim of running jobs whose lease expired.
|
||||
CREATE INDEX scheduled_jobs_lease_idx
|
||||
ON scheduled_jobs (lease_expires_at)
|
||||
WHERE status = 'running';
|
||||
|
||||
-- Serves the dead job gauge and operator queries; dead jobs are rare.
|
||||
CREATE INDEX scheduled_jobs_dead_idx
|
||||
ON scheduled_jobs (kind, updated_at)
|
||||
WHERE status = 'dead';
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE scheduled_jobs;
|
||||
@@ -0,0 +1,288 @@
|
||||
-- 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
|
||||
);
|
||||
Reference in new issue
Block a user