navree-queue 1.4.0

Navree QueueModule: database and memory job queues, workers, retries with backoff, unique and delayed jobs, job batches and operations with progress.
Documentation
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
//! [`QueueOptions`] (configuration section `queue`), [`QueueDriver`] and
//! [`WorkOptions`].

use std::time::Duration;

use navree_config::__private::{selector_error, selector_name};
use navree_config::{ConfigSection, ConfigTable, DriverName, DriverNameError};
use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::drivers::SLOT;

/// Where queued jobs are stored.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum QueueDriver {
    /// The `jobs` and `failed_jobs` tables of the app database
    /// (`"database"`, the default): jobs survive restarts and are shared by
    /// every process using the database. Needs `DatabaseModule`.
    #[default]
    Database,
    /// In-process memory (`"memory"`): jobs are lost when the process
    /// exits. For tests and single-process development.
    Memory,
    /// Redis (`"redis"`): the `dyn QueueStore` provider named `redis`,
    /// which navree-redis's `RedisModule` registers; every process using
    /// the same Redis server shares the jobs. Needs `RedisModule`.
    Redis,
    /// A store a module registers under this name with
    /// [`m.queue_store`](crate::ModuleBuilderQueueExt::queue_store)
    /// (`"amritsar_queue"`); its settings are `queue.{name}`. Holding a
    /// built-in name, it is that built-in driver.
    Registered(DriverName),
}

impl QueueDriver {
    /// The configuration name: `database`, `memory`, `redis`, or the name a
    /// store is registered under.
    pub fn as_str(self) -> &'static str {
        match self {
            QueueDriver::Database => "database",
            QueueDriver::Memory => "memory",
            QueueDriver::Redis => "redis",
            QueueDriver::Registered(name) => name.as_str(),
        }
    }

    /// The driver, with a `Registered` built-in name turned into that
    /// built-in (`Registered("memory")` is `Memory`).
    pub(crate) fn resolved(self) -> QueueDriver {
        match self {
            QueueDriver::Registered(name) => match name.as_str() {
                "database" => QueueDriver::Database,
                "memory" => QueueDriver::Memory,
                "redis" => QueueDriver::Redis,
                _ => self,
            },
            other => other,
        }
    }
}

/// The configuration name, as [`as_str`](QueueDriver::as_str) gives it.
impl Serialize for QueueDriver {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.as_str())
    }
}

/// `database`, `memory` and `redis` are the built-in drivers, also when
/// written as a table whose only key is the name (`{ memory = {} }`); any
/// other lower-case name (a letter, then letters, digits or `_`) is a store a
/// module registers, which the boot resolves. Anything else, a table of any
/// other key included, is an error that lists the names and never repeats
/// the value.
impl<'de> Deserialize<'de> for QueueDriver {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        let name = selector_name(deserializer, "driver", &SLOT)?;
        match name.as_str() {
            "database" => Ok(QueueDriver::Database),
            "memory" => Ok(QueueDriver::Memory),
            "redis" => Ok(QueueDriver::Redis),
            other => match DriverName::new(other) {
                Ok(name) => Ok(QueueDriver::Registered(name)),
                Err(DriverNameError::Invalid) => {
                    Err(serde::de::Error::custom(selector_error("driver", &SLOT)))
                }
                Err(error) => Err(serde::de::Error::custom(error)),
            },
        }
    }
}

/// `QueueModule` settings: configuration section `queue`.
///
/// ```toml
/// [queue]
/// driver = "database"          # or "memory", "redis", or a store a module registers
/// default_queue = "default"    # where jobs with an empty queue name go
/// workers = 4                  # concurrent jobs per `queue:work` process
/// poll_interval_ms = 1000      # how long an idle worker waits before polling again
/// queues = ["high", "default"] # what `queue:work` processes, in priority order
/// ```
///
/// Every field has a default, so a missing section is valid.
/// `queues` may also be one comma-separated string
/// (`APP_QUEUE__QUEUES=high,default`); when empty, workers process
/// `default_queue`.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ConfigSection)]
#[config(key = "queue", docs = "/docs/digging-deeper/queues/", validate = Self::check)]
#[serde(default)]
pub struct QueueOptions {
    /// Where jobs are stored (default [`QueueDriver::Database`]).
    #[config(driver = "database, memory, redis", register = "m.queue_store")]
    pub driver: QueueDriver,
    /// The queue of jobs dispatched with an empty queue name, and the queue
    /// workers process when [`queues`](QueueOptions::queues) is empty
    /// (default `default`, the queue [`JobOptions`](navree_contracts::JobOptions)
    /// names by default).
    pub default_queue: String,
    /// How many jobs one [`Queue::work`](crate::Queue::work) call runs at
    /// the same time (default 4).
    pub workers: usize,
    /// How long an idle worker waits before polling again, in milliseconds
    /// (default 1000).
    pub poll_interval_ms: u64,
    /// The queues workers process, highest priority first (default: just
    /// `default_queue`).
    #[serde(deserialize_with = "navree_config::comma_list")]
    pub queues: Vec<String>,
    /// Operations: their routes, heartbeat and watchdog (section
    /// `queue.operations`).
    #[config(table)]
    pub operations: OperationsOptions,
}

