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