Skip to main content

navree_queue/
module.rs

1//! [`QueueModule`].
2
3use std::sync::Arc;
4
5use navree_config::{Config, ConfigSection, ModuleBuilderConfigExt};
6use navree_contracts::{Clock, Dispatcher, JobMonitor, JobRegistration};
7use navree_db::{Db, ModuleBuilderDbExt};
8use navree_http::ModuleBuilderHttpExt;
9use navree_kernel::{
10    AppContext, BoxError, ConfiguredModule, Factory, Module, ModuleBuilder, ProviderKey, Resolver,
11};
12use navree_realtime::ModuleBuilderRealtimeExt;
13use navree_schedule::ModuleBuilderScheduleExt;
14use navree_telemetry::{Telemetry, TracePolicy, TracePolicySection};
15
16use crate::operations::{QueueMonitor, authorize_channel};
17use crate::store::{DatabaseStore, MemoryStore, Store};
18use crate::{
19    Operations, OperationsController, Queue, QueueDriver, QueueOptions, QueueStore, SweepReport,
20    commands, migration,
21};
22
23/// The queue module. Global; provides and exports [`Queue`] (also as the
24/// app's `dyn Dispatcher`, so mail, events, notifications and schedules
25/// queue through it, and as the `dyn JobMonitor` behind
26/// `ctx.progress(..)`), [`Operations`] and [`QueueOptions`]; contributes
27/// the `queue` migrations (tables `jobs`, `failed_jobs`, `job_batches` and
28/// `operations`), the [`OperationsController`] routes, the private channel
29/// `operations.{id}` and the scheduled task `queue.watchdog` (every
30/// minute, in apps with `ScheduleModule`); registers the commands
31/// `queue:work [--queue a,b] [--once] [--stop-when-empty] [--max-jobs N]`,
32/// `queue:failed`, `queue:retry <id|all>`, `queue:flush`,
33/// `queue:batches [--limit N]`, `queue:watchdog` and
34/// `queue:prune [--hours N]`.
35///
36/// Workers run the handler of every
37/// [`JobRegistration`](navree_contracts::JobRegistration) contributed by the
38/// app's modules (`m.job::<J>()`).
39///
40/// ```no_run
41/// use navree_kernel::Navree;
42/// use navree_queue::{QueueDriver, QueueModule, QueueOptions};
43///
44/// # fn main() -> Result<(), navree_kernel::BoxError> {
45/// Navree::app()
46///     .module(QueueModule::for_root(QueueOptions {
47///         driver: QueueDriver::Memory,
48///         ..QueueOptions::default()
49///     }))
50///     .run()
51/// # }
52/// ```
53///
54/// Used plainly (`.module(QueueModule)`) or through
55/// [`from_config`](QueueModule::from_config), it reads the `queue`
56/// configuration section, so the app must include `ConfigModule`. The
57/// database driver (the default) needs `DatabaseModule`.
58#[derive(Clone, Copy, Debug, Default)]
59pub struct QueueModule;
60
61impl QueueModule {
62    /// The module with explicit options (configure it once, in the app root).
63    pub fn for_root(options: QueueOptions) -> impl Module {
64        ConfiguredModule::<QueueModule, _>::for_root(options, register)
65    }
66
67    /// The module configured from section `queue` of the app configuration.
68    pub fn from_config() -> impl Module {
69        ConfiguredModule::<QueueModule, QueueOptions>::from_config(register)
70    }
71}
72
73impl Module for QueueModule {
74    fn register(&self, m: &mut ModuleBuilder) {
75        register(m, None);
76    }
77}
78
79fn register(m: &mut ModuleBuilder, options: Option<QueueOptions>) {
80    m.global();
81    let mut queue_deps = vec![ProviderKey::of::<QueueOptions>()];
82    match options {
83        Some(options) => {
84            if options.driver == QueueDriver::Database {
85                queue_deps.push(ProviderKey::of::<Db>());
86            }
87            let options = Arc::new(options);
88            m.factory(Factory::<QueueOptions>::new(move |_| {
89                let options = options.clone();
90                async move {
91                    options
92                        .validate()
93                        .map_err(|message| format!("invalid queue options: {message}"))?;
94                    Ok(options)
95                }
96            }));
97        }
98        None => {
99            m.config::<QueueOptions>();
100        }
101    }
102    m.exports::<QueueOptions>()
103        .factory(
104            Factory::<Queue>::new(|r: Resolver| async move {
105                let options = r.get::<QueueOptions>().await?;
106                let store = match options.driver {
107                    QueueDriver::Database => {
108                        Store::Database(DatabaseStore::new((*r.get::<Db>().await?).clone()))
109                    }
110                    QueueDriver::Memory => Store::Memory(MemoryStore::default()),
111                    QueueDriver::Redis => {
112                        let store = r.app().get_named::<dyn QueueStore>("redis").await.map_err(
113                            |error| {
114                                format!(
115                                    "queue.driver = \"redis\" needs RedisModule (navree-redis) in the app: {error}"
116                                )
117                            },
118                        )?;
119                        Store::Custom("Redis", store)
120                    }
121                };
122                let app = r.app();
123                let clock = app.try_get::<dyn Clock>().await;
124                let registrations = app
125                    .contributions::<JobRegistration>()
126                    .into_iter()
127                    .map(|c| (*c.value).clone());
128                let telemetry = Telemetry::from_app(&app).await;
129                let policy = match app.try_get::<Config>().await {
130                    Some(config) => TracePolicy::from_section(
131                        config.section_or_default::<TracePolicySection>(TracePolicy::SECTION)?,
132                        |name| std::env::var(name).ok(),
133                    )?,
134                    None => TracePolicy::default(),
135                };
136                Ok(Arc::new(
137                    Queue::new(
138                        store,
139                        (*options).clone(),
140                        clock,
141                        registrations,
142                        Some(app.downgrade()),
143                    )
144                    .instrumented(telemetry, policy),
145                ))
146            })
147            .deps(queue_deps),
148        )
149        .exports::<Queue>()
150        .factory(
151            Factory::<dyn Dispatcher>::new(|r: Resolver| async move {
152                Ok(r.get::<Queue>().await? as Arc<dyn Dispatcher>)
153            })
154            .deps(vec![ProviderKey::of::<Queue>()]),
155        )
156        .exports::<dyn Dispatcher>()
157        .factory(
158            Factory::<dyn JobMonitor>::new(|r: Resolver| async move {
159                let queue = (*r.get::<Queue>().await?).clone();
160                Ok(Arc::new(QueueMonitor { queue }) as Arc<dyn JobMonitor>)
161            })
162            .deps(vec![ProviderKey::of::<Queue>()]),
163        )
164        .exports::<dyn JobMonitor>()
165        // Operations live in the app database; an app without
166        // `DatabaseModule` still boots, and using them is
167        // `QueueError::NoDatabase`.
168        .factory(
169            Factory::<Operations>::new(|r: Resolver| async move {
170                let queue = (*r.get::<Queue>().await?).clone();
171                let options = r.get::<QueueOptions>().await?;
172                let app = r.app();
173                let db = app.try_get::<Db>().await.map(|db| (*db).clone());
174                Ok(Arc::new(Operations::new(
175                    db,
176                    queue,
177                    options.operations.clone(),
178                    Some(app.downgrade()),
179                )))
180            })
181            .deps(vec![
182                ProviderKey::of::<Queue>(),
183                ProviderKey::of::<QueueOptions>(),
184            ]),
185        )
186        .exports::<Operations>()
187        .controller::<OperationsController>()
188        .channel("operations.{id}", authorize_channel)
189        .migrations(migration::migrations());
190    #[cfg(feature = "ui")]
191    m.controller::<crate::ui::OperationProgressController>();
192    // Runs only in apps with `ScheduleModule`; inert otherwise.
193    m.schedule(|s| {
194        s.task(WATCHDOG_TASK, run_watchdog)
195            .every_minute()
196            .without_overlapping();
197    });
198    for command in commands::commands() {
199        m.command(command);
200    }
201}
202
203/// The name of the scheduled watchdog task.
204const WATCHDOG_TASK: &str = "queue.watchdog";
205
206/// One scheduled watchdog run: [`Operations::sweep`], unless
207/// `queue.operations.watchdog` is false.
208async fn run_watchdog(app: AppContext) -> Result<(), BoxError> {
209    let options = app.get::<QueueOptions>().await?;
210    if !options.operations.watchdog {
211        return Ok(());
212    }
213    let report = app.get::<Operations>().await?.sweep().await?;
214    if report != SweepReport::default() {
215        tracing::info!(
216            target: "navree::job",
217            failed = report.failed,
218            redispatched = report.redispatched,
219            finished = report.finished,
220            "watchdog swept stale operations"
221        );
222    }
223    Ok(())
224}