Skip to main content

navree_queue/
lib.rs

1//! # navree-queue
2//!
3//! `QueueModule`: database and memory job queues, workers, retries with
4//! backoff, unique and delayed jobs, job batches, and operations
5//! (user-visible long work with progress).
6//!
7//! - [`QueueModule`] is global. It provides [`Queue`] and registers it as the
8//!   app's `dyn Dispatcher`, so navree-mail, navree-events, navree-notify and
9//!   navree-schedule queue through it without depending on this crate. Its
10//!   settings are [`QueueOptions`] (configuration section `queue`).
11//! - Jobs implement [`navree_contracts::Job`]; a module registers each job type
12//!   with `m.job::<J>()` ([`ModuleBuilderJobsExt`](navree_contracts::ModuleBuilderJobsExt)).
13//!   Dispatching a type no module registered fails with
14//!   [`QueueError::UnknownJob`].
15//! - Drivers ([`QueueDriver`]): `database` (tables `jobs` and `failed_jobs`,
16//!   created by the `queue` migration set; workers in several processes
17//!   share them), `memory` (one process, for tests and development) and
18//!   `redis` (the [`QueueStore`] provider named `redis`, from navree-redis's
19//!   `RedisModule`). They behave the same; [`QueueStore`] states the
20//!   contract other drivers implement, and a module registers one under a
21//!   name of its own with [`m.queue_store`](ModuleBuilderQueueExt::queue_store),
22//!   which `queue.driver` then selects.
23//! - Workers ([`Queue::work`], command `queue:work`) reserve jobs atomically
24//!   (SQLite: `UPDATE … WHERE id = (SELECT … LIMIT 1) RETURNING`;
25//!   PostgreSQL adds `FOR UPDATE SKIP LOCKED`; MySQL, which cannot return
26//!   the rows of an `UPDATE`, locks the candidate with `SELECT … FOR UPDATE
27//!   SKIP LOCKED` in a short transaction first), run each attempt within the
28//!   job's `timeout_secs` (a panic or a timeout is a failed attempt), retry
29//!   failed attempts after [`Backoff::delay_for`](navree_contracts::Backoff::delay_for)
30//!   and move a job that used its `max_attempts` to the failed jobs
31//!   ([`Queue::failed`], [`Queue::retry`], [`Queue::flush_failed`]). A
32//!   reservation abandoned by a crashed worker is taken over once it is older
33//!   than the job's timeout plus [`STALE_RESERVATION_GRACE_SECS`].
34//! - Unique jobs (`unique_for_secs`): while an identical job (same type and
35//!   payload, or the envelope's `unique_key`) is pending and inside the
36//!   window, dispatching returns the pending job's id instead of queueing.
37//! - [`Queue::dispatch_in`] queues as part of a unit of work: nothing is
38//!   queued if it rolls back. Plain dispatches (and `dyn Dispatcher`) do
39//!   the same with the current unit of work (`navree_db::Uow::current`, e.g.
40//!   the request's while a handler runs) when there is an unfinished one.
41//! - Batches ([`Batch`], table `job_batches`): jobs dispatched together
42//!   and followed as one, with `then`, `catch` and `finally` callbacks;
43//!   the first failure cancels the rest unless the batch
44//!   [`allow_failures`](Batch::allow_failures). A job reports progress
45//!   with `ctx.progress(done, total, note)` and sees a cancelled batch
46//!   through it ([`JobCancelled`](navree_contracts::JobCancelled)).
47//! - Operations ([`Operations`], table `operations`): user-visible long
48//!   work with an owner, a workspace, a status, progress, a result and a
49//!   heartbeat, driven by its job or batch. Routes `GET /api/operations`,
50//!   `GET /api/operations/{id}`, the SSE stream
51//!   `GET /api/operations/{id}/events` and the cooperative cancel
52//!   `DELETE /api/operations/{id}` ([`OperationsController`]); every
53//!   change is broadcast as `operation.updated` on the private channel
54//!   `operations.{id}`. The owner and holders of `operations.view` (app-wide
55//!   or in the operation's workspace) may see one. A watchdog
56//!   ([`Operations::sweep`]) fails or restarts operations that stopped
57//!   responding: scheduled every minute in apps with `ScheduleModule`,
58//!   or `queue:watchdog` from system cron.
59//! - Every attempt is logged at target `navree::job` with the job type
60//!   (`name`), id, queue, attempt, `duration_ms` and `outcome`
61//!   (`succeeded`, `released`, `failed` or `cancelled`); payloads are never
62//!   logged.
63//! - Introspection: [`Queue::status`] (a queue's waiting, delayed and
64//!   running jobs and how long its oldest job has waited),
65//!   [`Queue::pending_jobs`] and [`Queue::pending_job`], [`Queue::failed_job`]
66//!   and [`Queue::forget`] (delete one failed job).
67//! - Supervision: [`Queue::work_supervised`] runs workers for a supervisor
68//!   (navree-fleet): its own concurrency and stop token, and [`WorkHooks`]
69//!   asked before each reservation (pause) and told every [`Attempt`].
70//! - Commands: `queue:work [--queue a,b] [--once] [--stop-when-empty]
71//!   [--max-jobs N]`, `queue:failed`, `queue:retry <id|all>`,
72//!   `queue:flush`, `queue:batches [--limit N]`, `queue:watchdog` and
73//!   `queue:prune [--hours N]`.
74//! - Testing: [`QueueFake`] records dispatched jobs and batches for
75//!   assertions; [`Queue::run_pending`] runs every available job before
76//!   returning.
77//!
78//! ```no_run
79//! use navree_contracts::{BoxError, Job, JobContext, JobOptions, ModuleBuilderJobsExt};
80//! use navree_kernel::{Navree, Module, ModuleBuilder};
81//! use navree_queue::{Queue, QueueModule};
82//! use serde::{Deserialize, Serialize};
83//!
84//! #[derive(Serialize, Deserialize)]
85//! struct SendInvoice {
86//!     invoice_id: u64,
87//! }
88//!
89//! impl Job for SendInvoice {
90//!     const NAME: &'static str = "billing.send_invoice";
91//!
92//!     fn options() -> JobOptions {
93//!         JobOptions {
94//!             queue: "emails".into(),
95//!             max_attempts: 5,
96//!             ..JobOptions::default()
97//!         }
98//!     }
99//!
100//!     async fn handle(self, ctx: JobContext) -> Result<(), BoxError> {
101//!         // Resolve services from `ctx.app`, open a unit of work, ...
102//!         let _ = (self.invoice_id, ctx.attempt);
103//!         Ok(())
104//!     }
105//! }
106//!
107//! struct BillingModule;
108//!
109//! impl Module for BillingModule {
110//!     fn register(&self, m: &mut ModuleBuilder) {
111//!         m.job::<SendInvoice>();
112//!     }
113//! }
114//!
115//! # async fn dispatch(queue: &Queue) -> Result<(), navree_queue::QueueError> {
116//! // Anywhere with access to the app:
117//! let id = queue.dispatch(SendInvoice { invoice_id: 42 }).await?;
118//! # let _ = id;
119//! # Ok(())
120//! # }
121//!
122//! fn main() -> Result<(), navree_kernel::BoxError> {
123//!     // `<app> queue:work --queue emails,default` runs the jobs.
124//!     Navree::app()
125//!         .module(navree_config::ConfigModule::for_root(
126//!             navree_config::ConfigSources::defaults(),
127//!         ))
128//!         .module(navree_db::DatabaseModule::from_config())
129//!         .module(QueueModule::from_config())
130//!         .module(BillingModule)
131//!         .run()
132//! }
133//! ```
134#![forbid(unsafe_code)]
135#![cfg_attr(docsrs, feature(doc_cfg))]
136
137mod batch;
138mod commands;
139mod drivers;
140mod error;
141mod fake;
142mod migration;
143mod module;
144mod operations;
145mod options;
146mod queue;
147mod record;
148mod store;
149#[cfg(feature = "ui")]
150pub mod ui;
151mod worker;
152
153pub use batch::{Batch, JobBatch};
154pub use drivers::ModuleBuilderQueueExt;
155pub use error::QueueError;
156pub use fake::{QueueFake, RecordedBatch};
157pub use migration::{FAILED_JOBS_TABLE, JOB_BATCHES_TABLE, JOBS_TABLE, OPERATIONS_TABLE};
158pub use module::QueueModule;
159pub use operations::{
160    FAILED_MESSAGE, OPERATION_EVENT, OPERATION_UPDATED_EVENT, Operation, OperationProgress,
161    OperationRecord, OperationStatus, Operations, OperationsController, STALLED_MESSAGE,
162    SweepReport, operation_topic,
163};
164pub use options::{OperationsOptions, QueueDriver, QueueOptions};
165pub use queue::Queue;
166pub use record::{
167    FailedJob, FailedJobBrief, FailedSummary, Membership, NewJob, PendingJob, PendingQuery,
168    PendingState, QueueStatus, ReservedJob, RetryTarget,
169};
170pub use store::QueueStore;
171/// The cancellation token [`Supervision::stop`] takes (tokio-util's).
172pub use tokio_util::sync::CancellationToken;
173pub use worker::{
174    Attempt, AttemptOutcome, STALE_RESERVATION_GRACE_SECS, Supervision, WorkHooks, WorkOptions,
175    WorkStats,
176};