Skip to main content

navree_queue/
queue.rs

1//! [`Queue`]: dispatching jobs and managing failed ones.
2
3use std::collections::HashMap;
4use std::fmt;
5use std::sync::Arc;
6use std::time::Duration;
7
8use navree_contracts::{BoxError, BoxFuture, Clock, Dispatcher, Job, JobEnvelope, JobRegistration};
9use navree_db::Uow;
10use navree_kernel::__private::is_community_plugin;
11use navree_kernel::{AppContext, ModuleInfo, WeakAppContext};
12use navree_telemetry::{Telemetry, TelemetryContext, TraceContext, TracePolicy};
13use sha2::{Digest, Sha256};
14use uuid::Uuid;
15
16use crate::batch::{Batch, BatchRow, JobBatch};
17use crate::operations::RunningJobs;
18use crate::record::{
19    FailedJob, FailedSummary, Membership, NewJob, PendingJob, PendingQuery, QueueStatus,
20    RetryTarget,
21};
22use crate::store::Store;
23use crate::{QueueError, QueueOptions};
24
25/// The job queue: provided and exported by [`QueueModule`](crate::QueueModule),
26/// which also registers it as the app's `dyn Dispatcher`.
27///
28/// Jobs are stored by the configured driver until a worker
29/// ([`work`](Queue::work), command `queue:work`) runs them with the handler
30/// a module registered (`m.job::<J>()`).
31///
32/// `Queue` is a cheap handle: clones share the same driver.
33#[derive(Clone)]
34pub struct Queue {
35    pub(crate) inner: Arc<Inner>,
36}
37
38pub(crate) struct Inner {
39    pub(crate) store: Store,
40    pub(crate) options: QueueOptions,
41    /// The app's `dyn Clock`, if it registers one.
42    clock: Option<Arc<dyn Clock>>,
43    /// Job handlers by job type.
44    pub(crate) registry: HashMap<&'static str, JobRegistration>,
45    /// The app, for job contexts and the shutdown token.
46    app: Option<WeakAppContext>,
47    /// Where job attempts are reported (`JobProcessed`, `JobFailed`).
48    pub(crate) telemetry: Telemetry,
49    /// How each attempt's trace starts (`observe.tracing`).
50    pub(crate) policy: TracePolicy,
51    /// The jobs this process's workers are running.
52    pub(crate) running: RunningJobs,
53}
54
55impl Queue {
56    pub(crate) fn new(
57        store: Store,
58        options: QueueOptions,
59        clock: Option<Arc<dyn Clock>>,
60        registrations: impl IntoIterator<Item = JobRegistration>,
61        app: Option<WeakAppContext>,
62    ) -> Queue {
63        let mut registry = HashMap::new();
64        for registration in registrations {
65            registry.entry(registration.name).or_insert(registration);
66        }
67        Queue {
68            inner: Arc::new(Inner {
69                store,
70                options,
71                clock,
72                registry,
73                app,
74                telemetry: Telemetry::disabled(),
75                policy: TracePolicy::default(),
76                running: RunningJobs::default(),
77            }),
78        }
79    }
80
81    /// Reports job attempts to `telemetry` and traces them by `policy`
82    /// (on a queue no clone was made of yet).
83    pub(crate) fn instrumented(mut self, telemetry: Telemetry, policy: TracePolicy) -> Queue {
84        if let Some(inner) = Arc::get_mut(&mut self.inner) {
85            inner.telemetry = telemetry;
86            inner.policy = policy;
87        }
88        self
89    }
90
91    /// Queues the job in `envelope` as the work of operation `operation`,
92    /// as part of `uow`.
93    pub(crate) async fn push_for_operation_in(
94        &self,
95        uow: &Uow,
96        envelope: JobEnvelope,
97        operation: Uuid,
98    ) -> Result<String, QueueError> {
99        let delay = envelope_delay(&envelope);
100        let mut job = self.prepare(envelope, delay)?;
101        job.membership.operation_id = Some(operation.to_string());
102        self.store_in(uow, job).await
103    }
104
105    /// Queues the job in `envelope` as the work of operation `operation`
106    /// (joining the current unit of work like [`dispatch`](Queue::dispatch)).
107    pub(crate) async fn push_for_operation(
108        &self,
109        envelope: JobEnvelope,
110        operation: Uuid,
111    ) -> Result<String, QueueError> {
112        let delay = envelope_delay(&envelope);
113        let mut job = self.prepare(envelope, delay)?;
114        job.membership.operation_id = Some(operation.to_string());
115        self.store(job).await
116    }
117
118    /// The options the queue runs with.
119    pub fn options(&self) -> &QueueOptions {
120        &self.inner.options
121    }
122
123    /// Queues `job` to run as soon as a worker is free; returns its id.
124    ///
125    /// Inside a unit of work's scope ([`Uow::current`]: a request handler,
126    /// `Db::transaction`) the job joins it, as with
127    /// [`dispatch_in`](Queue::dispatch_in): it is queued only if that unit
128    /// of work commits, and workers see it after the commit. (On SQLite
129    /// this is also what keeps the insert from waiting for the
130    /// transaction's write lock.) Elsewhere, or once the current unit of
131    /// work has finished, the job is stored at once. The same holds for
132    /// [`later`](Queue::later), [`push`](Queue::push) and `dyn Dispatcher`.
133    pub async fn dispatch<J: Job>(&self, job: J) -> Result<String, QueueError> {
134        self.push(envelope(&job)?).await
135    }
136
137    /// Queues `job` as part of the unit of work `uow`: with the database
138    /// driver the row is written in its transaction, otherwise the job is
139    /// queued once it commits. Either way a rolled-back unit of work queues
140    /// nothing, and workers never see the job before the commit. Returns the
141    /// id the job gets.
142    pub async fn dispatch_in<J: Job>(&self, uow: &Uow, job: J) -> Result<String, QueueError> {
143        self.push_in(uow, envelope(&job)?).await
144    }
145
146    /// Queues `job` to run no earlier than `delay` from now (millisecond
147    /// precision); returns its id. Joins the current unit of work like
148    /// [`dispatch`](Queue::dispatch).
149    pub async fn later<J: Job>(&self, job: J, delay: Duration) -> Result<String, QueueError> {
150        let job = self.prepare(envelope(&job)?, delay)?;
151        self.store(job).await
152    }
153
154    /// Queues a serialized job (what `dyn Dispatcher` does), honouring its
155    /// `delay_secs`; returns its id. Joins the current unit of work like
156    /// [`dispatch`](Queue::dispatch).
157    pub async fn push(&self, envelope: JobEnvelope) -> Result<String, QueueError> {
158        let delay = envelope_delay(&envelope);
159        let job = self.prepare(envelope, delay)?;
160        self.store(job).await
161    }
162
163    /// Stores `job` in the current unit of work when there is an unfinished
164    /// one, at once otherwise. `QueueFake` records at once.
165    async fn store(&self, job: NewJob) -> Result<String, QueueError> {
166        if !matches!(self.inner.store, Store::Fake(_))
167            && let Some(uow) = Uow::current()
168            && !uow.is_finished().await
169        {
170            return self.store_in(&uow, job).await;
171        }
172        self.inner.store.insert(job).await
173    }
174
175    /// Queues a serialized job as part of `uow` (see
176    /// [`dispatch_in`](Queue::dispatch_in)); returns its id.
177    ///
178    /// With the memory and Redis drivers, a unique job is deduplicated when
179    /// the unit of work commits, so the id returned here is the new job's id
180    /// even if a pending duplicate later takes its place.
181    pub async fn push_in(&self, uow: &Uow, envelope: JobEnvelope) -> Result<String, QueueError> {
182        let delay = envelope_delay(&envelope);
183        let job = self.prepare(envelope, delay)?;
184        self.store_in(uow, job).await
185    }
186
187    /// Queues a serialized job from inside a
188    /// [`ChangeObserver`](navree_db::ChangeObserver), as part of the commit
189    /// it observes: `uow` is the unit of work the observer is given, which
190    /// runs statements in the transaction being committed. With the
191    /// database driver the row is written through it; otherwise the job is
192    /// queued once `uow` has committed. A commit that fails queues nothing.
193    /// Returns the id the job gets.
194    pub async fn push_observed(
195        &self,
196        uow: &Uow,
197        envelope: JobEnvelope,
198    ) -> Result<String, QueueError> {
199        let delay = envelope_delay(&envelope);
200        let job = self.prepare(envelope, delay)?;
201        self.store_in(uow, job).await
202    }
203
204    /// Stores `job` as part of `uow`.
205    async fn store_in(&self, uow: &Uow, job: NewJob) -> Result<String, QueueError> {
206        match &self.inner.store {
207            Store::Database(store) => store.insert_in(uow, &job).await,
208            Store::Memory(_) | Store::Fake(_) | Store::Custom(..) => {
209                let id = job.id.clone();
210                let queue = self.clone();
211                uow.after_commit(move || {
212                    Box::pin(async move {
213                        let id = job.id.clone();
214                        if let Err(error) = queue.inner.store.insert(job).await {
215                            tracing::error!(target: "navree::job", job_id = %id, %error, "cannot queue a job after commit");
216                        }
217                    })
218                });
219                Ok(id)
220            }
221        }
222    }
223
224    /// Every failed job, newest first.
225    pub async fn failed(&self) -> Result<Vec<FailedJob>, QueueError> {
226        self.inner.store.failed().await
227    }
228
229    /// How many jobs failed, how many of them at or after `since`, and the
230    /// newest `limit`, without their payloads: what to read on a page polled
231    /// every few seconds, where [`failed`](Queue::failed) would read the
232    /// whole table.
233    pub async fn failed_summary(
234        &self,
235        since: chrono::DateTime<chrono::Utc>,
236        limit: usize,
237    ) -> Result<FailedSummary, QueueError> {
238        self.inner.store.failed_summary(since, limit).await
239    }
240
241    /// Puts failed jobs back on their queues, to run as soon as possible
242    /// with their attempts starting over (same id and options, not unique);
243    /// returns how many. `retry("all")` or [`RetryTarget::All`] retries
244    /// every failed job; an unknown id is
245    /// [`QueueError::FailedJobNotFound`].
246    pub async fn retry(&self, target: impl Into<RetryTarget>) -> Result<u64, QueueError> {
247        let target = target.into();
248        self.inner.store.retry(&target, self.now_ms()).await
249    }
250
251    /// Deletes every failed job; returns how many.
252    pub async fn flush_failed(&self) -> Result<u64, QueueError> {
253        self.inner.store.flush_failed().await
254    }
255
256    /// How many jobs of `queue` are not finished yet: waiting, delayed or
257    /// running.
258    pub async fn pending_count(&self, queue: &str) -> Result<u64, QueueError> {
259        self.inner.store.pending_count(queue).await
260    }
261
262    /// The failed job with id `id`, if there is one.
263    pub async fn failed_job(&self, id: &str) -> Result<Option<FailedJob>, QueueError> {
264        self.inner.store.failed_job(id).await
265    }
266
267    /// Deletes one failed job (it is not retried);
268    /// [`QueueError::FailedJobNotFound`] when there is none with that id.
269    pub async fn forget(&self, id: &str) -> Result<(), QueueError> {
270        self.inner.store.forget(id).await
271    }
272
273    /// `queue` now: how many jobs wait (available now), are delayed
274    /// (available later) and run (reserved by a worker), and since when its
275    /// oldest waiting job is available, so
276    /// [`oldest_wait`](QueueStatus::oldest_wait) is how far the queue is
277    /// behind. One query with the database driver.
278    pub async fn status(&self, queue: &str) -> Result<QueueStatus, QueueError> {
279        self.inner.store.status(queue, self.now_ms()).await
280    }
281
282    /// The jobs that are not finished yet, oldest first (by availability):
283    /// waiting, delayed and running, filtered by `query`.
284    pub async fn pending_jobs(&self, query: &PendingQuery) -> Result<Vec<PendingJob>, QueueError> {
285        self.inner.store.pending_jobs(query, self.now_ms()).await
286    }
287
288    /// The unfinished job with id `id`, if there is one.
289    pub async fn pending_job(&self, id: &str) -> Result<Option<PendingJob>, QueueError> {
290        self.inner.store.pending_job(id, self.now_ms()).await
291    }
292
293    /// Dispatches `batch`: stores the batch and queues its jobs, all at
294    /// once; returns the stored batch. Joins the current unit of work like
295    /// [`dispatch`](Queue::dispatch). A batch with no jobs finishes at once
296    /// (its `then` and `finally` are queued with it).
297    ///
298    /// Every job type in the batch, callbacks included, must be registered
299    /// ([`QueueError::UnknownJob`] otherwise, and nothing is queued).
300    pub async fn dispatch_batch(&self, batch: Batch) -> Result<JobBatch, QueueError> {
301        let (row, jobs) = self.prepare_batch(batch)?;
302        if !matches!(self.inner.store, Store::Fake(_))
303            && let Some(uow) = Uow::current()
304            && !uow.is_finished().await
305        {
306            return self.store_batch_in(&uow, row, jobs).await;
307        }
308        let batch = row.to_batch();
309        self.inner.store.insert_batch(row, jobs).await?;
310        Ok(batch)
311    }
312
313    /// Dispatches `batch` as part of the unit of work `uow` (see
314    /// [`dispatch_in`](Queue::dispatch_in)): nothing is stored if it rolls
315    /// back.
316    pub async fn dispatch_batch_in(&self, uow: &Uow, batch: Batch) -> Result<JobBatch, QueueError> {
317        let (row, jobs) = self.prepare_batch(batch)?;
318        self.store_batch_in(uow, row, jobs).await
319    }
320
321    /// The batch `id`, with its counts as they are now.
322    pub async fn find_batch(&self, id: &str) -> Result<Option<JobBatch>, QueueError> {
323        Ok(self
324            .inner
325            .store
326            .find_batch(id)
327            .await?
328            .map(|row| row.to_batch()))
329    }
330
331    /// The most recent batches, newest first, at most `limit`.
332    pub async fn batches(&self, limit: usize) -> Result<Vec<JobBatch>, QueueError> {
333        Ok(self
334            .inner
335            .store
336            .batches(limit)
337            .await?
338            .iter()
339            .map(BatchRow::to_batch)
340            .collect())
341    }
342
343    /// Cancels batch `id`: its jobs that have not started are skipped, and
344    /// running ones see it through `ctx.is_cancelled()` and
345    /// `ctx.progress(..)`. `finally` still runs once every job has ended;
346    /// `then` does not. A finished batch stays as it is. Returns the batch
347    /// afterwards (`None` when there is none).
348    pub async fn cancel_batch(&self, id: &str) -> Result<Option<JobBatch>, QueueError> {
349        let now = self.now_ms();
350        Ok(self
351            .inner
352            .store
353            .cancel_batch(id, now)
354            .await?
355            .map(|row| row.to_batch()))
356    }
357
358    /// Deletes the batches whose jobs and callbacks all finished more than
359    /// `older_than` ago; returns how many.
360    pub async fn prune_batches(&self, older_than: Duration) -> Result<u64, QueueError> {
361        let before = self
362            .now_ms()
363            .saturating_sub(i64::try_from(older_than.as_millis()).unwrap_or(i64::MAX));
364        self.inner.store.prune_batches(before).await
365    }
366
367    /// The batch row and the jobs to store for `batch` (callbacks due at
368    /// once included).
369    fn prepare_batch(&self, batch: Batch) -> Result<(BatchRow, Vec<NewJob>), QueueError> {
370        if let Store::Custom(name, _) = &self.inner.store {
371            return Err(QueueError::Store(
372                format!("the {name} queue driver does not support batches").into(),
373            ));
374        }
375        batch.check()?;
376        let fake = matches!(self.inner.store, Store::Fake(_));
377        let callbacks = [
378            &batch.callbacks.then,
379            &batch.callbacks.catch,
380            &batch.callbacks.finally,
381        ];
382        for callback in callbacks.into_iter().flatten() {
383            if !fake && !self.inner.registry.contains_key(callback.job_type.as_str()) {
384                return Err(QueueError::UnknownJob {
385                    job_type: callback.job_type.clone(),
386                });
387            }
388        }
389        let now = self.now_ms();
390        let mut row = BatchRow::new(Uuid::now_v7().to_string(), &batch, now);
391        let mut jobs = Vec::with_capacity(batch.jobs.len());
392        for envelope in batch.jobs {
393            let mut job = self.prepare(not_unique(envelope), Duration::ZERO)?;
394            job.membership = Membership::batch_job(&row.id, row.operation_id.as_deref());
395            jobs.push(job);
396        }
397        for envelope in row.start_empty(now) {
398            jobs.push(self.prepare_callback(envelope, &row)?);
399        }
400        Ok((row, jobs))
401    }
402
403    /// A batch callback that became due, as the job to store.
404    pub(crate) fn prepare_callback(
405        &self,
406        envelope: JobEnvelope,
407        row: &BatchRow,
408    ) -> Result<NewJob, QueueError> {
409        let mut job = self.prepare(not_unique(envelope), Duration::ZERO)?;
410        job.membership = Membership::batch_callback(&row.id, row.operation_id.as_deref());
411        Ok(job)
412    }
413
414    /// Stores a prepared batch as part of `uow`.
415    async fn store_batch_in(
416        &self,
417        uow: &Uow,
418        row: BatchRow,
419        jobs: Vec<NewJob>,
420    ) -> Result<JobBatch, QueueError> {
421        let batch = row.to_batch();
422        match &self.inner.store {
423            Store::Database(_) => self.inner.store.insert_batch_in(uow, &row, &jobs).await?,
424            Store::Memory(_) | Store::Fake(_) | Store::Custom(..) => {
425                let queue = self.clone();
426                uow.after_commit(move || {
427                    Box::pin(async move {
428                        let id = row.id.clone();
429                        if let Err(error) = queue.inner.store.insert_batch(row, jobs).await {
430                            tracing::error!(target: "navree::job", batch_id = %id, %error, "cannot queue a batch after commit");
431                        }
432                    })
433                });
434            }
435        }
436        Ok(batch)
437    }
438
439    /// The current time in Unix milliseconds (the app's `dyn Clock` when it
440    /// has one).
441    pub(crate) fn now_ms(&self) -> i64 {
442        match &self.inner.clock {
443            Some(clock) => clock.now().timestamp_millis(),
444            None => chrono::Utc::now().timestamp_millis(),
445        }
446    }
447
448    /// The app, while it is alive.
449    pub(crate) fn app(&self) -> Result<AppContext, QueueError> {
450        self.inner
451            .app
452            .as_ref()
453            .and_then(WeakAppContext::upgrade)
454            .ok_or(QueueError::ShutDown)
455    }
456
457    /// Checks the job type and fills in the queue, times (available after
458    /// `delay`) and id.
459    fn prepare(&self, envelope: JobEnvelope, delay: Duration) -> Result<NewJob, QueueError> {
460        let fake = matches!(self.inner.store, Store::Fake(_));
461        if !fake && !self.inner.registry.contains_key(envelope.job_type.as_str()) {
462            return Err(QueueError::UnknownJob {
463                job_type: envelope.job_type,
464            });
465        }
466        let now = self.now_ms();
467        let delay_ms = i64::try_from(delay.as_millis()).unwrap_or(i64::MAX);
468        let mut options = envelope.options;
469        if options.queue.trim().is_empty() {
470            options.queue.clone_from(&self.inner.options.default_queue);
471        }
472        let unique_key = match (envelope.unique_key, options.unique_for_secs) {
473            (Some(key), _) => Some(key),
474            (None, Some(_)) => Some(unique_key(&envelope.job_type, &envelope.payload)),
475            (None, None) => None,
476        };
477        let unique_for_ms = options
478            .unique_for_secs
479            .map(|secs| i64::try_from(secs.saturating_mul(1000)).unwrap_or(i64::MAX));
480        Ok(NewJob {
481            id: Uuid::now_v7().to_string(),
482            queue: options.queue.clone(),
483            job_type: envelope.job_type,
484            payload: envelope.payload,
485            options,
486            available_at: now.saturating_add(delay_ms),
487            created_at: now,
488            unique_key,
489            unique_for_ms,
490            trace_parent: current_traceparent(),
491            membership: Membership::default(),
492        })
493    }
494}
495
496/// The `traceparent` of the current request's or job's span, when it has a
497/// trace: a dispatched job continues it.
498fn current_traceparent() -> Option<String> {
499    TelemetryContext::with_current(|context| context.trace().map(TraceContext::traceparent))
500        .flatten()
501}
502
503/// `envelope` without uniqueness: every job of a batch counts.
504fn not_unique(mut envelope: JobEnvelope) -> JobEnvelope {
505    envelope.unique_key = None;
506    envelope.options.unique_for_secs = None;
507    envelope
508}
509
510/// The envelope's `delay_secs`.
511fn envelope_delay(envelope: &JobEnvelope) -> Duration {
512    Duration::from_secs(envelope.delay_secs.unwrap_or(0))
513}
514
515/// `<job type>:<hex SHA-256 of the JSON payload>`.
516fn unique_key(job_type: &str, payload: &serde_json::Value) -> String {
517    let digest = Sha256::digest(payload.to_string().as_bytes());
518    format!("{job_type}:{}", hex::encode(digest))
519}
520
521/// The envelope of `job`.
522fn envelope<J: Job>(job: &J) -> Result<JobEnvelope, QueueError> {
523    Ok(JobEnvelope {
524        job_type: J::NAME.to_owned(),
525        payload: serde_json::to_value(job).map_err(QueueError::Payload)?,
526        options: J::options(),
527        delay_secs: None,
528        unique_key: None,
529    })
530}
531
532impl Dispatcher for Queue {
533    fn dispatch_envelope(&self, env: JobEnvelope) -> BoxFuture<'_, Result<String, BoxError>> {
534        Box::pin(async move { Ok(self.push(env).await?) })
535    }
536}
537
538impl fmt::Debug for Queue {
539    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
540        let mut job_types: Vec<_> = self.inner.registry.keys().collect();
541        job_types.sort();
542        f.debug_struct("Queue")
543            .field("driver", &self.inner.store.name())
544            .field("job_types", &job_types)
545            .finish_non_exhaustive()
546    }
547}
548
549/// Every job registration of the app's modules, in dependency order, so that
550/// [`Queue::new`] keeps the first module's handler of a name, as it always
551/// did. A name that a second, different module registers is reported once for
552/// that module: a warning, or an error when either module belongs to a plugin
553/// that is not one of the framework's own. A module that registers one name
554/// twice says nothing.
555pub(crate) fn job_registrations(app: &AppContext) -> Result<Vec<JobRegistration>, String> {
556    let mut registrations = Vec::new();
557    // The modules that registered each name, in order.
558    let mut owners: HashMap<&'static str, Vec<ModuleInfo>> = HashMap::new();
559    let mut errors = Vec::new();
560    for contributed in app.contributions::<JobRegistration>() {
561        let name = contributed.value.name;
562        registrations.push((*contributed.value).clone());
563        let module = contributed.module;
564        let modules = owners.entry(name).or_default();
565        if modules.iter().any(|known| known.id == module.id) {
566            continue;
567        }
568        if let Some(first) = modules.first() {
569            let (first_name, second_name) = (first.name, module.name);
570            if is_community_plugin(app, first.id) || is_community_plugin(app, module.id) {
571                errors.push(format!(
572                    "job `{name}` is registered by both `{first_name}` and `{second_name}`; give one another name"
573                ));
574            } else {
575                tracing::warn!(
576                    target: "navree::queue",
577                    "job `{name}` is registered by both `{first_name}` and `{second_name}`; `{first_name}`'s runs, and this becomes an error in 2.0"
578                );
579            }
580        }
581        modules.push(module);
582    }
583    if errors.is_empty() {
584        Ok(registrations)
585    } else {
586        Err(errors.join("\n"))
587    }
588}