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