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