impl Default for QueueOptions {
    fn default() -> Self {
        Self {
            driver: QueueDriver::Database,
            default_queue: "default".to_owned(),
            workers: 4,
            poll_interval_ms: 1000,
            queues: Vec::new(),
            operations: OperationsOptions::default(),
        }
    }
}

/// Operations settings: configuration section `queue.operations`.
///
/// ```toml
/// [queue.operations]
/// routes = true                        # GET/DELETE /api/operations/{id}, the SSE stream
/// watchdog = true                      # sweep stale operations every minute (with ScheduleModule)
/// heartbeat_secs = 30                  # how often a running job's operation shows it is alive
/// stale_after_secs = 300               # no heartbeat for this long: the watchdog steps in
/// max_redispatches = 3                 # restarts of an idempotent operation's job
/// progress_interval_ms = 500           # ctx.progress writes at most this often per job
/// stream_poll_ms = 1000                # how often an SSE stream re-reads the operation
/// view_permission = "operations.view"  # see other users' operations
/// cancel_permission = "operations.cancel"
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, ConfigTable)]
#[serde(default)]
#[non_exhaustive]
pub struct OperationsOptions {
    /// Mounts the `/api/operations` routes (default true; they also need
    /// `DatabaseModule` and an authenticator).
    pub routes: bool,
    /// Schedules the watchdog ([`Operations::sweep`](crate::Operations::sweep))
    /// every minute, as task `queue.watchdog`, in apps with
    /// `ScheduleModule` (default true). Without `ScheduleModule`, run
    /// `queue:watchdog` every minute from system cron instead.
    pub watchdog: bool,
    /// How often the worker renews the heartbeat of a running job's
    /// operation, in seconds (default 30).
    pub heartbeat_secs: u64,
    /// A pending or running operation without a heartbeat for this many
    /// seconds is stale (default 300): see `queue:watchdog`.
    pub stale_after_secs: u64,
    /// How many times the watchdog dispatches the job of a stale
    /// idempotent operation again before failing it (default 3).
    pub max_redispatches: u32,
    /// `ctx.progress` writes to the database at most this often per job, in
    /// milliseconds (default 500); a report with `done == total` is always
    /// written.
    pub progress_interval_ms: u64,
    /// How often an SSE stream re-reads its operation, in milliseconds
    /// (default 1000). Changes made in the same process arrive at once.
    pub stream_poll_ms: u64,
    /// The permission that shows other users' operations (default
    /// `operations.view`), app-wide or in the operation's workspace.
    pub view_permission: String,
    /// The permission that cancels other users' operations (default
    /// `operations.cancel`).
    pub cancel_permission: String,
}

impl Default for OperationsOptions {
    fn default() -> Self {
        Self {
            routes: true,
            watchdog: true,
            heartbeat_secs: 30,
            stale_after_secs: 300,
            max_redispatches: 3,
            progress_interval_ms: 500,
            stream_poll_ms: 1000,
            view_permission: "operations.view".to_owned(),
            cancel_permission: "operations.cancel".to_owned(),
        }
    }
}

impl OperationsOptions {
    /// [`heartbeat_secs`](OperationsOptions::heartbeat_secs) as a `Duration`.
    pub fn heartbeat_interval(&self) -> Duration {
        Duration::from_secs(self.heartbeat_secs.max(1))
    }

