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