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//! A job queued is announced with `NOTIFY axa_queue` when its transaction commits,
8//! and [`Queue::run`] listens on one connection of its pool, so an idle loop starts
9//! a job at once rather than at its next poll. Polling every
10//! [`QueueOptions::poll_interval`] stays, for a job whose time comes, and for any
11//! notice lost while the listener reconnects.
12//!
13//! ```no_run
14//! use std::time::Duration;
15//! use axa_postgres_job_queue::{NewJob, Queue, QueueOptions, Schedule};
16//! use tokio::sync::watch;
17//!
18//! # async fn example(uri: &str) -> axa_postgres_job_queue::Result<()> {
19//! let mut queue = Queue::connect(uri, QueueOptions::default()).await?;
20//! queue.handle("Report", |args| async move {
21//!     let id = args["id"].as_i64().ok_or("no id")?;
22//!     println!("report {id}");
23//!     Ok::<(), &str>(())
24//! });
25//! queue.limit("Report", 1); // at most one at a time in this process
26//! queue.schedule(Schedule::every(
27//!     "nightly-report",
28//!     Duration::from_hours(24),
29//!     NewJob::new("Report", serde_json::json!({ "id": 0 })),
30//! )?)?;
31//!
32//! let id = queue
33//!     .enqueue_job(&NewJob::new("Report", serde_json::json!({ "id": 7 })).run_in(Duration::from_mins(5)))
34//!     .await?;
35//! let queue = std::sync::Arc::new(queue);
36//! let (stop, stopped) = watch::channel(false);
37//! let jobs = tokio::spawn(queue.clone().run(stopped));
38//! // ... serve until told to stop, then:
39//! let _ = stop.send(true);
40//! let _ = jobs.await;
41//! # let _ = id;
42//! # Ok(())
43//! # }
44//! ```
45//!
46//! A job moves from `queued` to `running` to `completed` or `failed`, with the
47//! failure text kept on the row. A queued job can be `cancelled`.
48//!
49//! # A person's acts
50//!
51//! A job row is state: it changes as the job runs, and retention deletes it. What a
52//! person does to a job is a record. [`cancel()`] stops a queued job, and [`retry()`]
53//! queues a failed one again or releases one from review. Each takes the caller's
54//! transaction and a `by` and `reason`, and appends the act to `axa_job_acts` in the
55//! same statement as the change, so the act, the change, and the service's own audit
56//! row commit together or not at all. There is no form that takes a pool. An act that
57//! does not apply, such as cancelling a running job, changes nothing and writes no
58//! act.
59//!
60//! ```no_run
61//! # async fn example(queue: &axa_postgres_job_queue::Queue, id: uuid::Uuid) -> axa_postgres_job_queue::Result<()> {
62//! let mut transaction = queue.pool().begin().await?;
63//! let cancelled = axa_postgres_job_queue::cancel(&mut transaction, id, "ops:alice", "customer_asked").await?;
64//! // ... write the service's own audit row on the same transaction ...
65//! transaction.commit().await?;
66//! # let _ = cancelled;
67//! # Ok(())
68//! # }
69//! ```
70//!
71//! `by` and `reason` are codes, not content: at most [`MAX_REASON_CHARS`] characters
72//! with no line breaks, and the table refuses anything else. `axa_job_acts` is only
73//! ever inserted into, and its triggers refuse `UPDATE`, `DELETE`, and `TRUNCATE`,
74//! whoever sends them. An act names its job by id, with no foreign key, so it outlives
75//! the job's row. [`Queue::acts`] reads a job's acts.
76//!
77//! # Attempts
78//!
79//! A job gets [`QueueOptions::max_attempts`] tries, unless it was queued with its
80//! own limit. The default is one, because a retry repeats the job's work, and only
81//! its author knows that is safe. Each retry waits about twice as long as the last,
82//! starting from [`QueueOptions::retry_backoff`], spread at random over the upper
83//! half of that wait so jobs that failed together do not all come back at once. A
84//! handler that knows better, such as from a receiver's `Retry-After`, returns
85//! [`RetryAfter`] as its error. A job that panics counts as failed, and its loop
86//! carries on.
87//!
88//! # Lost jobs
89//!
90//! A running job reports in every [`QueueOptions::heartbeat_interval`], so a job
91//! may run for as long as it needs. One not heard from for
92//! [`QueueOptions::stale_minutes`] is assumed lost with its worker. If it has
93//! attempts left it is queued again, and otherwise it is marked failed, so a crash
94//! can never loop for ever. Each claim is identified by its attempt, so a run that
95//! was given up on cannot then overwrite the result of its replacement.
96//!
97//! # How many at once
98//!
99//! A process runs [`QueueOptions::workers`] job loops, so at most that many jobs at
100//! once. [`Queue::limit`] caps one job type below that, in this process. A limit is
101//! per process and not across replicas: three processes with a limit of one may run
102//! three. Work that must never overlap anywhere needs a lock of its own.
103//!
104//! # When a job runs
105//!
106//! [`NewJob::run_in`] and [`NewJob::run_at`] delay a job, and [`NewJob::priority`]
107//! puts it ahead of others that are ready. Delay is measured on the database's
108//! clock. A delayed job is claimed only once it is due, and then about as soon as a
109//! loop next polls.
110//!
111//! # Schedules
112//!
113//! A [`Schedule`] queues a job every interval. Each due time becomes one ordinary
114//! job, so its retries, status, limit, and recovery are the queue's. The schedule's
115//! row in `axa_schedule` is locked while its job is queued, in the same
116//! transaction, so across any number of replicas each due time is queued once.
117//!
118//! - **No drift.** The next time is counted from when the last was due, not from
119//!   when it ran.
120//! - **Missed times run once.** After every process was down, one job is queued,
121//!   and the schedule keeps its place: the next time is still a whole number of
122//!   intervals from the first.
123//! - **No stacking.** When the schedule's last job is still queued or running at a
124//!   due time, that time is skipped.
125//! - **The first time** is [`Schedule::first_at`], or as soon as the row is made.
126//!   It applies only when the row is made, so a schedule every 24 hours first due
127//!   at 02:00 runs at 02:00 each day, on the database's clock in UTC.
128//!
129//! [`Schedule::cron`] queues a job at the times a cron pattern names, such as
130//! `"0 2 * * *"` for 02:00 each day, in UTC on the database's clock. Its due times
131//! are the pattern's, so the same three rules hold: each due time is queued once, times
132//! missed while every process was down queue one job and the next time is the
133//! pattern's next after now, and a due time is skipped while the last job is queued or
134//! running. Its first time is the pattern's next after the row is made, and a changed
135//! pattern takes its next time from the new pattern.
136//!
137//! [`Queue::run`] ticks the schedules on every poll, and a service with no job
138//! loops can call [`Queue::tick_schedules`] itself. A schedule's job type must be
139//! handled by some worker, or its jobs wait. A schedule removed from code leaves a
140//! row that nothing reads.
141//!
142//! # One job at a time per key
143//!
144//! [`NewJob::unique`] names a key, such as `"sync:42"`, and while a job of the same
145//! name, tenant, and key is queued or running, queuing another adds nothing and
146//! answers the id of the one there. The first job's arguments, priority, and time
147//! stand. Once it completes, fails, is cancelled, or goes to review, the key is free
148//! again. The table holds to this with a unique index, so it holds across
149//! replicas and for a job queued in a transaction that has not yet committed: a
150//! second enqueue of the key waits for that transaction, and then either finds its
151//! job or queues its own. [`retry()`] leaves a failed job alone while another of its
152//! key is queued or running.
153//!
154//! # Queuing inside a transaction
155//!
156//! [`enqueue_on`] takes the caller's transaction, so a job and the record it is
157//! about commit together or not at all. [`Queue::enqueue`] uses its own
158//! connection, so a job queued that way can outlive a rollback.
159//!
160//! # Personal data
161//!
162//! The `args` column is plain JSONB, and finished rows are deleted after
163//! [`QueueOptions::retention_days`], so a job table does not become a second copy
164//! of the data. Prefer an id to a snapshot, and never put a secret in arguments.
165//! [`JobInfo`] leaves the arguments out. Its error text is whatever the job's
166//! error said, so it is for operators, and is not to be sent to a client. An act
167//! keeps no arguments either, and nothing logs its `by` or `reason`.
168
169use std::{
170    collections::{HashMap, HashSet},
171    fmt,
172    future::Future,
173    pin::Pin,
174    sync::Arc,
175    time::Duration,
176};
177
178use sqlx::{
179    PgConnection, PgExecutor, PgPool, Postgres, Row, Transaction,
180    postgres::{PgPoolOptions, PgRow},
181};
182use tokio::sync::{Notify, OwnedSemaphorePermit, Semaphore, watch};
183use uuid::Uuid;
184
185/// An instant, in UTC: every time the queue keeps or takes. Re-exported from `jiff`, so
186/// a service needs no dependency of its own to name one.
187pub use jiff::Timestamp;
188
189/// What this crate's functions return.
190pub type Result<T, E = Error> = std::result::Result<T, E>;
191
192/// What went wrong.
193#[derive(Debug)]
194#[non_exhaustive]
195pub enum Error {
196    /// The database refused or could not be reached.
197    Database(sqlx::Error),
198    /// A job's arguments could not be encoded.
199    Encode(serde_json::Error),
200    /// A job failed, or the queue met something it cannot read.
201    Job(String),
202    /// Who or why, given for a person's act, or a job's unique key, is empty,
203    /// longer than [`MAX_REASON_CHARS`], or has a line break.
204    NotACode {
205        /// Which it was: `by`, `reason`, or `unique key`.
206        what: &'static str,
207    },
208    /// A job's tenant is not a tenant id: see [`is_tenant_id`].
209    NotATenant,
210    /// A schedule is a mistake in code, found at boot: a name that is empty, over 200
211    /// characters, or used twice, an interval under a second, or a cron pattern that does
212    /// not parse or names no time to come.
213    Schedule(String),
214    /// A figure was too large to compute: a count, or a time that does not fit.
215    Overflow(&'static str),
216    /// A figure given is out of range, so it is refused, not held to a limit: a setting
217    /// in [`QueueOptions`], or the delay of a [`RetryAfter`].
218    OutOfRange(&'static str),
219}
220
221impl fmt::Display for Error {
222    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223        match self {
224            Self::Database(error) => error.fmt(f),
225            Self::Encode(error) => error.fmt(f),
226            Self::Job(text) => write!(f, "worker error: {text}"),
227            Self::NotACode { what } => write!(
228                f,
229                "`{what}` must be 1 to {MAX_REASON_CHARS} characters with no line breaks"
230            ),
231            Self::Schedule(text) => write!(f, "schedule error: {text}"),
232            Self::Overflow(figure) => write!(f, "{figure}: the value is too large to compute"),
233            Self::OutOfRange(figure) => write!(f, "{figure}: the value is out of range"),
234            Self::NotATenant => f.write_str(
235                "a job's tenant must be 1 to 63 lower-case letters, digits, and hyphens, \
236                 not starting or ending with a hyphen",
237            ),
238        }
239    }
240}
241
242impl std::error::Error for Error {
243    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
244        match self {
245            Self::Database(error) => Some(error),
246            Self::Encode(error) => Some(error),
247            Self::Job(_)
248            | Self::NotACode { .. }
249            | Self::NotATenant
250            | Self::Schedule(_)
251            | Self::Overflow(_)
252            | Self::OutOfRange(_) => None,
253        }
254    }
255}
256
257impl From<sqlx::Error> for Error {
258    fn from(error: sqlx::Error) -> Self {
259        Self::Database(error)
260    }
261}
262
263impl From<serde_json::Error> for Error {
264    fn from(error: serde_json::Error) -> Self {
265        Self::Encode(error)
266    }
267}
268
269type JobFuture = Pin<Box<dyn Future<Output = Result<(), Failure>> + Send>>;
270type Handler = Arc<dyn Fn(Option<String>, serde_json::Value) -> JobFuture + Send + Sync>;
271
272const SETUP: &str = "CREATE TABLE IF NOT EXISTS axa_queue (
273    id UUID PRIMARY KEY,
274    name TEXT NOT NULL,
275    args JSONB NOT NULL,
276    status TEXT NOT NULL DEFAULT 'queued',
277    error TEXT,
278    run_at TIMESTAMPTZ NOT NULL DEFAULT now(),
279    started_at TIMESTAMPTZ,
280    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
281    updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
282)";
283const SETUP_INDEX: &str =
284    "CREATE INDEX IF NOT EXISTS axa_queue_ready ON axa_queue (run_at) WHERE status = 'queued'";
285/// Tables created by Axa 0.1.0 have no `attempts` column.
286const SETUP_ATTEMPTS: &str =
287    "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS attempts INTEGER NOT NULL DEFAULT 0";
288/// A job's own limit on tries, when it has one.
289const SETUP_MAX_ATTEMPTS: &str =
290    "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS max_attempts INTEGER";
291/// Higher runs first. Tables created before axa-postgres-job-queue have none.
292const SETUP_PRIORITY: &str =
293    "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS priority SMALLINT NOT NULL DEFAULT 0";
294/// A job's own time limit, when it has one.
295const SETUP_TIMEOUT: &str = "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS timeout_ms BIGINT";
296/// The tenant a job runs for, when it has one, as an auth crate's `Tenant` names it.
297const SETUP_TENANT: &str = "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS tenant TEXT
298    CONSTRAINT axa_queue_tenant_id CHECK (tenant ~ '^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$')";
299/// The key a job is unique by while it is queued or running, when it has one.
300const SETUP_UNIQUE_KEY: &str = "ALTER TABLE axa_queue ADD COLUMN IF NOT EXISTS unique_key TEXT
301    CONSTRAINT axa_queue_unique_key_code
302    CHECK (length(unique_key) BETWEEN 1 AND 200 AND unique_key !~ '[[:cntrl:]]')";
303/// At most one job queued or running per name, tenant, and key.
304const SETUP_UNIQUE_INDEX: &str = "CREATE UNIQUE INDEX IF NOT EXISTS axa_queue_unique
305    ON axa_queue (name, (COALESCE(tenant, '')), unique_key)
306    WHERE unique_key IS NOT NULL AND status IN ('queued', 'running')";
307const SETUP_CLAIM_INDEX: &str = "CREATE INDEX IF NOT EXISTS axa_queue_claim
308    ON axa_queue (priority DESC, run_at) WHERE status = 'queued'";
309const SETUP_SCHEDULE: &str = "CREATE TABLE IF NOT EXISTS axa_schedule (
310    name TEXT PRIMARY KEY,
311    due_at TIMESTAMPTZ NOT NULL,
312    last_job UUID,
313    interval_ms BIGINT,
314    seen_at TIMESTAMPTZ NOT NULL DEFAULT now(),
315    archived_at TIMESTAMPTZ,
316    created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
317    updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
318)";
319/// A person's acts on jobs. This table is a record (P-7): it is only ever inserted
320/// into, and its triggers refuse every change. A job row is state, and retention
321/// deletes it, so an act names its job by id with no foreign key, and keeps the job's
322/// name and attempts as they were when the act was done.
323/// A schedule's cron pattern, when it has one instead of an interval.
324const SETUP_SCHEDULE_CRON: &str = "ALTER TABLE axa_schedule ADD COLUMN IF NOT EXISTS cron TEXT";
325const SETUP_ACTS: &str = "CREATE TABLE IF NOT EXISTS axa_job_acts (
326    id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
327    job_id UUID NOT NULL,
328    job_name TEXT NOT NULL,
329    act TEXT NOT NULL CHECK (act IN ('cancelled', 'retried', 'released')),
330    attempts INTEGER NOT NULL,
331    by TEXT NOT NULL CHECK (length(by) BETWEEN 1 AND 200 AND by !~ '[[:cntrl:]]'),
332    reason TEXT NOT NULL CHECK (length(reason) BETWEEN 1 AND 200 AND reason !~ '[[:cntrl:]]'),
333    at TIMESTAMPTZ NOT NULL DEFAULT now()
334)";
335const SETUP_ACTS_INDEX: &str =
336    "CREATE INDEX IF NOT EXISTS axa_job_acts_job ON axa_job_acts (job_id, id)";
337/// Refuses whatever fired it, whoever sent it.
338const SETUP_ACTS_REFUSE: &str = "CREATE OR REPLACE FUNCTION axa_job_acts_refuse() RETURNS trigger
339LANGUAGE plpgsql AS $$
340BEGIN
341    RAISE EXCEPTION '% on % is refused: acts on jobs are only ever added to',
342        TG_OP, TG_TABLE_NAME;
343END
344$$";
345const SETUP_ACTS_ROWS: &str = "CREATE OR REPLACE TRIGGER axa_job_acts_refuse
346    BEFORE UPDATE OR DELETE ON axa_job_acts
347    FOR EACH ROW EXECUTE FUNCTION axa_job_acts_refuse()";
348const SETUP_ACTS_TRUNCATE: &str = "CREATE OR REPLACE TRIGGER axa_job_acts_refuse_truncate
349    BEFORE TRUNCATE ON axa_job_acts
350    FOR EACH STATEMENT EXECUTE FUNCTION axa_job_acts_refuse()";
351/// `ENABLE ALWAYS` keeps the refusals on when `session_replication_role` is
352/// `replica`, which otherwise turns triggers off.
353const SETUP_ACTS_ALWAYS: &str = "ALTER TABLE axa_job_acts
354    ENABLE ALWAYS TRIGGER axa_job_acts_refuse,
355    ENABLE ALWAYS TRIGGER axa_job_acts_refuse_truncate";
356/// The channel a queued job is announced on.
357pub const NOTIFY_CHANNEL: &str = "axa_queue";
358/// Announces new jobs once per statement, delivered when the transaction commits.
359const SETUP_NOTIFY_FUNCTION: &str = "CREATE OR REPLACE FUNCTION axa_queue_notify() RETURNS trigger
360LANGUAGE plpgsql AS $$
361BEGIN
362    PERFORM pg_notify('axa_queue', '');
363    RETURN NULL;
364END
365$$";
366const SETUP_NOTIFY: &str = "CREATE OR REPLACE TRIGGER axa_queue_notify
367    AFTER INSERT ON axa_queue
368    FOR EACH STATEMENT EXECUTE FUNCTION axa_queue_notify()";
369/// The refusing triggers [`Queue::check`] requires, each set to fire always.
370const ACTS_TRIGGERS: [&str; 2] = ["axa_job_acts_refuse", "axa_job_acts_refuse_truncate"];
371const MISSING_TRIGGERS: &str = "SELECT want FROM unnest($1::text[]) AS want
372    WHERE NOT EXISTS (
373        SELECT 1 FROM pg_trigger t
374        WHERE t.tgrelid = to_regclass('axa_job_acts') AND t.tgname = want
375          AND t.tgenabled::text = 'A'
376    )";
377/// What a job queued for a tenant fails with when its handler takes no tenant.
378const NO_TENANT_HANDLER: &str =
379    "the job has a tenant, and its handler takes none: register it with handle_with_tenant";
380
381/// Advisory lock key for table setup: `axa_q` as bytes.
382const SETUP_LOCK: i64 = 0x0061_7861_5F71;
383
384const ENQUEUE: &str = "INSERT INTO axa_queue
385    (id, name, args, max_attempts, priority, run_at, timeout_ms, tenant)
386    VALUES ($1, $2, $3, $4, $5, COALESCE($6, now() + make_interval(secs => $7)), $8, $9)";
387/// Queue a job with a key, or find the one of its name, tenant, and key already
388/// queued or running. `DO UPDATE`, which changes nothing, rather than `DO NOTHING`,
389/// because it returns the job there even when it committed after this statement
390/// began, as a job queued in another transaction may have. `inserted` tells which.
391const ENQUEUE_UNIQUE: &str = "INSERT INTO axa_queue
392    (id, name, args, max_attempts, priority, run_at, timeout_ms, tenant, unique_key)
393    VALUES ($1, $2, $3, $4, $5, COALESCE($6, now() + make_interval(secs => $7)), $8, $9, $10)
394    ON CONFLICT (name, (COALESCE(tenant, '')), unique_key)
395        WHERE unique_key IS NOT NULL AND status IN ('queued', 'running')
396    DO UPDATE SET unique_key = EXCLUDED.unique_key
397    RETURNING id";
398const CLAIM: &str = "UPDATE axa_queue
399    SET status = 'running', started_at = now(), updated_at = now(), attempts = attempts + 1
400    WHERE id = (
401        SELECT id FROM axa_queue
402        WHERE status = 'queued' AND run_at <= now() AND name = ANY($1)
403        ORDER BY priority DESC, run_at
404        FOR UPDATE SKIP LOCKED
405        LIMIT 1
406    )
407    RETURNING id, name, args, attempts, max_attempts, timeout_ms, tenant";
408/// `attempts` identifies this run of the job, so a run that was given up on
409/// finds no row here and changes nothing.
410const HEARTBEAT: &str = "UPDATE axa_queue SET updated_at = now()
411    WHERE id = $1 AND attempts = $2 AND status = 'running'";
412const FINISH: &str = "UPDATE axa_queue SET status = $3, error = $4, updated_at = now()
413    WHERE id = $1 AND attempts = $2 AND status = 'running'";
414const RETRY: &str = "UPDATE axa_queue
415    SET status = 'queued', error = $3, started_at = NULL, updated_at = now(),
416        run_at = now() + make_interval(secs => $4)
417    WHERE id = $1 AND attempts = $2 AND status = 'running'";
418const REQUEUE_STALE: &str = "UPDATE axa_queue
419    SET status = 'queued', started_at = NULL, updated_at = now()
420    WHERE status = 'running' AND updated_at < now() - make_interval(mins => $1)
421      AND attempts < COALESCE(max_attempts, $2)";
422const FAIL_STALE: &str = "UPDATE axa_queue
423    SET status = 'failed', error = 'abandoned by its worker', updated_at = now()
424    WHERE status = 'running' AND updated_at < now() - make_interval(mins => $1)
425      AND attempts >= COALESCE(max_attempts, $2)";
426const PURGE: &str = "DELETE FROM axa_queue
427    WHERE status IN ('completed', 'failed', 'cancelled')
428      AND updated_at < now() - make_interval(days => $1)";
429const STATUS: &str = "SELECT id, name, status, attempts, max_attempts, priority, error,
430    timeout_ms, tenant, unique_key, run_at, started_at, created_at, updated_at FROM axa_queue WHERE id = $1";
431/// A run that lost its claim stops, and its job waits for a person. Another run
432/// may hold the row by now, and this stops that one too, at its next report.
433/// A row already completed is left alone.
434const MARK_LOST: &str =
435    "UPDATE axa_queue SET status = 'needs_review', error = $2, updated_at = now()
436    WHERE id = $1 AND status IN ('queued', 'running', 'failed')";
437/// Cancel a queued job and keep the act, in one statement. A job in any other state
438/// changes nothing and writes no act.
439const CANCEL: &str = "WITH changed AS (
440        UPDATE axa_queue SET status = 'cancelled', updated_at = now()
441        WHERE id = $1 AND status = 'queued'
442        RETURNING id, name, attempts
443    )
444    INSERT INTO axa_job_acts (job_id, job_name, act, attempts, by, reason)
445    SELECT id, name, 'cancelled', attempts, $2, $3 FROM changed";
446/// A retried job gets one more try. `attempts` keeps rising, as it identifies
447/// each run, so a run given up on still cannot write over the new one. The act is
448/// `released` for a job in review and `retried` for a failed one, and is kept in the
449/// same statement.
450const RETRY_FAILED: &str = "WITH target AS (
451        SELECT id, status FROM axa_queue
452        WHERE id = $1 AND status IN ('failed', 'needs_review')
453          AND NOT EXISTS (
454              SELECT 1 FROM axa_queue other
455              WHERE other.unique_key = axa_queue.unique_key
456                AND other.name = axa_queue.name
457                AND COALESCE(other.tenant, '') = COALESCE(axa_queue.tenant, '')
458                AND other.status IN ('queued', 'running')
459          )
460        FOR UPDATE
461    ), changed AS (
462        UPDATE axa_queue q
463        SET status = 'queued', run_at = now(), started_at = NULL, updated_at = now(),
464            max_attempts = q.attempts + 1
465        FROM target WHERE q.id = target.id
466        RETURNING q.id, q.name, q.attempts, target.status AS was
467    )
468    INSERT INTO axa_job_acts (job_id, job_name, act, attempts, by, reason)
469    SELECT id, name, CASE was WHEN 'needs_review' THEN 'released' ELSE 'retried' END,
470        attempts, $2, $3
471    FROM changed";
472const ACTS: &str = "SELECT id, job_id, job_name, act, attempts, by, reason, at
473    FROM axa_job_acts WHERE job_id = $1 ORDER BY id";
474const COUNTS: &str = "SELECT
475    count(*) FILTER (WHERE status = 'queued' AND run_at <= now()) AS ready,
476    count(*) FILTER (WHERE status = 'queued' AND run_at > now()) AS waiting,
477    count(*) FILTER (WHERE status = 'running') AS running,
478    count(*) FILTER (WHERE status = 'completed') AS completed,
479    count(*) FILTER (WHERE status = 'failed') AS failed,
480    count(*) FILTER (WHERE status = 'cancelled') AS cancelled,
481    count(*) FILTER (WHERE status = 'needs_review') AS needs_review,
482    EXTRACT(EPOCH FROM now() - min(run_at) FILTER (WHERE status = 'queued' AND run_at <= now()))::float8 AS oldest
483    FROM axa_queue";
484/// Make the row, or say this schedule is still in code: restore it if it was
485/// archived, and note the interval or pattern. A changed pattern takes its next time,
486/// `$5`, from the new pattern. `seen_at` moves at most once a minute, so a tick does
487/// not write each poll. A cron schedule's first time is `$2`, its next after now.
488const SCHEDULE_CREATE: &str = "INSERT INTO axa_schedule (name, due_at, interval_ms, cron)
489    VALUES ($1, COALESCE($2, now()), $3, $4)
490    ON CONFLICT (name) DO UPDATE
491    SET seen_at = now(), archived_at = NULL, interval_ms = EXCLUDED.interval_ms,
492        cron = EXCLUDED.cron,
493        due_at = CASE WHEN EXCLUDED.cron IS NOT NULL
494                       AND axa_schedule.cron IS DISTINCT FROM EXCLUDED.cron
495                  THEN EXCLUDED.due_at ELSE axa_schedule.due_at END
496    WHERE axa_schedule.archived_at IS NOT NULL
497       OR axa_schedule.interval_ms IS DISTINCT FROM EXCLUDED.interval_ms
498       OR axa_schedule.cron IS DISTINCT FROM EXCLUDED.cron
499       OR axa_schedule.seen_at < now() - interval '1 minute'";
500const SCHEDULE_LOCK: &str =
501    "SELECT last_job, due_at <= now() AS due, now() AS now FROM axa_schedule
502    WHERE name = $1 AND archived_at IS NULL FOR UPDATE SKIP LOCKED";
503/// Archive schedules no live process has in code. A row any process still ticks
504/// is seen within a minute, so one unseen for `stale_minutes` is in none, and an
505/// old replica in a rolling deploy keeps its schedules until it stops.
506const SCHEDULE_ARCHIVE: &str = "UPDATE axa_schedule SET archived_at = now(), updated_at = now()
507    WHERE archived_at IS NULL AND name <> ALL($1)
508      AND seen_at < now() - make_interval(mins => $2)";
509const SCHEDULES: &str = "SELECT s.name, s.interval_ms, s.cron, s.due_at, s.last_job, s.seen_at,
510    s.archived_at, s.created_at, q.status AS last_status, q.error AS last_error
511    FROM axa_schedule s LEFT JOIN axa_queue q ON q.id = s.last_job ORDER BY s.name";
512const SCHEDULE_BUSY: &str = "SELECT EXISTS (SELECT 1 FROM axa_queue
513    WHERE id = $1 AND status IN ('queued', 'running'))";
514/// The next due time after now, a whole number of intervals from the last, on the
515/// database's clock. One expression gives no drift, one catch-up, and no stacking.
516const SCHEDULE_ADVANCE: &str = "UPDATE axa_schedule
517    SET due_at = due_at + make_interval(secs => $2)
518            * (floor(EXTRACT(EPOCH FROM now() - due_at)::float8 / $2) + 1),
519        last_job = COALESCE($3, last_job), updated_at = now()
520    WHERE name = $1";
521/// A cron schedule's next due time, `$2`, the pattern's next after now.
522const SCHEDULE_ADVANCE_TO: &str = "UPDATE axa_schedule
523    SET due_at = $2, last_job = COALESCE($3, last_job), updated_at = now()
524    WHERE name = $1";
525
526/// The statements that make the queue's tables, in order, each safe to repeat. A
527/// service whose role may not change the schema runs these in a migration, and calls
528/// [`Queue::connect_existing`]. They need Postgres 14 or later.
529pub const SETUP_STATEMENTS: [&str; 20] = [
530    SETUP,
531    SETUP_ATTEMPTS,
532    SETUP_MAX_ATTEMPTS,
533    SETUP_INDEX,
534    SETUP_PRIORITY,
535    SETUP_TIMEOUT,
536    SETUP_TENANT,
537    SETUP_UNIQUE_KEY,
538    SETUP_UNIQUE_INDEX,
539    SETUP_CLAIM_INDEX,
540    SETUP_SCHEDULE,
541    SETUP_SCHEDULE_CRON,
542    SETUP_ACTS,
543    SETUP_ACTS_INDEX,
544    SETUP_ACTS_REFUSE,
545    SETUP_ACTS_ROWS,
546    SETUP_ACTS_TRUNCATE,
547    SETUP_ACTS_ALWAYS,
548    SETUP_NOTIFY_FUNCTION,
549    SETUP_NOTIFY,
550];
551
552/// The longest `by` or `reason` kept on an act, in characters.
553pub const MAX_REASON_CHARS: usize = 200;
554
555/// The shortest gap between heartbeats, so a zero setting cannot spin.
556const MIN_HEARTBEAT: Duration = Duration::from_millis(20);
557
558/// The longest wait between attempts.
559const MAX_BACKOFF: Duration = Duration::from_hours(1);
560
561/// The longest error text kept on a row.
562const MAX_ERROR: usize = 1024;
563
564/// The most a backoff doubles: 16 doublings.
565const MAX_DOUBLING_FACTOR: u32 = 1 << 16;
566
567/// How long to wait before the attempt after `attempts`, doubling each time.
568#[must_use]
569pub fn backoff(base: Duration, attempts: i32) -> Option<Duration> {
570    // Fewer than one attempt is invalid, so it has no wait.
571    let doublings = u32::try_from(attempts.checked_sub(1)?).ok()?.min(16);
572    let factor = 1_u32.checked_shl(doublings).unwrap_or(MAX_DOUBLING_FACTOR);
573    // ARI-2: a wait that does not fit is the cap.
574    Some(
575        base.checked_mul(factor)
576            .unwrap_or(MAX_BACKOFF)
577            .min(MAX_BACKOFF),
578    )
579}
580
581/// The shortest delay a job may choose with [`RetryAfter`].
582pub const MIN_RETRY_AFTER: Duration = Duration::from_secs(1);
583
584/// A job's error that also says when to try it again, such as a receiver's
585/// `Retry-After`. Return it as a handler's error: the next attempt waits `delay`,
586/// which is from [`MIN_RETRY_AFTER`] to an hour, rather than the backoff. It still
587/// counts as an attempt, so a job out of attempts fails as any other.
588#[derive(Debug, Clone)]
589pub struct RetryAfter {
590    delay: Duration,
591    reason: String,
592}
593
594impl RetryAfter {
595    /// Try again after `delay`, keeping `reason` as the job's error.
596    ///
597    /// # Errors
598    ///
599    /// [`Error::OutOfRange`] when `delay` is under [`MIN_RETRY_AFTER`] or over an hour.
600    /// It is refused, not held to those limits.
601    pub fn new(delay: Duration, reason: impl Into<String>) -> Result<Self> {
602        if !(MIN_RETRY_AFTER..=MAX_BACKOFF).contains(&delay) {
603            return Err(Error::OutOfRange("retry after"));
604        }
605        Ok(Self {
606            delay,
607            reason: reason.into(),
608        })
609    }
610
611    /// The delay the job asked for.
612    #[must_use]
613    pub const fn delay(&self) -> Duration {
614        self.delay
615    }
616}
617
618impl fmt::Display for RetryAfter {
619    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
620        f.write_str(&self.reason)
621    }
622}
623
624impl std::error::Error for RetryAfter {}
625
626/// How a run failed: the text kept on the row, and any delay the job chose.
627struct Failure {
628    text: String,
629    retry_in: Option<Duration>,
630}
631
632impl Failure {
633    fn from_error<E: fmt::Display + 'static>(error: E) -> Self {
634        let any: &dyn std::any::Any = &error;
635        // A handler's own error, or one boxed, as `axa`'s workers hand theirs on.
636        let retry_in = any
637            .downcast_ref::<RetryAfter>()
638            .or_else(|| {
639                any.downcast_ref::<Box<dyn std::error::Error + Send + Sync>>()
640                    .and_then(|boxed| boxed.downcast_ref::<RetryAfter>())
641            })
642            .map(RetryAfter::delay);
643        Self {
644            text: error.to_string(),
645            retry_in,
646        }
647    }
648}
649
650impl From<String> for Failure {
651    fn from(text: String) -> Self {
652        Self {
653            text,
654            retry_in: None,
655        }
656    }
657}
658
659impl fmt::Display for Failure {
660    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
661        f.write_str(&self.text)
662    }
663}
664
665/// Spread `wait` over its upper half at random, so jobs that failed together do
666/// not all try again at once. `None` when the spread does not fit a `Duration`.
667#[must_use]
668pub fn jittered(wait: Duration) -> Option<Duration> {
669    // Below one million, so the spread is from one half to the whole of `wait`.
670    let random = u32::try_from(Uuid::new_v4().as_u128() % 1_000_000).ok()?;
671    wait.checked_mul(1_000_000_u32.checked_add(random)?)?
672        .checked_div(2_000_000)
673}
674
675/// How long to wait before the attempt after `attempts`: the delay a job chose,
676/// held between [`MIN_RETRY_AFTER`] and an hour, or else the doubling backoff
677/// from `base`, jittered.
678#[must_use]
679pub fn retry_wait(base: Duration, attempts: i32, chosen: Option<Duration>) -> Option<Duration> {
680    match chosen {
681        // WRK-41: a delay a job chose is between the shortest and the longest wait, or
682        // it has no wait.
683        Some(delay) => (MIN_RETRY_AFTER..=MAX_BACKOFF)
684            .contains(&delay)
685            .then_some(delay),
686        None => backoff(base, attempts).and_then(jittered),
687    }
688}
689
690/// Cut `text` to at most [`MAX_ERROR`] bytes, on a character boundary.
691fn cut(mut text: String) -> String {
692    if text.len() > MAX_ERROR {
693        let end = text.floor_char_boundary(MAX_ERROR);
694        text.truncate(end);
695    }
696    text
697}
698
699/// Why a run is stopped when its times do not fit.
700const TIMING: &str = "a time for the run is too large to compute";
701
702/// When a worker stops a job it cannot report on: two heartbeats before another worker
703/// may take it. `None` when the times do not fit. [`QueueOptions::check`] keeps
704/// the heartbeat to a quarter of the stale time, so this is at half of it or later.
705fn give_up_after(stale_minutes: i32, every: Duration) -> Option<Duration> {
706    let stale = Duration::from_secs(u64::try_from(stale_minutes).ok()?.checked_mul(60)?);
707    stale.checked_sub(every.checked_mul(2)?)
708}
709
710fn millis(duration: Duration) -> i64 {
711    i64::try_from(duration.as_millis()).unwrap_or(i64::MAX)
712}
713
714fn from_millis(millis: i64) -> Duration {
715    Duration::from_millis(u64::try_from(millis).unwrap_or(0))
716}
717
718/// When a new job may first run.
719#[derive(Debug, Clone, Copy, PartialEq, Eq)]
720enum When {
721    Now,
722    At(Timestamp),
723    In(Duration),
724}
725
726/// A job to queue: its type, its arguments, and when and how it runs.
727#[derive(Clone)]
728pub struct NewJob {
729    name: String,
730    args: serde_json::Value,
731    max_attempts: Option<i32>,
732    priority: i16,
733    when: When,
734    timeout: Option<Duration>,
735    tenant: Option<String>,
736    unique_key: Option<String>,
737}
738
739impl fmt::Debug for NewJob {
740    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
741        f.debug_struct("NewJob")
742            .field("name", &self.name)
743            .field("max_attempts", &self.max_attempts)
744            .field("priority", &self.priority)
745            .field("when", &self.when)
746            .field("timeout", &self.timeout)
747            .field("tenant", &self.tenant)
748            .field("unique_key", &self.unique_key)
749            .finish_non_exhaustive()
750    }
751}
752
753impl NewJob {
754    /// A job for the handler named `name`, ready now, with the queue's limit on
755    /// tries and priority zero.
756    pub fn new(name: impl Into<String>, args: serde_json::Value) -> Self {
757        Self {
758            name: name.into(),
759            args,
760            max_attempts: None,
761            priority: 0,
762            when: When::Now,
763            timeout: None,
764            tenant: None,
765            unique_key: None,
766        }
767    }
768
769    /// Queue this job only if no job of its name, tenant, and `key` is queued or
770    /// running: otherwise queuing it adds nothing and answers the id of the one
771    /// there, whose arguments, priority, and time stand. The key is a code, at most
772    /// [`MAX_REASON_CHARS`] characters with no line breaks, such as `"sync:42"`, and
773    /// is kept on the job's row, so it holds no secret or personal data. Enqueuing
774    /// refuses any other key with [`Error::NotACode`].
775    #[must_use]
776    pub fn unique(mut self, key: impl Into<String>) -> Self {
777        self.unique_key = Some(key.into());
778        self
779    }
780
781    /// Run this job for `tenant`, the id an auth crate's `Tenant` gives, which its
782    /// handler receives beside the arguments, so that it can open its own tenant
783    /// transaction. Only a handler registered with [`Queue::handle_with_tenant`] runs
784    /// it. Enqueuing refuses an id that is not a tenant id, with
785    /// [`Error::NotATenant`].
786    #[must_use]
787    pub fn tenant(mut self, tenant: impl Into<String>) -> Self {
788        self.tenant = Some(tenant.into());
789        self
790    }
791
792    /// Stop a run of this job past `limit`, and count it as failed with the reason.
793    /// A job has no time limit unless it is given one.
794    #[must_use]
795    pub const fn timeout(mut self, limit: Duration) -> Self {
796        self.timeout = Some(limit);
797        self
798    }
799
800    /// Tries this job gets, including the first, or the queue's when `None`.
801    #[must_use]
802    pub const fn max_attempts(mut self, max_attempts: Option<i32>) -> Self {
803        self.max_attempts = max_attempts;
804        self
805    }
806
807    /// Run ahead of ready jobs with a lower priority. Zero by default, and may be
808    /// negative.
809    #[must_use]
810    pub const fn priority(mut self, priority: i16) -> Self {
811        self.priority = priority;
812        self
813    }
814
815    /// Run no sooner than `delay` from now, on the database's clock.
816    #[must_use]
817    pub const fn run_in(mut self, delay: Duration) -> Self {
818        self.when = When::In(delay);
819        self
820    }
821
822    /// Run no sooner than `at`.
823    #[must_use]
824    pub const fn run_at(mut self, at: Timestamp) -> Self {
825        self.when = When::At(at);
826        self
827    }
828
829    /// The handler this job is for.
830    #[must_use]
831    pub fn name(&self) -> &str {
832        &self.name
833    }
834
835    /// The tenant this job runs for, if any.
836    #[must_use]
837    pub fn tenant_id(&self) -> Option<&str> {
838        self.tenant.as_deref()
839    }
840
841    /// The key this job is unique by, if any.
842    #[must_use]
843    pub fn unique_key(&self) -> Option<&str> {
844        self.unique_key.as_deref()
845    }
846}
847
848/// The longest tenant id, which a DNS label also allows.
849pub const MAX_TENANT_ID_LEN: usize = 63;
850
851/// Whether `id` is a tenant id: lower-case ASCII letters, digits, and hyphens, not
852/// starting or ending with a hyphen, from 1 to 63 characters, as a DNS label is, and as
853/// the auth crates' `Tenant` holds. The table's check holds to the same rule.
854#[must_use]
855pub fn is_tenant_id(id: &str) -> bool {
856    (1..=MAX_TENANT_ID_LEN).contains(&id.len())
857        && !id.starts_with('-')
858        && !id.ends_with('-')
859        && id
860            .bytes()
861            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
862}
863
864/// Add `job` on `executor`, usually the caller's transaction, and return its id.
865/// The job then commits or rolls back with the transaction. A job with a
866/// [`NewJob::unique`] key that is already queued or running adds nothing, and the id
867/// is that job's.
868///
869/// # Errors
870///
871/// Fails on a database error, with [`Error::NotATenant`] for a tenant that is not a
872/// tenant id, and with [`Error::NotACode`] for a key that is not a code, before
873/// anything is written.
874pub async fn enqueue_on<'e, E: PgExecutor<'e>>(executor: E, job: &NewJob) -> Result<Uuid> {
875    if job
876        .tenant
877        .as_deref()
878        .is_some_and(|tenant| !is_tenant_id(tenant))
879    {
880        return Err(Error::NotATenant);
881    }
882    if let Some(key) = job.unique_key.as_deref() {
883        check_code(key, "unique key")?;
884    }
885    let id = Uuid::new_v4();
886    let (at, delay) = match job.when {
887        When::Now => (None, 0.0_f64),
888        When::At(at) => (Some(at), 0.0_f64),
889        When::In(delay) => (None, delay.as_secs_f64()),
890    };
891    let query = sqlx::query(if job.unique_key.is_some() {
892        ENQUEUE_UNIQUE
893    } else {
894        ENQUEUE
895    })
896    .bind(id)
897    .bind(&job.name)
898    .bind(&job.args)
899    .bind(job.max_attempts)
900    .bind(job.priority)
901    .bind(at.map(jiff_sqlx::Timestamp::from))
902    .bind(delay)
903    .bind(job.timeout.map(millis))
904    .bind(job.tenant.as_deref());
905    if let Some(key) = job.unique_key.as_deref() {
906        Ok(query.bind(key).fetch_one(executor).await?.try_get("id")?)
907    } else {
908        query.execute(executor).await?;
909        Ok(id)
910    }
911}
912
913/// Add every job in `jobs` on `connection`, returning their ids in order. On a
914/// transaction they commit or roll back together; [`Queue::enqueue_all`] opens one.
915///
916/// # Errors
917///
918/// Fails on a database error, after which a transaction must be rolled back.
919pub async fn enqueue_all_on(connection: &mut PgConnection, jobs: &[NewJob]) -> Result<Vec<Uuid>> {
920    let mut ids = Vec::with_capacity(jobs.len());
921    for job in jobs {
922        ids.push(enqueue_on(&mut *connection, job).await?);
923    }
924    Ok(ids)
925}
926
927/// Refuse who or why for a person's act unless it is a code.
928fn check_code(text: &str, what: &'static str) -> Result<()> {
929    if text.is_empty()
930        || text.chars().count() > MAX_REASON_CHARS
931        || text.chars().any(char::is_control)
932    {
933        Err(Error::NotACode { what })
934    } else {
935        Ok(())
936    }
937}
938
939/// Cancel the job `id` if it is still queued, as an act of `by`, for `reason`, kept in
940/// `axa_job_acts` in the caller's transaction, so that the caller's own audit row
941/// commits with it. Answers whether it was cancelled. A job already claimed runs on:
942/// cancelling cannot stop work in progress. A job in any other state, or no such job,
943/// changes nothing and writes no act.
944///
945/// The job's row stays locked until the transaction ends, so keep it short.
946///
947/// # Errors
948///
949/// Fails on a database error, and with [`Error::NotACode`] when `by` or `reason` is
950/// empty, longer than [`MAX_REASON_CHARS`], or has a line break, before anything is
951/// written.
952pub async fn cancel(
953    transaction: &mut Transaction<'_, Postgres>,
954    id: Uuid,
955    by: &str,
956    reason: &str,
957) -> Result<bool> {
958    act(transaction, CANCEL, id, by, reason).await
959}
960
961/// Queue the job `id` again, now, for one more try, if it failed or waits for review,
962/// as an act of `by`, for `reason`, kept in `axa_job_acts` in the caller's
963/// transaction. The act is [`ActKind::Retried`] for a failed job and
964/// [`ActKind::Released`] for one in review. Answers whether it was queued again. A job
965/// in any other state, or no such job, changes nothing and writes no act. Its last
966/// error stays until it next runs.
967///
968/// # Errors
969///
970/// Fails on a database error, and with [`Error::NotACode`] when `by` or `reason` is
971/// empty, longer than [`MAX_REASON_CHARS`], or has a line break, before anything is
972/// written.
973pub async fn retry(
974    transaction: &mut Transaction<'_, Postgres>,
975    id: Uuid,
976    by: &str,
977    reason: &str,
978) -> Result<bool> {
979    act(transaction, RETRY_FAILED, id, by, reason).await
980}
981
982/// Run one act's statement, which changes the job and keeps the act together.
983async fn act(
984    transaction: &mut Transaction<'_, Postgres>,
985    statement: &'static str,
986    id: Uuid,
987    by: &str,
988    reason: &str,
989) -> Result<bool> {
990    check_code(by, "by")?;
991    check_code(reason, "reason")?;
992    let kept = sqlx::query(statement)
993        .bind(id)
994        .bind(by)
995        .bind(reason)
996        .execute(&mut **transaction)
997        .await?
998        .rows_affected();
999    Ok(kept == 1)
1000}
1001
1002/// What a person did to a job.
1003#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1004#[non_exhaustive]
1005pub enum ActKind {
1006    /// Cancelled it while it was queued.
1007    Cancelled,
1008    /// Queued it again after it failed.
1009    Retried,
1010    /// Released it from review, to run again.
1011    Released,
1012}
1013
1014impl ActKind {
1015    fn parse(text: &str) -> Result<Self> {
1016        match text {
1017            "cancelled" => Ok(Self::Cancelled),
1018            "retried" => Ok(Self::Retried),
1019            "released" => Ok(Self::Released),
1020            _ => Err(Error::Job("an act with an unknown kind".to_string())),
1021        }
1022    }
1023}
1024
1025/// One act of a person on a job, as `axa_job_acts` keeps it. It outlives the job's
1026/// row, which retention deletes.
1027#[derive(Debug, Clone)]
1028#[non_exhaustive]
1029pub struct Act {
1030    /// The act's row. It rises with each act.
1031    pub id: i64,
1032    /// The job it was done to.
1033    pub job_id: Uuid,
1034    /// The handler that job is for.
1035    pub job_name: String,
1036    /// What was done.
1037    pub kind: ActKind,
1038    /// The job's runs so far when it was done.
1039    pub attempts: i32,
1040    /// Who did it, as the service named them.
1041    pub by: String,
1042    /// Why, as a short code.
1043    pub reason: String,
1044    /// When, on the database's clock.
1045    pub at: Timestamp,
1046}
1047
1048/// Where a job is.
1049#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1050pub enum JobState {
1051    /// Waiting to be claimed, now or at its time.
1052    Queued,
1053    /// Claimed by a job loop.
1054    Running,
1055    /// Finished.
1056    Completed,
1057    /// Out of tries, or given up on.
1058    Failed,
1059    /// Cancelled before it ran.
1060    Cancelled,
1061    /// Its run lost its claim and was stopped, so it may have run in part or
1062    /// twice. It is never retried by itself: a person looks, and calls
1063    /// [`retry()`] to release it.
1064    NeedsReview,
1065}
1066
1067impl JobState {
1068    fn parse(text: &str) -> Result<Self> {
1069        match text {
1070            "queued" => Ok(Self::Queued),
1071            "running" => Ok(Self::Running),
1072            "completed" => Ok(Self::Completed),
1073            "failed" => Ok(Self::Failed),
1074            "cancelled" => Ok(Self::Cancelled),
1075            "needs_review" => Ok(Self::NeedsReview),
1076            _ => Err(Error::Job("a job row with an unknown status".to_string())),
1077        }
1078    }
1079}
1080
1081/// What the queue knows of one job. Its arguments are left out.
1082#[derive(Debug, Clone)]
1083#[non_exhaustive]
1084pub struct JobInfo {
1085    /// The job's id.
1086    pub id: Uuid,
1087    /// The handler it is for.
1088    pub name: String,
1089    /// Where it is.
1090    pub state: JobState,
1091    /// Runs so far, including one in progress.
1092    pub attempts: i32,
1093    /// Its own limit on tries, or `None` for the queue's.
1094    pub max_attempts: Option<i32>,
1095    /// Its priority.
1096    pub priority: i16,
1097    /// Its time limit, if it was given one.
1098    pub timeout: Option<Duration>,
1099    /// The tenant it runs for, if any.
1100    pub tenant: Option<String>,
1101    /// The key it is unique by while queued or running, if any.
1102    pub unique_key: Option<String>,
1103    /// The text of its last failure. For operators only: it is whatever the job's
1104    /// error said.
1105    pub error: Option<String>,
1106    /// When it may run next, or last could.
1107    pub run_at: Timestamp,
1108    /// When its latest run started.
1109    pub started_at: Option<Timestamp>,
1110    /// When it was queued.
1111    pub created_at: Timestamp,
1112    /// When its row last changed.
1113    pub updated_at: Timestamp,
1114}
1115
1116/// How many jobs are in each state, for metrics.
1117#[derive(Debug, Clone, Copy, Default, PartialEq)]
1118#[non_exhaustive]
1119pub struct Counts {
1120    /// Queued and due.
1121    pub ready: i64,
1122    /// Queued for a later time.
1123    pub waiting: i64,
1124    /// Claimed and running.
1125    pub running: i64,
1126    /// Finished, and not yet deleted by retention.
1127    pub completed: i64,
1128    /// Failed, and not yet deleted by retention.
1129    pub failed: i64,
1130    /// Cancelled, and not yet deleted by retention.
1131    pub cancelled: i64,
1132    /// Stopped after losing their claim, waiting for a person. Never deleted by
1133    /// retention.
1134    pub needs_review: i64,
1135    /// Seconds the oldest ready job has waited, or zero. A rising value means jobs
1136    /// are not being run.
1137    pub oldest_ready_seconds: f64,
1138}
1139
1140/// A job queued every interval, or at the times a cron pattern names. See
1141/// [Schedules](crate#schedules).
1142#[derive(Clone)]
1143pub struct Schedule {
1144    name: String,
1145    times: Times,
1146    first: Option<Timestamp>,
1147    job: NewJob,
1148}
1149
1150/// When a schedule is due.
1151#[derive(Clone)]
1152enum Times {
1153    Every(Duration),
1154    /// The parsed pattern, and the pattern as written, which `croner` would rewrite.
1155    Cron(Box<croner::Cron>, String),
1156}
1157
1158impl Times {
1159    fn interval(&self) -> Option<Duration> {
1160        match self {
1161            Self::Every(interval) => Some(*interval),
1162            Self::Cron(..) => None,
1163        }
1164    }
1165
1166    fn pattern(&self) -> Option<&str> {
1167        match self {
1168            Self::Every(_) => None,
1169            Self::Cron(_, pattern) => Some(pattern),
1170        }
1171    }
1172}
1173
1174/// The time after `now` a cron pattern names, in UTC.
1175fn next_after(cron: &croner::Cron, now: Timestamp) -> Result<Timestamp> {
1176    cron.find_next_occurrence(&InUtc(now), false)
1177        .map(|next| next.0)
1178        .map_err(|error| Error::Job(format!("the cron pattern has no next time: {error}")))
1179}
1180
1181/// An instant as `croner` reads it, on a wall clock in UTC, which has no daylight
1182/// saving, so every wall clock time is one instant. `croner`'s own `jiff` support is for
1183/// an older `jiff`, so the crate gives it this one time zone itself.
1184#[derive(Clone, Copy)]
1185struct InUtc(Timestamp);
1186
1187impl croner::CronDateTime for InUtc {
1188    fn to_civil(&self) -> croner::CivilDateTime {
1189        let time = jiff::tz::TimeZone::UTC.to_datetime(self.0);
1190        croner::CivilDateTime::new(
1191            croner::CivilDate::from_parts_unchecked(
1192                i32::from(time.year()),
1193                time.month().unsigned_abs().into(),
1194                time.day().unsigned_abs().into(),
1195            ),
1196            croner::CivilTime::from_parts_unchecked(
1197                time.hour().unsigned_abs().into(),
1198                time.minute().unsigned_abs().into(),
1199                time.second().unsigned_abs().into(),
1200            ),
1201        )
1202    }
1203
1204    fn civil_weekday(&self) -> croner::Weekday {
1205        let day = jiff::tz::TimeZone::UTC
1206            .to_datetime(self.0)
1207            .weekday()
1208            .to_sunday_zero_offset();
1209        croner::Weekday::from_days_from_sunday(day.unsigned_abs().into())
1210    }
1211
1212    fn resolve_civil(
1213        &self,
1214        civil: croner::CivilDateTime,
1215    ) -> Result<croner::Resolution<Self>, croner::errors::CronError> {
1216        let part =
1217            |value: u32| i8::try_from(value).map_err(|_| croner::errors::CronError::InvalidDate);
1218        let year =
1219            i16::try_from(civil.year()).map_err(|_| croner::errors::CronError::InvalidDate)?;
1220        let time = jiff::civil::DateTime::new(
1221            year,
1222            part(civil.month())?,
1223            part(civil.day())?,
1224            part(civil.hour())?,
1225            part(civil.minute())?,
1226            part(civil.second())?,
1227            0,
1228        )
1229        .and_then(|time| jiff::tz::TimeZone::UTC.to_timestamp(time))
1230        .map_err(|_| croner::errors::CronError::InvalidDate)?;
1231        Ok(croner::Resolution::Single(Self(time)))
1232    }
1233
1234    fn checked_add_seconds(&self, seconds: i64) -> Option<Self> {
1235        self.0
1236            .checked_add(jiff::SignedDuration::from_secs(seconds))
1237            .ok()
1238            .map(Self)
1239    }
1240
1241    fn cmp_instant(&self, other: &Self) -> std::cmp::Ordering {
1242        self.0.cmp(&other.0)
1243    }
1244}
1245
1246/// A time column of `row`.
1247fn time(row: &PgRow, column: &str) -> Result<Timestamp> {
1248    Ok(row.try_get::<jiff_sqlx::Timestamp, _>(column)?.to_jiff())
1249}
1250
1251/// A time column of `row` that may be `NULL`.
1252fn time_or_none(row: &PgRow, column: &str) -> Result<Option<Timestamp>> {
1253    Ok(row
1254        .try_get::<Option<jiff_sqlx::Timestamp>, _>(column)?
1255        .map(jiff_sqlx::Timestamp::to_jiff))
1256}
1257
1258impl fmt::Debug for Schedule {
1259    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1260        f.debug_struct("Schedule")
1261            .field("name", &self.name)
1262            .field("interval", &self.times.interval())
1263            .field("cron", &self.times.pattern())
1264            .field("first", &self.first)
1265            .field("job", &self.job)
1266            .finish()
1267    }
1268}
1269
1270impl Schedule {
1271    /// Queue `job` every `interval`, under the schedule name `name`. The name keys
1272    /// its row, so keep it stable across releases. A delay set on `job` is ignored.
1273    ///
1274    /// # Errors
1275    ///
1276    /// [`Error::Schedule`] when the name is empty or over 200 characters, or the
1277    /// interval is under a second: these are mistakes in code, found at boot.
1278    pub fn every(name: impl Into<String>, interval: Duration, job: NewJob) -> Result<Self> {
1279        let name = checked_name(name.into())?;
1280        if interval < Duration::from_secs(1) {
1281            return Err(Error::Schedule(format!(
1282                "the schedule {name} needs an interval of at least a second"
1283            )));
1284        }
1285        Ok(Self {
1286            name,
1287            times: Times::Every(interval),
1288            first: None,
1289            job: NewJob {
1290                when: When::Now,
1291                ..job
1292            },
1293        })
1294    }
1295
1296    /// Queue `job` at each time the cron `pattern` names, in UTC on the database's
1297    /// clock, under the schedule name `name`. The pattern has five fields, minute to
1298    /// day of week, or six with seconds first, as `croner` reads them: `"0 2 * * *"` is
1299    /// 02:00 each day, and `"0 9 * * MON-FRI"` 09:00 each weekday. A delay set on `job`
1300    /// is ignored. The first time is the pattern's next after the row is made.
1301    ///
1302    /// # Errors
1303    ///
1304    /// [`Error::Schedule`] when the name is empty or over 200 characters, or the
1305    /// pattern does not parse or names no time to come: these are mistakes in code,
1306    /// found at boot.
1307    pub fn cron(name: impl Into<String>, pattern: &str, job: NewJob) -> Result<Self> {
1308        let name = checked_name(name.into())?;
1309        let cron: croner::Cron = pattern.parse().map_err(|error| {
1310            Error::Schedule(format!(
1311                "the schedule {name} has a bad cron pattern: {error}"
1312            ))
1313        })?;
1314        if next_after(&cron, Timestamp::now()).is_err() {
1315            return Err(Error::Schedule(format!(
1316                "the cron pattern of the schedule {name} names no time to come"
1317            )));
1318        }
1319        Ok(Self {
1320            name,
1321            times: Times::Cron(Box::new(cron), pattern.to_string()),
1322            first: None,
1323            job: NewJob {
1324                when: When::Now,
1325                ..job
1326            },
1327        })
1328    }
1329
1330    /// The first due time, used only when the schedule's row is made. With an
1331    /// interval of 24 hours and a first time at 02:00 UTC, the job runs at 02:00
1332    /// each day. Without one, the first is as soon as the row is made. A cron
1333    /// schedule's first time is its pattern's, and it ignores this.
1334    #[must_use]
1335    pub const fn first_at(mut self, first: Timestamp) -> Self {
1336        self.first = Some(first);
1337        self
1338    }
1339
1340    /// The schedule's interval, or `None` for a cron schedule.
1341    #[must_use]
1342    pub fn interval(&self) -> Option<Duration> {
1343        self.times.interval()
1344    }
1345
1346    /// The schedule's cron pattern, or `None` for one every interval.
1347    #[must_use]
1348    pub fn cron_pattern(&self) -> Option<&str> {
1349        self.times.pattern()
1350    }
1351
1352    /// The schedule's name.
1353    #[must_use]
1354    pub fn name(&self) -> &str {
1355        &self.name
1356    }
1357}
1358
1359/// Refuse a schedule name that is empty or over 200 characters.
1360fn checked_name(name: String) -> Result<String> {
1361    if name.is_empty() || name.len() > 200 {
1362        return Err(Error::Schedule(
1363            "a schedule name must be 1 to 200 characters".to_string(),
1364        ));
1365    }
1366    Ok(name)
1367}
1368
1369/// What the table holds of one schedule.
1370#[derive(Debug, Clone)]
1371#[non_exhaustive]
1372pub struct ScheduleInfo {
1373    /// Its name.
1374    pub name: String,
1375    /// Its interval, as the code last had it, or `None` for a cron schedule.
1376    pub interval: Option<Duration>,
1377    /// Its cron pattern, as the code last had it, or `None` for one every interval.
1378    pub cron: Option<String>,
1379    /// When it is next due.
1380    pub due_at: Timestamp,
1381    /// The last job it queued.
1382    pub last_job: Option<Uuid>,
1383    /// That job's state, unless retention deleted it.
1384    pub last_state: Option<JobState>,
1385    /// That job's last failure text. For operators only.
1386    pub last_error: Option<String>,
1387    /// When a live process last had it in code, to within a minute.
1388    pub seen_at: Timestamp,
1389    /// When it was archived, as no live process had it in code. An archived
1390    /// schedule queues nothing, and a schedule of that name in code restores it.
1391    pub archived_at: Option<Timestamp>,
1392    /// When its row was made.
1393    pub created_at: Timestamp,
1394}
1395
1396/// Queue tuning.
1397#[derive(Debug, Clone)]
1398pub struct QueueOptions {
1399    /// Concurrent job loops, so the most jobs this process runs at once.
1400    pub workers: usize,
1401    /// Sleep between polls of an empty queue, and between schedule ticks.
1402    pub poll_interval: Duration,
1403    /// A running job not heard from for this many minutes is assumed lost with
1404    /// its worker.
1405    pub stale_minutes: i32,
1406    /// How often a running job reports in: at least 20 ms, and at most a quarter of
1407    /// `stale_minutes`. [`QueueOptions::check`] refuses anything else.
1408    pub heartbeat_interval: Duration,
1409    /// Tries a job gets, including the first, unless it has its own limit. One
1410    /// means no retries.
1411    pub max_attempts: i32,
1412    /// The wait before the first retry.
1413    pub retry_backoff: Duration,
1414    /// Days to keep finished and cancelled rows.
1415    pub retention_days: i32,
1416    /// How often to recover stale jobs and delete old rows.
1417    pub maintenance_interval: Duration,
1418}
1419
1420impl QueueOptions {
1421    /// Whether these settings can run a queue. A setting out of range is refused here,
1422    /// not held to a limit.
1423    ///
1424    /// # Errors
1425    ///
1426    /// [`Error::OutOfRange`], naming the setting: `workers` that do not fit a `u32`;
1427    /// `stale_minutes` under one or too many to count in seconds; or a
1428    /// `heartbeat_interval` under 20 ms or over a quarter of `stale_minutes`, so that a
1429    /// run gives up two heartbeats before it is stale, and no earlier than half of it.
1430    pub fn check(&self) -> Result<()> {
1431        if u32::try_from(self.workers).is_err() {
1432            return Err(Error::OutOfRange("workers"));
1433        }
1434        let stale = u64::try_from(self.stale_minutes)
1435            .ok()
1436            .filter(|minutes| *minutes >= 1)
1437            .and_then(|minutes| minutes.checked_mul(60))
1438            .map(Duration::from_secs)
1439            .ok_or(Error::OutOfRange("stale_minutes"))?;
1440        let fits = self.heartbeat_interval >= MIN_HEARTBEAT
1441            && self
1442                .heartbeat_interval
1443                .checked_mul(4)
1444                .is_some_and(|four| four <= stale);
1445        if !fits {
1446            return Err(Error::OutOfRange("heartbeat_interval"));
1447        }
1448        Ok(())
1449    }
1450}
1451
1452impl Default for QueueOptions {
1453    fn default() -> Self {
1454        Self {
1455            workers: 2,
1456            poll_interval: Duration::from_secs(1),
1457            stale_minutes: 60,
1458            heartbeat_interval: Duration::from_mins(1),
1459            max_attempts: 1,
1460            retry_backoff: Duration::from_secs(30),
1461            retention_days: 7,
1462            maintenance_interval: Duration::from_mins(5),
1463        }
1464    }
1465}
1466
1467/// A Postgres-backed job queue.
1468pub struct Queue {
1469    pool: PgPool,
1470    handlers: HashMap<String, Handler>,
1471    limits: HashMap<String, Arc<Semaphore>>,
1472    schedules: Vec<Schedule>,
1473    options: QueueOptions,
1474}
1475
1476impl fmt::Debug for Queue {
1477    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1478        f.debug_struct("Queue")
1479            .field("handlers", &self.handlers.len())
1480            .field("limits", &self.limits.len())
1481            .field("schedules", &self.schedules.len())
1482            .field("options", &self.options)
1483            .finish_non_exhaustive()
1484    }
1485}
1486
1487/// A claimed job, as `run_one` holds it.
1488struct Claimed {
1489    id: Uuid,
1490    name: String,
1491    args: serde_json::Value,
1492    attempts: i32,
1493    limit: i32,
1494    timeout: Option<Duration>,
1495    tenant: Option<String>,
1496}
1497
1498/// How a run ended.
1499enum Outcome {
1500    /// The job answered, or failed, timed out, or panicked, with this text.
1501    Done(Result<(), Failure>),
1502    /// The run lost its claim and was stopped, for this reason.
1503    Lost(String),
1504}
1505
1506impl Queue {
1507    /// A queue on `pool`, checking and changing nothing. Call [`Queue::check`] at
1508    /// boot. Give the pool at least `workers + 2` connections.
1509    ///
1510    /// # Errors
1511    ///
1512    /// [`Error::OutOfRange`] when `options` fail [`QueueOptions::check`].
1513    pub fn from_pool(pool: PgPool, options: QueueOptions) -> Result<Self> {
1514        options.check()?;
1515        Ok(Self {
1516            pool,
1517            handlers: HashMap::new(),
1518            limits: HashMap::new(),
1519            schedules: Vec::new(),
1520            options,
1521        })
1522    }
1523
1524    /// Open a pool sized for the job loops, without touching the schema.
1525    async fn open(uri: &str, options: QueueOptions) -> Result<Self> {
1526        options.check()?;
1527        let loops = u32::try_from(options.workers).map_err(|_| Error::OutOfRange("workers"))?;
1528        let pool = PgPoolOptions::new()
1529            // The loops, housekeeping, schedules, and the listener.
1530            .max_connections(loops.checked_add(3).ok_or(Error::Overflow("connections"))?)
1531            .connect(uri)
1532            .await?;
1533        Self::from_pool(pool, options)
1534    }
1535
1536    /// Connect to tables that a migration made, and change no schema, for a database
1537    /// role that may not. A migration runs [`SETUP_STATEMENTS`].
1538    ///
1539    /// # Errors
1540    ///
1541    /// Fails when the database cannot be reached, a table is missing or out of date,
1542    /// or a trigger of `axa_job_acts` is missing or not set to fire always, so a
1543    /// service finds out at boot rather than at its first job. There is no way to run
1544    /// without the triggers.
1545    pub async fn connect_existing(uri: &str, options: QueueOptions) -> Result<Self> {
1546        let queue = Self::open(uri, options).await?;
1547        queue.check().await?;
1548        Ok(queue)
1549    }
1550
1551    /// Connect and create the tables if needed, which runs DDL at boot. Use
1552    /// [`Queue::connect_existing`] where a service's role may not.
1553    ///
1554    /// # Errors
1555    ///
1556    /// Fails when the database cannot be reached or the tables not created.
1557    pub async fn connect(uri: &str, options: QueueOptions) -> Result<Self> {
1558        let queue = Self::open(uri, options).await?;
1559        // `CREATE ... IF NOT EXISTS` is not safe against itself: two services
1560        // booting together can both pass the check and one then fails on a
1561        // catalog constraint. The lock makes setup run one at a time, and
1562        // ends with the transaction.
1563        let mut setup = queue.pool.begin().await?;
1564        sqlx::query("SELECT pg_advisory_xact_lock($1)")
1565            .bind(SETUP_LOCK)
1566            .execute(&mut *setup)
1567            .await?;
1568        for statement in SETUP_STATEMENTS {
1569            sqlx::query(statement).execute(&mut *setup).await?;
1570        }
1571        setup.commit().await?;
1572        Ok(queue)
1573    }
1574
1575    /// Check that the tables exist and are up to date, and that the triggers of
1576    /// `axa_job_acts` are there and set to fire always.
1577    ///
1578    /// # Errors
1579    ///
1580    /// Fails when the database cannot be reached, a table is missing or out of date,
1581    /// or a trigger is missing or turned off.
1582    pub async fn check(&self) -> Result<()> {
1583        sqlx::query(
1584            "SELECT attempts, max_attempts, priority, timeout_ms, tenant, unique_key FROM axa_queue LIMIT 0",
1585        )
1586        .execute(&self.pool)
1587        .await?;
1588        sqlx::query(
1589            "SELECT name, due_at, last_job, interval_ms, cron, seen_at, archived_at FROM axa_schedule LIMIT 0",
1590        )
1591            .execute(&self.pool)
1592            .await?;
1593        sqlx::query(
1594            "SELECT id, job_id, job_name, act, attempts, by, reason, at FROM axa_job_acts LIMIT 0",
1595        )
1596        .execute(&self.pool)
1597        .await?;
1598        let mut missing: Vec<String> = sqlx::query_scalar(MISSING_TRIGGERS)
1599            .bind(ACTS_TRIGGERS.to_vec())
1600            .fetch_all(&self.pool)
1601            .await?;
1602        let unique_index: bool =
1603            sqlx::query_scalar("SELECT to_regclass('axa_queue_unique') IS NOT NULL")
1604                .fetch_one(&self.pool)
1605                .await?;
1606        if !unique_index {
1607            missing.push("axa_queue_unique".to_string());
1608        }
1609        if missing.is_empty() {
1610            Ok(())
1611        } else {
1612            Err(Error::Database(sqlx::Error::Configuration(
1613                format!(
1614                    "the job queue is missing, or has turned off, {}: run SETUP_STATEMENTS",
1615                    missing.join(", ")
1616                )
1617                .into(),
1618            )))
1619        }
1620    }
1621
1622    /// The pool, for a service's own queries or [`enqueue_on`] outside a
1623    /// transaction.
1624    #[must_use]
1625    pub const fn pool(&self) -> &PgPool {
1626        &self.pool
1627    }
1628
1629    /// The options this queue runs with.
1630    #[must_use]
1631    pub const fn options(&self) -> &QueueOptions {
1632        &self.options
1633    }
1634
1635    /// Run `handler` for jobs named `name`. Its error text is kept on the job's
1636    /// row. Registering a name again replaces its handler.
1637    ///
1638    /// A job queued for a tenant, with [`NewJob::tenant`], is failed rather than run
1639    /// here, as this handler would run it with no tenant: register a handler that
1640    /// takes one with [`Queue::handle_with_tenant`].
1641    pub fn handle<F, Fut, E>(&mut self, name: impl Into<String>, handler: F)
1642    where
1643        F: Fn(serde_json::Value) -> Fut + Send + Sync + 'static,
1644        Fut: Future<Output = std::result::Result<(), E>> + Send + 'static,
1645        E: fmt::Display + 'static,
1646    {
1647        let handler = Arc::new(handler);
1648        let run: Handler = Arc::new(move |tenant, args| {
1649            if tenant.is_some() {
1650                return Box::pin(std::future::ready(Err(NO_TENANT_HANDLER
1651                    .to_string()
1652                    .into())));
1653            }
1654            let job = handler(args);
1655            Box::pin(async move { job.await.map_err(Failure::from_error) })
1656        });
1657        self.handlers.insert(name.into(), run);
1658    }
1659
1660    /// Run `handler` for jobs named `name`, handing it the job's tenant, or `None` for
1661    /// a job queued with none, beside its arguments, so that it can open its own
1662    /// tenant transaction. Claiming stays fair across jobs, not tenants. Registering a
1663    /// name again replaces its handler.
1664    pub fn handle_with_tenant<F, Fut, E>(&mut self, name: impl Into<String>, handler: F)
1665    where
1666        F: Fn(Option<String>, serde_json::Value) -> Fut + Send + Sync + 'static,
1667        Fut: Future<Output = std::result::Result<(), E>> + Send + 'static,
1668        E: fmt::Display + 'static,
1669    {
1670        let handler = Arc::new(handler);
1671        let run: Handler = Arc::new(move |tenant, args| {
1672            let job = handler(tenant, args);
1673            Box::pin(async move { job.await.map_err(Failure::from_error) })
1674        });
1675        self.handlers.insert(name.into(), run);
1676    }
1677
1678    /// Run at most `jobs` jobs named `name` at once in this process, and at least
1679    /// one. Other jobs keep the remaining loops busy.
1680    pub fn limit(&mut self, name: impl Into<String>, jobs: usize) {
1681        self.limits
1682            .insert(name.into(), Arc::new(Semaphore::new(jobs.max(1))));
1683    }
1684
1685    /// Queue a job on every due time of `schedule`.
1686    ///
1687    /// # Errors
1688    ///
1689    /// [`Error::Schedule`] when a schedule of that name was added already.
1690    pub fn schedule(&mut self, schedule: Schedule) -> Result<()> {
1691        if self.schedules.iter().any(|s| s.name == schedule.name) {
1692            return Err(Error::Schedule(format!(
1693                "the schedule {} was added twice",
1694                schedule.name
1695            )));
1696        }
1697        self.schedules.push(schedule);
1698        Ok(())
1699    }
1700
1701    /// Add a job and return its id.
1702    ///
1703    /// # Errors
1704    ///
1705    /// Fails on a database error.
1706    pub async fn enqueue(&self, name: &str, args: serde_json::Value) -> Result<Uuid> {
1707        enqueue_on(&self.pool, &NewJob::new(name, args)).await
1708    }
1709
1710    /// Add a job with its own limit on tries, or the queue's when `None`.
1711    ///
1712    /// # Errors
1713    ///
1714    /// Fails on a database error.
1715    pub async fn enqueue_limited(
1716        &self,
1717        name: &str,
1718        args: serde_json::Value,
1719        max_attempts: Option<i32>,
1720    ) -> Result<Uuid> {
1721        enqueue_on(
1722            &self.pool,
1723            &NewJob::new(name, args).max_attempts(max_attempts),
1724        )
1725        .await
1726    }
1727
1728    /// Add `job` and return its id.
1729    ///
1730    /// # Errors
1731    ///
1732    /// Fails on a database error.
1733    pub async fn enqueue_job(&self, job: &NewJob) -> Result<Uuid> {
1734        enqueue_on(&self.pool, job).await
1735    }
1736
1737    /// Add every job in `jobs` in one transaction, so all are queued or none.
1738    ///
1739    /// # Errors
1740    ///
1741    /// Fails on a database error, and then none was queued.
1742    pub async fn enqueue_all(&self, jobs: &[NewJob]) -> Result<Vec<Uuid>> {
1743        let mut transaction = self.pool.begin().await?;
1744        let ids = enqueue_all_on(&mut transaction, jobs).await?;
1745        transaction.commit().await?;
1746        Ok(ids)
1747    }
1748
1749    /// What the queue knows of the job `id`, or `None` when there is no such job,
1750    /// as after retention deleted it.
1751    ///
1752    /// # Errors
1753    ///
1754    /// Fails on a database error.
1755    pub async fn job(&self, id: Uuid) -> Result<Option<JobInfo>> {
1756        let Some(row) = sqlx::query(STATUS)
1757            .bind(id)
1758            .fetch_optional(&self.pool)
1759            .await?
1760        else {
1761            return Ok(None);
1762        };
1763        Ok(Some(JobInfo {
1764            id: row.try_get("id")?,
1765            name: row.try_get("name")?,
1766            state: JobState::parse(row.try_get::<&str, _>("status")?)?,
1767            attempts: row.try_get("attempts")?,
1768            max_attempts: row.try_get("max_attempts")?,
1769            priority: row.try_get("priority")?,
1770            timeout: row
1771                .try_get::<Option<i64>, _>("timeout_ms")?
1772                .map(from_millis),
1773            tenant: row.try_get("tenant")?,
1774            unique_key: row.try_get("unique_key")?,
1775            error: row.try_get("error")?,
1776            run_at: time(&row, "run_at")?,
1777            started_at: time_or_none(&row, "started_at")?,
1778            created_at: time(&row, "created_at")?,
1779            updated_at: time(&row, "updated_at")?,
1780        }))
1781    }
1782
1783    /// Every act a person did to the job `id`, oldest first, for a service's own
1784    /// review screens. Acts are kept after retention deletes the job's row. A person
1785    /// acts with [`cancel()`] and [`retry()`], in the caller's transaction.
1786    ///
1787    /// # Errors
1788    ///
1789    /// Fails on a database error.
1790    pub async fn acts(&self, id: Uuid) -> Result<Vec<Act>> {
1791        let rows = sqlx::query(ACTS).bind(id).fetch_all(&self.pool).await?;
1792        rows.iter()
1793            .map(|row| {
1794                Ok(Act {
1795                    id: row.try_get("id")?,
1796                    job_id: row.try_get("job_id")?,
1797                    job_name: row.try_get("job_name")?,
1798                    kind: ActKind::parse(row.try_get::<&str, _>("act")?)?,
1799                    attempts: row.try_get("attempts")?,
1800                    by: row.try_get("by")?,
1801                    reason: row.try_get("reason")?,
1802                    at: time(row, "at")?,
1803                })
1804            })
1805            .collect()
1806    }
1807
1808    /// How many jobs are in each state.
1809    ///
1810    /// # Errors
1811    ///
1812    /// Fails on a database error.
1813    pub async fn counts(&self) -> Result<Counts> {
1814        let row = sqlx::query(COUNTS).fetch_one(&self.pool).await?;
1815        Ok(Counts {
1816            ready: row.try_get("ready")?,
1817            waiting: row.try_get("waiting")?,
1818            running: row.try_get("running")?,
1819            completed: row.try_get("completed")?,
1820            failed: row.try_get("failed")?,
1821            cancelled: row.try_get("cancelled")?,
1822            needs_review: row.try_get("needs_review")?,
1823            oldest_ready_seconds: row.try_get::<Option<f64>, _>("oldest")?.unwrap_or(0.0_f64),
1824        })
1825    }
1826
1827    /// Check the database connection.
1828    ///
1829    /// # Errors
1830    ///
1831    /// Fails when the database does not answer.
1832    pub async fn ping(&self) -> Result<()> {
1833        sqlx::query("SELECT 1").execute(&self.pool).await?;
1834        Ok(())
1835    }
1836
1837    /// Recover jobs abandoned by a worker that died: queue again those with
1838    /// attempts left and fail the rest, returning how many were queued again.
1839    ///
1840    /// # Errors
1841    ///
1842    /// Fails on a database error.
1843    pub async fn requeue_stale(&self) -> Result<u64> {
1844        sqlx::query(FAIL_STALE)
1845            .bind(self.options.stale_minutes)
1846            .bind(self.options.max_attempts)
1847            .execute(&self.pool)
1848            .await?;
1849        let result = sqlx::query(REQUEUE_STALE)
1850            .bind(self.options.stale_minutes)
1851            .bind(self.options.max_attempts)
1852            .execute(&self.pool)
1853            .await?;
1854        Ok(result.rows_affected())
1855    }
1856
1857    /// Delete finished and cancelled rows older than the retention period,
1858    /// returning how many went.
1859    ///
1860    /// # Errors
1861    ///
1862    /// Fails on a database error.
1863    pub async fn purge_finished(&self) -> Result<u64> {
1864        let result = sqlx::query(PURGE)
1865            .bind(self.options.retention_days)
1866            .execute(&self.pool)
1867            .await?;
1868        Ok(result.rows_affected())
1869    }
1870
1871    /// Queue a job for each schedule that is due, returning how many were queued.
1872    /// [`Queue::run`] calls this on every poll. Any number of processes may call it
1873    /// at once: each due time is queued once.
1874    ///
1875    /// # Errors
1876    ///
1877    /// Fails on a database error, which leaves that schedule due for the next tick.
1878    pub async fn tick_schedules(&self) -> Result<usize> {
1879        let mut queued: usize = 0;
1880        for schedule in &self.schedules {
1881            if self.tick(schedule).await? {
1882                queued = queued
1883                    .checked_add(1)
1884                    .ok_or(Error::Overflow("schedules queued"))?;
1885            }
1886        }
1887        Ok(queued)
1888    }
1889
1890    /// One schedule's tick, returning whether it queued a job.
1891    async fn tick(&self, schedule: &Schedule) -> Result<bool> {
1892        // Outside the transaction: an upsert locks the row it meets, and replicas
1893        // would then wait on each other instead of skipping.
1894        let first = match &schedule.times {
1895            Times::Every(_) => schedule.first,
1896            Times::Cron(cron, _) => {
1897                let now: jiff_sqlx::Timestamp = sqlx::query_scalar("SELECT now()")
1898                    .fetch_one(&self.pool)
1899                    .await?;
1900                Some(next_after(cron, now.to_jiff())?)
1901            }
1902        };
1903        sqlx::query(SCHEDULE_CREATE)
1904            .bind(&schedule.name)
1905            .bind(first.map(jiff_sqlx::Timestamp::from))
1906            .bind(schedule.times.interval().map(millis))
1907            .bind(schedule.times.pattern())
1908            .execute(&self.pool)
1909            .await?;
1910        let mut transaction = self.pool.begin().await?;
1911        // Another process holding the row is queuing this time already.
1912        let Some(row) = sqlx::query(SCHEDULE_LOCK)
1913            .bind(&schedule.name)
1914            .fetch_optional(&mut *transaction)
1915            .await?
1916        else {
1917            return Ok(false);
1918        };
1919        if !row.try_get::<bool, _>("due")? {
1920            transaction.commit().await?;
1921            return Ok(false);
1922        }
1923        let busy = match row.try_get::<Option<Uuid>, _>("last_job")? {
1924            Some(last) => {
1925                sqlx::query_scalar::<_, bool>(SCHEDULE_BUSY)
1926                    .bind(last)
1927                    .fetch_one(&mut *transaction)
1928                    .await?
1929            }
1930            None => false,
1931        };
1932        let job = if busy {
1933            tracing::info!(schedule = %schedule.name, "schedule skipped, its last job has not finished");
1934            None
1935        } else {
1936            Some(enqueue_on(&mut *transaction, &schedule.job).await?)
1937        };
1938        match &schedule.times {
1939            Times::Every(interval) => {
1940                sqlx::query(SCHEDULE_ADVANCE)
1941                    .bind(&schedule.name)
1942                    .bind(interval.as_secs_f64())
1943                    .bind(job)
1944                    .execute(&mut *transaction)
1945                    .await?;
1946            }
1947            Times::Cron(cron, _) => {
1948                sqlx::query(SCHEDULE_ADVANCE_TO)
1949                    .bind(&schedule.name)
1950                    .bind(jiff_sqlx::Timestamp::from(next_after(
1951                        cron,
1952                        time(&row, "now")?,
1953                    )?))
1954                    .bind(job)
1955                    .execute(&mut *transaction)
1956                    .await?;
1957            }
1958        }
1959        transaction.commit().await?;
1960        if job.is_some() {
1961            tracing::debug!(schedule = %schedule.name, "schedule queued its job");
1962        }
1963        Ok(job.is_some())
1964    }
1965
1966    /// Archive the schedules that no live process has in code, returning how many
1967    /// were archived. Rows are kept, for audit. Housekeeping runs this.
1968    ///
1969    /// # Errors
1970    ///
1971    /// Fails on a database error.
1972    pub async fn archive_schedules(&self) -> Result<u64> {
1973        let names: Vec<&str> = self.schedules.iter().map(|s| s.name.as_str()).collect();
1974        let result = sqlx::query(SCHEDULE_ARCHIVE)
1975            .bind(&names)
1976            .bind(self.options.stale_minutes)
1977            .execute(&self.pool)
1978            .await?;
1979        Ok(result.rows_affected())
1980    }
1981
1982    /// Every schedule the table holds, archived or not, with its last job's state.
1983    ///
1984    /// # Errors
1985    ///
1986    /// Fails on a database error.
1987    pub async fn schedules(&self) -> Result<Vec<ScheduleInfo>> {
1988        let rows = sqlx::query(SCHEDULES).fetch_all(&self.pool).await?;
1989        rows.iter()
1990            .map(|row| {
1991                Ok(ScheduleInfo {
1992                    name: row.try_get("name")?,
1993                    interval: row
1994                        .try_get::<Option<i64>, _>("interval_ms")?
1995                        .map(from_millis),
1996                    cron: row.try_get("cron")?,
1997                    due_at: time(row, "due_at")?,
1998                    last_job: row.try_get("last_job")?,
1999                    last_state: row
2000                        .try_get::<Option<&str>, _>("last_status")?
2001                        .map(JobState::parse)
2002                        .transpose()?,
2003                    last_error: row.try_get("last_error")?,
2004                    seen_at: time(row, "seen_at")?,
2005                    archived_at: time_or_none(row, "archived_at")?,
2006                    created_at: time(row, "created_at")?,
2007                })
2008            })
2009            .collect()
2010    }
2011
2012    /// One round of housekeeping. Failures are logged, because the next round
2013    /// can try again.
2014    async fn maintain(&self) {
2015        match self.archive_schedules().await {
2016            Ok(0) => {}
2017            Ok(archived) => tracing::info!(archived, "archived schedules no longer in code"),
2018            Err(error) => tracing::error!(%error, "could not archive schedules"),
2019        }
2020        if let Err(error) = self.requeue_stale().await {
2021            tracing::error!(%error, "could not recover stale jobs");
2022        }
2023        if let Err(error) = self.purge_finished().await {
2024            tracing::error!(%error, "could not delete old jobs");
2025        }
2026    }
2027
2028    /// Run `job` to its end in its own task, reporting in as it goes, so a panic
2029    /// stops only the job. The job is stopped when its time limit passes, when its
2030    /// claim is found taken, or when this future is dropped.
2031    async fn supervise(&self, job: JobFuture, claim: &Claimed) -> Outcome {
2032        let mut job = AbortOnDrop(tokio::spawn(job));
2033        let every = self.options.heartbeat_interval;
2034        let Some(give_up) = give_up_after(self.options.stale_minutes, every) else {
2035            return Outcome::Lost(TIMING.to_string());
2036        };
2037        let mut last_heard = tokio::time::Instant::now();
2038        let Some(mut give_up_at) = last_heard.checked_add(give_up) else {
2039            return Outcome::Lost(TIMING.to_string());
2040        };
2041        // A heartbeat is given at most `every` to answer, and runs beside the job, so
2042        // a database that hangs holds up neither the job's time limit nor giving up.
2043        let beat = || {
2044            tokio::time::timeout(
2045                every,
2046                sqlx::query(HEARTBEAT)
2047                    .bind(claim.id)
2048                    .bind(claim.attempts)
2049                    .execute(&self.pool),
2050            )
2051        };
2052        let mut beating = None;
2053        let Some(mut next_beat) = tokio::time::Instant::now().checked_add(every) else {
2054            return Outcome::Lost(TIMING.to_string());
2055        };
2056        let mut failing = false;
2057        let limit = match claim.timeout {
2058            Some(timeout) => match tokio::time::Instant::now().checked_add(timeout) {
2059                Some(at) => Some(at),
2060                None => return Outcome::Lost(TIMING.to_string()),
2061            },
2062            None => None,
2063        };
2064        let deadline = async {
2065            match limit {
2066                Some(at) => tokio::time::sleep_until(at).await,
2067                None => std::future::pending().await,
2068            }
2069        };
2070        tokio::pin!(deadline);
2071        loop {
2072            tokio::select! {
2073                finished = &mut job.0 => {
2074                    return Outcome::Done(finished.unwrap_or_else(|_| {
2075                        Err(Error::Job("the job panicked".to_string()).to_string().into())
2076                    }));
2077                }
2078                () = &mut deadline => {
2079                    let limit = claim.timeout.unwrap_or(Duration::ZERO);
2080                    return Outcome::Done(Err(
2081                        Error::Job(format!("timed out after {}s", limit.as_secs_f64())).to_string().into(),
2082                    ));
2083                }
2084                () = tokio::time::sleep_until(give_up_at), if failing => {
2085                    return Outcome::Lost(format!(
2086                        "it could not report in for {}s, near the {} minutes after which another worker may take it",
2087                        give_up.as_secs(),
2088                        self.options.stale_minutes
2089                    ));
2090                }
2091                () = tokio::time::sleep_until(next_beat), if beating.is_none() => {
2092                    beating = Some(Box::pin(beat()));
2093                }
2094                answer = async {
2095                    match beating.as_mut() {
2096                        Some(beat) => beat.await,
2097                        None => std::future::pending().await,
2098                    }
2099                }, if beating.is_some() => {
2100                    beating = None;
2101                    let Some(next) = tokio::time::Instant::now().checked_add(every) else {
2102                        return Outcome::Lost(TIMING.to_string());
2103                    };
2104                    next_beat = next;
2105                    match answer {
2106                        Ok(Ok(done)) if done.rows_affected() == 1 => {
2107                            last_heard = tokio::time::Instant::now();
2108                            let Some(at) = last_heard.checked_add(give_up) else {
2109                                return Outcome::Lost(TIMING.to_string());
2110                            };
2111                            give_up_at = at;
2112                            failing = false;
2113                        }
2114                        Ok(Ok(_)) => return Outcome::Lost("another worker or recovery took its claim".to_string()),
2115                        Ok(Err(error)) => {
2116                            tracing::warn!(id = %claim.id, %error, "job heartbeat failed");
2117                            failing = true;
2118                        }
2119                        Err(_) => {
2120                            tracing::warn!(id = %claim.id, "job heartbeat did not answer in time");
2121                            failing = true;
2122                        }
2123                    }
2124                }
2125            }
2126        }
2127    }
2128
2129    /// Mark a run's job for review, trying until the database answers, as the
2130    /// run must not be taken for a crash and retried.
2131    async fn mark_lost(&self, claim: &Claimed, reason: &str) {
2132        let text = Error::Job(format!("stopped: {reason}")).to_string();
2133        let every = self.options.heartbeat_interval;
2134        loop {
2135            match sqlx::query(MARK_LOST)
2136                .bind(claim.id)
2137                .bind(&text)
2138                .execute(&self.pool)
2139                .await
2140            {
2141                Ok(_) => return,
2142                Err(error) => {
2143                    tracing::error!(id = %claim.id, %error, "could not mark a lost job for review");
2144                    tokio::time::sleep(every).await;
2145                }
2146            }
2147        }
2148    }
2149
2150    /// The job names this loop may claim now, holding a place under each limit
2151    /// that has one free. The places not used are given back when dropped.
2152    fn claimable(&self) -> (Vec<String>, HashMap<String, OwnedSemaphorePermit>) {
2153        let mut places = HashMap::new();
2154        let mut names = Vec::new();
2155        for name in self.handlers.keys() {
2156            match self.limits.get(name) {
2157                None => names.push(name.clone()),
2158                Some(limit) => {
2159                    if let Ok(place) = limit.clone().try_acquire_owned() {
2160                        places.insert(name.clone(), place);
2161                        names.push(name.clone());
2162                    }
2163                }
2164            }
2165        }
2166        (names, places)
2167    }
2168
2169    async fn claim(&self, names: &[String]) -> Result<Option<Claimed>> {
2170        let Some(row) = sqlx::query(CLAIM)
2171            .bind(names)
2172            .fetch_optional(&self.pool)
2173            .await?
2174        else {
2175            return Ok(None);
2176        };
2177        Ok(Some(Claimed {
2178            id: row.try_get("id")?,
2179            name: row.try_get("name")?,
2180            args: row.try_get("args")?,
2181            attempts: row.try_get("attempts")?,
2182            limit: row
2183                .try_get::<Option<i32>, _>("max_attempts")?
2184                .unwrap_or(self.options.max_attempts),
2185            timeout: row
2186                .try_get::<Option<i64>, _>("timeout_ms")?
2187                .map(from_millis),
2188            tenant: row.try_get("tenant")?,
2189        }))
2190    }
2191
2192    /// Claim and run one job, returning whether there was one. A job's own
2193    /// failure is recorded on its row, not returned.
2194    ///
2195    /// # Errors
2196    ///
2197    /// Fails on a database error.
2198    pub async fn run_one(&self) -> Result<bool> {
2199        let (names, mut places) = self.claimable();
2200        if names.is_empty() {
2201            return Ok(false);
2202        }
2203        let Some(job) = self.claim(&names).await? else {
2204            return Ok(false);
2205        };
2206        // Keep only the place this job takes.
2207        let _place = places.remove(&job.name);
2208        drop(places);
2209        let outcome = match self.handlers.get(&job.name) {
2210            Some(handler) => {
2211                let run = handler(job.tenant.clone(), job.args.clone());
2212                self.supervise(run, &job).await
2213            }
2214            None => Outcome::Done(Err(Error::Job(format!("no handler for job {}", job.name))
2215                .to_string()
2216                .into())),
2217        };
2218        let (id, name, attempts) = (job.id, job.name.as_str(), job.attempts);
2219        let finished = match outcome {
2220            Outcome::Lost(reason) => {
2221                tracing::error!(job = %name, %id, attempts, %reason, "job stopped, it lost its claim");
2222                self.mark_lost(&job, &reason).await;
2223                return Ok(true);
2224            }
2225            Outcome::Done(Ok(())) => {
2226                sqlx::query(FINISH)
2227                    .bind(id)
2228                    .bind(attempts)
2229                    .bind("completed")
2230                    .bind(None::<String>)
2231                    .execute(&self.pool)
2232                    .await?
2233            }
2234            Outcome::Done(Err(error)) if attempts < job.limit => {
2235                tracing::warn!(job = %name, %id, attempts, %error, "job failed, will retry");
2236                let wait = retry_wait(self.options.retry_backoff, attempts, error.retry_in)
2237                    .ok_or(Error::Overflow("retry wait"))?;
2238                sqlx::query(RETRY)
2239                    .bind(id)
2240                    .bind(attempts)
2241                    .bind(cut(error.text))
2242                    .bind(wait.as_secs_f64())
2243                    .execute(&self.pool)
2244                    .await?
2245            }
2246            Outcome::Done(Err(error)) => {
2247                tracing::error!(job = %name, %id, attempts, %error, "job failed");
2248                sqlx::query(FINISH)
2249                    .bind(id)
2250                    .bind(attempts)
2251                    .bind("failed")
2252                    .bind(cut(error.text))
2253                    .execute(&self.pool)
2254                    .await?
2255            }
2256        };
2257        if finished.rows_affected() == 0 {
2258            // It ran to its end, but its claim had been taken, so the job may be
2259            // running again elsewhere.
2260            tracing::error!(job = %name, %id, "job finished after losing its claim");
2261            self.mark_lost(
2262                &job,
2263                "it finished after another worker or recovery took its claim",
2264            )
2265            .await;
2266        }
2267        Ok(true)
2268    }
2269
2270    /// Run job loops, housekeeping, and schedules until `shutdown` changes to
2271    /// `true`. Jobs in progress finish first, so a caller that must stop by a
2272    /// time limit drops this future at it, which aborts those jobs and leaves them
2273    /// for stale recovery. Housekeeping runs straight away, to recover anything a
2274    /// previous process left behind, and then on a timer.
2275    pub async fn run(self: Arc<Self>, shutdown: watch::Receiver<bool>) {
2276        let mut loops = Vec::new();
2277        loops.push(AbortOnDrop(tokio::spawn(every_until(
2278            shutdown.clone(),
2279            self.options.maintenance_interval,
2280            {
2281                let queue = self.clone();
2282                move || {
2283                    let queue = queue.clone();
2284                    async move { queue.maintain().await }
2285                }
2286            },
2287        ))));
2288        if !self.schedules.is_empty() {
2289            let queue = self.clone();
2290            loops.push(AbortOnDrop(tokio::spawn(every_until(
2291                shutdown.clone(),
2292                self.options.poll_interval,
2293                move || {
2294                    let queue = queue.clone();
2295                    async move {
2296                        if let Err(error) = queue.tick_schedules().await {
2297                            tracing::error!(%error, "could not queue scheduled jobs");
2298                        }
2299                    }
2300                },
2301            ))));
2302        }
2303        let wake = Arc::new(Notify::new());
2304        loops.push(AbortOnDrop(tokio::spawn(listen(
2305            self.pool.clone(),
2306            wake.clone(),
2307            self.options.poll_interval,
2308            shutdown.clone(),
2309        ))));
2310        for _ in 0..self.options.workers.max(1) {
2311            let queue = self.clone();
2312            let wake = wake.clone();
2313            let mut shutdown = shutdown.clone();
2314            loops.push(AbortOnDrop(tokio::spawn(async move {
2315                while !*shutdown.borrow() {
2316                    let round = async {
2317                        queue.run_one().await.unwrap_or_else(|error| {
2318                            tracing::error!(%error, "job queue error");
2319                            false
2320                        })
2321                    };
2322                    work_or_wait(&wake, queue.options.poll_interval, &mut shutdown, round).await;
2323                }
2324            })));
2325        }
2326        for job_loop in &mut loops {
2327            let _ = (&mut job_loop.0).await;
2328        }
2329    }
2330
2331    /// The names of the job types this queue handles.
2332    #[must_use]
2333    pub fn handled(&self) -> HashSet<&str> {
2334        self.handlers.keys().map(String::as_str).collect()
2335    }
2336}
2337
2338/// Run `round`, and when it found no work, wait for `poll`, a wake, or shutdown. The
2339/// wait is listened for before `round` starts, so a notice that comes while `round`
2340/// looks, after it found nothing, still wakes the loop rather than being lost.
2341async fn work_or_wait(
2342    wake: &Notify,
2343    poll: Duration,
2344    shutdown: &mut watch::Receiver<bool>,
2345    round: impl Future<Output = bool>,
2346) {
2347    let woken = wake.notified();
2348    tokio::pin!(woken);
2349    woken.as_mut().enable();
2350    if !round.await {
2351        tokio::select! {
2352            () = tokio::time::sleep(poll) => {},
2353            () = woken => {},
2354            _ = shutdown.changed() => {},
2355        }
2356    }
2357}
2358
2359/// Wake the idle job loops at each notice on [`NOTIFY_CHANNEL`], until `shutdown`.
2360/// A listener that fails is opened again after `gap`, the loops polling meanwhile.
2361async fn listen(
2362    pool: PgPool,
2363    wake: Arc<Notify>,
2364    gap: Duration,
2365    mut shutdown: watch::Receiver<bool>,
2366) {
2367    while !*shutdown.borrow() {
2368        match sqlx::postgres::PgListener::connect_with(&pool).await {
2369            Ok(mut listener) => match listener.listen(NOTIFY_CHANNEL).await {
2370                Ok(()) => loop {
2371                    tokio::select! {
2372                        notice = listener.try_recv() => match notice {
2373                            // A notice, or a dropped connection, which the next call opens again:
2374                            // a notice sent meanwhile is lost, so wake the loops to look.
2375                            Ok(_) => wake.notify_waiters(),
2376                            Err(error) => {
2377                                tracing::warn!(%error, "job queue listener failed, polling");
2378                                break;
2379                            }
2380                        },
2381                        _ = shutdown.changed() => return,
2382                    }
2383                },
2384                Err(error) => tracing::warn!(%error, "job queue could not listen, polling"),
2385            },
2386            Err(error) => tracing::warn!(%error, "job queue could not listen, polling"),
2387        }
2388        tokio::select! {
2389            () = tokio::time::sleep(gap) => {},
2390            _ = shutdown.changed() => {},
2391        }
2392    }
2393}
2394
2395/// Run `round` now and then every `gap`, until `shutdown` is `true`.
2396async fn every_until<F, Fut>(mut shutdown: watch::Receiver<bool>, gap: Duration, round: F)
2397where
2398    F: Fn() -> Fut,
2399    Fut: Future<Output = ()>,
2400{
2401    while !*shutdown.borrow() {
2402        round().await;
2403        tokio::select! {
2404            () = tokio::time::sleep(gap) => {},
2405            _ = shutdown.changed() => {},
2406        }
2407    }
2408}
2409
2410/// A task that is aborted when its handle is dropped, so that dropping
2411/// [`Queue::run`] stops its loops and their jobs instead of leaving them running.
2412struct AbortOnDrop<T>(tokio::task::JoinHandle<T>);
2413
2414impl<T> Drop for AbortOnDrop<T> {
2415    fn drop(&mut self) {
2416        self.0.abort();
2417    }
2418}
2419
2420#[cfg(test)]
2421#[expect(clippy::string_slice, reason = "RCA-SCOPE-4: tests may slice strings")]
2422mod tests {
2423    use super::*;
2424
2425    #[test]
2426    fn the_time_to_give_up_is_two_heartbeats_before_the_stale_time() {
2427        let beat = Duration::from_secs(30);
2428        assert_eq!(give_up_after(60, beat), Some(Duration::from_mins(59)));
2429        // Two heartbeats that do not fit before the stale time have no time.
2430        assert_eq!(give_up_after(1, Duration::from_secs(40)), None);
2431        assert_eq!(give_up_after(60, Duration::MAX), None);
2432        // A stale time that does not fit, or is negative, has no time.
2433        assert_eq!(give_up_after(-1, beat), None);
2434        assert!(give_up_after(i32::MAX, Duration::ZERO).is_some());
2435    }
2436
2437    #[test]
2438    fn options_out_of_range_are_refused() {
2439        assert!(QueueOptions::default().check().is_ok());
2440        let refused = |change: fn(&mut QueueOptions)| {
2441            let mut options = QueueOptions::default();
2442            change(&mut options);
2443            options.check()
2444        };
2445        // More workers than a `u32` holds (a platform with a narrower `usize` has none).
2446        if let Ok(over) = usize::try_from(u64::from(u32::MAX) + 1) {
2447            let options = QueueOptions {
2448                workers: over,
2449                ..QueueOptions::default()
2450            };
2451            assert!(matches!(options.check(), Err(Error::OutOfRange("workers"))));
2452        }
2453        assert!(matches!(
2454            refused(|o| o.stale_minutes = 0_i32),
2455            Err(Error::OutOfRange("stale_minutes"))
2456        ));
2457        assert!(matches!(
2458            refused(|o| o.stale_minutes = -1_i32),
2459            Err(Error::OutOfRange("stale_minutes"))
2460        ));
2461        // A heartbeat over a quarter of the stale time, or under the least.
2462        assert!(matches!(
2463            refused(|o| o.heartbeat_interval = Duration::from_mins(16)),
2464            Err(Error::OutOfRange("heartbeat_interval"))
2465        ));
2466        assert!(refused(|o| o.heartbeat_interval = Duration::from_mins(15)).is_ok());
2467        assert!(matches!(
2468            refused(|o| o.heartbeat_interval = Duration::ZERO),
2469            Err(Error::OutOfRange("heartbeat_interval"))
2470        ));
2471        assert!(matches!(
2472            refused(|o| o.heartbeat_interval = Duration::MAX),
2473            Err(Error::OutOfRange("heartbeat_interval"))
2474        ));
2475    }
2476
2477    #[test]
2478    fn a_delay_out_of_range_is_refused() {
2479        assert!(RetryAfter::new(MIN_RETRY_AFTER, "x").is_ok());
2480        assert!(RetryAfter::new(MAX_BACKOFF, "x").is_ok());
2481        for delay in [
2482            Duration::ZERO,
2483            Duration::from_millis(999),
2484            MAX_BACKOFF + Duration::from_secs(1),
2485        ] {
2486            assert!(
2487                matches!(
2488                    RetryAfter::new(delay, "x"),
2489                    Err(Error::OutOfRange("retry after"))
2490                ),
2491                "{delay:?}"
2492            );
2493        }
2494        assert_eq!(
2495            Error::OutOfRange("retry after").to_string(),
2496            "retry after: the value is out of range"
2497        );
2498    }
2499
2500    #[test]
2501    fn a_figure_too_large_to_compute_is_named_in_its_error() {
2502        let error = Error::Overflow("schedules queued");
2503        assert_eq!(
2504            error.to_string(),
2505            "schedules queued: the value is too large to compute"
2506        );
2507        assert!(std::error::Error::source(&error).is_none());
2508    }
2509
2510    #[test]
2511    fn a_stored_word_that_is_not_a_known_state_or_act_is_refused() {
2512        assert!(JobState::parse("cancelled").is_ok());
2513        assert!(ActKind::parse("released").is_ok());
2514        let error = JobState::parse("lost").unwrap_err().to_string();
2515        assert!(error.contains("unknown status"), "{error}");
2516        let error = ActKind::parse("lost").unwrap_err().to_string();
2517        assert!(error.contains("unknown kind"), "{error}");
2518        let error = Error::NotATenant.to_string();
2519        assert!(error.contains("lower-case letters"), "{error}");
2520    }
2521
2522    #[tokio::test]
2523    async fn a_wake_during_a_round_that_found_nothing_is_not_lost() {
2524        let wake = Notify::new();
2525        let (_stop, mut shutdown) = watch::channel(false);
2526        // The notice comes while the round looks, before the loop would wait.
2527        let round = async {
2528            wake.notify_waiters();
2529            false
2530        };
2531        let waited = tokio::time::timeout(
2532            Duration::from_secs(5),
2533            work_or_wait(&wake, Duration::from_hours(1), &mut shutdown, round),
2534        )
2535        .await;
2536        assert!(
2537            waited.is_ok(),
2538            "the wake was lost and the loop waited for its poll"
2539        );
2540    }
2541
2542    #[test]
2543    fn each_retry_waits_twice_as_long_up_to_a_limit() {
2544        let base = Duration::from_secs(30);
2545        assert_eq!(backoff(base, 1), Some(base));
2546        assert_eq!(backoff(base, 2), Some(base * 2));
2547        assert_eq!(backoff(base, 3), Some(base * 4));
2548        assert_eq!(backoff(base, 1_000), Some(MAX_BACKOFF));
2549        assert_eq!(backoff(base, 0), None);
2550        assert_eq!(backoff(base, i32::MIN), None);
2551    }
2552
2553    #[test]
2554    fn a_retry_waits_a_jittered_backoff_or_the_delay_the_job_chose() {
2555        let base = Duration::from_secs(30);
2556        for _ in 0_i32..200_i32 {
2557            let wait = retry_wait(base, 2, None).unwrap();
2558            assert!(wait >= base && wait <= base * 2, "{wait:?}");
2559        }
2560        let waits: HashSet<_> = (0_i32..20_i32)
2561            .map(|_| retry_wait(base, 1, None).unwrap())
2562            .collect();
2563        assert!(waits.len() > 1, "the waits are spread");
2564        assert_eq!(retry_wait(Duration::ZERO, 3, None), Some(Duration::ZERO));
2565        assert_eq!(retry_wait(base, 0, None), None);
2566        let chosen = Some(Duration::from_secs(90));
2567        assert_eq!(retry_wait(base, 1, chosen), Some(Duration::from_secs(90)));
2568        // A delay out of range has no wait.
2569        assert_eq!(retry_wait(base, 1, Some(Duration::ZERO)), None);
2570        assert_eq!(retry_wait(base, 1, Some(Duration::from_hours(9))), None);
2571    }
2572
2573    #[test]
2574    fn a_jittered_wait_is_between_half_and_the_whole_and_one_that_does_not_fit_has_none() {
2575        let wait = Duration::from_secs(40);
2576        for _ in 0_i32..200_i32 {
2577            let spread = jittered(wait).unwrap();
2578            assert!(spread >= wait / 2 && spread <= wait, "{spread:?}");
2579        }
2580        assert_eq!(jittered(Duration::ZERO), Some(Duration::ZERO));
2581        assert_eq!(jittered(Duration::MAX), None);
2582    }
2583
2584    #[test]
2585    fn a_retry_after_error_carries_its_delay_and_others_none() {
2586        let chosen = Failure::from_error(RetryAfter::new(Duration::from_secs(7), "busy").unwrap());
2587        assert_eq!(
2588            (chosen.text.as_str(), chosen.retry_in),
2589            ("busy", Some(Duration::from_secs(7)))
2590        );
2591        let boxed: Box<dyn std::error::Error + Send + Sync> =
2592            Box::new(RetryAfter::new(Duration::from_secs(8), "boxed").unwrap());
2593        assert_eq!(
2594            Failure::from_error(boxed).retry_in,
2595            Some(Duration::from_secs(8))
2596        );
2597        let plain = Failure::from_error("broken".to_string());
2598        assert_eq!((plain.text.as_str(), plain.retry_in), ("broken", None));
2599    }
2600
2601    #[test]
2602    fn the_debug_text_leaves_out_arguments() {
2603        let job = NewJob::new("Report", serde_json::json!({ "nhs": "943 476 5919" }));
2604        let schedule = Schedule::every("nightly", Duration::from_hours(1), job.clone()).unwrap();
2605        let cron = Schedule::cron("at-two", "0 2 * * *", job.clone()).unwrap();
2606        for text in [
2607            format!("{job:?}"),
2608            format!("{schedule:?}"),
2609            format!("{cron:?}"),
2610        ] {
2611            assert!(text.contains("Report"), "{text}");
2612            assert!(!text.contains("943"), "{text}");
2613        }
2614    }
2615
2616    #[test]
2617    fn a_by_or_reason_that_is_not_a_code_is_refused() {
2618        assert!(check_code("ops:alice", "by").is_ok());
2619        assert!(check_code(&"é".repeat(MAX_REASON_CHARS), "reason").is_ok());
2620        for bad in [
2621            String::new(),
2622            "é".repeat(MAX_REASON_CHARS + 1),
2623            "two\nlines".to_string(),
2624            "a\ttab".to_string(),
2625        ] {
2626            let error = check_code(&bad, "reason").unwrap_err();
2627            assert!(matches!(error, Error::NotACode { what: "reason" }));
2628            assert!(!error.to_string().contains("lines"), "the text is left out");
2629        }
2630    }
2631
2632    #[test]
2633    fn a_long_error_is_cut_on_a_character_boundary() {
2634        // One byte first, so byte MAX_ERROR falls inside an `é`, and the cut steps back.
2635        let text = format!("a{}", "é".repeat(MAX_ERROR));
2636        let kept = cut(text);
2637        assert_eq!(kept.len(), MAX_ERROR - 1);
2638        assert!(kept[1..].chars().all(|c| c == 'é'));
2639        assert_eq!(cut("short".to_string()), "short");
2640    }
2641
2642    #[test]
2643    fn a_schedule_under_a_second_is_refused_at_boot() {
2644        let error = Schedule::every(
2645            "fast",
2646            Duration::from_millis(10),
2647            NewJob::new("J", serde_json::Value::Null),
2648        )
2649        .unwrap_err();
2650        assert!(matches!(&error, Error::Schedule(_)), "{error:?}");
2651        assert!(error.to_string().contains("at least a second"), "{error}");
2652    }
2653
2654    #[test]
2655    fn a_bad_cron_pattern_is_refused_at_boot() {
2656        let error = Schedule::cron(
2657            "bad",
2658            "61 * * * *",
2659            NewJob::new("J", serde_json::Value::Null),
2660        )
2661        .unwrap_err();
2662        assert!(matches!(&error, Error::Schedule(_)), "{error:?}");
2663        assert!(error.to_string().contains("bad cron pattern"), "{error}");
2664    }
2665
2666    #[test]
2667    fn a_cron_schedule_names_its_next_times_in_utc() {
2668        let schedule = Schedule::cron(
2669            "weekdays",
2670            "0 9 * * MON-FRI",
2671            NewJob::new("J", serde_json::Value::Null),
2672        )
2673        .unwrap();
2674        assert_eq!(schedule.cron_pattern(), Some("0 9 * * MON-FRI"));
2675        assert_eq!(schedule.interval(), None);
2676        let Times::Cron(cron, _) = &schedule.times else {
2677            panic!("a cron schedule")
2678        };
2679        // Friday 2026-11-13 09:00 UTC is due, so the next after it is Monday's.
2680        let friday: Timestamp = "2026-11-13T09:00:00Z".parse().unwrap();
2681        let monday: Timestamp = "2026-11-16T09:00:00Z".parse().unwrap();
2682        assert_eq!(next_after(cron, friday).unwrap(), monday);
2683        assert_eq!(
2684            Schedule::every(
2685                "e",
2686                Duration::from_secs(5),
2687                NewJob::new("J", serde_json::Value::Null)
2688            )
2689            .unwrap()
2690            .interval(),
2691            Some(Duration::from_secs(5))
2692        );
2693    }
2694
2695    #[test]
2696    fn a_cron_schedule_counts_in_utc_across_a_month_end_and_a_clock_change() {
2697        let next = |pattern: &str, after: &str| {
2698            let cron: croner::Cron = pattern.parse().unwrap();
2699            next_after(&cron, after.parse().unwrap())
2700                .unwrap()
2701                .to_string()
2702        };
2703        // The 31st skips a month of 30 days, and the year end is an ordinary midnight.
2704        assert_eq!(
2705            next("0 0 31 * *", "2026-11-15T00:00:00Z"),
2706            "2026-12-31T00:00:00Z"
2707        );
2708        assert_eq!(
2709            next("30 23 * * *", "2026-12-31T23:30:00Z"),
2710            "2027-01-01T23:30:00Z"
2711        );
2712        assert_eq!(
2713            next("0 12 29 2 *", "2026-03-01T00:00:00Z"),
2714            "2028-02-29T12:00:00Z"
2715        );
2716        // Clocks in Europe go forward at 01:00 UTC on 2026-03-29 and back at 01:00 UTC
2717        // on 2026-10-25, and in the US back on 2026-11-01. UTC has no such change, so
2718        // 01:30 comes once each day, 24 hours apart.
2719        assert_eq!(
2720            next("30 1 * * *", "2026-03-28T01:30:00Z"),
2721            "2026-03-29T01:30:00Z"
2722        );
2723        assert_eq!(
2724            next("30 1 * * *", "2026-10-25T01:30:00Z"),
2725            "2026-10-26T01:30:00Z"
2726        );
2727        assert_eq!(
2728            next("0 6 * * *", "2026-11-01T06:00:00Z"),
2729            "2026-11-02T06:00:00Z"
2730        );
2731        // A time part way through a second goes on to the next whole one.
2732        assert_eq!(
2733            next("* * * * * *", "2026-11-15T00:00:00.5Z"),
2734            "2026-11-15T00:00:01Z"
2735        );
2736    }
2737
2738    #[test]
2739    fn a_schedule_with_no_name_is_refused_at_boot() {
2740        let error = Schedule::every(
2741            "",
2742            Duration::from_secs(1),
2743            NewJob::new("J", serde_json::Value::Null),
2744        )
2745        .unwrap_err();
2746        assert!(matches!(&error, Error::Schedule(_)), "{error:?}");
2747        assert!(error.to_string().contains("1 to 200 characters"), "{error}");
2748    }
2749
2750    #[tokio::test]
2751    async fn a_schedule_added_twice_is_refused_at_boot() {
2752        let pool = PgPoolOptions::new()
2753            .connect_lazy("postgres://u@localhost/none")
2754            .unwrap();
2755        let mut queue = Queue::from_pool(pool, QueueOptions::default()).unwrap();
2756        let job = NewJob::new("J", serde_json::Value::Null);
2757        queue
2758            .schedule(Schedule::every("a", Duration::from_secs(5), job.clone()).unwrap())
2759            .unwrap();
2760        let error = queue
2761            .schedule(Schedule::every("a", Duration::from_secs(9), job).unwrap())
2762            .unwrap_err();
2763        assert!(error.to_string().contains("added twice"), "{error}");
2764    }
2765
2766    #[test]
2767    fn a_schedule_ignores_a_delay_on_its_job() {
2768        let job = NewJob::new("J", serde_json::Value::Null).run_in(Duration::from_hours(1));
2769        let schedule = Schedule::every("s", Duration::from_secs(5), job).unwrap();
2770        assert_eq!(schedule.job.when, When::Now);
2771    }
2772
2773    #[test]
2774    fn an_error_keeps_what_caused_it_and_only_a_database_or_encoding_error_has_a_source() {
2775        use std::error::Error as _;
2776        let encoding = serde_json::from_str::<u8>("x").unwrap_err();
2777        let text = encoding.to_string();
2778        let error = Error::from(encoding);
2779        assert!(matches!(error, Error::Encode(_)));
2780        assert_eq!(error.to_string(), text);
2781        assert_eq!(error.source().map(ToString::to_string), Some(text));
2782        let database = Error::Database(sqlx::Error::RowNotFound);
2783        assert!(database.source().is_some());
2784        for none in [
2785            Error::Job("it broke".into()),
2786            Error::NotACode { what: "by" },
2787            Error::NotATenant,
2788        ] {
2789            assert!(none.source().is_none(), "{none}");
2790        }
2791    }
2792
2793    #[test]
2794    fn a_cron_pattern_that_names_no_time_to_come_is_refused_at_boot() {
2795        // The 30th of February.
2796        let error = Schedule::cron(
2797            "never",
2798            "0 0 30 2 *",
2799            NewJob::new("J", serde_json::Value::Null),
2800        )
2801        .unwrap_err();
2802        assert!(matches!(&error, Error::Schedule(_)), "{error:?}");
2803        assert!(
2804            error.to_string().contains("names no time to come"),
2805            "{error}"
2806        );
2807    }
2808
2809    #[test]
2810    fn a_job_and_a_schedule_say_their_names_and_a_failure_its_text() {
2811        let job = NewJob::new("SendMail", serde_json::Value::Null);
2812        assert_eq!(job.name(), "SendMail");
2813        let schedule = Schedule::every("hourly", Duration::from_hours(1), job).unwrap();
2814        assert_eq!(schedule.name(), "hourly");
2815        assert_eq!(
2816            Failure::from("the receiver is busy".to_string()).to_string(),
2817            "the receiver is busy"
2818        );
2819    }
2820
2821    #[tokio::test]
2822    async fn a_queue_shows_how_much_it_holds_and_its_options_and_never_its_pool() {
2823        let pool = sqlx::postgres::PgPoolOptions::new()
2824            .connect_lazy("postgres://axa:secret-password@127.0.0.1:1/axa")
2825            .unwrap();
2826        let options = QueueOptions {
2827            workers: 3,
2828            ..QueueOptions::default()
2829        };
2830        let mut queue = Queue::from_pool(pool, options).unwrap();
2831        queue.handle("A", |_: serde_json::Value| async { Ok::<(), String>(()) });
2832        queue.limit("A", 1);
2833        queue
2834            .schedule(
2835                Schedule::every(
2836                    "hourly",
2837                    Duration::from_hours(1),
2838                    NewJob::new("A", serde_json::Value::Null),
2839                )
2840                .unwrap(),
2841            )
2842            .unwrap();
2843        assert_eq!(queue.options().workers, 3);
2844        let shown = format!("{queue:?}");
2845        assert!(
2846            shown.starts_with("Queue { handlers: 1, limits: 1, schedules: 1, options: "),
2847            "{shown}"
2848        );
2849        assert!(!shown.contains("secret-password"), "{shown}");
2850    }
2851}