    /// [`progress_interval_ms`](OperationsOptions::progress_interval_ms) as
    /// a `Duration`.
    pub fn progress_interval(&self) -> Duration {
        Duration::from_millis(self.progress_interval_ms)
    }

    /// [`stream_poll_ms`](OperationsOptions::stream_poll_ms) as a
    /// `Duration`.
    pub fn stream_poll_interval(&self) -> Duration {
        Duration::from_millis(self.stream_poll_ms.max(1))
    }

    fn problems(&self) -> Vec<&'static str> {
        let mut problems = Vec::new();
        if self.heartbeat_secs == 0 {
            problems.push("operations.heartbeat_secs must be at least 1");
        }
        if self.stale_after_secs <= self.heartbeat_secs {
            problems
                .push("operations.stale_after_secs must be more than operations.heartbeat_secs");
        }
        if self.stream_poll_ms == 0 {
            problems.push("operations.stream_poll_ms must be at least 1");
        }
        if self.view_permission.trim().is_empty() {
            problems.push("operations.view_permission must not be empty");
        }
        if self.cancel_permission.trim().is_empty() {
            problems.push("operations.cancel_permission must not be empty");
        }
        problems
    }
}

impl QueueOptions {
    /// The queues workers process when none are given: [`queues`](QueueOptions::queues),
    /// or just [`default_queue`](QueueOptions::default_queue).
    pub fn worker_queues(&self) -> Vec<String> {
        if self.queues.is_empty() {
            vec![self.default_queue.clone()]
        } else {
            self.queues.clone()
        }
    }

    /// [`poll_interval_ms`](QueueOptions::poll_interval_ms) as a `Duration`.
    pub fn poll_interval(&self) -> Duration {
        Duration::from_millis(self.poll_interval_ms)
    }

    /// Checks the values (the boot calls this).
    fn check(&self) -> Result<(), String> {
        let mut problems = Vec::new();
        if self.default_queue.trim().is_empty() {
            problems.push("default_queue must not be empty");
        }
        if self.workers == 0 {
            problems.push("workers must be at least 1");
        }
        if self.poll_interval_ms == 0 {
            problems.push("poll_interval_ms must be at least 1");
        }
        problems.extend(self.operations.problems());
        if problems.is_empty() {
            Ok(())
        } else {
            Err(problems.join("; "))
        }
    }
}

#[cfg(test)]
mod tests {
    use navree_config::{Config, ConfigSources, FieldType};

    use super::*;

    fn config(sources: ConfigSources) -> Config {
        Config::load(&sources).expect("configuration loads")
    }

    #[test]
    fn defaults_match_the_plan() {
        let options = QueueOptions::default();
        assert_eq!(options.driver, QueueDriver::Database);
        assert_eq!(options.default_queue, "default");
        assert_eq!(options.workers, 4);
        assert_eq!(options.poll_interval_ms, 1000);
        assert!(options.queues.is_empty());
        assert_eq!(options.worker_queues(), vec!["default".to_owned()]);
    }

    #[test]
    fn missing_section_uses_defaults() {
        let options = config(ConfigSources::new())
            .typed::<QueueOptions>()
            .expect("valid");
        assert_eq!(options, QueueOptions::default());
    }

    #[test]
    fn section_queue_is_read_and_queues_may_be_comma_separated() {
        let sources = ConfigSources::new().env_vars(
            "APP_",
            [
                ("APP_QUEUE__DRIVER", "memory"),
                ("APP_QUEUE__WORKERS", "2"),
                ("APP_QUEUE__QUEUES", "high, default"),
            ],
        );
        let options = config(sources).typed::<QueueOptions>().expect("valid");
        assert_eq!(options.driver, QueueDriver::Memory);
        assert_eq!(options.workers, 2);
        assert_eq!(
            options.queues,
            vec!["high".to_owned(), "default".to_owned()]
        );
        assert_eq!(options.worker_queues(), options.queues);
    }

