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