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::__private::{selector_error, selector_name};
7use navree_config::{ConfigSection, ConfigTable, DriverName, DriverNameError};
8use serde::{Deserialize, Deserializer, Serialize, Serializer};
9
10use crate::drivers::SLOT;
11
12/// Where queued jobs are stored.
13#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
14#[non_exhaustive]
15pub enum QueueDriver {
16    /// The `jobs` and `failed_jobs` tables of the app database
17    /// (`"database"`, the default): jobs survive restarts and are shared by
18    /// every process using the database. Needs `DatabaseModule`.
19    #[default]
20    Database,
21    /// In-process memory (`"memory"`): jobs are lost when the process
22    /// exits. For tests and single-process development.
23    Memory,
24    /// Redis (`"redis"`): the `dyn QueueStore` provider named `redis`,
25    /// which navree-redis's `RedisModule` registers; every process using
26    /// the same Redis server shares the jobs. Needs `RedisModule`.
27    Redis,
28    /// A store a module registers under this name with
29    /// [`m.queue_store`](crate::ModuleBuilderQueueExt::queue_store)
30    /// (`"amritsar_queue"`); its settings are `queue.{name}`. Holding a
31    /// built-in name, it is that built-in driver.
32    Registered(DriverName),
33}
34
35impl QueueDriver {
36    /// The configuration name: `database`, `memory`, `redis`, or the name a
37    /// store is registered under.
38    pub fn as_str(self) -> &'static str {
39        match self {
40            QueueDriver::Database => "database",
41            QueueDriver::Memory => "memory",
42            QueueDriver::Redis => "redis",
43            QueueDriver::Registered(name) => name.as_str(),
44        }
45    }
46
47    /// The driver, with a `Registered` built-in name turned into that
48    /// built-in (`Registered("memory")` is `Memory`).
49    pub(crate) fn resolved(self) -> QueueDriver {
50        match self {
51            QueueDriver::Registered(name) => match name.as_str() {
52                "database" => QueueDriver::Database,
53                "memory" => QueueDriver::Memory,
54                "redis" => QueueDriver::Redis,
55                _ => self,
56            },
57            other => other,
58        }
59    }
60}
61
62/// The configuration name, as [`as_str`](QueueDriver::as_str) gives it.
63impl Serialize for QueueDriver {
64    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
65        serializer.serialize_str(self.as_str())
66    }
67}
68
69/// `database`, `memory` and `redis` are the built-in drivers, also when
70/// written as a table whose only key is the name (`{ memory = {} }`); any
71/// other lower-case name (a letter, then letters, digits or `_`) is a store a
72/// module registers, which the boot resolves. Anything else, a table of any
73/// other key included, is an error that lists the names and never repeats
74/// the value.
75impl<'de> Deserialize<'de> for QueueDriver {
76    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
77        let name = selector_name(deserializer, "driver", &SLOT)?;
78        match name.as_str() {
79            "database" => Ok(QueueDriver::Database),
80            "memory" => Ok(QueueDriver::Memory),
81            "redis" => Ok(QueueDriver::Redis),
82            other => match DriverName::new(other) {
83                Ok(name) => Ok(QueueDriver::Registered(name)),
84                Err(DriverNameError::Invalid) => {
85                    Err(serde::de::Error::custom(selector_error("driver", &SLOT)))
86                }
87                Err(error) => Err(serde::de::Error::custom(error)),
88            },
89        }
90    }
91}
92
93/// `QueueModule` settings: configuration section `queue`.
94///
95/// ```toml
96/// [queue]
97/// driver = "database"          # or "memory", "redis", or a store a module registers
98/// default_queue = "default"    # where jobs with an empty queue name go
99/// workers = 4                  # concurrent jobs per `queue:work` process
100/// poll_interval_ms = 1000      # how long an idle worker waits before polling again
101/// queues = ["high", "default"] # what `queue:work` processes, in priority order
102/// ```
103///
104/// Every field has a default, so a missing section is valid.
105/// `queues` may also be one comma-separated string
106/// (`APP_QUEUE__QUEUES=high,default`); when empty, workers process
107/// `default_queue`.
108#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ConfigSection)]
109#[config(key = "queue", docs = "/docs/digging-deeper/queues/", validate = Self::check)]
110#[serde(default)]
111pub struct QueueOptions {
112    /// Where jobs are stored (default [`QueueDriver::Database`]).
113    #[config(driver = "database, memory, redis", register = "m.queue_store")]
114    pub driver: QueueDriver,
115    /// The queue of jobs dispatched with an empty queue name, and the queue
116    /// workers process when [`queues`](QueueOptions::queues) is empty
117    /// (default `default`, the queue [`JobOptions`](navree_contracts::JobOptions)
118    /// names by default).
119    pub default_queue: String,
120    /// How many jobs one [`Queue::work`](crate::Queue::work) call runs at
121    /// the same time (default 4).
122    pub workers: usize,
123    /// How long an idle worker waits before polling again, in milliseconds
124    /// (default 1000).
125    pub poll_interval_ms: u64,
126    /// The queues workers process, highest priority first (default: just
127    /// `default_queue`).
128    #[serde(deserialize_with = "navree_config::comma_list")]
129    pub queues: Vec<String>,
130    /// Operations: their routes, heartbeat and watchdog (section
131    /// `queue.operations`).
132    #[config(table)]
133    pub operations: OperationsOptions,
134}
135
136impl Default for QueueOptions {
137    fn default() -> Self {
138        Self {
139            driver: QueueDriver::Database,
140            default_queue: "default".to_owned(),
141            workers: 4,
142            poll_interval_ms: 1000,
143            queues: Vec::new(),
144            operations: OperationsOptions::default(),
145        }
146    }
147}
148
149/// Operations settings: configuration section `queue.operations`.
150///
151/// ```toml
152/// [queue.operations]
153/// routes = true                        # GET/DELETE /api/operations/{id}, the SSE stream
154/// watchdog = true                      # sweep stale operations every minute (with ScheduleModule)
155/// heartbeat_secs = 30                  # how often a running job's operation shows it is alive
156/// stale_after_secs = 300               # no heartbeat for this long: the watchdog steps in
157/// max_redispatches = 3                 # restarts of an idempotent operation's job
158/// progress_interval_ms = 500           # ctx.progress writes at most this often per job
159/// stream_poll_ms = 1000                # how often an SSE stream re-reads the operation
160/// view_permission = "operations.view"  # see other users' operations
161/// cancel_permission = "operations.cancel"
162/// ```
163#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ConfigTable)]
164#[serde(default)]
165#[non_exhaustive]
166pub struct OperationsOptions {
167    /// Mounts the `/api/operations` routes (default true; they also need
168    /// `DatabaseModule` and an authenticator).
169    pub routes: bool,
170    /// Schedules the watchdog ([`Operations::sweep`](crate::Operations::sweep))
171    /// every minute, as task `queue.watchdog`, in apps with
172    /// `ScheduleModule` (default true). Without `ScheduleModule`, run
173    /// `queue:watchdog` every minute from system cron instead.
174    pub watchdog: bool,
175    /// How often the worker renews the heartbeat of a running job's
176    /// operation, in seconds (default 30).
177    pub heartbeat_secs: u64,
178    /// A pending or running operation without a heartbeat for this many
179    /// seconds is stale (default 300): see `queue:watchdog`.
180    pub stale_after_secs: u64,
181    /// How many times the watchdog dispatches the job of a stale
182    /// idempotent operation again before failing it (default 3).
183    pub max_redispatches: u32,
184    /// `ctx.progress` writes to the database at most this often per job, in
185    /// milliseconds (default 500); a report with `done == total` is always
186    /// written.
187    pub progress_interval_ms: u64,
188    /// How often an SSE stream re-reads its operation, in milliseconds
189    /// (default 1000). Changes made in the same process arrive at once.
190    pub stream_poll_ms: u64,
191    /// The permission that shows other users' operations (default
192    /// `operations.view`), app-wide or in the operation's workspace.
193    pub view_permission: String,
194    /// The permission that cancels other users' operations (default
195    /// `operations.cancel`).
196    pub cancel_permission: String,
197}
198
199impl Default for OperationsOptions {
200    fn default() -> Self {
201        Self {
202            routes: true,
203            watchdog: true,
204            heartbeat_secs: 30,
205            stale_after_secs: 300,
206            max_redispatches: 3,
207            progress_interval_ms: 500,
208            stream_poll_ms: 1000,
209            view_permission: "operations.view".to_owned(),
210            cancel_permission: "operations.cancel".to_owned(),
211        }
212    }
213}
214
215impl OperationsOptions {
216    /// [`heartbeat_secs`](OperationsOptions::heartbeat_secs) as a `Duration`.
217    pub fn heartbeat_interval(&self) -> Duration {
218        Duration::from_secs(self.heartbeat_secs.max(1))
219    }
220
221    /// [`progress_interval_ms`](OperationsOptions::progress_interval_ms) as
222    /// a `Duration`.
223    pub fn progress_interval(&self) -> Duration {
224        Duration::from_millis(self.progress_interval_ms)
225    }
226
227    /// [`stream_poll_ms`](OperationsOptions::stream_poll_ms) as a
228    /// `Duration`.
229    pub fn stream_poll_interval(&self) -> Duration {
230        Duration::from_millis(self.stream_poll_ms.max(1))
231    }
232
233    fn problems(&self) -> Vec<&'static str> {
234        let mut problems = Vec::new();
235        if self.heartbeat_secs == 0 {
236            problems.push("operations.heartbeat_secs must be at least 1");
237        }
238        if self.stale_after_secs <= self.heartbeat_secs {
239            problems
240                .push("operations.stale_after_secs must be more than operations.heartbeat_secs");
241        }
242        if self.stream_poll_ms == 0 {
243            problems.push("operations.stream_poll_ms must be at least 1");
244        }
245        if self.view_permission.trim().is_empty() {
246            problems.push("operations.view_permission must not be empty");
247        }
248        if self.cancel_permission.trim().is_empty() {
249            problems.push("operations.cancel_permission must not be empty");
250        }
251        problems
252    }
253}
254
255impl QueueOptions {
256    /// The queues workers process when none are given: [`queues`](QueueOptions::queues),
257    /// or just [`default_queue`](QueueOptions::default_queue).
258    pub fn worker_queues(&self) -> Vec<String> {
259        if self.queues.is_empty() {
260            vec![self.default_queue.clone()]
261        } else {
262            self.queues.clone()
263        }
264    }
265
266    /// [`poll_interval_ms`](QueueOptions::poll_interval_ms) as a `Duration`.
267    pub fn poll_interval(&self) -> Duration {
268        Duration::from_millis(self.poll_interval_ms)
269    }
270
271    /// Checks the values (the boot calls this).
272    fn check(&self) -> Result<(), String> {
273        let mut problems = Vec::new();
274        if self.default_queue.trim().is_empty() {
275            problems.push("default_queue must not be empty");
276        }
277        if self.workers == 0 {
278            problems.push("workers must be at least 1");
279        }
280        if self.poll_interval_ms == 0 {
281            problems.push("poll_interval_ms must be at least 1");
282        }
283        problems.extend(self.operations.problems());
284        if problems.is_empty() {
285            Ok(())
286        } else {
287            Err(problems.join("; "))
288        }
289    }
290}
291
292#[cfg(test)]
293mod tests {
294    use navree_config::{Config, ConfigSources, FieldType};
295
296    use super::*;
297
298    fn config(sources: ConfigSources) -> Config {
299        Config::load(&sources).expect("configuration loads")
300    }
301
302    #[test]
303    fn defaults_match_the_plan() {
304        let options = QueueOptions::default();
305        assert_eq!(options.driver, QueueDriver::Database);
306        assert_eq!(options.default_queue, "default");
307        assert_eq!(options.workers, 4);
308        assert_eq!(options.poll_interval_ms, 1000);
309        assert!(options.queues.is_empty());
310        assert_eq!(options.worker_queues(), vec!["default".to_owned()]);
311    }
312
313    #[test]
314    fn missing_section_uses_defaults() {
315        let options = config(ConfigSources::new())
316            .typed::<QueueOptions>()
317            .expect("valid");
318        assert_eq!(options, QueueOptions::default());
319    }
320
321    #[test]
322    fn section_queue_is_read_and_queues_may_be_comma_separated() {
323        let sources = ConfigSources::new().env_vars(
324            "APP_",
325            [
326                ("APP_QUEUE__DRIVER", "memory"),
327                ("APP_QUEUE__WORKERS", "2"),
328                ("APP_QUEUE__QUEUES", "high, default"),
329            ],
330        );
331        let options = config(sources).typed::<QueueOptions>().expect("valid");
332        assert_eq!(options.driver, QueueDriver::Memory);
333        assert_eq!(options.workers, 2);
334        assert_eq!(
335            options.queues,
336            vec!["high".to_owned(), "default".to_owned()]
337        );
338        assert_eq!(options.worker_queues(), options.queues);
339    }
340
341    #[test]
342    fn redis_is_a_driver_name() {
343        let sources = ConfigSources::new().env_vars("APP_", [("APP_QUEUE__DRIVER", "redis")]);
344        let options = config(sources).typed::<QueueOptions>().expect("valid");
345        assert_eq!(options.driver, QueueDriver::Redis);
346        assert_eq!(
347            [
348                QueueDriver::Database,
349                QueueDriver::Memory,
350                QueueDriver::Redis
351            ]
352            .map(QueueDriver::as_str),
353            ["database", "memory", "redis"]
354        );
355        // A name that is a lower-case word reads as a store a module
356        // registers; the boot looks for it.
357        let sources = ConfigSources::new().env_vars("APP_", [("APP_QUEUE__DRIVER", "carrier")]);
358        let options = config(sources).typed::<QueueOptions>().expect("valid");
359        assert_eq!(options.driver.as_str(), "carrier");
360        assert!(matches!(options.driver, QueueDriver::Registered(_)));
361
362        // Anything else is refused as the configuration is read, with a text
363        // that lists the names and never repeats the value.
364        let error = serde_json::from_value::<QueueDriver>(serde_json::json!("carrier-pigeon"))
365            .unwrap_err()
366            .to_string();
367        assert_eq!(
368            error,
369            "the driver must be `database`, `memory`, `redis` or the name of a queue store registered with m.queue_store (a lower-case letter, then lower-case letters, digits or _)"
370        );
371        assert!(!error.contains("carrier-pigeon"), "{error}");
372        let sources =
373            ConfigSources::new().env_vars("APP_", [("APP_QUEUE__DRIVER", "carrier-pigeon")]);
374        assert!(config(sources).typed::<QueueOptions>().is_err());
375    }
376
377    #[test]
378    fn queue_driver_keeps_copy_and_its_static_name() {
379        fn copy<T: Copy>(_: T) {}
380        let driver = QueueDriver::Registered(DriverName::from_static("amritsar_queue"));
381        copy(driver);
382        let name: &'static str = driver.as_str();
383        assert_eq!(name, "amritsar_queue");
384        assert_eq!(
385            QueueDriver::Registered(DriverName::from_static("memory")).resolved(),
386            QueueDriver::Memory
387        );
388        assert_eq!(
389            QueueDriver::Registered(DriverName::from_static("database")).resolved(),
390            QueueDriver::Database
391        );
392        assert_eq!(
393            QueueDriver::Registered(DriverName::from_static("redis")).resolved(),
394            QueueDriver::Redis
395        );
396        assert_eq!(driver.resolved(), driver);
397    }
398
399    #[test]
400    fn queue_config_of_today_reads_as_before() {
401        for (text, driver) in [
402            ("database", QueueDriver::Database),
403            ("memory", QueueDriver::Memory),
404            ("redis", QueueDriver::Redis),
405        ] {
406            assert_eq!(
407                serde_json::from_value::<QueueDriver>(serde_json::json!(text)).unwrap(),
408                driver
409            );
410            assert_eq!(serde_json::to_value(driver).unwrap(), text);
411            assert_eq!(driver.as_str(), text);
412        }
413        assert_eq!(QueueDriver::default(), QueueDriver::Database);
414        assert_eq!(
415            serde_json::to_value(QueueOptions::default()).unwrap()["driver"],
416            "database"
417        );
418        let defaults = QueueOptions::defaults().expect("defaults");
419        assert_eq!(defaults["driver"], "database");
420
421        // A whole section reads as it did.
422        let options: QueueOptions = serde_json::from_value(
423            serde_json::json!({"driver": "memory", "workers": 2, "queues": ["high", "default"]}),
424        )
425        .unwrap();
426        assert_eq!(options.driver, QueueDriver::Memory);
427        assert_eq!(options.workers, 2);
428        assert_eq!(options.queues, ["high", "default"]);
429
430        // A name no module has registered yet still reads, and prints as itself.
431        let read: QueueDriver = serde_json::from_value(serde_json::json!("dak_ludhiana")).unwrap();
432        assert_eq!(read.as_str(), "dak_ludhiana");
433        assert_eq!(serde_json::to_value(read).unwrap(), "dak_ludhiana");
434    }
435
436    #[test]
437    fn queue_driver_written_as_a_one_key_table_reads_as_before() {
438        for (table, driver, text) in [
439            (
440                serde_json::json!({"redis": {}}),
441                QueueDriver::Redis,
442                "redis",
443            ),
444            (
445                serde_json::json!({"memory": null}),
446                QueueDriver::Memory,
447                "memory",
448            ),
449            (
450                serde_json::json!({"database": {"pool": 4}}),
451                QueueDriver::Database,
452                "database",
453            ),
454        ] {
455            let read = serde_json::from_value::<QueueDriver>(table).unwrap();
456            assert_eq!(read, driver);
457            assert_eq!(serde_json::to_value(read).unwrap(), text);
458        }
459        let options: QueueOptions =
460            serde_json::from_value(serde_json::json!({"driver": {"memory": {}}, "workers": 3}))
461                .unwrap();
462        assert_eq!(options.driver, QueueDriver::Memory);
463        assert_eq!(options.workers, 3);
464
465        // A table never names a store a module registers, and reading one
466        // adds no name to the process's names.
467        let refused = "the driver must be `database`, `memory`, `redis` or the name of a queue store registered with m.queue_store (a lower-case letter, then lower-case letters, digits or _)";
468        for (table, name) in [
469            (serde_json::json!({"dak": {}}), "dak"),
470            (
471                serde_json::json!({"jalandhar_queue": {"depot": 4}}),
472                "jalandhar_queue",
473            ),
474        ] {
475            let error = serde_json::from_value::<QueueDriver>(table)
476                .unwrap_err()
477                .to_string();
478            assert_eq!(error, refused);
479            assert!(!error.contains(name), "{error}");
480        }
481        assert_eq!(DriverName::lookup("jalandhar_queue"), None);
482    }
483
484    #[test]
485    fn section_queue_operations_is_read_from_nested_keys() {
486        let sources = ConfigSources::new().env_vars(
487            "APP_",
488            [
489                ("APP_QUEUE__OPERATIONS__ROUTES", "false"),
490                ("APP_QUEUE__OPERATIONS__WATCHDOG", "false"),
491                ("APP_QUEUE__OPERATIONS__STALE_AFTER_SECS", "600"),
492                ("APP_QUEUE__OPERATIONS__VIEW_PERMISSION", "reports.view"),
493            ],
494        );
495        let options = config(sources).typed::<QueueOptions>().expect("valid");
496        let operations = options.operations;
497        assert!(!operations.routes && !operations.watchdog);
498        assert_eq!(operations.stale_after_secs, 600);
499        assert_eq!(operations.view_permission, "reports.view");
500        // The rest keep their defaults.
501        assert_eq!(operations.heartbeat_secs, 30);
502        assert_eq!(operations.max_redispatches, 3);
503        assert_eq!(operations.progress_interval_ms, 500);
504        assert_eq!(operations.stream_poll_ms, 1000);
505        assert_eq!(operations.cancel_permission, "operations.cancel");
506    }
507
508    #[test]
509    fn validation_checks_the_operations_settings() {
510        let invalid = |change: fn(&mut OperationsOptions)| {
511            let mut options = QueueOptions::default();
512            change(&mut options.operations);
513            options.validate().unwrap_err()
514        };
515        assert!(invalid(|o| o.heartbeat_secs = 0).contains("heartbeat_secs"));
516        assert!(invalid(|o| o.stale_after_secs = 30).contains("stale_after_secs"));
517        assert!(invalid(|o| o.stream_poll_ms = 0).contains("stream_poll_ms"));
518        assert!(invalid(|o| o.view_permission = " ".into()).contains("view_permission"));
519        assert!(invalid(|o| o.cancel_permission = String::new()).contains("cancel_permission"));
520        assert!(QueueOptions::default().validate().is_ok());
521    }
522
523    #[test]
524    fn validation_rejects_zero_workers_and_empty_default_queue() {
525        let options = QueueOptions {
526            workers: 0,
527            ..QueueOptions::default()
528        };
529        assert!(options.validate().unwrap_err().contains("workers"));
530        let options = QueueOptions {
531            default_queue: " ".into(),
532            ..QueueOptions::default()
533        };
534        assert!(options.validate().unwrap_err().contains("default_queue"));
535        let options = QueueOptions {
536            poll_interval_ms: 0,
537            ..QueueOptions::default()
538        };
539        assert!(options.validate().unwrap_err().contains("poll_interval_ms"));
540    }
541
542    #[test]
543    fn the_section_describes_itself() {
544        let schema = QueueOptions::schema().expect("schema");
545        assert_eq!(schema.key, "queue");
546        assert_eq!(schema.docs.as_deref(), Some("/docs/digging-deeper/queues/"));
547        assert!(
548            schema.unmarked_secrets().is_empty(),
549            "{:?}",
550            schema.unmarked_secrets()
551        );
552        let field = |name: &str| {
553            schema
554                .fields
555                .iter()
556                .find(|field| field.name == name)
557                .expect(name)
558        };
559        assert_eq!(
560            field("driver").ty,
561            FieldType::Driver {
562                built_in: vec!["database".into(), "memory".into(), "redis".into()],
563                register: "m.queue_store".into(),
564            }
565        );
566        assert_eq!(field("queues").ty, FieldType::list(FieldType::String));
567        let operations = field("operations");
568        assert_eq!(operations.ty, FieldType::Table);
569        assert!(
570            operations
571                .fields
572                .iter()
573                .any(|field| field.name == "stale_after_secs")
574        );
575        let defaults = QueueOptions::defaults().expect("defaults");
576        assert_eq!(defaults["driver"], "database");
577        assert_eq!(defaults["workers"], 4);
578        assert_eq!(defaults["operations"]["heartbeat_secs"], 30);
579    }
580}