    #[test]
    fn redis_is_a_driver_name() {
        let sources = ConfigSources::new().env_vars("APP_", [("APP_QUEUE__DRIVER", "redis")]);
        let options = config(sources).typed::<QueueOptions>().expect("valid");
        assert_eq!(options.driver, QueueDriver::Redis);
        assert_eq!(
            [
                QueueDriver::Database,
                QueueDriver::Memory,
                QueueDriver::Redis
            ]
            .map(QueueDriver::as_str),
            ["database", "memory", "redis"]
        );
        // A name that is a lower-case word reads as a store a module
        // registers; the boot looks for it.
        let sources = ConfigSources::new().env_vars("APP_", [("APP_QUEUE__DRIVER", "carrier")]);
        let options = config(sources).typed::<QueueOptions>().expect("valid");
        assert_eq!(options.driver.as_str(), "carrier");
        assert!(matches!(options.driver, QueueDriver::Registered(_)));

        // Anything else is refused as the configuration is read, with a text
        // that lists the names and never repeats the value.
        let error = serde_json::from_value::<QueueDriver>(serde_json::json!("carrier-pigeon"))
            .unwrap_err()
            .to_string();
        assert_eq!(
            error,
            "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 _)"
        );
        assert!(!error.contains("carrier-pigeon"), "{error}");
        let sources =
            ConfigSources::new().env_vars("APP_", [("APP_QUEUE__DRIVER", "carrier-pigeon")]);
        assert!(config(sources).typed::<QueueOptions>().is_err());
    }

    #[test]
    fn queue_driver_keeps_copy_and_its_static_name() {
        fn copy<T: Copy>(_: T) {}
        let driver = QueueDriver::Registered(DriverName::from_static("amritsar_queue"));
        copy(driver);
        let name: &'static str = driver.as_str();
        assert_eq!(name, "amritsar_queue");
        assert_eq!(
            QueueDriver::Registered(DriverName::from_static("memory")).resolved(),
            QueueDriver::Memory
        );
        assert_eq!(
            QueueDriver::Registered(DriverName::from_static("database")).resolved(),
            QueueDriver::Database
        );
        assert_eq!(
            QueueDriver::Registered(DriverName::from_static("redis")).resolved(),
            QueueDriver::Redis
        );
        assert_eq!(driver.resolved(), driver);
    }

    #[test]
    fn queue_config_of_today_reads_as_before() {
        for (text, driver) in [
            ("database", QueueDriver::Database),
            ("memory", QueueDriver::Memory),
            ("redis", QueueDriver::Redis),
        ] {
            assert_eq!(
                serde_json::from_value::<QueueDriver>(serde_json::json!(text)).unwrap(),
                driver
            );
            assert_eq!(serde_json::to_value(driver).unwrap(), text);
            assert_eq!(driver.as_str(), text);
        }
        assert_eq!(QueueDriver::default(), QueueDriver::Database);
        assert_eq!(
            serde_json::to_value(QueueOptions::default()).unwrap()["driver"],
            "database"
        );
        let defaults = QueueOptions::defaults().expect("defaults");
        assert_eq!(defaults["driver"], "database");

        // A whole section reads as it did.
        let options: QueueOptions = serde_json::from_value(
            serde_json::json!({"driver": "memory", "workers": 2, "queues": ["high", "default"]}),
        )
        .unwrap();
        assert_eq!(options.driver, QueueDriver::Memory);
        assert_eq!(options.workers, 2);
        assert_eq!(options.queues, ["high", "default"]);

        // A name no module has registered yet still reads, and prints as itself.
        let read: QueueDriver = serde_json::from_value(serde_json::json!("dak_ludhiana")).unwrap();
        assert_eq!(read.as_str(), "dak_ludhiana");
        assert_eq!(serde_json::to_value(read).unwrap(), "dak_ludhiana");
    }

