Skip to main content

axa_postgres_job_queue/
lib.rs

1//! A Postgres job queue, worker pool, and recurring schedules.
2//!
3//! Jobs live in one `axa_queue` table. Each job loop claims the ready job with the
4//! highest priority, oldest first, in a single statement using `FOR UPDATE SKIP
5//! LOCKED`, so two loops can never claim the same row and no broker is needed.
6//!
7//! ```no_run
8//! use std::time::Duration;
9//! use axa_postgres_job_queue::{NewJob, Queue, QueueOptions, Schedule};
10//! use tokio::sync::watch;
11//!
12//! # async fn example(uri: &str) -> axa_postgres_job_queue::Result<()> {
13//! let mut queue = Queue::connect(uri, QueueOptions::default()).await?;
14//! queue.handle("Report", |args| async move {
15//!     let id = args["id"].as_i64().ok_or("no id")?;
16//!     println!("report {id}");
17//!     Ok::<(), &str>(())
18//! });
19//! queue.limit("Report", 1); // at most one at a time in this process
20//! queue.schedule(Schedule::every(
21//!     "nightly-report",
22//!     Duration::from_hours(24),
23//!     NewJob::new("Report", serde_json::json!({ "id": 0 })),
24//! ));
25//!
26//! let id = queue
27//!     .enqueue_job(&NewJob::new("Report", serde_json::json!({ "id": 7 })).run_in(Duration::from_mins(5)))
28//!     .await?;
29//! let queue = std::sync::Arc::new(queue);
30//! let (stop, stopped) = watch::channel(false);
31//! let jobs = tokio::spawn(queue.clone().run(stopped));
32//! // ... serve until told to stop, then:
33//! let _ = stop.send(true);
34//! let _ = jobs.await;
35//! # let _ = id;
36//! # Ok(())
37//! # }
38//! ```
39//!
40//! A job moves from `queued` to `running` to `completed` or `failed`, with the
41//! failure text kept on the row. A queued job can be `cancelled`.
42//!
43//! # A person's acts
44//!
45//! A job row is state: it changes as the job runs, and retention deletes it. What a
46//! person does to a job is a record. [`cancel()`] stops a queued job, and [`retry()`]
47//! queues a failed one again or releases one from review. Each takes the caller's
48//! transaction and a `by` and `reason`, and appends the act to `axa_job_acts` in the
49//! same statement as the change, so the act, the change, and the service's own audit
50//! row commit together or not at all. There is no form that takes a pool. An act that
51//! does not apply, such as cancelling a running job, changes nothing and writes no
52//! act.
53//!
54//! ```no_run
55//! # async fn example(queue: &axa_postgres_job_queue::Queue, id: uuid::Uuid) -> axa_postgres_job_queue::Result<()> {
56//! let mut transaction = queue.pool().begin().await?;
57//! let cancelled = axa_postgres_job_queue::cancel(&mut transaction, id, "ops:alice", "customer_asked").await?;
58//! // ... write the service's own audit row on the same transaction ...
59//! transaction.commit().await?;
60//! # let _ = cancelled;
61//! # Ok(())
62//! # }
63//! ```
64//!
65//! `by` and `reason` are codes, not content: at most [`MAX_REASON_CHARS`] characters
66//! with no line breaks, and the table refuses anything else. `axa_job_acts` is only
67//! ever inserted into, and its triggers refuse `UPDATE`, `DELETE`, and `TRUNCATE`,
68//! whoever sends them. An act names its job by id, with no foreign key, so it outlives
69//! the job's row. [`Queue::acts`] reads a job's acts.
70//!
71//! # Attempts
72//!
73//! A job gets [`QueueOptions::max_attempts`] tries, unless it was queued with its
74//! own limit. The default is one, because a retry repeats the job's work, and only
75//! its author knows that is safe. Each retry waits twice as long as the last,
76//! starting from [`QueueOptions::retry_backoff`]. A job that panics counts as
77//! failed, and its loop carries on.
78//!
79//! # Lost jobs
80//!
81//! A running job reports in every [`QueueOptions::heartbeat_interval`], so a job
82//! may run for as long as it needs. One not heard from for
83//! [`QueueOptions::stale_minutes`] is assumed lost with its worker. If it has
84//! attempts left it is queued again, and otherwise it is marked failed, so a crash
85//! can never loop for ever. Each claim is identified by its attempt, so a run that
86//! was given up on cannot then overwrite the result of its replacement.
87//!
88//! # How many at once
89//!
90//! A process runs [`QueueOptions::workers`] job loops, so at most that many jobs at
91//! once. [`Queue::limit`] caps one job type below that, in this process. A limit is
92//! per process and not across replicas: three processes with a limit of one may run
93//! three. Work that must never overlap anywhere needs a lock of its own.
94//!
95//! # When a job runs
96//!
97//! [`NewJob::run_in`] and [`NewJob::run_at`] delay a job, and [`NewJob::priority`]
98//! puts it ahead of others that are ready. Delay is measured on the database's
99//! clock. A delayed job is claimed only once it is due, and then about as soon as a
100//! loop next polls.
101//!
102//! # Schedules
103//!
104//! A [`Schedule`] queues a job every interval. Each due time becomes one ordinary
105//! job, so its retries, status, limit, and recovery are the queue's. The schedule's
106//! row in `axa_schedule` is locked while its job is queued, in the same
107//! transaction, so across any number of replicas each due time is queued once.
108//!
109//! - **No drift.** The next time is counted from when the last was due, not from
110//!   when it ran.
111//! - **Missed times run once.** After every process was down, one job is queued,
112//!   and the schedule keeps its place: the next time is still a whole number of
113//!   intervals from the first.
114//! - **No stacking.** When the schedule's last job is still queued or running at a
115//!   due time, that time is skipped.
116//! - **The first time** is [`Schedule::first_at`], or as soon as the row is made.
117//!   It applies only when the row is made, so a schedule every 24 hours first due
118//!   at 02:00 runs at 02:00 each day, on the database's clock in UTC.
119//!
120//! [`Schedule::cron`] queues a job at the times a cron pattern names, such as
121//! `"0 2 * * *"` for 02:00 each day, in UTC on the database's clock. Its due times
122//! are the pattern's, so the same three rules hold: each due time is queued once, times
123//! missed while every process was down queue one job and the next time is the
124//! pattern's next after now, and a due time is skipped while the last job is queued or
125//! running. Its first time is the pattern's next after the row is made, and a changed
126//! pattern takes its next time from the new pattern.
127//!
128//! [`Queue::run`] ticks the schedules on every poll, and a service with no job
129//! loops can call [`Queue::tick_schedules`] itself. A schedule's job type must be
130//! handled by some worker, or its jobs wait. A schedule removed from code leaves a
131//! row that nothing reads.
132//!
133//! # One job at a time per key
134//!
135//! [`NewJob::unique`] names a key, such as `"sync:42"`, and while a job of the same
136//! name, tenant, and key is queued or running, queuing another adds nothing and
137//! answers the id of the one there. The first job's arguments, priority, and time
138//! stand. Once it completes, fails, is cancelled, or goes to review, the key is free
139//! again. The table holds to this with a unique index, so it holds across
140//! replicas and for a job queued in a transaction that has not yet committed: a
141//! second enqueue of the key waits for that transaction, and then either finds its
142//! job or queues its own. [`retry()`] leaves a failed job alone while another of its
143//! key is queued or running.
144//!
145//! # Queuing inside a transaction
146//!
147//! [`enqueue_on`] takes the caller's transaction, so a job and the record it is
148//! about commit together or not at all. [`Queue::enqueue`] uses its own
149//! connection, so a job queued that way can outlive a rollback.
150//!
151//! # Personal data
152//!
153//! The `args` column is plain JSONB, and finished rows are deleted after
154//! [`QueueOptions::retention_days`], so a job table does not become a second copy
155//! of the data. Prefer an id to a snapshot, and never put a secret in arguments.
156//! [`JobInfo`] leaves the arguments out. Its error text is whatever the job's
157//! error said, so it is for operators, and is not to be sent to a client. An act
158//! keeps no arguments either, and nothing logs its `by` or `reason`.
159
160use std::{
161    collections::{HashMap, HashSet},
162    fmt,
163    future::Future,
164    pin::Pin,
165    sync::Arc,
166    time::Duration,
167};
168
169use sqlx::{PgConnection, PgExecutor, PgPool, Postgres, Row, Transaction, postgres::PgPoolOptions};
170use tokio::sync::{OwnedSemaphorePermit, Semaphore, watch};
171use uuid::Uuid;
172
173pub use sqlx::types::chrono::{DateTime, Utc};
174
175/// What this crate's functions return.
176pub type Result<T, E = Error> = std::result::Result<T, E>;
177
178/// What went wrong.
179#[derive(Debug)]
180#[non_exhaustive]
181pub enum Error {
182    /// The database refused or could not be reached.
183    Database(sqlx::Error),
184    /// A job's arguments could not be encoded.
185    Encode(serde_json::Error),
186    /// A job failed, or the queue met something it cannot read.
187    Job(String),
188    /// Who or why, given for a person's act, or a job's unique key, is empty,
189    /// longer than [`MAX_REASON_CHARS`], or has a line break.
190    NotACode {
191        /// Which it was: `by`, `reason`, or `unique key`.
192        what: &'static str,
193    },
194    /// A job's tenant is not a tenant id: see [`is_tenant_id`].
195    NotATenant,
196}
197
198impl fmt::Display for Error {
199    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
200        match self {
201            Self::Database(error) => error.fmt(f),
202            Self::Encode(error) => error.fmt(f),
203            Self::Job(text) => write!(f, "worker error: {text}"),
204            Self::NotACode { what } => write!(
205                f,
206                "`{what}` must be 1 to {MAX_REASON_CHARS} characters with no line breaks"
207            ),
208            Self::NotATenant => f.write_str(
209                "a job's tenant must be 1 to 63 lower-case letters, digits, and hyphens, \
210                 not starting or ending with a hyphen",
211            ),
212        }
213    }
214}
215
216impl std::error::Error for Error {
217    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
218        match self {
219            Self::Database(error) => Some(error),
220            Self::Encode(error) => Some(error),
221            Self::Job(_) | Self::NotACode { .. } | Self::NotATenant => None,
222        }
223    }
224}
225
226impl From<sqlx::Error> for Error {
227    fn from(error: sqlx::Error) -> Self {
228        Self::Database(error)
229    }
230}
231
232impl From<serde_json::Error> for Error {
233    fn from(error: serde_json::Error) -> Self {
234        Self::Encode(error)
235    }
236}
237
238type JobFuture = Pin<Box<dyn Future<Output = Result<(), String>> + Send>>;
239type Handler = Arc<dyn Fn(Option<String>, serde_json::Value) -> JobFuture + Send + Sync>;
240
241const SETUP: &str = "CREATE TABLE IF NOT EXISTS axa_queue (
242    id UUID PRIMARY KEY,
243    name TEXT NOT NULL,
244    args JSONB NOT NULL,
245    status TEXT NOT NULL DEFAULT 'queued',
246    error TEXT,
247    run_at TIMESTAMPTZ NOT NULL DEFAULT now(),
248    started_at TIMESTAMPTZ,
249    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
250    updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
251)";
252const SETUP_INDEX: &str =
253    "CREATE INDEX IF NOT EXISTS axa_queue_ready ON axa_queue (run_at) WHERE status = 'queued'";
254/// Tables created by Axa 0.1.0 have no `attempts` column.
255const SETUP_ATTEMPTS: &str =
256    "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS attempts INTEGER NOT NULL DEFAULT 0";
257/// A job's own limit on tries, when it has one.
258const SETUP_MAX_ATTEMPTS: &str =
259    "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS max_attempts INTEGER";
260/// Higher runs first. Tables created before axa-postgres-job-queue have none.
261const SETUP_PRIORITY: &str =
262    "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS priority SMALLINT NOT NULL DEFAULT 0";
263/// A job's own time limit, when it has one.
264const SETUP_TIMEOUT: &str = "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS timeout_ms BIGINT";
265/// The tenant a job runs for, when it has one, as an auth crate's `Tenant` names it.
266const SETUP_TENANT: &str = "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS tenant TEXT
267    CONSTRAINT axa_queue_tenant_id CHECK (tenant ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$')";
268/// The key a job is unique by while it is queued or running, when it has one.
269const SETUP_UNIQUE_KEY: &str = "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS unique_key TEXT
270    CONSTRAINT axa_queue_unique_key_code
271    CHECK (length(unique_key) BETWEEN 1 AND 200 AND unique_key !~ '[[:cntrl:]]')";
272/// At most one job queued or running per name, tenant, and key.
273const SETUP_UNIQUE_INDEX: &str = "CREATE UNIQUE INDEX IF NOT EXISTS axa_queue_unique
274    ON axa_queue (name, (COALESCE(tenant, '')), unique_key)
275    WHERE unique_key IS NOT NULL AND status IN ('queued', 'running')";
276const SETUP_CLAIM_INDEX: &str = "CREATE INDEX IF NOT EXISTS axa_queue_claim
277    ON axa_queue (priority DESC, run_at) WHERE status = 'queued'";
278const SETUP_SCHEDULE: &str = "CREATE TABLE IF NOT EXISTS axa_schedule (
279    name TEXT PRIMARY KEY,
280    due_at TIMESTAMPTZ NOT NULL,
281    last_job UUID,
282    interval_ms BIGINT,
283    seen_at TIMESTAMPTZ NOT NULL DEFAULT now(),
284    archived_at TIMESTAMPTZ,
285    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
286    updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
287)";
288/// A person's acts on jobs. This table is a record (P-7): it is only ever inserted
289/// into, and its triggers refuse every change. A job row is state, and retention
290/// deletes it, so an act names its job by id with no foreign key, and keeps the job's
291/// name and attempts as they were when the act was done.
292/// A schedule's cron pattern, when it has one instead of an interval.
293const SETUP_SCHEDULE_CRON: &str = "ALTER TABLE axa_schedule ADD COLUMN IF NOT EXISTS cron TEXT";
294const SETUP_ACTS: &str = "CREATE TABLE IF NOT EXISTS axa_job_acts (
295    id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
296    job_id UUID NOT NULL,
297    job_name TEXT NOT NULL,
298    act TEXT NOT NULL CHECK (act IN ('cancelled', 'retried', 'released')),
299    attempts INTEGER NOT NULL,
300    by TEXT NOT NULL CHECK (length(by) BETWEEN 1 AND 200 AND by !~ '[[:cntrl:]]'),
301    reason TEXT NOT NULL CHECK (length(reason) BETWEEN 1 AND 200 AND reason !~ '[[:cntrl:]]'),
302    at TIMESTAMPTZ NOT NULL DEFAULT now()
303)";
304const SETUP_ACTS_INDEX: &str =
305    "CREATE INDEX IF NOT EXISTS axa_job_acts_job ON axa_job_acts (job_id, id)";
306/// Refuses whatever fired it, whoever sent it.
307const SETUP_ACTS_REFUSE: &str = "CREATE OR REPLACE FUNCTION axa_job_acts_refuse() RETURNS trigger
308LANGUAGE plpgsql AS $$
309BEGIN
310    RAISE EXCEPTION '% on % is refused: acts on jobs are only ever added to',
311        TG_OP, TG_TABLE_NAME;
312END
313$$";
314const SETUP_ACTS_ROWS: &str = "CREATE OR REPLACE TRIGGER axa_job_acts_refuse
315    BEFORE UPDATE OR DELETE ON axa_job_acts
316    FOR EACH ROW EXECUTE FUNCTION axa_job_acts_refuse()";
317const SETUP_ACTS_TRUNCATE: &str = "CREATE OR REPLACE TRIGGER axa_job_acts_refuse_truncate
318    BEFORE TRUNCATE ON axa_job_acts
319    FOR EACH STATEMENT EXECUTE FUNCTION axa_job_acts_refuse()";
320/// `ENABLE ALWAYS` keeps the refusals on when `session_replication_role` is
321/// `replica`, which otherwise turns triggers off.
322const SETUP_ACTS_ALWAYS: &str = "ALTER TABLE axa_job_acts
323    ENABLE ALWAYS TRIGGER axa_job_acts_refuse,
324    ENABLE ALWAYS TRIGGER axa_job_acts_refuse_truncate";
325/// The refusing triggers [`Queue::check`] requires, each set to fire always.
326const ACTS_TRIGGERS: [&str; 2] = ["axa_job_acts_refuse", "axa_job_acts_refuse_truncate"];
327const MISSING_TRIGGERS: &str = "SELECT want FROM unnest($1::text[]) AS want
328    WHERE NOT EXISTS (
329        SELECT 1 FROM pg_trigger t
330        WHERE t.tgrelid = to_regclass('axa_job_acts') AND t.tgname = want
331          AND t.tgenabled::text = 'A'
332    )";
333/// What a job queued for a tenant fails with when its handler takes no tenant.
334const NO_TENANT_HANDLER: &str =
335    "the job has a tenant, and its handler takes none: register it with handle_with_tenant";
336
337/// Advisory lock key for table setup: `axa_q` as bytes.
338const SETUP_LOCK: i64 = 0x0061_7861_5F71;
339
340const ENQUEUE: &str = "INSERT INTO axa_queue
341    (id, name, args, max_attempts, priority, run_at, timeout_ms, tenant)
342    VALUES ($1, $2, $3, $4, $5, COALESCE($6, now() + make_interval(secs => $7)), $8, $9)";
343/// Queue a job with a key, or find the one of its name, tenant, and key already
344/// queued or running. `DO UPDATE`, which changes nothing, rather than `DO NOTHING`,
345/// because it returns the job there even when it committed after this statement
346/// began, as a job queued in another transaction may have. `inserted` tells which.
347const ENQUEUE_UNIQUE: &str = "INSERT INTO axa_queue
348    (id, name, args, max_attempts, priority, run_at, timeout_ms, tenant, unique_key)
349    VALUES ($1, $2, $3, $4, $5, COALESCE($6, now() + make_interval(secs => $7)), $8, $9, $10)
350    ON CONFLICT (name, (COALESCE(tenant, '')), unique_key)
351        WHERE unique_key IS NOT NULL AND status IN ('queued', 'running')
352    DO UPDATE SET unique_key = EXCLUDED.unique_key
353    RETURNING id";
354const CLAIM: &str = "UPDATE axa_queue
355    SET status = 'running', started_at = now(), updated_at = now(), attempts = attempts + 1
356    WHERE id = (
357        SELECT id FROM axa_queue
358        WHERE status = 'queued' AND run_at <= now() AND name = ANY($1)
359        ORDER BY priority DESC, run_at
360        FOR UPDATE SKIP LOCKED
361        LIMIT 1
362    )
363    RETURNING id, name, args, attempts, max_attempts, timeout_ms, tenant";
364/// `attempts` identifies this run of the job, so a run that was given up on
365/// finds no row here and changes nothing.
366const HEARTBEAT: &str = "UPDATE axa_queue SET updated_at = now()
367    WHERE id = $1 AND attempts = $2 AND status = 'running'";
368const FINISH: &str = "UPDATE axa_queue SET status = $3, error = $4, updated_at = now()
369    WHERE id = $1 AND attempts = $2 AND status = 'running'";
370const RETRY: &str = "UPDATE axa_queue
371    SET status = 'queued', error = $3, started_at = NULL, updated_at = now(),
372        run_at = now() + make_interval(secs => $4)
373    WHERE id = $1 AND attempts = $2 AND status = 'running'";
374const REQUEUE_STALE: &str = "UPDATE axa_queue
375    SET status = 'queued', started_at = NULL, updated_at = now()
376    WHERE status = 'running' AND updated_at < now() - make_interval(mins => $1)
377      AND attempts < COALESCE(max_attempts, $2)";
378const FAIL_STALE: &str = "UPDATE axa_queue
379    SET status = 'failed', error = 'abandoned by its worker', updated_at = now()
380    WHERE status = 'running' AND updated_at < now() - make_interval(mins => $1)
381      AND attempts >= COALESCE(max_attempts, $2)";
382const PURGE: &str = "DELETE FROM axa_queue
383    WHERE status IN ('completed', 'failed', 'cancelled')
384      AND updated_at < now() - make_interval(days => $1)";
385const STATUS: &str = "SELECT id, name, status, attempts, max_attempts, priority, error,
386    timeout_ms, tenant, unique_key, run_at, started_at, created_at, updated_at FROM axa_queue WHERE id = $1";
387/// A run that lost its claim stops, and its job waits for a person. Another run
388/// may hold the row by now, and this stops that one too, at its next report.
389/// A row already completed is left alone.
390const MARK_LOST: &str =
391    "UPDATE axa_queue SET status = 'needs_review', error = $2, updated_at = now()
392    WHERE id = $1 AND status IN ('queued', 'running', 'failed')";
393/// Cancel a queued job and keep the act, in one statement. A job in any other state
394/// changes nothing and writes no act.
395const CANCEL: &str = "WITH changed AS (
396        UPDATE axa_queue SET status = 'cancelled', updated_at = now()
397        WHERE id = $1 AND status = 'queued'
398        RETURNING id, name, attempts
399    )
400    INSERT INTO axa_job_acts (job_id, job_name, act, attempts, by, reason)
401    SELECT id, name, 'cancelled', attempts, $2, $3 FROM changed";
402/// A retried job gets one more try. `attempts` keeps rising, as it identifies
403/// each run, so a run given up on still cannot write over the new one. The act is
404/// `released` for a job in review and `retried` for a failed one, and is kept in the
405/// same statement.
406const RETRY_FAILED: &str = "WITH target AS (
407        SELECT id, status FROM axa_queue
408        WHERE id = $1 AND status IN ('failed', 'needs_review')
409          AND NOT EXISTS (
410              SELECT 1 FROM axa_queue other
411              WHERE other.unique_key = axa_queue.unique_key
412                AND other.name = axa_queue.name
413                AND COALESCE(other.tenant, '') = COALESCE(axa_queue.tenant, '')
414                AND other.status IN ('queued', 'running')
415          )
416        FOR UPDATE
417    ), changed AS (
418        UPDATE axa_queue q
419        SET status = 'queued', run_at = now(), started_at = NULL, updated_at = now(),
420            max_attempts = q.attempts + 1
421        FROM target WHERE q.id = target.id
422        RETURNING q.id, q.name, q.attempts, target.status AS was
423    )
424    INSERT INTO axa_job_acts (job_id, job_name, act, attempts, by, reason)
425    SELECT id, name, CASE was WHEN 'needs_review' THEN 'released' ELSE 'retried' END,
426        attempts, $2, $3
427    FROM changed";
428const ACTS: &str = "SELECT id, job_id, job_name, act, attempts, by, reason, at
429    FROM axa_job_acts WHERE job_id = $1 ORDER BY id";
430const COUNTS: &str = "SELECT
431    count(*) FILTER (WHERE status = 'queued' AND run_at <= now()) AS ready,
432    count(*) FILTER (WHERE status = 'queued' AND run_at > now()) AS waiting,
433    count(*) FILTER (WHERE status = 'running') AS running,
434    count(*) FILTER (WHERE status = 'completed') AS completed,
435    count(*) FILTER (WHERE status = 'failed') AS failed,
436    count(*) FILTER (WHERE status = 'cancelled') AS cancelled,
437    count(*) FILTER (WHERE status = 'needs_review') AS needs_review,
438    EXTRACT(EPOCH FROM now() - min(run_at) FILTER (WHERE status = 'queued' AND run_at <= now()))::float8 AS oldest
439    FROM axa_queue";
440/// Make the row, or say this schedule is still in code: restore it if it was
441/// archived, and note the interval or pattern. A changed pattern takes its next time,
442/// `$5`, from the new pattern. `seen_at` moves at most once a minute, so a tick does
443/// not write each poll. A cron schedule's first time is `$2`, its next after now.
444const SCHEDULE_CREATE: &str = "INSERT INTO axa_schedule (name, due_at, interval_ms, cron)
445    VALUES ($1, COALESCE($2, now()), $3, $4)
446    ON CONFLICT (name) DO UPDATE
447    SET seen_at = now(), archived_at = NULL, interval_ms = EXCLUDED.interval_ms,
448        cron = EXCLUDED.cron,
449        due_at = CASE WHEN EXCLUDED.cron IS NOT NULL
450                       AND axa_schedule.cron IS DISTINCT FROM EXCLUDED.cron
451                  THEN EXCLUDED.due_at ELSE axa_schedule.due_at END
452    WHERE axa_schedule.archived_at IS NOT NULL
453       OR axa_schedule.interval_ms IS DISTINCT FROM EXCLUDED.interval_ms
454       OR axa_schedule.cron IS DISTINCT FROM EXCLUDED.cron
455       OR axa_schedule.seen_at < now() - interval '1 minute'";
456const SCHEDULE_LOCK: &str =
457    "SELECT last_job, due_at <= now() AS due, now() AS now FROM axa_schedule
458    WHERE name = $1 AND archived_at IS NULL FOR UPDATE SKIP LOCKED";
459/// Archive schedules no live process has in code. A row any process still ticks
460/// is seen within a minute, so one unseen for `stale_minutes` is in none, and an
461/// old replica in a rolling deploy keeps its schedules until it stops.
462const SCHEDULE_ARCHIVE: &str = "UPDATE axa_schedule SET archived_at = now(), updated_at = now()
463    WHERE archived_at IS NULL AND name <> ALL($1)
464      AND seen_at < now() - make_interval(mins => $2)";
465const SCHEDULES: &str = "SELECT s.name, s.interval_ms, s.cron, s.due_at, s.last_job, s.seen_at,
466    s.archived_at, s.created_at, q.status AS last_status, q.error AS last_error
467    FROM axa_schedule s LEFT JOIN axa_queue q ON q.id = s.last_job ORDER BY s.name";
468const SCHEDULE_BUSY: &str = "SELECT EXISTS (SELECT 1 FROM axa_queue
469    WHERE id = $1 AND status IN ('queued', 'running'))";
470/// The next due time after now, a whole number of intervals from the last, on the
471/// database's clock. One expression gives no drift, one catch-up, and no stacking.
472const SCHEDULE_ADVANCE: &str = "UPDATE axa_schedule
473    SET due_at = due_at + make_interval(secs => $2)
474            * (floor(EXTRACT(EPOCH FROM now() - due_at)::float8 / $2) + 1),
475        last_job = COALESCE($3, last_job), updated_at = now()
476    WHERE name = $1";
477/// A cron schedule's next due time, `$2`, the pattern's next after now.
478const SCHEDULE_ADVANCE_TO: &str = "UPDATE axa_schedule
479    SET due_at = $2, last_job = COALESCE($3, last_job), updated_at = now()
480    WHERE name = $1";
481
482/// The statements that make the queue's tables, in order, each safe to repeat. A
483/// service whose role may not change the schema runs these in a migration, and calls
484/// [`Queue::connect_existing`]. They need Postgres 14 or later.
485pub const SETUP_STATEMENTS: [&str; 18] = [
486    SETUP,
487    SETUP_ATTEMPTS,
488    SETUP_MAX_ATTEMPTS,
489    SETUP_INDEX,
490    SETUP_PRIORITY,
491    SETUP_TIMEOUT,
492    SETUP_TENANT,
493    SETUP_UNIQUE_KEY,
494    SETUP_UNIQUE_INDEX,
495    SETUP_CLAIM_INDEX,
496    SETUP_SCHEDULE,
497    SETUP_SCHEDULE_CRON,
498    SETUP_ACTS,
499    SETUP_ACTS_INDEX,
500    SETUP_ACTS_REFUSE,
501    SETUP_ACTS_ROWS,
502    SETUP_ACTS_TRUNCATE,
503    SETUP_ACTS_ALWAYS,
504];
505
506/// The longest `by` or `reason` kept on an act, in characters.
507pub const MAX_REASON_CHARS: usize = 200;
508
509/// The shortest gap between heartbeats, so a zero setting cannot spin.
510const MIN_HEARTBEAT: Duration = Duration::from_millis(20);
511
512/// The longest wait between attempts.
513const MAX_BACKOFF: Duration = Duration::from_hours(1);
514
515/// The longest error text kept on a row.
516const MAX_ERROR: usize = 1024;
517
518/// How long to wait before the attempt after `attempts`, doubling each time.
519#[must_use]
520pub fn backoff(base: Duration, attempts: i32) -> Duration {
521    let doublings = u32::try_from(attempts.saturating_sub(1))
522        .unwrap_or(0)
523        .min(16);
524    base.saturating_mul(1 << doublings).min(MAX_BACKOFF)
525}
526
527/// Cut `text` to at most [`MAX_ERROR`] bytes, on a character boundary.
528fn cut(mut text: String) -> String {
529    if text.len() > MAX_ERROR {
530        let mut end = MAX_ERROR;
531        while !text.is_char_boundary(end) {
532            end -= 1;
533        }
534        text.truncate(end);
535    }
536    text
537}
538
539fn millis(duration: Duration) -> i64 {
540    i64::try_from(duration.as_millis()).unwrap_or(i64::MAX)
541}
542
543fn from_millis(millis: i64) -> Duration {
544    Duration::from_millis(u64::try_from(millis).unwrap_or(0))
545}
546
547/// When a new job may first run.
548#[derive(Debug, Clone, Copy, PartialEq, Eq)]
549enum When {
550    Now,
551    At(DateTime<Utc>),
552    In(Duration),
553}
554
555/// A job to queue: its type, its arguments, and when and how it runs.
556#[derive(Clone)]
557pub struct NewJob {
558    name: String,
559    args: serde_json::Value,
560    max_attempts: Option<i32>,
561    priority: i16,
562    when: When,
563    timeout: Option<Duration>,
564    tenant: Option<String>,
565    unique_key: Option<String>,
566}
567
568impl fmt::Debug for NewJob {
569    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
570        f.debug_struct("NewJob")
571            .field("name", &self.name)
572            .field("max_attempts", &self.max_attempts)
573            .field("priority", &self.priority)
574            .field("when", &self.when)
575            .field("timeout", &self.timeout)
576            .field("tenant", &self.tenant)
577            .field("unique_key", &self.unique_key)
578            .finish_non_exhaustive()
579    }
580}
581
582impl NewJob {
583    /// A job for the handler named `name`, ready now, with the queue's limit on
584    /// tries and priority zero.
585    pub fn new(name: impl Into<String>, args: serde_json::Value) -> Self {
586        Self {
587            name: name.into(),
588            args,
589            max_attempts: None,
590            priority: 0,
591            when: When::Now,
592            timeout: None,
593            tenant: None,
594            unique_key: None,
595        }
596    }
597
598    /// Queue this job only if no job of its name, tenant, and `key` is queued or
599    /// running: otherwise queuing it adds nothing and answers the id of the one
600    /// there, whose arguments, priority, and time stand. The key is a code, at most
601    /// [`MAX_REASON_CHARS`] characters with no line breaks, such as `"sync:42"`, and
602    /// is kept on the job's row, so it holds no secret or personal data. Enqueuing
603    /// refuses any other key with [`Error::NotACode`].
604    #[must_use]
605    pub fn unique(mut self, key: impl Into<String>) -> Self {
606        self.unique_key = Some(key.into());
607        self
608    }
609
610    /// Run this job for `tenant`, the id an auth crate's `Tenant` gives, which its
611    /// handler receives beside the arguments, so that it can open its own tenant
612    /// transaction. Only a handler registered with [`Queue::handle_with_tenant`] runs
613    /// it. Enqueuing refuses an id that is not a tenant id, with
614    /// [`Error::NotATenant`].
615    #[must_use]
616    pub fn tenant(mut self, tenant: impl Into<String>) -> Self {
617        self.tenant = Some(tenant.into());
618        self
619    }
620
621    /// Stop a run of this job past `limit`, and count it as failed with the reason.
622    /// A job has no time limit unless it is given one.
623    #[must_use]
624    pub const fn timeout(mut self, limit: Duration) -> Self {
625        self.timeout = Some(limit);
626        self
627    }
628
629    /// Tries this job gets, including the first, or the queue's when `None`.
630    #[must_use]
631    pub const fn max_attempts(mut self, max_attempts: Option<i32>) -> Self {
632        self.max_attempts = max_attempts;
633        self
634    }
635
636    /// Run ahead of ready jobs with a lower priority. Zero by default, and may be
637    /// negative.
638    #[must_use]
639    pub const fn priority(mut self, priority: i16) -> Self {
640        self.priority = priority;
641        self
642    }
643
644    /// Run no sooner than `delay` from now, on the database's clock.
645    #[must_use]
646    pub const fn run_in(mut self, delay: Duration) -> Self {
647        self.when = When::In(delay);
648        self
649    }
650
651    /// Run no sooner than `at`.
652    #[must_use]
653    pub const fn run_at(mut self, at: DateTime<Utc>) -> Self {
654        self.when = When::At(at);
655        self
656    }
657
658    /// The handler this job is for.
659    #[must_use]
660    pub fn name(&self) -> &str {
661        &self.name
662    }
663
664    /// The tenant this job runs for, if any.
665    #[must_use]
666    pub fn tenant_id(&self) -> Option<&str> {
667        self.tenant.as_deref()
668    }
669
670    /// The key this job is unique by, if any.
671    #[must_use]
672    pub fn unique_key(&self) -> Option<&str> {
673        self.unique_key.as_deref()
674    }
675}
676
677/// The longest tenant id, which a DNS label also allows.
678pub const MAX_TENANT_ID_LEN: usize = 63;
679
680/// Whether `id` is a tenant id: lower-case ASCII letters, digits, and hyphens, not
681/// starting or ending with a hyphen, from 1 to 63 characters, as a DNS label is, and as
682/// the auth crates' `Tenant` holds. The table's check holds to the same rule.
683#[must_use]
684pub fn is_tenant_id(id: &str) -> bool {
685    (1..=MAX_TENANT_ID_LEN).contains(&id.len())
686        && !id.starts_with('-')
687        && !id.ends_with('-')
688        && id
689            .bytes()
690            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
691}
692
693/// Add `job` on `executor`, usually the caller's transaction, and return its id.
694/// The job then commits or rolls back with the transaction. A job with a
695/// [`NewJob::unique`] key that is already queued or running adds nothing, and the id
696/// is that job's.
697///
698/// # Errors
699///
700/// Fails on a database error, with [`Error::NotATenant`] for a tenant that is not a
701/// tenant id, and with [`Error::NotACode`] for a key that is not a code, before
702/// anything is written.
703pub async fn enqueue_on<'e, E: PgExecutor<'e>>(executor: E, job: &NewJob) -> Result<Uuid> {
704    if job
705        .tenant
706        .as_deref()
707        .is_some_and(|tenant| !is_tenant_id(tenant))
708    {
709        return Err(Error::NotATenant);
710    }
711    if let Some(key) = job.unique_key.as_deref() {
712        check_code(key, "unique key")?;
713    }
714    let id = Uuid::new_v4();
715    let (at, delay) = match job.when {
716        When::Now => (None, 0.0),
717        When::At(at) => (Some(at), 0.0),
718        When::In(delay) => (None, delay.as_secs_f64()),
719    };
720    let query = sqlx::query(if job.unique_key.is_some() {
721        ENQUEUE_UNIQUE
722    } else {
723        ENQUEUE
724    })
725    .bind(id)
726    .bind(&job.name)
727    .bind(&job.args)
728    .bind(job.max_attempts)
729    .bind(job.priority)
730    .bind(at)
731    .bind(delay)
732    .bind(job.timeout.map(millis))
733    .bind(job.tenant.as_deref());
734    if let Some(key) = job.unique_key.as_deref() {
735        Ok(query.bind(key).fetch_one(executor).await?.try_get("id")?)
736    } else {
737        query.execute(executor).await?;
738        Ok(id)
739    }
740}
741
742/// Add every job in `jobs` on `connection`, returning their ids in order. On a
743/// transaction they commit or roll back together; [`Queue::enqueue_all`] opens one.
744///
745/// # Errors
746///
747/// Fails on a database error, after which a transaction must be rolled back.
748pub async fn enqueue_all_on(connection: &mut PgConnection, jobs: &[NewJob]) -> Result<Vec<Uuid>> {
749    let mut ids = Vec::with_capacity(jobs.len());
750    for job in jobs {
751        ids.push(enqueue_on(&mut *connection, job).await?);
752    }
753    Ok(ids)
754}
755
756/// Refuse who or why for a person's act unless it is a code.
757fn check_code(text: &str, what: &'static str) -> Result<()> {
758    if text.is_empty()
759        || text.chars().count() > MAX_REASON_CHARS
760        || text.chars().any(char::is_control)
761    {
762        Err(Error::NotACode { what })
763    } else {
764        Ok(())
765    }
766}
767
768/// Cancel the job `id` if it is still queued, as an act of `by`, for `reason`, kept in
769/// `axa_job_acts` in the caller's transaction, so that the caller's own audit row
770/// commits with it. Answers whether it was cancelled. A job already claimed runs on:
771/// cancelling cannot stop work in progress. A job in any other state, or no such job,
772/// changes nothing and writes no act.
773///
774/// The job's row stays locked until the transaction ends, so keep it short.
775///
776/// # Errors
777///
778/// Fails on a database error, and with [`Error::NotACode`] when `by` or `reason` is
779/// empty, longer than [`MAX_REASON_CHARS`], or has a line break, before anything is
780/// written.
781pub async fn cancel(
782    transaction: &mut Transaction<'_, Postgres>,
783    id: Uuid,
784    by: &str,
785    reason: &str,
786) -> Result<bool> {
787    act(transaction, CANCEL, id, by, reason).await
788}
789
790/// Queue the job `id` again, now, for one more try, if it failed or waits for review,
791/// as an act of `by`, for `reason`, kept in `axa_job_acts` in the caller's
792/// transaction. The act is [`ActKind::Retried`] for a failed job and
793/// [`ActKind::Released`] for one in review. Answers whether it was queued again. A job
794/// in any other state, or no such job, changes nothing and writes no act. Its last
795/// error stays until it next runs.
796///
797/// # Errors
798///
799/// Fails on a database error, and with [`Error::NotACode`] when `by` or `reason` is
800/// empty, longer than [`MAX_REASON_CHARS`], or has a line break, before anything is
801/// written.
802pub async fn retry(
803    transaction: &mut Transaction<'_, Postgres>,
804    id: Uuid,
805    by: &str,
806    reason: &str,
807) -> Result<bool> {
808    act(transaction, RETRY_FAILED, id, by, reason).await
809}
810
811/// Run one act's statement, which changes the job and keeps the act together.
812async fn act(
813    transaction: &mut Transaction<'_, Postgres>,
814    statement: &'static str,
815    id: Uuid,
816    by: &str,
817    reason: &str,
818) -> Result<bool> {
819    check_code(by, "by")?;
820    check_code(reason, "reason")?;
821    let kept = sqlx::query(statement)
822        .bind(id)
823        .bind(by)
824        .bind(reason)
825        .execute(&mut **transaction)
826        .await?
827        .rows_affected();
828    Ok(kept == 1)
829}
830
831/// What a person did to a job.
832#[derive(Debug, Clone, Copy, PartialEq, Eq)]
833#[non_exhaustive]
834pub enum ActKind {
835    /// Cancelled it while it was queued.
836    Cancelled,
837    /// Queued it again after it failed.
838    Retried,
839    /// Released it from review, to run again.
840    Released,
841}
842
843impl ActKind {
844    fn parse(text: &str) -> Result<Self> {
845        match text {
846            "cancelled" => Ok(Self::Cancelled),
847            "retried" => Ok(Self::Retried),
848            "released" => Ok(Self::Released),
849            _ => Err(Error::Job("an act with an unknown kind".to_string())),
850        }
851    }
852}
853
854/// One act of a person on a job, as `axa_job_acts` keeps it. It outlives the job's
855/// row, which retention deletes.
856#[derive(Debug, Clone)]
857#[non_exhaustive]
858pub struct Act {
859    /// The act's row. It rises with each act.
860    pub id: i64,
861    /// The job it was done to.
862    pub job_id: Uuid,
863    /// The handler that job is for.
864    pub job_name: String,
865    /// What was done.
866    pub kind: ActKind,
867    /// The job's runs so far when it was done.
868    pub attempts: i32,
869    /// Who did it, as the service named them.
870    pub by: String,
871    /// Why, as a short code.
872    pub reason: String,
873    /// When, on the database's clock.
874    pub at: DateTime<Utc>,
875}
876
877/// Where a job is.
878#[derive(Debug, Clone, Copy, PartialEq, Eq)]
879pub enum JobState {
880    /// Waiting to be claimed, now or at its time.
881    Queued,
882    /// Claimed by a job loop.
883    Running,
884    /// Finished.
885    Completed,
886    /// Out of tries, or given up on.
887    Failed,
888    /// Cancelled before it ran.
889    Cancelled,
890    /// Its run lost its claim and was stopped, so it may have run in part or
891    /// twice. It is never retried by itself: a person looks, and calls
892    /// [`retry()`] to release it.
893    NeedsReview,
894}
895
896impl JobState {
897    fn parse(text: &str) -> Result<Self> {
898        match text {
899            "queued" => Ok(Self::Queued),
900            "running" => Ok(Self::Running),
901            "completed" => Ok(Self::Completed),
902            "failed" => Ok(Self::Failed),
903            "cancelled" => Ok(Self::Cancelled),
904            "needs_review" => Ok(Self::NeedsReview),
905            _ => Err(Error::Job("a job row with an unknown status".to_string())),
906        }
907    }
908}
909
910/// What the queue knows of one job. Its arguments are left out.
911#[derive(Debug, Clone)]
912#[non_exhaustive]
913pub struct JobInfo {
914    /// The job's id.
915    pub id: Uuid,
916    /// The handler it is for.
917    pub name: String,
918    /// Where it is.
919    pub state: JobState,
920    /// Runs so far, including one in progress.
921    pub attempts: i32,
922    /// Its own limit on tries, or `None` for the queue's.
923    pub max_attempts: Option<i32>,
924    /// Its priority.
925    pub priority: i16,
926    /// Its time limit, if it was given one.
927    pub timeout: Option<Duration>,
928    /// The tenant it runs for, if any.
929    pub tenant: Option<String>,
930    /// The key it is unique by while queued or running, if any.
931    pub unique_key: Option<String>,
932    /// The text of its last failure. For operators only: it is whatever the job's
933    /// error said.
934    pub error: Option<String>,
935    /// When it may run next, or last could.
936    pub run_at: DateTime<Utc>,
937    /// When its latest run started.
938    pub started_at: Option<DateTime<Utc>>,
939    /// When it was queued.
940    pub created_at: DateTime<Utc>,
941    /// When its row last changed.
942    pub updated_at: DateTime<Utc>,
943}
944
945/// How many jobs are in each state, for metrics.
946#[derive(Debug, Clone, Copy, Default, PartialEq)]
947#[non_exhaustive]
948pub struct Counts {
949    /// Queued and due.
950    pub ready: i64,
951    /// Queued for a later time.
952    pub waiting: i64,
953    /// Claimed and running.
954    pub running: i64,
955    /// Finished, and not yet deleted by retention.
956    pub completed: i64,
957    /// Failed, and not yet deleted by retention.
958    pub failed: i64,
959    /// Cancelled, and not yet deleted by retention.
960    pub cancelled: i64,
961    /// Stopped after losing their claim, waiting for a person. Never deleted by
962    /// retention.
963    pub needs_review: i64,
964    /// Seconds the oldest ready job has waited, or zero. A rising value means jobs
965    /// are not being run.
966    pub oldest_ready_seconds: f64,
967}
968
969/// A job queued every interval, or at the times a cron pattern names. See
970/// [Schedules](crate#schedules).
971#[derive(Clone)]
972pub struct Schedule {
973    name: String,
974    times: Times,
975    first: Option<DateTime<Utc>>,
976    job: NewJob,
977}
978
979/// When a schedule is due.
980#[derive(Clone)]
981enum Times {
982    Every(Duration),
983    /// The parsed pattern, and the pattern as written, which `croner` would rewrite.
984    Cron(Box<croner::Cron>, String),
985}
986
987impl Times {
988    fn interval(&self) -> Option<Duration> {
989        match self {
990            Self::Every(interval) => Some(*interval),
991            Self::Cron(..) => None,
992        }
993    }
994
995    fn pattern(&self) -> Option<&str> {
996        match self {
997            Self::Every(_) => None,
998            Self::Cron(_, pattern) => Some(pattern),
999        }
1000    }
1001}
1002
1003/// The time after `now` a cron pattern names.
1004fn next_after(cron: &croner::Cron, now: DateTime<Utc>) -> Result<DateTime<Utc>> {
1005    cron.find_next_occurrence(&now, false)
1006        .map_err(|error| Error::Job(format!("the cron pattern has no next time: {error}")))
1007}
1008
1009impl fmt::Debug for Schedule {
1010    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1011        f.debug_struct("Schedule")
1012            .field("name", &self.name)
1013            .field("interval", &self.times.interval())
1014            .field("cron", &self.times.pattern())
1015            .field("first", &self.first)
1016            .field("job", &self.job)
1017            .finish()
1018    }
1019}
1020
1021impl Schedule {
1022    /// Queue `job` every `interval`, under the schedule name `name`. The name keys
1023    /// its row, so keep it stable across releases. A delay set on `job` is ignored.
1024    ///
1025    /// # Panics
1026    ///
1027    /// When the name is empty or over 200 characters, or the interval is under a
1028    /// second, as Axum panics on a bad route: these are mistakes in code, found at
1029    /// boot.
1030    pub fn every(name: impl Into<String>, interval: Duration, job: NewJob) -> Self {
1031        let name = checked_name(name.into());
1032        assert!(
1033            interval >= Duration::from_secs(1),
1034            "the schedule {name} needs an interval of at least a second"
1035        );
1036        Self {
1037            name,
1038            times: Times::Every(interval),
1039            first: None,
1040            job: NewJob {
1041                when: When::Now,
1042                ..job
1043            },
1044        }
1045    }
1046
1047    /// Queue `job` at each time the cron `pattern` names, in UTC on the database's
1048    /// clock, under the schedule name `name`. The pattern has five fields, minute to
1049    /// day of week, or six with seconds first, as `croner` reads them: `"0 2 * * *"` is
1050    /// 02:00 each day, and `"0 9 * * MON-FRI"` 09:00 each weekday. A delay set on `job`
1051    /// is ignored. The first time is the pattern's next after the row is made.
1052    ///
1053    /// # Panics
1054    ///
1055    /// When the name is empty or over 200 characters, or the pattern does not parse
1056    /// or names no time to come, as Axum panics on a bad route: these are mistakes in
1057    /// code, found at boot.
1058    pub fn cron(name: impl Into<String>, pattern: &str, job: NewJob) -> Self {
1059        let name = checked_name(name.into());
1060        let cron: croner::Cron = pattern
1061            .parse()
1062            .unwrap_or_else(|error| panic!("the schedule {name} has a bad cron pattern: {error}"));
1063        assert!(
1064            next_after(&cron, Utc::now()).is_ok(),
1065            "the cron pattern of the schedule {name} names no time to come"
1066        );
1067        Self {
1068            name,
1069            times: Times::Cron(Box::new(cron), pattern.to_string()),
1070            first: None,
1071            job: NewJob {
1072                when: When::Now,
1073                ..job
1074            },
1075        }
1076    }
1077
1078    /// The first due time, used only when the schedule's row is made. With an
1079    /// interval of 24 hours and a first time at 02:00 UTC, the job runs at 02:00
1080    /// each day. Without one, the first is as soon as the row is made. A cron
1081    /// schedule's first time is its pattern's, and it ignores this.
1082    #[must_use]
1083    pub const fn first_at(mut self, first: DateTime<Utc>) -> Self {
1084        self.first = Some(first);
1085        self
1086    }
1087
1088    /// The schedule's interval, or `None` for a cron schedule.
1089    #[must_use]
1090    pub fn interval(&self) -> Option<Duration> {
1091        self.times.interval()
1092    }
1093
1094    /// The schedule's cron pattern, or `None` for one every interval.
1095    #[must_use]
1096    pub fn cron_pattern(&self) -> Option<&str> {
1097        self.times.pattern()
1098    }
1099
1100    /// The schedule's name.
1101    #[must_use]
1102    pub fn name(&self) -> &str {
1103        &self.name
1104    }
1105}
1106
1107/// Refuse a schedule name that is empty or over 200 characters.
1108fn checked_name(name: String) -> String {
1109    assert!(
1110        !name.is_empty() && name.len() <= 200,
1111        "a schedule name must be 1 to 200 characters"
1112    );
1113    name
1114}
1115
1116/// What the table holds of one schedule.
1117#[derive(Debug, Clone)]
1118#[non_exhaustive]
1119pub struct ScheduleInfo {
1120    /// Its name.
1121    pub name: String,
1122    /// Its interval, as the code last had it, or `None` for a cron schedule.
1123    pub interval: Option<Duration>,
1124    /// Its cron pattern, as the code last had it, or `None` for one every interval.
1125    pub cron: Option<String>,
1126    /// When it is next due.
1127    pub due_at: DateTime<Utc>,
1128    /// The last job it queued.
1129    pub last_job: Option<Uuid>,
1130    /// That job's state, unless retention deleted it.
1131    pub last_state: Option<JobState>,
1132    /// That job's last failure text. For operators only.
1133    pub last_error: Option<String>,
1134    /// When a live process last had it in code, to within a minute.
1135    pub seen_at: DateTime<Utc>,
1136    /// When it was archived, as no live process had it in code. An archived
1137    /// schedule queues nothing, and a schedule of that name in code restores it.
1138    pub archived_at: Option<DateTime<Utc>>,
1139    /// When its row was made.
1140    pub created_at: DateTime<Utc>,
1141}
1142
1143/// Queue tuning.
1144#[derive(Debug, Clone)]
1145pub struct QueueOptions {
1146    /// Concurrent job loops, so the most jobs this process runs at once.
1147    pub workers: usize,
1148    /// Sleep between polls of an empty queue, and between schedule ticks.
1149    pub poll_interval: Duration,
1150    /// A running job not heard from for this many minutes is assumed lost with
1151    /// its worker.
1152    pub stale_minutes: i32,
1153    /// How often a running job reports in. Keep it well under `stale_minutes`.
1154    pub heartbeat_interval: Duration,
1155    /// Tries a job gets, including the first, unless it has its own limit. One
1156    /// means no retries.
1157    pub max_attempts: i32,
1158    /// The wait before the first retry.
1159    pub retry_backoff: Duration,
1160    /// Days to keep finished and cancelled rows.
1161    pub retention_days: i32,
1162    /// How often to recover stale jobs and delete old rows.
1163    pub maintenance_interval: Duration,
1164}
1165
1166impl Default for QueueOptions {
1167    fn default() -> Self {
1168        Self {
1169            workers: 2,
1170            poll_interval: Duration::from_secs(1),
1171            stale_minutes: 60,
1172            heartbeat_interval: Duration::from_mins(1),
1173            max_attempts: 1,
1174            retry_backoff: Duration::from_secs(30),
1175            retention_days: 7,
1176            maintenance_interval: Duration::from_mins(5),
1177        }
1178    }
1179}
1180
1181/// A Postgres-backed job queue.
1182pub struct Queue {
1183    pool: PgPool,
1184    handlers: HashMap<String, Handler>,
1185    limits: HashMap<String, Arc<Semaphore>>,
1186    schedules: Vec<Schedule>,
1187    options: QueueOptions,
1188}
1189
1190impl fmt::Debug for Queue {
1191    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1192        f.debug_struct("Queue")
1193            .field("handlers", &self.handlers.len())
1194            .field("limits", &self.limits.len())
1195            .field("schedules", &self.schedules.len())
1196            .field("options", &self.options)
1197            .finish_non_exhaustive()
1198    }
1199}
1200
1201/// A claimed job, as `run_one` holds it.
1202struct Claimed {
1203    id: Uuid,
1204    name: String,
1205    args: serde_json::Value,
1206    attempts: i32,
1207    limit: i32,
1208    timeout: Option<Duration>,
1209    tenant: Option<String>,
1210}
1211
1212/// How a run ended.
1213enum Outcome {
1214    /// The job answered, or failed, timed out, or panicked, with this text.
1215    Done(Result<(), String>),
1216    /// The run lost its claim and was stopped, for this reason.
1217    Lost(String),
1218}
1219
1220impl Queue {
1221    /// A queue on `pool`, checking and changing nothing. Call [`Queue::check`] at
1222    /// boot. Give the pool at least `workers + 2` connections.
1223    #[must_use]
1224    pub fn from_pool(pool: PgPool, options: QueueOptions) -> Self {
1225        Self {
1226            pool,
1227            handlers: HashMap::new(),
1228            limits: HashMap::new(),
1229            schedules: Vec::new(),
1230            options,
1231        }
1232    }
1233
1234    /// Open a pool sized for the job loops, without touching the schema.
1235    async fn open(uri: &str, options: QueueOptions) -> Result<Self> {
1236        let loops = u32::try_from(options.workers).unwrap_or(u32::MAX);
1237        let pool = PgPoolOptions::new()
1238            .max_connections(loops.saturating_add(2))
1239            .connect(uri)
1240            .await?;
1241        Ok(Self::from_pool(pool, options))
1242    }
1243
1244    /// Connect to tables that a migration made, and change no schema, for a database
1245    /// role that may not. A migration runs [`SETUP_STATEMENTS`].
1246    ///
1247    /// # Errors
1248    ///
1249    /// Fails when the database cannot be reached, a table is missing or out of date,
1250    /// or a trigger of `axa_job_acts` is missing or not set to fire always, so a
1251    /// service finds out at boot rather than at its first job. There is no way to run
1252    /// without the triggers.
1253    pub async fn connect_existing(uri: &str, options: QueueOptions) -> Result<Self> {
1254        let queue = Self::open(uri, options).await?;
1255        queue.check().await?;
1256        Ok(queue)
1257    }
1258
1259    /// Connect and create the tables if needed, which runs DDL at boot. Use
1260    /// [`Queue::connect_existing`] where a service's role may not.
1261    ///
1262    /// # Errors
1263    ///
1264    /// Fails when the database cannot be reached or the tables not created.
1265    pub async fn connect(uri: &str, options: QueueOptions) -> Result<Self> {
1266        let queue = Self::open(uri, options).await?;
1267        // `CREATE ... IF NOT EXISTS` is not safe against itself: two services
1268        // booting together can both pass the check and one then fails on a
1269        // catalog constraint. The lock makes setup run one at a time, and
1270        // ends with the transaction.
1271        let mut setup = queue.pool.begin().await?;
1272        sqlx::query("SELECT pg_advisory_xact_lock($1)")
1273            .bind(SETUP_LOCK)
1274            .execute(&mut *setup)
1275            .await?;
1276        for statement in SETUP_STATEMENTS {
1277            sqlx::query(statement).execute(&mut *setup).await?;
1278        }
1279        setup.commit().await?;
1280        Ok(queue)
1281    }
1282
1283    /// Check that the tables exist and are up to date, and that the triggers of
1284    /// `axa_job_acts` are there and set to fire always.
1285    ///
1286    /// # Errors
1287    ///
1288    /// Fails when the database cannot be reached, a table is missing or out of date,
1289    /// or a trigger is missing or turned off.
1290    pub async fn check(&self) -> Result<()> {
1291        sqlx::query(
1292            "SELECT attempts, max_attempts, priority, timeout_ms, tenant, unique_key FROM axa_queue LIMIT 0",
1293        )
1294        .execute(&self.pool)
1295        .await?;
1296        sqlx::query(
1297            "SELECT name, due_at, last_job, interval_ms, cron, seen_at, archived_at FROM axa_schedule LIMIT 0",
1298        )
1299            .execute(&self.pool)
1300            .await?;
1301        sqlx::query(
1302            "SELECT id, job_id, job_name, act, attempts, by, reason, at FROM axa_job_acts LIMIT 0",
1303        )
1304        .execute(&self.pool)
1305        .await?;
1306        let mut missing: Vec<String> = sqlx::query_scalar(MISSING_TRIGGERS)
1307            .bind(ACTS_TRIGGERS.to_vec())
1308            .fetch_all(&self.pool)
1309            .await?;
1310        let unique_index: bool =
1311            sqlx::query_scalar("SELECT to_regclass('axa_queue_unique') IS NOT NULL")
1312                .fetch_one(&self.pool)
1313                .await?;
1314        if !unique_index {
1315            missing.push("axa_queue_unique".to_string());
1316        }
1317        if missing.is_empty() {
1318            Ok(())
1319        } else {
1320            Err(Error::Database(sqlx::Error::Configuration(
1321                format!(
1322                    "the job queue is missing, or has turned off, {}: run SETUP_STATEMENTS",
1323                    missing.join(", ")
1324                )
1325                .into(),
1326            )))
1327        }
1328    }
1329
1330    /// The pool, for a service's own queries or [`enqueue_on`] outside a
1331    /// transaction.
1332    #[must_use]
1333    pub const fn pool(&self) -> &PgPool {
1334        &self.pool
1335    }
1336
1337    /// The options this queue runs with.
1338    #[must_use]
1339    pub const fn options(&self) -> &QueueOptions {
1340        &self.options
1341    }
1342
1343    /// Run `handler` for jobs named `name`. Its error text is kept on the job's
1344    /// row. Registering a name again replaces its handler.
1345    ///
1346    /// A job queued for a tenant, with [`NewJob::tenant`], is failed rather than run
1347    /// here, as this handler would run it with no tenant: register a handler that
1348    /// takes one with [`Queue::handle_with_tenant`].
1349    pub fn handle<F, Fut, E>(&mut self, name: impl Into<String>, handler: F)
1350    where
1351        F: Fn(serde_json::Value) -> Fut + Send + Sync + 'static,
1352        Fut: Future<Output = std::result::Result<(), E>> + Send + 'static,
1353        E: fmt::Display + 'static,
1354    {
1355        let handler = Arc::new(handler);
1356        let run: Handler = Arc::new(move |tenant, args| {
1357            if tenant.is_some() {
1358                return Box::pin(std::future::ready(Err(NO_TENANT_HANDLER.to_string())));
1359            }
1360            let job = handler(args);
1361            Box::pin(async move { job.await.map_err(|error| error.to_string()) })
1362        });
1363        self.handlers.insert(name.into(), run);
1364    }
1365
1366    /// Run `handler` for jobs named `name`, handing it the job's tenant, or `None` for
1367    /// a job queued with none, beside its arguments, so that it can open its own
1368    /// tenant transaction. Claiming stays fair across jobs, not tenants. Registering a
1369    /// name again replaces its handler.
1370    pub fn handle_with_tenant<F, Fut, E>(&mut self, name: impl Into<String>, handler: F)
1371    where
1372        F: Fn(Option<String>, serde_json::Value) -> Fut + Send + Sync + 'static,
1373        Fut: Future<Output = std::result::Result<(), E>> + Send + 'static,
1374        E: fmt::Display + 'static,
1375    {
1376        let handler = Arc::new(handler);
1377        let run: Handler = Arc::new(move |tenant, args| {
1378            let job = handler(tenant, args);
1379            Box::pin(async move { job.await.map_err(|error| error.to_string()) })
1380        });
1381        self.handlers.insert(name.into(), run);
1382    }
1383
1384    /// Run at most `jobs` jobs named `name` at once in this process, and at least
1385    /// one. Other jobs keep the remaining loops busy.
1386    pub fn limit(&mut self, name: impl Into<String>, jobs: usize) {
1387        self.limits
1388            .insert(name.into(), Arc::new(Semaphore::new(jobs.max(1))));
1389    }
1390
1391    /// Queue a job on every due time of `schedule`.
1392    ///
1393    /// # Panics
1394    ///
1395    /// When a schedule of that name was added already.
1396    pub fn schedule(&mut self, schedule: Schedule) {
1397        assert!(
1398            self.schedules.iter().all(|s| s.name != schedule.name),
1399            "the schedule {} was added twice",
1400            schedule.name
1401        );
1402        self.schedules.push(schedule);
1403    }
1404
1405    /// Add a job and return its id.
1406    ///
1407    /// # Errors
1408    ///
1409    /// Fails on a database error.
1410    pub async fn enqueue(&self, name: &str, args: serde_json::Value) -> Result<Uuid> {
1411        enqueue_on(&self.pool, &NewJob::new(name, args)).await
1412    }
1413
1414    /// Add a job with its own limit on tries, or the queue's when `None`.
1415    ///
1416    /// # Errors
1417    ///
1418    /// Fails on a database error.
1419    pub async fn enqueue_limited(
1420        &self,
1421        name: &str,
1422        args: serde_json::Value,
1423        max_attempts: Option<i32>,
1424    ) -> Result<Uuid> {
1425        enqueue_on(
1426            &self.pool,
1427            &NewJob::new(name, args).max_attempts(max_attempts),
1428        )
1429        .await
1430    }
1431
1432    /// Add `job` and return its id.
1433    ///
1434    /// # Errors
1435    ///
1436    /// Fails on a database error.
1437    pub async fn enqueue_job(&self, job: &NewJob) -> Result<Uuid> {
1438        enqueue_on(&self.pool, job).await
1439    }
1440
1441    /// Add every job in `jobs` in one transaction, so all are queued or none.
1442    ///
1443    /// # Errors
1444    ///
1445    /// Fails on a database error, and then none was queued.
1446    pub async fn enqueue_all(&self, jobs: &[NewJob]) -> Result<Vec<Uuid>> {
1447        let mut transaction = self.pool.begin().await?;
1448        let ids = enqueue_all_on(&mut transaction, jobs).await?;
1449        transaction.commit().await?;
1450        Ok(ids)
1451    }
1452
1453    /// What the queue knows of the job `id`, or `None` when there is no such job,
1454    /// as after retention deleted it.
1455    ///
1456    /// # Errors
1457    ///
1458    /// Fails on a database error.
1459    pub async fn job(&self, id: Uuid) -> Result<Option<JobInfo>> {
1460        let Some(row) = sqlx::query(STATUS)
1461            .bind(id)
1462            .fetch_optional(&self.pool)
1463            .await?
1464        else {
1465            return Ok(None);
1466        };
1467        Ok(Some(JobInfo {
1468            id: row.try_get("id")?,
1469            name: row.try_get("name")?,
1470            state: JobState::parse(row.try_get::<&str, _>("status")?)?,
1471            attempts: row.try_get("attempts")?,
1472            max_attempts: row.try_get("max_attempts")?,
1473            priority: row.try_get("priority")?,
1474            timeout: row
1475                .try_get::<Option<i64>, _>("timeout_ms")?
1476                .map(from_millis),
1477            tenant: row.try_get("tenant")?,
1478            unique_key: row.try_get("unique_key")?,
1479            error: row.try_get("error")?,
1480            run_at: row.try_get("run_at")?,
1481            started_at: row.try_get("started_at")?,
1482            created_at: row.try_get("created_at")?,
1483            updated_at: row.try_get("updated_at")?,
1484        }))
1485    }
1486
1487    /// Every act a person did to the job `id`, oldest first, for a service's own
1488    /// review screens. Acts are kept after retention deletes the job's row. A person
1489    /// acts with [`cancel()`] and [`retry()`], in the caller's transaction.
1490    ///
1491    /// # Errors
1492    ///
1493    /// Fails on a database error.
1494    pub async fn acts(&self, id: Uuid) -> Result<Vec<Act>> {
1495        let rows = sqlx::query(ACTS).bind(id).fetch_all(&self.pool).await?;
1496        rows.iter()
1497            .map(|row| {
1498                Ok(Act {
1499                    id: row.try_get("id")?,
1500                    job_id: row.try_get("job_id")?,
1501                    job_name: row.try_get("job_name")?,
1502                    kind: ActKind::parse(row.try_get::<&str, _>("act")?)?,
1503                    attempts: row.try_get("attempts")?,
1504                    by: row.try_get("by")?,
1505                    reason: row.try_get("reason")?,
1506                    at: row.try_get("at")?,
1507                })
1508            })
1509            .collect()
1510    }
1511
1512    /// How many jobs are in each state.
1513    ///
1514    /// # Errors
1515    ///
1516    /// Fails on a database error.
1517    pub async fn counts(&self) -> Result<Counts> {
1518        let row = sqlx::query(COUNTS).fetch_one(&self.pool).await?;
1519        Ok(Counts {
1520            ready: row.try_get("ready")?,
1521            waiting: row.try_get("waiting")?,
1522            running: row.try_get("running")?,
1523            completed: row.try_get("completed")?,
1524            failed: row.try_get("failed")?,
1525            cancelled: row.try_get("cancelled")?,
1526            needs_review: row.try_get("needs_review")?,
1527            oldest_ready_seconds: row.try_get::<Option<f64>, _>("oldest")?.unwrap_or(0.0),
1528        })
1529    }
1530
1531    /// Check the database connection.
1532    ///
1533    /// # Errors
1534    ///
1535    /// Fails when the database does not answer.
1536    pub async fn ping(&self) -> Result<()> {
1537        sqlx::query("SELECT 1").execute(&self.pool).await?;
1538        Ok(())
1539    }
1540
1541    /// Recover jobs abandoned by a worker that died: queue again those with
1542    /// attempts left and fail the rest, returning how many were queued again.
1543    ///
1544    /// # Errors
1545    ///
1546    /// Fails on a database error.
1547    pub async fn requeue_stale(&self) -> Result<u64> {
1548        sqlx::query(FAIL_STALE)
1549            .bind(self.options.stale_minutes)
1550            .bind(self.options.max_attempts)
1551            .execute(&self.pool)
1552            .await?;
1553        let result = sqlx::query(REQUEUE_STALE)
1554            .bind(self.options.stale_minutes)
1555            .bind(self.options.max_attempts)
1556            .execute(&self.pool)
1557            .await?;
1558        Ok(result.rows_affected())
1559    }
1560
1561    /// Delete finished and cancelled rows older than the retention period,
1562    /// returning how many went.
1563    ///
1564    /// # Errors
1565    ///
1566    /// Fails on a database error.
1567    pub async fn purge_finished(&self) -> Result<u64> {
1568        let result = sqlx::query(PURGE)
1569            .bind(self.options.retention_days)
1570            .execute(&self.pool)
1571            .await?;
1572        Ok(result.rows_affected())
1573    }
1574
1575    /// Queue a job for each schedule that is due, returning how many were queued.
1576    /// [`Queue::run`] calls this on every poll. Any number of processes may call it
1577    /// at once: each due time is queued once.
1578    ///
1579    /// # Errors
1580    ///
1581    /// Fails on a database error, which leaves that schedule due for the next tick.
1582    pub async fn tick_schedules(&self) -> Result<usize> {
1583        let mut queued = 0;
1584        for schedule in &self.schedules {
1585            if self.tick(schedule).await? {
1586                queued += 1;
1587            }
1588        }
1589        Ok(queued)
1590    }
1591
1592    /// One schedule's tick, returning whether it queued a job.
1593    async fn tick(&self, schedule: &Schedule) -> Result<bool> {
1594        // Outside the transaction: an upsert locks the row it meets, and replicas
1595        // would then wait on each other instead of skipping.
1596        let first = match &schedule.times {
1597            Times::Every(_) => schedule.first,
1598            Times::Cron(cron, _) => {
1599                let now: DateTime<Utc> = sqlx::query_scalar("SELECT now()")
1600                    .fetch_one(&self.pool)
1601                    .await?;
1602                Some(next_after(cron, now)?)
1603            }
1604        };
1605        sqlx::query(SCHEDULE_CREATE)
1606            .bind(&schedule.name)
1607            .bind(first)
1608            .bind(schedule.times.interval().map(millis))
1609            .bind(schedule.times.pattern())
1610            .execute(&self.pool)
1611            .await?;
1612        let mut transaction = self.pool.begin().await?;
1613        // Another process holding the row is queuing this time already.
1614        let Some(row) = sqlx::query(SCHEDULE_LOCK)
1615            .bind(&schedule.name)
1616            .fetch_optional(&mut *transaction)
1617            .await?
1618        else {
1619            return Ok(false);
1620        };
1621        if !row.try_get::<bool, _>("due")? {
1622            transaction.commit().await?;
1623            return Ok(false);
1624        }
1625        let busy = match row.try_get::<Option<Uuid>, _>("last_job")? {
1626            Some(last) => {
1627                sqlx::query_scalar::<_, bool>(SCHEDULE_BUSY)
1628                    .bind(last)
1629                    .fetch_one(&mut *transaction)
1630                    .await?
1631            }
1632            None => false,
1633        };
1634        let job = if busy {
1635            tracing::info!(schedule = %schedule.name, "schedule skipped, its last job has not finished");
1636            None
1637        } else {
1638            Some(enqueue_on(&mut *transaction, &schedule.job).await?)
1639        };
1640        match &schedule.times {
1641            Times::Every(interval) => {
1642                sqlx::query(SCHEDULE_ADVANCE)
1643                    .bind(&schedule.name)
1644                    .bind(interval.as_secs_f64())
1645                    .bind(job)
1646                    .execute(&mut *transaction)
1647                    .await?;
1648            }
1649            Times::Cron(cron, _) => {
1650                sqlx::query(SCHEDULE_ADVANCE_TO)
1651                    .bind(&schedule.name)
1652                    .bind(next_after(cron, row.try_get("now")?)?)
1653                    .bind(job)
1654                    .execute(&mut *transaction)
1655                    .await?;
1656            }
1657        }
1658        transaction.commit().await?;
1659        if job.is_some() {
1660            tracing::debug!(schedule = %schedule.name, "schedule queued its job");
1661        }
1662        Ok(job.is_some())
1663    }
1664
1665    /// Archive the schedules that no live process has in code, returning how many
1666    /// were archived. Rows are kept, for audit. Housekeeping runs this.
1667    ///
1668    /// # Errors
1669    ///
1670    /// Fails on a database error.
1671    pub async fn archive_schedules(&self) -> Result<u64> {
1672        let names: Vec<&str> = self.schedules.iter().map(|s| s.name.as_str()).collect();
1673        let result = sqlx::query(SCHEDULE_ARCHIVE)
1674            .bind(&names)
1675            .bind(self.options.stale_minutes)
1676            .execute(&self.pool)
1677            .await?;
1678        Ok(result.rows_affected())
1679    }
1680
1681    /// Every schedule the table holds, archived or not, with its last job's state.
1682    ///
1683    /// # Errors
1684    ///
1685    /// Fails on a database error.
1686    pub async fn schedules(&self) -> Result<Vec<ScheduleInfo>> {
1687        let rows = sqlx::query(SCHEDULES).fetch_all(&self.pool).await?;
1688        rows.iter()
1689            .map(|row| {
1690                Ok(ScheduleInfo {
1691                    name: row.try_get("name")?,
1692                    interval: row
1693                        .try_get::<Option<i64>, _>("interval_ms")?
1694                        .map(from_millis),
1695                    cron: row.try_get("cron")?,
1696                    due_at: row.try_get("due_at")?,
1697                    last_job: row.try_get("last_job")?,
1698                    last_state: row
1699                        .try_get::<Option<&str>, _>("last_status")?
1700                        .map(JobState::parse)
1701                        .transpose()?,
1702                    last_error: row.try_get("last_error")?,
1703                    seen_at: row.try_get("seen_at")?,
1704                    archived_at: row.try_get("archived_at")?,
1705                    created_at: row.try_get("created_at")?,
1706                })
1707            })
1708            .collect()
1709    }
1710
1711    /// One round of housekeeping. Failures are logged, because the next round
1712    /// can try again.
1713    async fn maintain(&self) {
1714        match self.archive_schedules().await {
1715            Ok(0) => {}
1716            Ok(archived) => tracing::info!(archived, "archived schedules no longer in code"),
1717            Err(error) => tracing::error!(%error, "could not archive schedules"),
1718        }
1719        if let Err(error) = self.requeue_stale().await {
1720            tracing::error!(%error, "could not recover stale jobs");
1721        }
1722        if let Err(error) = self.purge_finished().await {
1723            tracing::error!(%error, "could not delete old jobs");
1724        }
1725    }
1726
1727    /// Run `job` to its end in its own task, reporting in as it goes, so a panic
1728    /// stops only the job. The job is stopped when its time limit passes, when its
1729    /// claim is found taken, or when this future is dropped.
1730    async fn supervise(&self, job: JobFuture, claim: &Claimed) -> Outcome {
1731        let mut job = AbortOnDrop(tokio::spawn(job));
1732        let every = self.options.heartbeat_interval.max(MIN_HEARTBEAT);
1733        // Not heard from for this long, a run is taken for lost by any worker.
1734        let stale =
1735            Duration::from_secs(u64::try_from(self.options.stale_minutes).unwrap_or(0) * 60);
1736        let mut last_heard = tokio::time::Instant::now();
1737        let limit = claim
1738            .timeout
1739            .map(|timeout| tokio::time::Instant::now() + timeout);
1740        let deadline = async {
1741            match limit {
1742                Some(at) => tokio::time::sleep_until(at).await,
1743                None => std::future::pending().await,
1744            }
1745        };
1746        tokio::pin!(deadline);
1747        loop {
1748            tokio::select! {
1749                finished = &mut job.0 => {
1750                    return Outcome::Done(finished.unwrap_or_else(|_| {
1751                        Err(Error::Job("the job panicked".to_string()).to_string())
1752                    }));
1753                }
1754                () = &mut deadline => {
1755                    let limit = claim.timeout.unwrap_or_default();
1756                    return Outcome::Done(Err(
1757                        Error::Job(format!("timed out after {}s", limit.as_secs_f64())).to_string(),
1758                    ));
1759                }
1760                () = tokio::time::sleep(every) => {
1761                    let beat = sqlx::query(HEARTBEAT)
1762                        .bind(claim.id)
1763                        .bind(claim.attempts)
1764                        .execute(&self.pool)
1765                        .await;
1766                    match beat {
1767                        Ok(done) if done.rows_affected() == 1 => last_heard = tokio::time::Instant::now(),
1768                        Ok(_) => return Outcome::Lost("another worker or recovery took its claim".to_string()),
1769                        Err(error) => {
1770                            tracing::warn!(id = %claim.id, %error, "job heartbeat failed");
1771                            if last_heard.elapsed() >= stale {
1772                                return Outcome::Lost(format!(
1773                                    "it could not report in for {} minutes",
1774                                    self.options.stale_minutes
1775                                ));
1776                            }
1777                        }
1778                    }
1779                }
1780            }
1781        }
1782    }
1783
1784    /// Mark a run's job for review, trying until the database answers, as the
1785    /// run must not be taken for a crash and retried.
1786    async fn mark_lost(&self, claim: &Claimed, reason: &str) {
1787        let text = Error::Job(format!("stopped: {reason}")).to_string();
1788        let every = self.options.heartbeat_interval.max(MIN_HEARTBEAT);
1789        loop {
1790            match sqlx::query(MARK_LOST)
1791                .bind(claim.id)
1792                .bind(&text)
1793                .execute(&self.pool)
1794                .await
1795            {
1796                Ok(_) => return,
1797                Err(error) => {
1798                    tracing::error!(id = %claim.id, %error, "could not mark a lost job for review");
1799                    tokio::time::sleep(every).await;
1800                }
1801            }
1802        }
1803    }
1804
1805    /// The job names this loop may claim now, holding a place under each limit
1806    /// that has one free. The places not used are given back when dropped.
1807    fn claimable(&self) -> (Vec<String>, HashMap<String, OwnedSemaphorePermit>) {
1808        let mut places = HashMap::new();
1809        let mut names = Vec::new();
1810        for name in self.handlers.keys() {
1811            match self.limits.get(name) {
1812                None => names.push(name.clone()),
1813                Some(limit) => {
1814                    if let Ok(place) = limit.clone().try_acquire_owned() {
1815                        places.insert(name.clone(), place);
1816                        names.push(name.clone());
1817                    }
1818                }
1819            }
1820        }
1821        (names, places)
1822    }
1823
1824    async fn claim(&self, names: &[String]) -> Result<Option<Claimed>> {
1825        let Some(row) = sqlx::query(CLAIM)
1826            .bind(names)
1827            .fetch_optional(&self.pool)
1828            .await?
1829        else {
1830            return Ok(None);
1831        };
1832        Ok(Some(Claimed {
1833            id: row.try_get("id")?,
1834            name: row.try_get("name")?,
1835            args: row.try_get("args")?,
1836            attempts: row.try_get("attempts")?,
1837            limit: row
1838                .try_get::<Option<i32>, _>("max_attempts")?
1839                .unwrap_or(self.options.max_attempts),
1840            timeout: row
1841                .try_get::<Option<i64>, _>("timeout_ms")?
1842                .map(from_millis),
1843            tenant: row.try_get("tenant")?,
1844        }))
1845    }
1846
1847    /// Claim and run one job, returning whether there was one. A job's own
1848    /// failure is recorded on its row, not returned.
1849    ///
1850    /// # Errors
1851    ///
1852    /// Fails on a database error.
1853    pub async fn run_one(&self) -> Result<bool> {
1854        let (names, mut places) = self.claimable();
1855        if names.is_empty() {
1856            return Ok(false);
1857        }
1858        let Some(job) = self.claim(&names).await? else {
1859            return Ok(false);
1860        };
1861        // Keep only the place this job takes.
1862        let _place = places.remove(&job.name);
1863        drop(places);
1864        let outcome = match self.handlers.get(&job.name) {
1865            Some(handler) => {
1866                let run = handler(job.tenant.clone(), job.args.clone());
1867                self.supervise(run, &job).await
1868            }
1869            None => Outcome::Done(Err(
1870                Error::Job(format!("no handler for job {}", job.name)).to_string()
1871            )),
1872        };
1873        let (id, name, attempts) = (job.id, job.name.as_str(), job.attempts);
1874        let finished = match outcome {
1875            Outcome::Lost(reason) => {
1876                tracing::error!(job = %name, %id, attempts, %reason, "job stopped, it lost its claim");
1877                self.mark_lost(&job, &reason).await;
1878                return Ok(true);
1879            }
1880            Outcome::Done(Ok(())) => {
1881                sqlx::query(FINISH)
1882                    .bind(id)
1883                    .bind(attempts)
1884                    .bind("completed")
1885                    .bind(None::<String>)
1886                    .execute(&self.pool)
1887                    .await?
1888            }
1889            Outcome::Done(Err(error)) if attempts < job.limit => {
1890                tracing::warn!(job = %name, %id, attempts, %error, "job failed, will retry");
1891                let wait = backoff(self.options.retry_backoff, attempts);
1892                sqlx::query(RETRY)
1893                    .bind(id)
1894                    .bind(attempts)
1895                    .bind(cut(error))
1896                    .bind(wait.as_secs_f64())
1897                    .execute(&self.pool)
1898                    .await?
1899            }
1900            Outcome::Done(Err(error)) => {
1901                tracing::error!(job = %name, %id, attempts, %error, "job failed");
1902                sqlx::query(FINISH)
1903                    .bind(id)
1904                    .bind(attempts)
1905                    .bind("failed")
1906                    .bind(cut(error))
1907                    .execute(&self.pool)
1908                    .await?
1909            }
1910        };
1911        if finished.rows_affected() == 0 {
1912            // It ran to its end, but its claim had been taken, so the job may be
1913            // running again elsewhere.
1914            tracing::error!(job = %name, %id, "job finished after losing its claim");
1915            self.mark_lost(
1916                &job,
1917                "it finished after another worker or recovery took its claim",
1918            )
1919            .await;
1920        }
1921        Ok(true)
1922    }
1923
1924    /// Run job loops, housekeeping, and schedules until `shutdown` changes to
1925    /// `true`. Jobs in progress finish first, so a caller that must stop by a
1926    /// time limit drops this future at it, which aborts those jobs and leaves them
1927    /// for stale recovery. Housekeeping runs straight away, to recover anything a
1928    /// previous process left behind, and then on a timer.
1929    pub async fn run(self: Arc<Self>, shutdown: watch::Receiver<bool>) {
1930        let mut loops = Vec::new();
1931        loops.push(AbortOnDrop(tokio::spawn(every_until(
1932            shutdown.clone(),
1933            self.options.maintenance_interval,
1934            {
1935                let queue = self.clone();
1936                move || {
1937                    let queue = queue.clone();
1938                    async move { queue.maintain().await }
1939                }
1940            },
1941        ))));
1942        if !self.schedules.is_empty() {
1943            let queue = self.clone();
1944            loops.push(AbortOnDrop(tokio::spawn(every_until(
1945                shutdown.clone(),
1946                self.options.poll_interval,
1947                move || {
1948                    let queue = queue.clone();
1949                    async move {
1950                        if let Err(error) = queue.tick_schedules().await {
1951                            tracing::error!(%error, "could not queue scheduled jobs");
1952                        }
1953                    }
1954                },
1955            ))));
1956        }
1957        for _ in 0..self.options.workers.max(1) {
1958            let queue = self.clone();
1959            let mut shutdown = shutdown.clone();
1960            loops.push(AbortOnDrop(tokio::spawn(async move {
1961                while !*shutdown.borrow() {
1962                    let worked = queue.run_one().await.unwrap_or_else(|error| {
1963                        tracing::error!(%error, "job queue error");
1964                        false
1965                    });
1966                    if !worked {
1967                        tokio::select! {
1968                            () = tokio::time::sleep(queue.options.poll_interval) => {},
1969                            _ = shutdown.changed() => {},
1970                        }
1971                    }
1972                }
1973            })));
1974        }
1975        for job_loop in &mut loops {
1976            let _ = (&mut job_loop.0).await;
1977        }
1978    }
1979
1980    /// The names of the job types this queue handles.
1981    #[must_use]
1982    pub fn handled(&self) -> HashSet<&str> {
1983        self.handlers.keys().map(String::as_str).collect()
1984    }
1985}
1986
1987/// Run `round` now and then every `gap`, until `shutdown` is `true`.
1988async fn every_until<F, Fut>(mut shutdown: watch::Receiver<bool>, gap: Duration, round: F)
1989where
1990    F: Fn() -> Fut,
1991    Fut: Future<Output = ()>,
1992{
1993    while !*shutdown.borrow() {
1994        round().await;
1995        tokio::select! {
1996            () = tokio::time::sleep(gap) => {},
1997            _ = shutdown.changed() => {},
1998        }
1999    }
2000}
2001
2002/// A task that is aborted when its handle is dropped, so that dropping
2003/// [`Queue::run`] stops its loops and their jobs instead of leaving them running.
2004struct AbortOnDrop<T>(tokio::task::JoinHandle<T>);
2005
2006impl<T> Drop for AbortOnDrop<T> {
2007    fn drop(&mut self) {
2008        self.0.abort();
2009    }
2010}
2011
2012#[cfg(test)]
2013mod tests {
2014    use super::*;
2015
2016    #[test]
2017    fn each_retry_waits_twice_as_long_up_to_a_limit() {
2018        let base = Duration::from_secs(30);
2019        assert_eq!(backoff(base, 1), base);
2020        assert_eq!(backoff(base, 2), base * 2);
2021        assert_eq!(backoff(base, 3), base * 4);
2022        assert_eq!(backoff(base, 1_000), MAX_BACKOFF);
2023    }
2024
2025    #[test]
2026    fn the_debug_text_leaves_out_arguments() {
2027        let job = NewJob::new("Report", serde_json::json!({ "nhs": "943 476 5919" }));
2028        let schedule = Schedule::every("nightly", Duration::from_hours(1), job.clone());
2029        let cron = Schedule::cron("at-two", "0 2 * * *", job.clone());
2030        for text in [
2031            format!("{job:?}"),
2032            format!("{schedule:?}"),
2033            format!("{cron:?}"),
2034        ] {
2035            assert!(text.contains("Report"), "{text}");
2036            assert!(!text.contains("943"), "{text}");
2037        }
2038    }
2039
2040    #[test]
2041    fn a_by_or_reason_that_is_not_a_code_is_refused() {
2042        assert!(check_code("ops:alice", "by").is_ok());
2043        assert!(check_code(&"é".repeat(MAX_REASON_CHARS), "reason").is_ok());
2044        for bad in [
2045            String::new(),
2046            "é".repeat(MAX_REASON_CHARS + 1),
2047            "two\nlines".to_string(),
2048            "a\ttab".to_string(),
2049        ] {
2050            let error = check_code(&bad, "reason").unwrap_err();
2051            assert!(matches!(error, Error::NotACode { what: "reason" }));
2052            assert!(!error.to_string().contains("lines"), "the text is left out");
2053        }
2054    }
2055
2056    #[test]
2057    fn a_long_error_is_cut_on_a_character_boundary() {
2058        let text = "é".repeat(MAX_ERROR);
2059        let kept = cut(text);
2060        assert!(kept.len() <= MAX_ERROR);
2061        assert!(kept.chars().all(|c| c == 'é'));
2062        assert_eq!(cut("short".to_string()), "short");
2063    }
2064
2065    #[test]
2066    #[should_panic(expected = "at least a second")]
2067    fn a_schedule_under_a_second_is_refused_at_boot() {
2068        let _ = Schedule::every(
2069            "fast",
2070            Duration::from_millis(10),
2071            NewJob::new("J", serde_json::Value::Null),
2072        );
2073    }
2074
2075    #[test]
2076    #[should_panic(expected = "bad cron pattern")]
2077    fn a_bad_cron_pattern_is_refused_at_boot() {
2078        let _ = Schedule::cron(
2079            "bad",
2080            "61 * * * *",
2081            NewJob::new("J", serde_json::Value::Null),
2082        );
2083    }
2084
2085    #[test]
2086    fn a_cron_schedule_names_its_next_times_in_utc() {
2087        let schedule = Schedule::cron(
2088            "weekdays",
2089            "0 9 * * MON-FRI",
2090            NewJob::new("J", serde_json::Value::Null),
2091        );
2092        assert_eq!(schedule.cron_pattern(), Some("0 9 * * MON-FRI"));
2093        assert_eq!(schedule.interval(), None);
2094        let Times::Cron(cron, _) = &schedule.times else {
2095            panic!("a cron schedule")
2096        };
2097        // Friday 2026-11-13 09:00 UTC is due, so the next after it is Monday's.
2098        let friday = DateTime::parse_from_rfc3339("2026-11-13T09:00:00Z")
2099            .unwrap()
2100            .with_timezone(&Utc);
2101        let monday = DateTime::parse_from_rfc3339("2026-11-16T09:00:00Z")
2102            .unwrap()
2103            .with_timezone(&Utc);
2104        assert_eq!(next_after(cron, friday).unwrap(), monday);
2105        assert_eq!(
2106            Schedule::every(
2107                "e",
2108                Duration::from_secs(5),
2109                NewJob::new("J", serde_json::Value::Null)
2110            )
2111            .interval(),
2112            Some(Duration::from_secs(5))
2113        );
2114    }
2115
2116    #[test]
2117    #[should_panic(expected = "1 to 200 characters")]
2118    fn a_schedule_with_no_name_is_refused_at_boot() {
2119        let _ = Schedule::every(
2120            "",
2121            Duration::from_secs(1),
2122            NewJob::new("J", serde_json::Value::Null),
2123        );
2124    }
2125
2126    #[tokio::test]
2127    #[should_panic(expected = "added twice")]
2128    async fn a_schedule_added_twice_is_refused_at_boot() {
2129        let pool = PgPoolOptions::new()
2130            .connect_lazy("postgres://u@localhost/none")
2131            .unwrap();
2132        let mut queue = Queue::from_pool(pool, QueueOptions::default());
2133        let job = NewJob::new("J", serde_json::Value::Null);
2134        queue.schedule(Schedule::every("a", Duration::from_secs(5), job.clone()));
2135        queue.schedule(Schedule::every("a", Duration::from_secs(9), job));
2136    }
2137
2138    #[test]
2139    fn a_schedule_ignores_a_delay_on_its_job() {
2140        let job = NewJob::new("J", serde_json::Value::Null).run_in(Duration::from_hours(1));
2141        let schedule = Schedule::every("s", Duration::from_secs(5), job);
2142        assert_eq!(schedule.job.when, When::Now);
2143    }
2144}