Skip to main content

navree_queue/
module.rs

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