    #[test]
    fn queue_driver_written_as_a_one_key_table_reads_as_before() {
        for (table, driver, text) in [
            (
                serde_json::json!({"redis": {}}),
                QueueDriver::Redis,
                "redis",
            ),
            (
                serde_json::json!({"memory": null}),
                QueueDriver::Memory,
                "memory",
            ),
            (
                serde_json::json!({"database": {"pool": 4}}),
                QueueDriver::Database,
                "database",
            ),
        ] {
            let read = serde_json::from_value::<QueueDriver>(table).unwrap();
            assert_eq!(read, driver);
            assert_eq!(serde_json::to_value(read).unwrap(), text);
        }
        let options: QueueOptions =
            serde_json::from_value(serde_json::json!({"driver": {"memory": {}}, "workers": 3}))
                .unwrap();
        assert_eq!(options.driver, QueueDriver::Memory);
        assert_eq!(options.workers, 3);

        // A table never names a store a module registers, and reading one
        // adds no name to the process's names.
        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 _)";
        for (table, name) in [
            (serde_json::json!({"dak": {}}), "dak"),
            (
                serde_json::json!({"jalandhar_queue": {"depot": 4}}),
                "jalandhar_queue",
            ),
        ] {
            let error = serde_json::from_value::<QueueDriver>(table)
                .unwrap_err()
                .to_string();
            assert_eq!(error, refused);
            assert!(!error.contains(name), "{error}");
        }
        assert_eq!(DriverName::lookup("jalandhar_queue"), None);
    }

    #[test]
    fn section_queue_operations_is_read_from_nested_keys() {
        let sources = ConfigSources::new().env_vars(
            "APP_",
            [
                ("APP_QUEUE__OPERATIONS__ROUTES", "false"),
                ("APP_QUEUE__OPERATIONS__WATCHDOG", "false"),
                ("APP_QUEUE__OPERATIONS__STALE_AFTER_SECS", "600"),
                ("APP_QUEUE__OPERATIONS__VIEW_PERMISSION", "reports.view"),
            ],
        );
        let options = config(sources).typed::<QueueOptions>().expect("valid");
        let operations = options.operations;
        assert!(!operations.routes && !operations.watchdog);
        assert_eq!(operations.stale_after_secs, 600);
        assert_eq!(operations.view_permission, "reports.view");
        // The rest keep their defaults.
        assert_eq!(operations.heartbeat_secs, 30);
        assert_eq!(operations.max_redispatches, 3);
        assert_eq!(operations.progress_interval_ms, 500);
        assert_eq!(operations.stream_poll_ms, 1000);
        assert_eq!(operations.cancel_permission, "operations.cancel");
    }

    #[test]
    fn validation_checks_the_operations_settings() {
        let invalid = |change: fn(&mut OperationsOptions)| {
            let mut options = QueueOptions::default();
            change(&mut options.operations);
            options.validate().unwrap_err()
        };
        assert!(invalid(|o| o.heartbeat_secs = 0).contains("heartbeat_secs"));
        assert!(invalid(|o| o.stale_after_secs = 30).contains("stale_after_secs"));
        assert!(invalid(|o| o.stream_poll_ms = 0).contains("stream_poll_ms"));
        assert!(invalid(|o| o.view_permission = " ".into()).contains("view_permission"));
        assert!(invalid(|o| o.cancel_permission = String::new()).contains("cancel_permission"));
        assert!(QueueOptions::default().validate().is_ok());
    }

    #[test]
    fn validation_rejects_zero_workers_and_empty_default_queue() {
        let options = QueueOptions {
            workers: 0,
            ..QueueOptions::default()
        };
        assert!(options.validate().unwrap_err().contains("workers"));
        let options = QueueOptions {
            default_queue: " ".into(),
            ..QueueOptions::default()
        };
        assert!(options.validate().unwrap_err().contains("default_queue"));
        let options = QueueOptions {
            poll_interval_ms: 0,
            ..QueueOptions::default()
        };
        assert!(options.validate().unwrap_err().contains("poll_interval_ms"));
    }

    #[test]
    fn the_section_describes_itself() {
        let schema = QueueOptions::schema().expect("schema");
        assert_eq!(schema.key, "queue");
        assert_eq!(schema.docs.as_deref(), Some("/docs/digging-deeper/queues/"));
        assert!(
            schema.unmarked_secrets().is_empty(),
            "{:?}",
            schema.unmarked_secrets()
        );
        let field = |name: &str| {
            schema
                .fields
                .iter()
                .find(|field| field.name == name)
                .expect(name)
        };
        assert_eq!(
            field("driver").ty,
            FieldType::Driver {
                built_in: vec!["database".into(), "memory".into(), "redis".into()],
                register: "m.queue_store".into(),
            }
        );
        assert_eq!(field("queues").ty, FieldType::list(FieldType::String));
        let operations = field("operations");
        assert_eq!(operations.ty, FieldType::Table);
        assert!(
            operations
                .fields
                .iter()
                .any(|field| field.name == "stale_after_secs")
        );
        let defaults = QueueOptions::defaults().expect("defaults");
        assert_eq!(defaults["driver"], "database");
        assert_eq!(defaults["workers"], 4);
        assert_eq!(defaults["operations"]["heartbeat_secs"], 30);
    }
}