Skip to main content

navree_queue/
options.rs

1//! [`QueueOptions`] (configuration section `queue`), [`QueueDriver`] and
2//! [`WorkOptions`].
3
4use std::time::Duration;
5
6use navree_config::{ConfigSection, ConfigTable};
7use serde::{Deserialize, Serialize};
8
9/// Where queued jobs are stored.
10#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
11#[serde(rename_all = "snake_case")]
12#[non_exhaustive]
13pub enum QueueDriver {
14    /// The `jobs` and `failed_jobs` tables of the app database
15    /// (`"database"`, the default): jobs survive restarts and are shared by
16    /// every process using the database. Needs `DatabaseModule`.
17    #[default]
18    Database,
19    /// In-process memory (`"memory"`): jobs are lost when the process
20    /// exits. For tests and single-process development.
21    Memory,
22    /// Redis (`"redis"`): the `dyn QueueStore` provider named `redis`,
23    /// which navree-redis's `RedisModule` registers; every process using
24    /// the same Redis server shares the jobs. Needs `RedisModule`.
25    Redis,
26}
27
28impl QueueDriver {
29    /// The configuration name: `database`, `memory` or `redis`.
30    pub fn as_str(self) -> &'static str {
31        match self {
32            QueueDriver::Database => "database",
33            QueueDriver::Memory => "memory",
34            QueueDriver::Redis => "redis",
35        }
36    }
37}
38
39/// `QueueModule` settings: configuration section `queue`.
40///
41/// ```toml
42/// [queue]
43/// driver = "database"          # or "memory", "redis"
44/// default_queue = "default"    # where jobs with an empty queue name go
45/// workers = 4                  # concurrent jobs per `queue:work` process
46/// poll_interval_ms = 1000      # how long an idle worker waits before polling again
47/// queues = ["high", "default"] # what `queue:work` processes, in priority order
48/// ```
49///
50/// Every field has a default, so a missing section is valid.
51/// `queues` may also be one comma-separated string
52/// (`APP_QUEUE__QUEUES=high,default`); when empty, workers process
53/// `default_queue`.
54#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ConfigSection)]
55#[config(key = "queue", docs = "/docs/digging-deeper/queues/", validate = Self::check)]
56#[serde(default)]
57pub struct QueueOptions {
58    /// Where jobs are stored (default [`QueueDriver::Database`]).
59    #[config(one_of = "database, memory, redis")]
60    pub driver: QueueDriver,
61    /// The queue of jobs dispatched with an empty queue name, and the queue
62    /// workers process when [`queues`](QueueOptions::queues) is empty
63    /// (default `default`, the queue [`JobOptions`](navree_contracts::JobOptions)
64    /// names by default).
65    pub default_queue: String,
66    /// How many jobs one [`Queue::work`](crate::Queue::work) call runs at
67    /// the same time (default 4).
68    pub workers: usize,
69    /// How long an idle worker waits before polling again, in milliseconds
70    /// (default 1000).
71    pub poll_interval_ms: u64,
72    /// The queues workers process, highest priority first (default: just
73    /// `default_queue`).
74    #[serde(deserialize_with = "navree_config::comma_list")]
75    pub queues: Vec<String>,
76    /// Operations: their routes, heartbeat and watchdog (section
77    /// `queue.operations`).
78    #[config(table)]
79    pub operations: OperationsOptions,
80}
81
82impl Default for QueueOptions {
83    fn default() -> Self {
84        Self {
85            driver: QueueDriver::Database,
86            default_queue: "default".to_owned(),
87            workers: 4,
88            poll_interval_ms: 1000,
89            queues: Vec::new(),
90            operations: OperationsOptions::default(),
91        }
92    }
93}
94
95/// Operations settings: configuration section `queue.operations`.
96///
97/// ```toml
98/// [queue.operations]
99/// routes = true                        # GET/DELETE /api/operations/{id}, the SSE stream
100/// watchdog = true                      # sweep stale operations every minute (with ScheduleModule)
101/// heartbeat_secs = 30                  # how often a running job's operation shows it is alive
102/// stale_after_secs = 300               # no heartbeat for this long: the watchdog steps in
103/// max_redispatches = 3                 # restarts of an idempotent operation's job
104/// progress_interval_ms = 500           # ctx.progress writes at most this often per job
105/// stream_poll_ms = 1000                # how often an SSE stream re-reads the operation
106/// view_permission = "operations.view"  # see other users' operations
107/// cancel_permission = "operations.cancel"
108/// ```
109#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ConfigTable)]
110#[serde(default)]
111#[non_exhaustive]
112pub struct OperationsOptions {
113    /// Mounts the `/api/operations` routes (default true; they also need
114    /// `DatabaseModule` and an authenticator).
115    pub routes: bool,
116    /// Schedules the watchdog ([`Operations::sweep`](crate::Operations::sweep))
117    /// every minute, as task `queue.watchdog`, in apps with
118    /// `ScheduleModule` (default true). Without `ScheduleModule`, run
119    /// `queue:watchdog` every minute from system cron instead.
120    pub watchdog: bool,
121    /// How often the worker renews the heartbeat of a running job's
122    /// operation, in seconds (default 30).
123    pub heartbeat_secs: u64,
124    /// A pending or running operation without a heartbeat for this many
125    /// seconds is stale (default 300): see `queue:watchdog`.
126    pub stale_after_secs: u64,
127    /// How many times the watchdog dispatches the job of a stale
128    /// idempotent operation again before failing it (default 3).
129    pub max_redispatches: u32,
130    /// `ctx.progress` writes to the database at most this often per job, in
131    /// milliseconds (default 500); a report with `done == total` is always
132    /// written.
133    pub progress_interval_ms: u64,
134    /// How often an SSE stream re-reads its operation, in milliseconds
135    /// (default 1000). Changes made in the same process arrive at once.
136    pub stream_poll_ms: u64,
137    /// The permission that shows other users' operations (default
138    /// `operations.view`), app-wide or in the operation's workspace.
139    pub view_permission: String,
140    /// The permission that cancels other users' operations (default
141    /// `operations.cancel`).
142    pub cancel_permission: String,
143}
144
145impl Default for OperationsOptions {
146    fn default() -> Self {
147        Self {
148            routes: true,
149            watchdog: true,
150            heartbeat_secs: 30,
151            stale_after_secs: 300,
152            max_redispatches: 3,
153            progress_interval_ms: 500,
154            stream_poll_ms: 1000,
155            view_permission: "operations.view".to_owned(),
156            cancel_permission: "operations.cancel".to_owned(),
157        }
158    }
159}
160
161impl OperationsOptions {
162    /// [`heartbeat_secs`](OperationsOptions::heartbeat_secs) as a `Duration`.
163    pub fn heartbeat_interval(&self) -> Duration {
164        Duration::from_secs(self.heartbeat_secs.max(1))
165    }
166
167    /// [`progress_interval_ms`](OperationsOptions::progress_interval_ms) as
168    /// a `Duration`.
169    pub fn progress_interval(&self) -> Duration {
170        Duration::from_millis(self.progress_interval_ms)
171    }
172
173    /// [`stream_poll_ms`](OperationsOptions::stream_poll_ms) as a
174    /// `Duration`.
175    pub fn stream_poll_interval(&self) -> Duration {
176        Duration::from_millis(self.stream_poll_ms.max(1))
177    }
178
179    fn problems(&self) -> Vec<&'static str> {
180        let mut problems = Vec::new();
181        if self.heartbeat_secs == 0 {
182            problems.push("operations.heartbeat_secs must be at least 1");
183        }
184        if self.stale_after_secs <= self.heartbeat_secs {
185            problems
186                .push("operations.stale_after_secs must be more than operations.heartbeat_secs");
187        }
188        if self.stream_poll_ms == 0 {
189            problems.push("operations.stream_poll_ms must be at least 1");
190        }
191        if self.view_permission.trim().is_empty() {
192            problems.push("operations.view_permission must not be empty");
193        }
194        if self.cancel_permission.trim().is_empty() {
195            problems.push("operations.cancel_permission must not be empty");
196        }
197        problems
198    }
199}
200
201impl QueueOptions {
202    /// The queues workers process when none are given: [`queues`](QueueOptions::queues),
203    /// or just [`default_queue`](QueueOptions::default_queue).
204    pub fn worker_queues(&self) -> Vec<String> {
205        if self.queues.is_empty() {
206            vec![self.default_queue.clone()]
207        } else {
208            self.queues.clone()
209        }
210    }
211
212    /// [`poll_interval_ms`](QueueOptions::poll_interval_ms) as a `Duration`.
213    pub fn poll_interval(&self) -> Duration {
214        Duration::from_millis(self.poll_interval_ms)
215    }
216
217    /// Checks the values (the boot calls this).
218    fn check(&self) -> Result<(), String> {
219        let mut problems = Vec::new();
220        if self.default_queue.trim().is_empty() {
221            problems.push("default_queue must not be empty");
222        }
223        if self.workers == 0 {
224            problems.push("workers must be at least 1");
225        }
226        if self.poll_interval_ms == 0 {
227            problems.push("poll_interval_ms must be at least 1");
228        }
229        problems.extend(self.operations.problems());
230        if problems.is_empty() {
231            Ok(())
232        } else {
233            Err(problems.join("; "))
234        }
235    }
236}
237
238#[cfg(test)]
239mod tests {
240    use navree_config::{Config, ConfigSources, FieldType};
241
242    use super::*;
243
244    fn config(sources: ConfigSources) -> Config {
245        Config::load(&sources).expect("configuration loads")
246    }
247
248    #[test]
249    fn defaults_match_the_plan() {
250        let options = QueueOptions::default();
251        assert_eq!(options.driver, QueueDriver::Database);
252        assert_eq!(options.default_queue, "default");
253        assert_eq!(options.workers, 4);
254        assert_eq!(options.poll_interval_ms, 1000);
255        assert!(options.queues.is_empty());
256        assert_eq!(options.worker_queues(), vec!["default".to_owned()]);
257    }
258
259    #[test]
260    fn missing_section_uses_defaults() {
261        let options = config(ConfigSources::new())
262            .typed::<QueueOptions>()
263            .expect("valid");
264        assert_eq!(options, QueueOptions::default());
265    }
266
267    #[test]
268    fn section_queue_is_read_and_queues_may_be_comma_separated() {
269        let sources = ConfigSources::new().env_vars(
270            "APP_",
271            [
272                ("APP_QUEUE__DRIVER", "memory"),
273                ("APP_QUEUE__WORKERS", "2"),
274                ("APP_QUEUE__QUEUES", "high, default"),
275            ],
276        );
277        let options = config(sources).typed::<QueueOptions>().expect("valid");
278        assert_eq!(options.driver, QueueDriver::Memory);
279        assert_eq!(options.workers, 2);
280        assert_eq!(
281            options.queues,
282            vec!["high".to_owned(), "default".to_owned()]
283        );
284        assert_eq!(options.worker_queues(), options.queues);
285    }
286
287    #[test]
288    fn redis_is_a_driver_name() {
289        let sources = ConfigSources::new().env_vars("APP_", [("APP_QUEUE__DRIVER", "redis")]);
290        let options = config(sources).typed::<QueueOptions>().expect("valid");
291        assert_eq!(options.driver, QueueDriver::Redis);
292        assert_eq!(
293            [
294                QueueDriver::Database,
295                QueueDriver::Memory,
296                QueueDriver::Redis
297            ]
298            .map(QueueDriver::as_str),
299            ["database", "memory", "redis"]
300        );
301        let sources = ConfigSources::new().env_vars("APP_", [("APP_QUEUE__DRIVER", "carrier")]);
302        assert!(config(sources).typed::<QueueOptions>().is_err());
303    }
304
305    #[test]
306    fn section_queue_operations_is_read_from_nested_keys() {
307        let sources = ConfigSources::new().env_vars(
308            "APP_",
309            [
310                ("APP_QUEUE__OPERATIONS__ROUTES", "false"),
311                ("APP_QUEUE__OPERATIONS__WATCHDOG", "false"),
312                ("APP_QUEUE__OPERATIONS__STALE_AFTER_SECS", "600"),
313                ("APP_QUEUE__OPERATIONS__VIEW_PERMISSION", "reports.view"),
314            ],
315        );
316        let options = config(sources).typed::<QueueOptions>().expect("valid");
317        let operations = options.operations;
318        assert!(!operations.routes && !operations.watchdog);
319        assert_eq!(operations.stale_after_secs, 600);
320        assert_eq!(operations.view_permission, "reports.view");
321        // The rest keep their defaults.
322        assert_eq!(operations.heartbeat_secs, 30);
323        assert_eq!(operations.max_redispatches, 3);
324        assert_eq!(operations.progress_interval_ms, 500);
325        assert_eq!(operations.stream_poll_ms, 1000);
326        assert_eq!(operations.cancel_permission, "operations.cancel");
327    }
328
329    #[test]
330    fn validation_checks_the_operations_settings() {
331        let invalid = |change: fn(&mut OperationsOptions)| {
332            let mut options = QueueOptions::default();
333            change(&mut options.operations);
334            options.validate().unwrap_err()
335        };
336        assert!(invalid(|o| o.heartbeat_secs = 0).contains("heartbeat_secs"));
337        assert!(invalid(|o| o.stale_after_secs = 30).contains("stale_after_secs"));
338        assert!(invalid(|o| o.stream_poll_ms = 0).contains("stream_poll_ms"));
339        assert!(invalid(|o| o.view_permission = " ".into()).contains("view_permission"));
340        assert!(invalid(|o| o.cancel_permission = String::new()).contains("cancel_permission"));
341        assert!(QueueOptions::default().validate().is_ok());
342    }
343
344    #[test]
345    fn validation_rejects_zero_workers_and_empty_default_queue() {
346        let options = QueueOptions {
347            workers: 0,
348            ..QueueOptions::default()
349        };
350        assert!(options.validate().unwrap_err().contains("workers"));
351        let options = QueueOptions {
352            default_queue: " ".into(),
353            ..QueueOptions::default()
354        };
355        assert!(options.validate().unwrap_err().contains("default_queue"));
356        let options = QueueOptions {
357            poll_interval_ms: 0,
358            ..QueueOptions::default()
359        };
360        assert!(options.validate().unwrap_err().contains("poll_interval_ms"));
361    }
362
363    #[test]
364    fn the_section_describes_itself() {
365        let schema = QueueOptions::schema().expect("schema");
366        assert_eq!(schema.key, "queue");
367        assert_eq!(schema.docs.as_deref(), Some("/docs/digging-deeper/queues/"));
368        assert!(
369            schema.unmarked_secrets().is_empty(),
370            "{:?}",
371            schema.unmarked_secrets()
372        );
373        let field = |name: &str| {
374            schema
375                .fields
376                .iter()
377                .find(|field| field.name == name)
378                .expect(name)
379        };
380        assert_eq!(
381            field("driver").ty,
382            FieldType::choice(&["database", "memory", "redis"])
383        );
384        assert_eq!(field("queues").ty, FieldType::list(FieldType::String));
385        let operations = field("operations");
386        assert_eq!(operations.ty, FieldType::Table);
387        assert!(
388            operations
389                .fields
390                .iter()
391                .any(|field| field.name == "stale_after_secs")
392        );
393        let defaults = QueueOptions::defaults().expect("defaults");
394        assert_eq!(defaults["driver"], "database");
395        assert_eq!(defaults["workers"], 4);
396        assert_eq!(defaults["operations"]["heartbeat_secs"], 30);
397    }
398}