Skip to main content

axa_postgres_job_queue/
lib.rs

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