Skip to main content

renox_core/queue/
mod.rs

1//! Background jobs stored in SQLite, with retries and a failed-jobs table.
2//!
3//! ```
4//! # use renox::prelude::*;
5//! # #[derive(Model, serde::Serialize, Default)] struct Order { id: i64 }
6//! use serde::{Deserialize, Serialize};
7//!
8//! #[derive(Serialize, Deserialize)]
9//! struct SendReceipt { order_id: i64 }
10//!
11//! impl Job for SendReceipt {
12//!     const NAME: &'static str = "send-receipt";
13//!     const MAX_ATTEMPTS: u32 = 5;
14//!
15//!     async fn handle(self, ctx: JobContext) -> Result {
16//!         let order = Order::find_or_404(&ctx.state.db, self.order_id).await?;
17//!         // … send it
18//! #       let _ = order;
19//!         Ok(())
20//!     }
21//! }
22//!
23//! # let _ =
24//! App::new().job::<SendReceipt>();            // register the handler
25//! # async fn demo(state: AppState, order_id: i64) -> Result {
26//! state.dispatch(SendReceipt { order_id }).await?;   // in a handler
27//! # Ok(()) }
28//! ```
29//!
30//! `serve` runs workers in the same process (`QUEUE_WORKERS`, default 2; 0 to
31//! turn off); `my-app queue:work` runs them on their own, and
32//! `queue:work --queue high,default` drains `high` before `default`.
33//!
34//! More than one job at a time:
35//!
36//! ```
37//! # use renox::prelude::*;
38//! # #[derive(serde::Serialize, serde::Deserialize)] struct Import { file: String }
39//! # impl Job for Import { const NAME: &'static str = "import"; async fn handle(self, _: JobContext) -> Result { Ok(()) } }
40//! # #[derive(serde::Serialize, serde::Deserialize)] struct Notify { user_id: i64 }
41//! # impl Job for Notify { const NAME: &'static str = "notify"; async fn handle(self, _: JobContext) -> Result { Ok(()) } }
42//! # async fn demo(state: AppState) -> Result {
43//! // One after another; a failure stops the rest.
44//! state.queue.chain()
45//!     .then(Import { file: "a.csv".into() })
46//!     .then(Notify { user_id: 7 })
47//!     .dispatch()
48//!     .await?;
49//!
50//! // Side by side, with progress and follow-up jobs.
51//! let batch = state.queue.batch("import-october")
52//!     .push(Import { file: "a.csv".into() })
53//!     .push(Import { file: "b.csv".into() })
54//!     .then(Notify { user_id: 7 })   // all succeeded
55//!     .catch(Notify { user_id: 1 })  // the first failure (which cancels the rest)
56//!     .dispatch()
57//!     .await?;
58//! let status = state.queue.batch_status(batch).await?; // total, pending, failed, progress()
59//! # let _ = status; Ok(()) }
60//! ```
61
62mod dashboard;
63mod worker;
64
65use std::collections::HashMap;
66use std::future::Future;
67use std::pin::Pin;
68use std::sync::Arc;
69use std::time::Duration;
70
71use serde::de::DeserializeOwned;
72use serde::{Deserialize, Serialize};
73use tokio::sync::Notify;
74
75pub use dashboard::{Dashboard, GATE as DASHBOARD_GATE, QueueCounts, QueueStats};
76pub use worker::Worker;
77
78use crate::db::{Db, Migration, Transaction};
79use crate::{AppState, Error, Result};
80
81pub(crate) const MIGRATIONS: &[Migration] = &[
82    crate::db::framework_migration!("queue", "00010101000100_create_jobs_table"),
83    crate::db::framework_migration!("queue", "00010101000110_add_chains_and_batches_to_jobs"),
84    crate::db::framework_migration!("queue", "00010101000120_add_callback_of_to_jobs"),
85];
86
87/// Payloads of `ENCRYPTED` jobs start with this; JSON never does.
88const SEALED: &str = "enc:";
89/// Cache rows claiming a unique job, holding its id.
90const UNIQUE_PREFIX: &str = "renox:unique:";
91
92/// A unit of background work. It is stored as JSON, so keep it to ids and
93/// small values rather than whole models.
94pub trait Job: Serialize + DeserializeOwned + Send + Sync + 'static {
95    /// A stable name; stored with each job, so don't rename it while jobs are queued.
96    const NAME: &'static str;
97    /// Its queue; `queue:work --queue high,default` drains queues in order.
98    const QUEUE: &'static str = "default";
99    /// Runs before the job is moved to `failed_jobs`.
100    const MAX_ATTEMPTS: u32 = 3;
101    /// How long one attempt may run.
102    const TIMEOUT: Duration = Duration::from_secs(60);
103    /// Store the payload encrypted with `APP_KEY` (it holds personal data or
104    /// secrets). The worker decrypts it; `failed_jobs` keeps it encrypted.
105    const ENCRYPTED: bool = false;
106    /// While a job with the same [`Job::unique_id`] is queued or running,
107    /// dispatching another returns the queued one's id instead, for up to
108    /// this long (the claim is dropped when the job finishes).
109    const UNIQUE_FOR: Option<Duration> = None;
110
111    /// Wait before retrying after the given failed attempt (1-based).
112    fn backoff(attempt: u32) -> Duration {
113        Duration::from_secs(10 * u64::from(attempt))
114    }
115
116    /// What makes two jobs "the same" for [`Job::UNIQUE_FOR`], e.g. the
117    /// order id. Empty (the default) makes every job of the type the same.
118    fn unique_id(&self) -> String {
119        String::new()
120    }
121
122    /// Conditions checked before each attempt; a job that can't run yet is
123    /// put back without using up an attempt.
124    fn middleware(&self) -> Vec<Middleware> {
125        Vec::new()
126    }
127
128    /// Does the work; an error fails the attempt (retried unless `Error::permanent`).
129    fn handle(self, ctx: JobContext) -> impl Future<Output = Result> + Send;
130
131    /// Runs once the job has failed for good (attempts used up, or a
132    /// permanent error), with the last error, e.g. to tell the user. `ctx`
133    /// is the last attempt's: the state, the job's id, the attempt, its batch.
134    fn failed(self, ctx: JobContext, error: String) -> impl Future<Output = ()> + Send {
135        let _ = (ctx, error);
136        async {}
137    }
138}
139
140/// A condition checked before a job's attempt; see [`Job::middleware`].
141///
142/// ```
143/// # use renox::prelude::*;
144/// use renox::queue::Middleware;
145/// # use std::time::Duration;
146/// # #[derive(serde::Serialize, serde::Deserialize)] struct SyncStock { shop_id: i64 }
147/// impl Job for SyncStock {
148///     const NAME: &'static str = "sync-stock";
149///
150///     fn middleware(&self) -> Vec<Middleware> {
151///         vec![
152///             // One sync per shop at a time; others wait 10 s and try again.
153///             Middleware::without_overlapping(format!("shop:{}", self.shop_id))
154///                 .release_after(Duration::from_secs(10)),
155///             // The supplier's API allows 60 calls a minute.
156///             Middleware::rate_limited("supplier-api", 60, Duration::from_secs(60)),
157///         ]
158///     }
159///
160///     async fn handle(self, _ctx: JobContext) -> Result { Ok(()) }
161/// }
162/// ```
163///
164/// Both use the cache (`CACHE_STORE`): with `memory`, they hold within one
165/// process; use `database` when several processes run workers.
166#[derive(Debug, Clone)]
167pub struct Middleware(MiddlewareKind);
168
169#[derive(Debug, Clone)]
170enum MiddlewareKind {
171    WithoutOverlapping {
172        key: String,
173        release_after: Duration,
174    },
175    RateLimited {
176        key: String,
177        max: u32,
178        per: Duration,
179    },
180}
181
182impl Middleware {
183    /// One job with this `key` at a time; others are put back for 5 seconds
184    /// (see [`Middleware::release_after`]).
185    pub fn without_overlapping(key: impl Into<String>) -> Self {
186        Self(MiddlewareKind::WithoutOverlapping {
187            key: key.into(),
188            release_after: Duration::from_secs(5),
189        })
190    }
191
192    /// At most `max` attempts with this `key` per `per` (a fixed window);
193    /// the rest are put back until the window ends.
194    pub fn rate_limited(key: impl Into<String>, max: u32, per: Duration) -> Self {
195        Self(MiddlewareKind::RateLimited {
196            key: key.into(),
197            max,
198            per: per.max(Duration::from_secs(1)),
199        })
200    }
201
202    /// How long a job waits before trying again when it would overlap.
203    pub fn release_after(mut self, wait: Duration) -> Self {
204        if let MiddlewareKind::WithoutOverlapping { release_after, .. } = &mut self.0 {
205            *release_after = wait;
206        }
207        self
208    }
209}
210
211/// A cap on how many jobs run per window, kept in a job's payload so its
212/// [`Job::middleware`] can return [`Middleware::rate_limited`]
213/// (`App::channel_rate_limit`, `App::mailer_rate_limit`).
214#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
215pub(crate) struct Limit {
216    max: u32,
217    per_secs: u64,
218}
219
220impl Limit {
221    pub(crate) fn new(max: u32, per: Duration) -> Self {
222        Self {
223            max,
224            per_secs: per.as_secs(),
225        }
226    }
227
228    /// The middleware for jobs sharing `key`, when a limit is set.
229    pub(crate) fn middleware(limit: Option<Self>, key: String) -> Vec<Middleware> {
230        limit
231            .map(|l| Middleware::rate_limited(key, l.max, Duration::from_secs(l.per_secs)))
232            .into_iter()
233            .collect()
234    }
235}
236
237/// What a job gets when it runs.
238#[non_exhaustive]
239pub struct JobContext {
240    /// The app's state (database, mailer, queue…).
241    pub state: AppState,
242    /// 1 on the first try.
243    pub attempt: u32,
244    /// The job's id (0 for [`AppState::dispatch_sync`]).
245    pub id: i64,
246    /// The batch it belongs to, or, for a batch's `then`/`catch`/`finally`
247    /// job, the batch it follows (read it with `queue.batch_status`).
248    pub batch_id: Option<i64>,
249}
250
251type RunFn =
252    Arc<dyn Fn(String, JobContext) -> Pin<Box<dyn Future<Output = Result> + Send>> + Send + Sync>;
253type FailedFn = Arc<
254    dyn Fn(String, JobContext, String) -> Pin<Box<dyn Future<Output = ()> + Send>> + Send + Sync,
255>;
256
257/// A registered job type: how to run it and when to retry it.
258#[derive(Clone)]
259pub(crate) struct JobHandler {
260    pub(crate) run: RunFn,
261    pub(crate) failed: FailedFn,
262    pub(crate) backoff: fn(u32) -> Duration,
263    pub(crate) timeout: Duration,
264    /// The unique claim's cache key, from the (decrypted) payload.
265    pub(crate) unique_key: fn(&str) -> Option<String>,
266    pub(crate) middleware: fn(&str) -> Vec<Middleware>,
267}
268
269/// The handler for `J`; `Registry::job` registers it.
270pub(crate) fn handler<J: Job>() -> JobHandler {
271    JobHandler {
272        run: Arc::new(|payload, ctx| {
273            Box::pin(async move {
274                // A payload that doesn't decode now never will.
275                let job: J = serde_json::from_str(&payload).map_err(crate::Error::permanent)?;
276                job.handle(ctx).await
277            })
278        }),
279        failed: Arc::new(|payload, ctx, error| {
280            Box::pin(async move {
281                if let Ok(job) = serde_json::from_str::<J>(&payload) {
282                    job.failed(ctx, error).await;
283                }
284            })
285        }),
286        backoff: J::backoff,
287        timeout: J::TIMEOUT,
288        unique_key: |payload| {
289            J::UNIQUE_FOR?;
290            let job: J = serde_json::from_str(payload).ok()?;
291            Some(unique_key::<J>(&job))
292        },
293        middleware: |payload| {
294            serde_json::from_str::<J>(payload)
295                .map(|job| job.middleware())
296                .unwrap_or_default()
297        },
298    }
299}
300
301fn unique_key<J: Job>(job: &J) -> String {
302    format!("{UNIQUE_PREFIX}{}:{}", J::NAME, job.unique_id())
303}
304
305pub(crate) type Handlers = Arc<HashMap<&'static str, JobHandler>>;
306
307/// A job ready to be stored: for chains, batches and their follow-ups.
308#[derive(Debug, Clone, Serialize, Deserialize)]
309pub(crate) struct Encoded {
310    queue: String,
311    job: String,
312    payload: String,
313    max_attempts: u32,
314}
315
316/// Dispatches jobs and wakes the workers of this process.
317#[derive(Clone)]
318pub struct Queue {
319    db: Db,
320    key: cookie::Key,
321    wake: Arc<Notify>,
322}
323
324pub(crate) fn unix_now() -> i64 {
325    crate::clock::unix_secs()
326}
327
328impl Queue {
329    pub(crate) fn new(db: Db, key: cookie::Key) -> Self {
330        Self {
331            db,
332            key,
333            wake: Arc::new(Notify::new()),
334        }
335    }
336
337    pub(crate) fn wake(&self) -> &Notify {
338        &self.wake
339    }
340
341    pub(crate) fn wake_workers(&self) {
342        self.wake.notify_waiters();
343    }
344
345    fn encode<J: Job>(&self, job: &J, queue: &str) -> Result<Encoded> {
346        let json = serde_json::to_string(job)?;
347        let payload = if J::ENCRYPTED {
348            format!("{SEALED}{}", crate::crypto::seal(&self.key, &json))
349        } else {
350            json
351        };
352        Ok(Encoded {
353            queue: queue.to_owned(),
354            job: J::NAME.to_owned(),
355            payload,
356            max_attempts: J::MAX_ATTEMPTS.max(1),
357        })
358    }
359
360    /// The JSON of a stored payload, decrypting an encrypted one.
361    pub(crate) fn open(&self, payload: &str) -> Result<String> {
362        match payload.strip_prefix(SEALED) {
363            Some(sealed) => Ok(crate::crypto::open(&self.key, sealed).map_err(Error::permanent)?),
364            None => Ok(payload.to_owned()),
365        }
366    }
367
368    /// Queues a job to run as soon as a worker is free; returns its id.
369    pub async fn dispatch<J: Job>(&self, job: J) -> Result<i64> {
370        self.dispatch_after(job, Duration::ZERO).await
371    }
372
373    /// Queues a job to run after `delay`; returns its id.
374    pub async fn dispatch_after<J: Job>(&self, job: J, delay: Duration) -> Result<i64> {
375        self.push(job, J::QUEUE, delay).await
376    }
377
378    /// Queues a job on `queue` instead of its [`Job::QUEUE`].
379    pub async fn dispatch_on<J: Job>(&self, queue: &str, job: J) -> Result<i64> {
380        self.push(job, queue, Duration::ZERO).await
381    }
382
383    async fn push<J: Job>(&self, job: J, queue: &str, delay: Duration) -> Result<i64> {
384        let encoded = self.encode(&job, queue)?;
385        let id = match J::UNIQUE_FOR {
386            None => insert(&self.db, &encoded, delay, None, None, None).await?,
387            Some(ttl) => {
388                let mut tx = self.db.begin().await?;
389                let id =
390                    insert_unique(&mut tx, &unique_key::<J>(&job), ttl, &encoded, delay).await?;
391                tx.commit().await?;
392                id
393            }
394        };
395        self.wake.notify_waiters();
396        Ok(id)
397    }
398
399    /// Queues a job inside `tx`, so it only exists if the transaction
400    /// commits; workers pick it up within a second of the commit. Use it
401    /// instead of `dispatch` while a transaction is open: on SQLite, which
402    /// writes one transaction at a time, `dispatch` would wait for `tx`.
403    ///
404    /// ```
405    /// # use renox::prelude::*;
406    /// # #[derive(serde::Serialize, serde::Deserialize)] struct SendReceipt { order_id: i64 }
407    /// # impl Job for SendReceipt { const NAME: &'static str = "r"; async fn handle(self, _: JobContext) -> Result { Ok(()) } }
408    /// # async fn demo(state: AppState) -> Result {
409    /// let mut tx = state.db.begin().await?;
410    /// let order_id: i64 = renox::db::sql("INSERT INTO orders (total) VALUES (?) RETURNING id")
411    ///     .bind(75_000)
412    ///     .scalar(&mut tx)
413    ///     .await?;
414    /// state.queue.dispatch_in(&mut tx, SendReceipt { order_id }).await?;
415    /// tx.commit().await?; // no order, no receipt
416    /// # Ok(()) }
417    /// ```
418    pub async fn dispatch_in<J: Job>(&self, tx: &mut Transaction, job: J) -> Result<i64> {
419        let encoded = self.encode(&job, J::QUEUE)?;
420        match J::UNIQUE_FOR {
421            None => insert(tx, &encoded, Duration::ZERO, None, None, None).await,
422            Some(ttl) => {
423                insert_unique(tx, &unique_key::<J>(&job), ttl, &encoded, Duration::ZERO).await
424            }
425        }
426    }
427
428    /// Jobs that run one after another: the next is queued when the one
429    /// before succeeds, and a job that fails for good stops the chain
430    /// (`queue:retry` resumes it).
431    pub fn chain(&self) -> Chain {
432        Chain {
433            queue: self.clone(),
434            jobs: Vec::new(),
435            error: None,
436        }
437    }
438
439    /// Jobs that run side by side, tracked together; see [`Batch`].
440    pub fn batch(&self, name: &str) -> Batch {
441        Batch {
442            queue: self.clone(),
443            name: name.to_owned(),
444            jobs: Vec::new(),
445            then: None,
446            catch: None,
447            finally: None,
448            allow_failures: false,
449            error: None,
450        }
451    }
452
453    /// How a batch is doing; `None` if there's no such batch.
454    pub async fn batch_status(&self, id: i64) -> Result<Option<BatchStatus>> {
455        let row = crate::db::sql(
456            "SELECT id, name, total, pending, failed, cancelled_at, finished_at, created_at \
457             FROM job_batches WHERE id = ?",
458        )
459        .bind(id)
460        .fetch_optional(&self.db)
461        .await?;
462        let Some(row) = row else {
463            return Ok(None);
464        };
465        Ok(Some(BatchStatus {
466            id: row.try_get("id")?,
467            name: row.try_get("name")?,
468            total: row.try_get("total")?,
469            pending: row.try_get("pending")?,
470            failed: row.try_get("failed")?,
471            cancelled: row.try_get::<Option<i64>>("cancelled_at")?.is_some(),
472            finished: row.try_get::<Option<i64>>("finished_at")?.is_some(),
473            created_at: crate::db::from_unix(row.try_get("created_at")?),
474        }))
475    }
476
477    /// Cancels a batch: its jobs that haven't run are skipped.
478    pub async fn cancel_batch(&self, id: i64) -> Result<bool> {
479        Ok(crate::db::sql(
480            "UPDATE job_batches SET cancelled_at = ? WHERE id = ? AND cancelled_at IS NULL",
481        )
482        .bind(unix_now())
483        .bind(id)
484        .execute(&self.db)
485        .await?
486            == 1)
487    }
488
489    /// Jobs waiting or running.
490    pub async fn pending(&self) -> Result<i64> {
491        Ok(crate::db::sql("SELECT COUNT(*) FROM jobs")
492            .scalar(&self.db)
493            .await?)
494    }
495
496    /// Jobs that failed for good, oldest first.
497    pub async fn failed(&self) -> Result<Vec<FailedJob>> {
498        let rows = crate::db::sql(
499            "SELECT id, queue, job, payload, error, failed_at FROM failed_jobs ORDER BY id",
500        )
501        .fetch_all(&self.db)
502        .await?;
503        rows.iter()
504            .map(|r| {
505                Ok(FailedJob {
506                    id: r.try_get("id")?,
507                    queue: r.try_get("queue")?,
508                    job: r.try_get("job")?,
509                    payload: r.try_get("payload")?,
510                    error: r.try_get("error")?,
511                    failed_at: crate::db::from_unix(r.try_get("failed_at")?),
512                })
513            })
514            .collect()
515    }
516
517    /// Puts the failed job `id` back on its queue with fresh attempts (and
518    /// its chain and batch); returns whether there was such a job.
519    pub async fn retry(&self, id: i64) -> Result<bool> {
520        Ok(self.move_failed(Some(id)).await? == 1)
521    }
522
523    /// Puts every failed job back on its queue; returns how many.
524    pub async fn retry_all(&self) -> Result<u64> {
525        self.move_failed(None).await
526    }
527
528    async fn move_failed(&self, id: Option<i64>) -> Result<u64> {
529        let mut tx = self.db.begin().await?;
530        let filter = if id.is_some() { " WHERE id = ?" } else { "" };
531        let mut batches = crate::db::sql(format!(
532            "UPDATE job_batches SET failed = failed - 1, pending = pending + 1, finished_at = NULL \
533             WHERE id IN (SELECT batch_id FROM failed_jobs{filter})"
534        ));
535        if let Some(id) = id {
536            batches = batches.bind(id);
537        }
538        batches.execute(&mut tx).await?;
539        let insert = format!(
540            "INSERT INTO jobs (queue, job, payload, max_attempts, available_at, created_at, chain, \
541             batch_id, callback_of) SELECT queue, job, payload, max_attempts, ?, ?, chain, batch_id, \
542             callback_of FROM failed_jobs{filter}"
543        );
544        let mut query = crate::db::sql(insert).bind(unix_now()).bind(unix_now());
545        if let Some(id) = id {
546            query = query.bind(id);
547        }
548        let moved = query.execute(&mut tx).await?;
549        let mut delete = crate::db::sql(format!("DELETE FROM failed_jobs{filter}"));
550        if let Some(id) = id {
551            delete = delete.bind(id);
552        }
553        delete.execute(&mut tx).await?;
554        tx.commit().await?;
555        self.wake.notify_waiters();
556        Ok(moved)
557    }
558
559    /// Deletes one failed job; returns whether it existed.
560    pub async fn forget_failed(&self, id: i64) -> Result<bool> {
561        Ok(crate::db::sql("DELETE FROM failed_jobs WHERE id = ?")
562            .bind(id)
563            .execute(&self.db)
564            .await?
565            == 1)
566    }
567
568    /// Deletes failed jobs older than `age`; returns how many.
569    pub async fn prune_failed(&self, age: Duration) -> Result<u64> {
570        Ok(
571            crate::db::sql("DELETE FROM failed_jobs WHERE failed_at < ?")
572                .bind(unix_now() - age.as_secs() as i64)
573                .execute(&self.db)
574                .await?,
575        )
576    }
577
578    /// Deletes batches that finished (or were cancelled) more than `age` ago.
579    pub async fn prune_batches(&self, age: Duration) -> Result<u64> {
580        let before = unix_now() - age.as_secs() as i64;
581        Ok(crate::db::sql(
582            "DELETE FROM job_batches WHERE (finished_at IS NOT NULL AND finished_at < ?) \
583             OR (cancelled_at IS NOT NULL AND cancelled_at < ? AND pending = 0)",
584        )
585        .bind(before)
586        .bind(before)
587        .execute(&self.db)
588        .await?)
589    }
590
591    /// Deletes failed jobs.
592    pub async fn flush_failed(&self) -> Result<u64> {
593        Ok(crate::db::sql("DELETE FROM failed_jobs")
594            .execute(&self.db)
595            .await?)
596    }
597}
598
599/// Stores one job; returns its id.
600async fn insert<'c>(
601    db: impl crate::db::Executor<'c>,
602    job: &Encoded,
603    delay: Duration,
604    chain: Option<String>,
605    batch_id: Option<i64>,
606    callback_of: Option<i64>,
607) -> Result<i64> {
608    let now = unix_now();
609    let id: i64 = crate::db::sql(
610        "INSERT INTO jobs (queue, job, payload, max_attempts, available_at, created_at, chain, \
611         batch_id, callback_of) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING id",
612    )
613    .bind(&job.queue)
614    .bind(&job.job)
615    .bind(&job.payload)
616    .bind(i64::from(job.max_attempts))
617    .bind(now + delay.as_secs() as i64)
618    .bind(now)
619    .bind(chain)
620    .bind(batch_id)
621    .bind(callback_of)
622    .scalar(db)
623    .await?;
624    Ok(id)
625}
626
627/// Stores a unique job unless its claim is held; returns its id or the
628/// holder's. The claim is a `cache` row (whatever `CACHE_STORE` is), so it
629/// holds across processes.
630async fn insert_unique(
631    tx: &mut Transaction,
632    key: &str,
633    ttl: Duration,
634    job: &Encoded,
635    delay: Duration,
636) -> Result<i64> {
637    let now = unix_now();
638    let claimed = crate::db::sql(
639        "INSERT INTO cache (key, value, expires_at) VALUES (?, '0', ?) \
640         ON CONFLICT (key) DO UPDATE SET value = '0', expires_at = excluded.expires_at \
641         WHERE cache.expires_at IS NOT NULL AND cache.expires_at <= ?",
642    )
643    .bind(key)
644    .bind(now + ttl.as_secs().max(1) as i64)
645    .bind(now)
646    .execute(&mut *tx)
647    .await?;
648    if claimed == 0 {
649        let holder: String = crate::db::sql("SELECT value FROM cache WHERE key = ?")
650            .bind(key)
651            .scalar(&mut *tx)
652            .await?;
653        return Ok(holder.parse().unwrap_or_default());
654    }
655    let id = insert(&mut *tx, job, delay, None, None, None).await?;
656    crate::db::sql("UPDATE cache SET value = ? WHERE key = ?")
657        .bind(id.to_string())
658        .bind(key)
659        .execute(&mut *tx)
660        .await?;
661    Ok(id)
662}
663
664/// Jobs that run one after another; from [`Queue::chain`].
665#[must_use = "a chain does nothing until dispatched"]
666pub struct Chain {
667    queue: Queue,
668    jobs: Vec<Encoded>,
669    error: Option<Error>,
670}
671
672impl Chain {
673    /// Adds a job to the end of the chain.
674    pub fn then<J: Job>(mut self, job: J) -> Self {
675        match self.queue.encode(&job, J::QUEUE) {
676            Ok(encoded) => self.jobs.push(encoded),
677            Err(err) => {
678                self.error.get_or_insert(err);
679            }
680        }
681        self
682    }
683
684    /// Queues the first job; returns its id (0 for an empty chain).
685    pub async fn dispatch(self) -> Result<i64> {
686        if let Some(err) = self.error {
687            return Err(err);
688        }
689        let mut jobs = self.jobs.into_iter();
690        let Some(first) = jobs.next() else {
691            return Ok(0);
692        };
693        let rest: Vec<Encoded> = jobs.collect();
694        let chain = (!rest.is_empty())
695            .then(|| serde_json::to_string(&rest))
696            .transpose()?;
697        let id = insert(&self.queue.db, &first, Duration::ZERO, chain, None, None).await?;
698        self.queue.wake_workers();
699        Ok(id)
700    }
701}
702
703/// Jobs that run side by side and are tracked together; from
704/// [`Queue::batch`]. The first job that fails for good cancels the batch
705/// (jobs that haven't run are skipped) unless [`Batch::allow_failures`].
706#[must_use = "a batch does nothing until dispatched"]
707pub struct Batch {
708    queue: Queue,
709    name: String,
710    jobs: Vec<Encoded>,
711    then: Option<Encoded>,
712    catch: Option<Encoded>,
713    finally: Option<Encoded>,
714    allow_failures: bool,
715    error: Option<Error>,
716}
717
718impl Batch {
719    fn encode<J: Job>(&mut self, job: J) -> Option<Encoded> {
720        match self.queue.encode(&job, J::QUEUE) {
721            Ok(encoded) => Some(encoded),
722            Err(err) => {
723                self.error.get_or_insert(err);
724                None
725            }
726        }
727    }
728
729    /// Adds a job to the batch.
730    pub fn push<J: Job>(mut self, job: J) -> Self {
731        if let Some(job) = self.encode(job) {
732            self.jobs.push(job);
733        }
734        self
735    }
736
737    /// Queued when every job has succeeded.
738    pub fn then<J: Job>(mut self, job: J) -> Self {
739        self.then = self.encode(job);
740        self
741    }
742
743    /// Queued when the first job fails for good.
744    pub fn catch<J: Job>(mut self, job: J) -> Self {
745        self.catch = self.encode(job);
746        self
747    }
748
749    /// Queued when every job has run or been skipped, however it went.
750    pub fn finally<J: Job>(mut self, job: J) -> Self {
751        self.finally = self.encode(job);
752        self
753    }
754
755    /// A job failing for good doesn't cancel the others.
756    pub fn allow_failures(mut self) -> Self {
757        self.allow_failures = true;
758        self
759    }
760
761    /// Stores the batch and its jobs; returns the batch id.
762    pub async fn dispatch(self) -> Result<i64> {
763        if let Some(err) = self.error {
764            return Err(err);
765        }
766        let json = |job: &Option<Encoded>| job.as_ref().map(serde_json::to_string).transpose();
767        let (then, catch, finally) = (json(&self.then)?, json(&self.catch)?, json(&self.finally)?);
768        let total = self.jobs.len() as i64;
769        let mut tx = self.queue.db.begin().await?;
770        let id: i64 = crate::db::sql(
771            "INSERT INTO job_batches (name, total, pending, allow_failures, then_job, catch_job, \
772             finally_job, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?) RETURNING id",
773        )
774        .bind(&self.name)
775        .bind(total)
776        .bind(total)
777        .bind(self.allow_failures)
778        .bind(then)
779        .bind(catch)
780        .bind(finally)
781        .bind(unix_now())
782        .scalar(&mut tx)
783        .await?;
784        for job in &self.jobs {
785            insert(&mut tx, job, Duration::ZERO, None, Some(id), None).await?;
786        }
787        if self.jobs.is_empty() {
788            finish_batch(&mut tx, id, 0).await?;
789        }
790        tx.commit().await?;
791        self.queue.wake_workers();
792        Ok(id)
793    }
794}
795
796/// Counts one of a batch's jobs as done (`failed`: for good) and queues the
797/// follow-up jobs that are due.
798pub(crate) async fn batch_job_done(tx: &mut Transaction, batch_id: i64, failed: bool) -> Result {
799    let row: Option<(i64, i64, Option<String>)> = crate::db::sql(
800        "UPDATE job_batches SET pending = pending - 1, failed = failed + ?, \
801         cancelled_at = CASE WHEN ? AND NOT allow_failures THEN COALESCE(cancelled_at, ?) \
802         ELSE cancelled_at END \
803         WHERE id = ? RETURNING pending, failed, catch_job",
804    )
805    .bind(i64::from(failed))
806    .bind(failed)
807    .bind(unix_now())
808    .bind(batch_id)
809    .fetch_as(&mut *tx)
810    .await?
811    .into_iter()
812    .next();
813    let Some((pending, failures, catch)) = row else {
814        return Ok(()); // pruned meanwhile
815    };
816    if failed && failures == 1 {
817        queue_follow_up(tx, catch, batch_id).await?;
818    }
819    if pending <= 0 {
820        finish_batch(tx, batch_id, failures).await?;
821    }
822    Ok(())
823}
824
825async fn finish_batch(tx: &mut Transaction, batch_id: i64, failures: i64) -> Result {
826    let (then, finally, cancelled): (Option<String>, Option<String>, Option<i64>) = crate::db::sql(
827        "UPDATE job_batches SET finished_at = ? WHERE id = ? \
828         RETURNING then_job, finally_job, cancelled_at",
829    )
830    .bind(unix_now())
831    .bind(batch_id)
832    .fetch_as(&mut *tx)
833    .await?
834    .into_iter()
835    .next()
836    .unwrap_or_default();
837    if failures == 0 && cancelled.is_none() {
838        queue_follow_up(tx, then, batch_id).await?;
839    }
840    queue_follow_up(tx, finally, batch_id).await
841}
842
843/// Queues a batch's `then`/`catch`/`finally` job, which sees the batch in
844/// `JobContext::batch_id` but isn't counted in it.
845async fn queue_follow_up(tx: &mut Transaction, job: Option<String>, batch_id: i64) -> Result {
846    if let Some(job) = job {
847        let job: Encoded = serde_json::from_str(&job)?;
848        insert(&mut *tx, &job, Duration::ZERO, None, None, Some(batch_id)).await?;
849    }
850    Ok(())
851}
852
853/// Queues the next job of a chain, handing it the rest.
854pub(crate) async fn continue_chain(tx: &mut Transaction, chain: &str) -> Result {
855    let rest: Vec<Encoded> = serde_json::from_str(chain)?;
856    let mut rest = rest.into_iter();
857    if let Some(next) = rest.next() {
858        let rest: Vec<Encoded> = rest.collect();
859        let chain = (!rest.is_empty())
860            .then(|| serde_json::to_string(&rest))
861            .transpose()?;
862        insert(&mut *tx, &next, Duration::ZERO, chain, None, None).await?;
863    }
864    Ok(())
865}
866
867/// Drops a unique job's claim.
868pub(crate) async fn release_unique(tx: &mut Transaction, key: &str) -> Result {
869    crate::db::sql("DELETE FROM cache WHERE key = ?")
870        .bind(key)
871        .execute(&mut *tx)
872        .await?;
873    Ok(())
874}
875
876/// How a batch is doing; from [`Queue::batch_status`].
877#[derive(Debug, Clone, Serialize)]
878#[non_exhaustive]
879pub struct BatchStatus {
880    /// The `job_batches` row id.
881    pub id: i64,
882    /// The name given to [`Queue::batch`].
883    pub name: String,
884    /// Jobs in the batch.
885    pub total: i64,
886    /// Jobs not run yet (or being retried).
887    pub pending: i64,
888    /// Jobs that failed for good.
889    pub failed: i64,
890    /// Cancelled by a failure (without `allow_failures`) or `cancel_batch`.
891    pub cancelled: bool,
892    /// Every job has run or been skipped.
893    pub finished: bool,
894    /// When it was made.
895    pub created_at: crate::db::DateTime,
896}
897
898impl BatchStatus {
899    /// Percent of the jobs that have run, 0–100.
900    pub fn progress(&self) -> u8 {
901        if self.total == 0 {
902            return 100;
903        }
904        ((self.total - self.pending) * 100 / self.total).clamp(0, 100) as u8
905    }
906}
907
908/// A job that used up its attempts.
909#[derive(Debug, Clone, Serialize)]
910#[non_exhaustive]
911pub struct FailedJob {
912    /// The `failed_jobs` row id, for `queue:retry` and `queue:forget`.
913    pub id: i64,
914    /// The queue it ran on.
915    pub queue: String,
916    /// The job type's [`Job::NAME`].
917    pub job: String,
918    /// The serialized job (JSON, or `enc:…` when encrypted).
919    pub payload: String,
920    /// The last attempt's error.
921    pub error: String,
922    /// When it failed for good.
923    pub failed_at: crate::db::DateTime,
924}
925
926impl AppState {
927    /// Shorthand for `state.queue.dispatch(job)`.
928    pub async fn dispatch<J: Job>(&self, job: J) -> Result<i64> {
929        self.queue.dispatch(job).await
930    }
931
932    /// Runs `job` now, in this task, instead of queueing it (no retries,
933    /// middleware or `failed` hook): the error, if any, is returned.
934    pub async fn dispatch_sync<J: Job>(&self, job: J) -> Result {
935        let ctx = JobContext {
936            state: self.clone(),
937            attempt: 1,
938            id: 0,
939            batch_id: None,
940        };
941        crate::context::scope_app(self.clone(), job.handle(ctx)).await
942    }
943}