Skip to main content

navree_queue/store/
mod.rs

1//! The drivers behind [`Queue`](crate::Queue) and the public
2//! [`QueueStore`] trait other crates implement drivers with.
3
4mod batches;
5mod database;
6mod memory;
7
8use std::sync::Arc;
9
10pub(crate) use database::DatabaseStore;
11pub(crate) use memory::MemoryStore;
12
13use chrono::{DateTime, Utc};
14use navree_contracts::{BoxFuture, JobEnvelope};
15use navree_db::Uow;
16
17use crate::batch::{BatchRow, Finish, Finished};
18use crate::record::{
19    FailedJob, FailedSummary, NewJob, PendingJob, PendingQuery, QueueStatus, ReservedJob,
20    RetryTarget, from_millis,
21};
22use crate::{QueueError, QueueFake};
23
24/// Turns a batch callback that became due into the job to store.
25pub(crate) type PrepareCallback<'a> =
26    dyn Fn(JobEnvelope, &BatchRow) -> Result<NewJob, QueueError> + Send + Sync + 'a;
27
28/// A queue driver implemented outside this crate (navree-redis's Redis
29/// driver is one): where jobs wait, are reserved by workers and end up when
30/// they fail. Times are Unix milliseconds from the app's clock, passed in by
31/// the queue; a store never reads its own clock to decide what is due.
32///
33/// The built-in `database` and `memory` drivers have the same semantics,
34/// which a store must keep:
35///
36/// - **Order.** [`reserve`](QueueStore::reserve) takes the job of the queue
37///   with the smallest `(available_at, id)` among those a worker may take:
38///   unreserved jobs whose `available_at` has come, and reserved jobs whose
39///   reservation is older than [`NewJob::stale_after_ms`] (a crashed
40///   worker's). Ids are UUID v7, so equal times run in dispatch order.
41/// - **Atomic reservations.** Two workers never reserve the same job at the
42///   same time. Reserving counts an attempt and records the worker.
43/// - **Ownership.** [`release`](QueueStore::release) and
44///   [`fail`](QueueStore::fail) act only while `worker` still holds the
45///   reservation, and return `false` otherwise (the job was taken over).
46/// - **Unique jobs.** A job with a [`unique_key`](NewJob::unique_key) is not
47///   stored while a pending job with the same key blocks it
48///   ([`NewJob::blocked_by`]); `insert` returns the pending job's id. An
49///   older pending job that no longer blocks loses its key.
50/// - **Failed jobs** are kept until [`retry`](QueueStore::retry) (which puts
51///   them back with [`FailedJob::requeued`]) or
52///   [`flush_failed`](QueueStore::flush_failed).
53/// - **Membership.** A job's [`membership`](NewJob::membership) (its
54///   operation) is stored with it and handed back on the [`ReservedJob`].
55///   Batches need the `database` or `memory` driver: dispatching one on
56///   another driver is an error.
57///
58/// Select a store with `queue.driver`: `redis` resolves the provider of
59/// `dyn QueueStore` named `redis`. Jobs dispatched inside a unit of work
60/// are inserted after it commits.
61pub trait QueueStore: Send + Sync + 'static {
62    /// Stores `job`; returns its id, or the id of the pending unique job
63    /// that takes its place.
64    fn insert(&self, job: NewJob) -> BoxFuture<'_, Result<String, QueueError>>;
65
66    /// Reserves the next job of `queue` for `worker` at `now`: increments
67    /// its attempts and records the reservation. `None` when no job is
68    /// available.
69    fn reserve<'a>(
70        &'a self,
71        queue: &'a str,
72        worker: &'a str,
73        now: i64,
74    ) -> BoxFuture<'a, Result<Option<ReservedJob>, QueueError>>;
75
76    /// Deletes `job`, which finished.
77    fn complete<'a>(&'a self, job: &'a ReservedJob) -> BoxFuture<'a, Result<(), QueueError>>;
78
79    /// Unreserves `job`, available again at `available_at`. `false` when
80    /// `worker` no longer holds the reservation.
81    fn release<'a>(
82        &'a self,
83        job: &'a ReservedJob,
84        worker: &'a str,
85        available_at: i64,
86    ) -> BoxFuture<'a, Result<bool, QueueError>>;
87
88    /// Moves `job` to the failed jobs with `error`, failed at `now`.
89    /// `false` when `worker` no longer holds the reservation.
90    fn fail<'a>(
91        &'a self,
92        job: &'a ReservedJob,
93        worker: &'a str,
94        error: &'a str,
95        now: i64,
96    ) -> BoxFuture<'a, Result<bool, QueueError>>;
97
98    /// Every failed job, newest first (by `failed_at`, then id).
99    fn failed(&self) -> BoxFuture<'_, Result<Vec<FailedJob>, QueueError>>;
100
101    /// How many jobs failed, how many of them at or after `since`, and the
102    /// newest `limit`. By default it reads [`failed`](QueueStore::failed);
103    /// a store that can count without reading every job should.
104    fn failed_summary(
105        &self,
106        since: DateTime<Utc>,
107        limit: usize,
108    ) -> BoxFuture<'_, Result<FailedSummary, QueueError>> {
109        Box::pin(async move { Ok(FailedSummary::of(&self.failed().await?, since, limit)) })
110    }
111
112    /// Moves the targeted failed jobs back to their queues at `now`
113    /// ([`FailedJob::requeued`]); returns how many (0 for an unknown id).
114    fn retry<'a>(
115        &'a self,
116        target: &'a RetryTarget,
117        now: i64,
118    ) -> BoxFuture<'a, Result<u64, QueueError>>;
119
120    /// Deletes every failed job; returns how many.
121    fn flush_failed(&self) -> BoxFuture<'_, Result<u64, QueueError>>;
122
123    /// How many jobs of `queue` are not finished: waiting, delayed or
124    /// reserved.
125    fn pending_count<'a>(&'a self, queue: &'a str) -> BoxFuture<'a, Result<u64, QueueError>>;
126}
127
128/// The driver of a queue.
129pub(crate) enum Store {
130    Database(DatabaseStore),
131    Memory(MemoryStore),
132    /// Records jobs, never runs them.
133    Fake(QueueFake),
134    /// A driver from another crate (`queue.driver = "redis"`), named for
135    /// `Debug`.
136    Custom(&'static str, Arc<dyn QueueStore>),
137}
138
139impl std::fmt::Debug for Store {
140    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
141        match self {
142            Store::Database(db) => f.debug_tuple("Database").field(db).finish(),
143            Store::Memory(memory) => f.debug_tuple("Memory").field(memory).finish(),
144            Store::Fake(fake) => f.debug_tuple("Fake").field(fake).finish(),
145            Store::Custom(name, _) => f.debug_tuple("Custom").field(name).finish(),
146        }
147    }
148}
149
150impl Store {
151    /// The driver's name, for `Debug`.
152    pub(crate) fn name(&self) -> &'static str {
153        match self {
154            Store::Database(_) => "Database",
155            Store::Memory(_) => "Memory",
156            Store::Fake(_) => "Fake",
157            Store::Custom(name, _) => name,
158        }
159    }
160
161    /// Stores `job`; returns its id, or the id of the pending unique job
162    /// that takes its place.
163    pub(crate) async fn insert(&self, job: NewJob) -> Result<String, QueueError> {
164        match self {
165            Store::Database(db) => db.insert(&job).await,
166            Store::Memory(memory) => Ok(memory.insert(job)),
167            Store::Fake(fake) => {
168                let id = job.id.clone();
169                fake.record(envelope_of(job));
170                Ok(id)
171            }
172            Store::Custom(_, store) => store.insert(job).await,
173        }
174    }
175
176    pub(crate) async fn reserve(
177        &self,
178        queue: &str,
179        worker: &str,
180        now: i64,
181    ) -> Result<Option<ReservedJob>, QueueError> {
182        match self {
183            Store::Database(db) => db.reserve(queue, worker, now).await,
184            Store::Memory(memory) => Ok(memory.reserve(queue, worker, now)),
185            Store::Fake(_) => Ok(None),
186            Store::Custom(_, store) => store.reserve(queue, worker, now).await,
187        }
188    }
189
190    pub(crate) async fn complete(&self, job: &ReservedJob) -> Result<(), QueueError> {
191        match self {
192            Store::Database(db) => db.complete(&job.id).await,
193            Store::Memory(memory) => {
194                memory.complete(&job.id);
195                Ok(())
196            }
197            Store::Fake(_) => Ok(()),
198            Store::Custom(_, store) => store.complete(job).await,
199        }
200    }
201
202    /// Unreserves `job`, available again at `available_at`. Returns false
203    /// when `worker` no longer holds the reservation.
204    pub(crate) async fn release(
205        &self,
206        job: &ReservedJob,
207        worker: &str,
208        available_at: i64,
209    ) -> Result<bool, QueueError> {
210        match self {
211            Store::Database(db) => db.release(&job.id, worker, available_at).await,
212            Store::Memory(memory) => Ok(memory.release(&job.id, worker, available_at)),
213            Store::Fake(_) => Ok(false),
214            Store::Custom(_, store) => store.release(job, worker, available_at).await,
215        }
216    }
217
218    /// Moves `job` to the failed jobs. Returns false when `worker` no
219    /// longer holds the reservation.
220    pub(crate) async fn fail(
221        &self,
222        job: &ReservedJob,
223        worker: &str,
224        error: &str,
225        now: i64,
226    ) -> Result<bool, QueueError> {
227        match self {
228            Store::Database(db) => db.fail(job, worker, error, now).await,
229            Store::Memory(memory) => Ok(memory.fail(job, worker, error, now)),
230            Store::Fake(_) => Ok(false),
231            Store::Custom(_, store) => store.fail(job, worker, error, now).await,
232        }
233    }
234
235    pub(crate) async fn failed_summary(
236        &self,
237        since: DateTime<Utc>,
238        limit: usize,
239    ) -> Result<FailedSummary, QueueError> {
240        match self {
241            Store::Database(db) => db.failed_summary(since, limit).await,
242            Store::Memory(memory) => Ok(FailedSummary::of(&memory.failed(), since, limit)),
243            Store::Fake(_) => Ok(FailedSummary::default()),
244            Store::Custom(_, store) => store.failed_summary(since, limit).await,
245        }
246    }
247
248    pub(crate) async fn failed(&self) -> Result<Vec<FailedJob>, QueueError> {
249        match self {
250            Store::Database(db) => db.failed().await,
251            Store::Memory(memory) => Ok(memory.failed()),
252            Store::Fake(_) => Ok(Vec::new()),
253            Store::Custom(_, store) => store.failed().await,
254        }
255    }
256
257    /// Moves the targeted failed jobs back to their queues; returns how many.
258    pub(crate) async fn retry(&self, target: &RetryTarget, now: i64) -> Result<u64, QueueError> {
259        let retried = match self {
260            Store::Database(db) => db.retry(target, now).await?,
261            Store::Memory(memory) => memory.retry(target, now),
262            Store::Fake(_) => 0,
263            Store::Custom(_, store) => store.retry(target, now).await?,
264        };
265        match target {
266            RetryTarget::Id(id) if retried == 0 => {
267                Err(QueueError::FailedJobNotFound { id: id.clone() })
268            }
269            _ => Ok(retried),
270        }
271    }
272
273    /// Deletes every failed job; returns how many.
274    pub(crate) async fn flush_failed(&self) -> Result<u64, QueueError> {
275        match self {
276            Store::Database(db) => db.flush_failed().await,
277            Store::Memory(memory) => Ok(memory.flush_failed()),
278            Store::Fake(_) => Ok(0),
279            Store::Custom(_, store) => store.flush_failed().await,
280        }
281    }
282
283    pub(crate) async fn pending_count(&self, queue: &str) -> Result<u64, QueueError> {
284        match self {
285            Store::Database(db) => db.pending_count(queue).await,
286            Store::Memory(memory) => Ok(memory.pending_count(queue)),
287            Store::Fake(fake) => Ok(fake.count_on(queue)),
288            Store::Custom(_, store) => store.pending_count(queue).await,
289        }
290    }
291
292    /// `queue`'s waiting, delayed and running jobs at `now`. A fake's
293    /// recorded jobs all count as waiting since `now`.
294    pub(crate) async fn status(&self, queue: &str, now: i64) -> Result<QueueStatus, QueueError> {
295        match self {
296            Store::Database(db) => db.status(queue, now).await,
297            Store::Memory(memory) => Ok(memory.status(queue, now)),
298            Store::Fake(fake) => {
299                let waiting = fake.count_on(queue);
300                Ok(QueueStatus {
301                    queue: queue.to_owned(),
302                    waiting,
303                    delayed: 0,
304                    running: 0,
305                    oldest_available_at: (waiting > 0).then(|| from_millis(now)),
306                    at: from_millis(now),
307                })
308            }
309            // `QueueStore` reports only how many jobs are pending: they
310            // all count as waiting, with no oldest wait.
311            Store::Custom(_, store) => Ok(QueueStatus {
312                queue: queue.to_owned(),
313                waiting: store.pending_count(queue).await?,
314                delayed: 0,
315                running: 0,
316                oldest_available_at: None,
317                at: from_millis(now),
318            }),
319        }
320    }
321
322    pub(crate) async fn pending_jobs(
323        &self,
324        query: &PendingQuery,
325        now: i64,
326    ) -> Result<Vec<PendingJob>, QueueError> {
327        match self {
328            Store::Database(db) => db.pending_jobs(query, now).await,
329            Store::Memory(memory) => Ok(memory.pending_jobs(query, now)),
330            Store::Fake(_) | Store::Custom(..) => Ok(Vec::new()),
331        }
332    }
333
334    pub(crate) async fn pending_job(
335        &self,
336        id: &str,
337        now: i64,
338    ) -> Result<Option<PendingJob>, QueueError> {
339        match self {
340            Store::Database(db) => db.pending_job(id, now).await,
341            Store::Memory(memory) => Ok(memory.pending_job(id, now)),
342            Store::Fake(_) | Store::Custom(..) => Ok(None),
343        }
344    }
345
346    pub(crate) async fn failed_job(&self, id: &str) -> Result<Option<FailedJob>, QueueError> {
347        match self {
348            Store::Database(db) => db.failed_job(id).await,
349            Store::Memory(memory) => Ok(memory.failed_job(id)),
350            Store::Fake(_) => Ok(None),
351            Store::Custom(_, store) => {
352                Ok(store.failed().await?.into_iter().find(|job| job.id == id))
353            }
354        }
355    }
356
357    /// Deletes failed job `id`; [`QueueError::FailedJobNotFound`] when
358    /// there is none.
359    pub(crate) async fn forget(&self, id: &str) -> Result<(), QueueError> {
360        let deleted = match self {
361            Store::Database(db) => db.forget(id).await?,
362            Store::Memory(memory) => memory.forget(id),
363            Store::Fake(_) => false,
364            Store::Custom(name, _) => {
365                return Err(QueueError::Store(
366                    format!("the {name} queue driver cannot forget one failed job").into(),
367                ));
368            }
369        };
370        if deleted {
371            Ok(())
372        } else {
373            Err(QueueError::FailedJobNotFound { id: id.to_owned() })
374        }
375    }
376
377    /// Stores a batch and its jobs at once.
378    pub(crate) async fn insert_batch(
379        &self,
380        row: BatchRow,
381        jobs: Vec<NewJob>,
382    ) -> Result<(), QueueError> {
383        match self {
384            Store::Database(db) => db.insert_batch(&row, &jobs).await,
385            Store::Memory(memory) => {
386                memory.insert_batch(row, jobs);
387                Ok(())
388            }
389            Store::Fake(fake) => {
390                // A batch with no jobs dispatches its callbacks at once:
391                // the fake records them like any other dispatch.
392                let (callbacks, members): (Vec<_>, Vec<_>) =
393                    jobs.into_iter().partition(|job| job.membership.callback);
394                fake.record_batch(row, members.into_iter().map(envelope_of).collect());
395                for callback in callbacks {
396                    fake.record(envelope_of(callback));
397                }
398                Ok(())
399            }
400            Store::Custom(name, _) => Err(no_batches(name)),
401        }
402    }
403
404    /// Stores a batch and its jobs in the transaction of `uow` (database
405    /// driver only; the others store once it commits).
406    pub(crate) async fn insert_batch_in(
407        &self,
408        uow: &Uow,
409        row: &BatchRow,
410        jobs: &[NewJob],
411    ) -> Result<(), QueueError> {
412        match self {
413            Store::Database(db) => db.insert_batch_in(uow, row, jobs).await,
414            Store::Memory(_) | Store::Fake(_) => Ok(()),
415            Store::Custom(name, _) => Err(no_batches(name)),
416        }
417    }
418
419    /// Finishes a reserved job of a batch (see
420    /// [`MemoryStore::finish_batch_job`]).
421    pub(crate) async fn finish_batch_job(
422        &self,
423        job: &ReservedJob,
424        worker: &str,
425        finish: Finish,
426        error: &str,
427        now: i64,
428        prepare: &PrepareCallback<'_>,
429    ) -> Result<Finished, QueueError> {
430        match self {
431            Store::Database(db) => {
432                db.finish_batch_job(job, worker, finish, error, now, prepare)
433                    .await
434            }
435            Store::Memory(memory) => {
436                memory.finish_batch_job(job, worker, finish, error, now, prepare)
437            }
438            Store::Fake(_) => Ok(Finished::Lost),
439            Store::Custom(name, _) => Err(no_batches(name)),
440        }
441    }
442
443    pub(crate) async fn find_batch(&self, id: &str) -> Result<Option<BatchRow>, QueueError> {
444        match self {
445            Store::Database(db) => db.find_batch(id).await,
446            Store::Memory(memory) => Ok(memory.find_batch(id)),
447            Store::Fake(fake) => Ok(fake.find_batch(id)),
448            Store::Custom(..) => Ok(None),
449        }
450    }
451
452    pub(crate) async fn batches(&self, limit: usize) -> Result<Vec<BatchRow>, QueueError> {
453        match self {
454            Store::Database(db) => db.batches(limit).await,
455            Store::Memory(memory) => Ok(memory.batches(limit)),
456            Store::Fake(fake) => Ok(fake.batch_rows(limit)),
457            Store::Custom(..) => Ok(Vec::new()),
458        }
459    }
460
461    pub(crate) async fn cancel_batch(
462        &self,
463        id: &str,
464        now: i64,
465    ) -> Result<Option<BatchRow>, QueueError> {
466        match self {
467            Store::Database(db) => db.cancel_batch(id, now).await,
468            Store::Memory(memory) => Ok(memory.cancel_batch(id, now)),
469            Store::Fake(fake) => Ok(fake.cancel_batch(id, now)),
470            Store::Custom(..) => Ok(None),
471        }
472    }
473
474    pub(crate) async fn prune_batches(&self, before: i64) -> Result<u64, QueueError> {
475        match self {
476            Store::Database(db) => db.prune_batches(before).await,
477            Store::Memory(memory) => Ok(memory.prune_batches(before)),
478            Store::Fake(_) | Store::Custom(..) => Ok(0),
479        }
480    }
481
482    /// How many stored jobs do the work of operation `operation_id`.
483    pub(crate) async fn count_for_operation(&self, operation_id: &str) -> Result<u64, QueueError> {
484        match self {
485            Store::Database(db) => db.count_for_operation(operation_id).await,
486            Store::Memory(memory) => Ok(memory.count_for_operation(operation_id)),
487            Store::Fake(_) => Ok(0),
488            // `QueueStore` cannot look jobs up by operation: count the work
489            // as still queued, so the watchdog never runs it twice (the
490            // driver hands a crashed worker's job to another worker).
491            Store::Custom(..) => Ok(1),
492        }
493    }
494}
495
496/// The error for a batch on a driver that cannot store batches.
497fn no_batches(driver: &str) -> QueueError {
498    QueueError::Store(format!("the {driver} queue driver does not support batches").into())
499}
500
501/// The envelope a fake records for `job` (its delay rounded up to whole
502/// seconds).
503pub(crate) fn envelope_of(job: NewJob) -> JobEnvelope {
504    let delay_ms = job.available_at.saturating_sub(job.created_at).max(0);
505    let delay_secs = u64::try_from(delay_ms.div_euclid(1000) + i64::from(delay_ms % 1000 != 0))
506        .unwrap_or_default();
507    JobEnvelope {
508        job_type: job.job_type,
509        payload: job.payload,
510        options: job.options,
511        delay_secs: (delay_secs > 0).then_some(delay_secs),
512        unique_key: job.unique_key,
513    }
514}