Skip to main content

navree_queue/
batch.rs

1//! Job batches: [`Batch`] (what to dispatch) and [`JobBatch`] (a dispatched
2//! batch's progress, as stored in `job_batches`).
3
4use chrono::{DateTime, Utc};
5use navree_contracts::{Job, JobEnvelope};
6use navree_db::Uow;
7use serde::{Deserialize, Serialize};
8use uuid::Uuid;
9
10use crate::record::from_millis;
11use crate::{Queue, QueueError};
12
13/// A group of jobs dispatched together and followed as one: how many are
14/// still pending, how many failed, whether the group was cancelled, plus
15/// callbacks for its outcome. Dispatch it with [`dispatch`](Batch::dispatch)
16/// or [`dispatch_in`](Batch::dispatch_in) (or the same methods on
17/// [`Queue`]: [`dispatch_batch`](crate::Queue::dispatch_batch),
18/// [`dispatch_batch_in`](crate::Queue::dispatch_batch_in)).
19///
20/// ```no_run
21/// # use navree_contracts::{BoxError, Job, JobContext};
22/// # use serde::{Deserialize, Serialize};
23/// # #[derive(Serialize, Deserialize)] struct ImportChunk { rows: Vec<u32> }
24/// # impl Job for ImportChunk { const NAME: &'static str = "import.chunk"; async fn handle(self, _: JobContext) -> Result<(), BoxError> { Ok(()) } }
25/// # #[derive(Serialize, Deserialize)] struct FinishImport { id: u32 }
26/// # impl Job for FinishImport { const NAME: &'static str = "import.finish"; async fn handle(self, _: JobContext) -> Result<(), BoxError> { Ok(()) } }
27/// # #[derive(Serialize, Deserialize)] struct ReportImportFailure { id: u32 }
28/// # impl Job for ReportImportFailure { const NAME: &'static str = "import.failed"; async fn handle(self, _: JobContext) -> Result<(), BoxError> { Ok(()) } }
29/// use navree_queue::{Batch, Queue};
30///
31/// # async fn example(queue: &Queue, uow: &navree_db::Uow) -> Result<(), navree_queue::QueueError> {
32/// let chunks = vec![vec![1, 2], vec![3, 4]];
33/// let batch = Batch::new("recipients.import")
34///     .add(chunks.into_iter().map(|rows| ImportChunk { rows }))
35///     .then(FinishImport { id: 7 })
36///     .catch(ReportImportFailure { id: 7 })
37///     .dispatch_in(queue, uow)
38///     .await?;
39/// println!("batch {} has {} jobs", batch.id, batch.total_jobs);
40/// # Ok(())
41/// # }
42/// ```
43///
44/// - The batch **finishes** when each of its jobs has succeeded, failed
45///   (used its attempts) or been skipped.
46/// - **`then`** runs once it finishes with no failed job and without being
47///   cancelled; **`catch`** runs as soon as the first job fails;
48///   **`finally`** runs once it finishes, whatever happened.
49/// - The first failed job **cancels** the batch, unless it
50///   [`allow_failures`](Batch::allow_failures): the jobs that have not
51///   started yet are then skipped. [`Queue::cancel_batch`](crate::Queue::cancel_batch)
52///   cancels it on demand; running jobs see it through
53///   `ctx.is_cancelled()` and `ctx.progress(..)`.
54/// - Jobs in a batch are never unique (`unique_for_secs` is ignored), so
55///   every job counts.
56#[derive(Clone, Debug)]
57pub struct Batch {
58    pub(crate) name: String,
59    pub(crate) jobs: Vec<JobEnvelope>,
60    pub(crate) callbacks: Callbacks,
61    pub(crate) allow_failures: bool,
62    pub(crate) operation_id: Option<Uuid>,
63    /// The first job that could not be serialized; dispatching fails with it.
64    pub(crate) error: Option<String>,
65    /// The queue every job goes to instead of its own (`on_queue`).
66    pub(crate) queue: Option<String>,
67}
68
69/// A batch's callback jobs.
70#[derive(Clone, Debug, Default, Serialize, Deserialize)]
71pub(crate) struct Callbacks {
72    #[serde(default, skip_serializing_if = "Option::is_none")]
73    pub(crate) then: Option<JobEnvelope>,
74    #[serde(default, skip_serializing_if = "Option::is_none")]
75    pub(crate) catch: Option<JobEnvelope>,
76    #[serde(default, skip_serializing_if = "Option::is_none")]
77    pub(crate) finally: Option<JobEnvelope>,
78}
79
80impl Batch {
81    /// An empty batch named `name` (`recipients.import`): what logs,
82    /// `queue:batches` and [`JobBatch::name`] show.
83    pub fn new(name: impl Into<String>) -> Self {
84        Self {
85            name: name.into(),
86            jobs: Vec::new(),
87            callbacks: Callbacks::default(),
88            allow_failures: false,
89            operation_id: None,
90            error: None,
91            queue: None,
92        }
93    }
94
95    /// Puts every job of the batch, and its callbacks, on `queue` instead
96    /// of the queue each job type names (`JobOptions::queue`): jobs added
97    /// before and after the call.
98    pub fn on_queue(mut self, queue: impl Into<String>) -> Self {
99        let queue = queue.into();
100        let callbacks = [
101            &mut self.callbacks.then,
102            &mut self.callbacks.catch,
103            &mut self.callbacks.finally,
104        ];
105        for envelope in self.jobs.iter_mut().chain(callbacks.into_iter().flatten()) {
106            envelope.options.queue = queue.clone();
107        }
108        self.queue = Some(queue);
109        self
110    }
111
112    /// Adds `jobs` to the batch.
113    // The builder's verb (`Batch::new(..).add(jobs)`); it takes jobs, not
114    // another batch, so `std::ops::Add` does not fit.
115    #[allow(clippy::should_implement_trait)]
116    pub fn add<J: Job>(mut self, jobs: impl IntoIterator<Item = J>) -> Self {
117        for job in jobs {
118            if let Some(envelope) = self.envelope(&job) {
119                self.jobs.push(envelope);
120            }
121        }
122        self
123    }
124
125    /// Adds one job to the batch.
126    pub fn push<J: Job>(self, job: J) -> Self {
127        self.add([job])
128    }
129
130    /// The job to dispatch once the batch finishes with no failed job and
131    /// without being cancelled.
132    pub fn then<J: Job>(mut self, job: J) -> Self {
133        self.callbacks.then = self.envelope(&job);
134        self
135    }
136
137    /// The job to dispatch as soon as one of the batch's jobs fails.
138    pub fn catch<J: Job>(mut self, job: J) -> Self {
139        self.callbacks.catch = self.envelope(&job);
140        self
141    }
142
143    /// The job to dispatch once the batch finishes, whatever happened.
144    pub fn finally<J: Job>(mut self, job: J) -> Self {
145        self.callbacks.finally = self.envelope(&job);
146        self
147    }
148
149    /// Keeps running the other jobs when one fails (by default the first
150    /// failure cancels the batch). `then` still runs only when no job
151    /// failed.
152    pub fn allow_failures(mut self) -> Self {
153        self.allow_failures = true;
154        self
155    }
156
157    /// Ties the batch to the operation `id` (see
158    /// [`Operations`](crate::Operations)): its progress becomes the
159    /// operation's, its jobs and callbacks report into it, and the
160    /// operation finishes when the batch and its callbacks have run.
161    /// [`Operations::dispatch_batch`](crate::Operations::dispatch_batch)
162    /// sets it for you.
163    pub fn operation(mut self, id: Uuid) -> Self {
164        self.operation_id = Some(id);
165        self
166    }
167
168    /// How many jobs the batch has.
169    pub fn len(&self) -> usize {
170        self.jobs.len()
171    }
172
173    /// Whether the batch has no jobs (it finishes as soon as it is
174    /// dispatched).
175    pub fn is_empty(&self) -> bool {
176        self.jobs.is_empty()
177    }
178
179    /// The batch's name.
180    pub fn name(&self) -> &str {
181        &self.name
182    }
183
184    /// Dispatches the batch on `queue`: the fluent form of
185    /// [`Queue::dispatch_batch`] (it joins the current unit of work the
186    /// same way).
187    pub async fn dispatch(self, queue: &Queue) -> Result<JobBatch, QueueError> {
188        queue.dispatch_batch(self).await
189    }
190
191    /// Dispatches the batch on `queue` as part of `uow`: the fluent form of
192    /// [`Queue::dispatch_batch_in`]. Nothing is stored if `uow` rolls back.
193    pub async fn dispatch_in(self, queue: &Queue, uow: &Uow) -> Result<JobBatch, QueueError> {
194        queue.dispatch_batch_in(uow, self).await
195    }
196
197    fn envelope<J: Job>(&mut self, job: &J) -> Option<JobEnvelope> {
198        match serde_json::to_value(job) {
199            Ok(payload) => {
200                let mut options = J::options();
201                if let Some(queue) = &self.queue {
202                    options.queue = queue.clone();
203                }
204                Some(JobEnvelope {
205                    job_type: J::NAME.to_owned(),
206                    payload,
207                    options,
208                    delay_secs: None,
209                    unique_key: None,
210                })
211            }
212            Err(error) => {
213                self.error
214                    .get_or_insert_with(|| format!("job `{}`: {error}", J::NAME));
215                None
216            }
217        }
218    }
219
220    /// The serialization error of the first job that had one.
221    pub(crate) fn check(&self) -> Result<(), QueueError> {
222        match &self.error {
223            Some(error) => Err(QueueError::Payload(serde::de::Error::custom(error))),
224            None => Ok(()),
225        }
226    }
227}
228
229/// A dispatched batch, as stored in `job_batches`: what
230/// [`Queue::find_batch`](crate::Queue::find_batch) and
231/// [`Queue::batches`](crate::Queue::batches) return.
232#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
233pub struct JobBatch {
234    /// The batch id.
235    pub id: String,
236    /// The name given to [`Batch::new`].
237    pub name: String,
238    /// How many jobs the batch has.
239    pub total_jobs: u64,
240    /// How many have not finished yet.
241    pub pending_jobs: u64,
242    /// How many failed (used their attempts).
243    pub failed_jobs: u64,
244    /// The ids of the failed jobs (see `queue:failed`).
245    pub failed_job_ids: Vec<String>,
246    /// Whether a failed job leaves the others running.
247    pub allow_failures: bool,
248    /// The operation the batch does the work of.
249    pub operation_id: Option<Uuid>,
250    /// When it was dispatched.
251    pub created_at: DateTime<Utc>,
252    /// When it was cancelled (by a failure or on demand).
253    pub cancelled_at: Option<DateTime<Utc>>,
254    /// When its last job finished.
255    pub finished_at: Option<DateTime<Utc>>,
256}
257
258impl JobBatch {
259    /// Jobs that have finished (succeeded, failed or skipped).
260    pub fn processed_jobs(&self) -> u64 {
261        self.total_jobs.saturating_sub(self.pending_jobs)
262    }
263
264    /// Finished jobs as a whole percentage of all jobs (100 for an empty
265    /// batch).
266    pub fn progress(&self) -> u8 {
267        if self.total_jobs == 0 {
268            return 100;
269        }
270        let percent = u128::from(self.processed_jobs()) * 100 / u128::from(self.total_jobs);
271        u8::try_from(percent).unwrap_or(100)
272    }
273
274    /// Whether every job has finished.
275    pub fn finished(&self) -> bool {
276        self.finished_at.is_some()
277    }
278
279    /// Whether the batch was cancelled.
280    pub fn cancelled(&self) -> bool {
281        self.cancelled_at.is_some()
282    }
283
284    /// Whether any job failed.
285    pub fn has_failures(&self) -> bool {
286        self.failed_jobs > 0
287    }
288}
289
290/// How one of a batch's jobs ended.
291#[derive(Clone, Copy, Debug, PartialEq, Eq)]
292pub(crate) enum Finish {
293    /// It ran and succeeded.
294    Succeeded,
295    /// It did not run (its batch or operation was cancelled) or stopped
296    /// because of that.
297    Skipped,
298    /// It used its attempts.
299    Failed,
300}
301
302/// A batch row as the drivers keep it.
303#[derive(Clone, Debug)]
304pub(crate) struct BatchRow {
305    pub(crate) id: String,
306    pub(crate) name: String,
307    pub(crate) total_jobs: u64,
308    pub(crate) pending_jobs: u64,
309    pub(crate) failed_jobs: u64,
310    pub(crate) failed_job_ids: Vec<String>,
311    pub(crate) callbacks: Callbacks,
312    /// Callbacks dispatched and not finished yet.
313    pub(crate) callbacks_pending: u64,
314    /// Callbacks that failed.
315    pub(crate) callbacks_failed: u64,
316    pub(crate) allow_failures: bool,
317    pub(crate) operation_id: Option<String>,
318    /// Unix milliseconds.
319    pub(crate) created_at: i64,
320    pub(crate) cancelled_at: Option<i64>,
321    pub(crate) finished_at: Option<i64>,
322}
323
324/// What finishing a reserved batch job did.
325#[derive(Clone, Debug)]
326pub(crate) enum Finished {
327    /// The worker no longer held the reservation: nothing changed.
328    Lost,
329    /// The job is gone (into the failed jobs when it failed); the batch
330    /// step, when its batch still exists.
331    Done(Option<Box<BatchStep>>),
332}
333
334/// What finishing a batch job or callback changed.
335#[derive(Clone, Debug)]
336pub(crate) struct BatchStep {
337    /// The batch afterwards.
338    pub(crate) batch: BatchRow,
339    /// The batch and every callback it dispatched have now all finished
340    /// (true for exactly one step of a batch).
341    pub(crate) settled_now: bool,
342}
343
344impl BatchRow {
345    /// A new batch row with `total_jobs` jobs, created at `now`.
346    pub(crate) fn new(id: String, batch: &Batch, now: i64) -> Self {
347        let total = batch.jobs.len() as u64;
348        Self {
349            id,
350            name: batch.name.clone(),
351            total_jobs: total,
352            pending_jobs: total,
353            failed_jobs: 0,
354            failed_job_ids: Vec::new(),
355            callbacks: batch.callbacks.clone(),
356            callbacks_pending: 0,
357            callbacks_failed: 0,
358            allow_failures: batch.allow_failures,
359            operation_id: batch.operation_id.map(|id| id.to_string()),
360            created_at: now,
361            cancelled_at: None,
362            finished_at: None,
363        }
364    }
365
366    /// For a batch with no jobs: it finishes as it is created. Returns the
367    /// callbacks due.
368    pub(crate) fn start_empty(&mut self, now: i64) -> Vec<JobEnvelope> {
369        if self.total_jobs == 0 {
370            self.finish(now)
371        } else {
372            Vec::new()
373        }
374    }
375
376    /// Records that job `job_id` ended with `finish` at `now`; returns the
377    /// callbacks due now (counted as pending).
378    pub(crate) fn job_finished(
379        &mut self,
380        job_id: &str,
381        finish: Finish,
382        now: i64,
383    ) -> Vec<JobEnvelope> {
384        if self.pending_jobs == 0 {
385            return Vec::new();
386        }
387        self.pending_jobs -= 1;
388        let mut due = Vec::new();
389        if finish == Finish::Failed {
390            self.failed_jobs += 1;
391            self.failed_job_ids.push(job_id.to_owned());
392            if self.failed_jobs == 1
393                && let Some(catch) = &self.callbacks.catch
394            {
395                due.push(catch.clone());
396            }
397            if !self.allow_failures && self.cancelled_at.is_none() {
398                self.cancelled_at = Some(now);
399            }
400        }
401        self.callbacks_pending += due.len() as u64;
402        if self.pending_jobs == 0 {
403            due.extend(self.finish(now));
404        }
405        due
406    }
407
408    /// Records that one of the batch's callbacks ended.
409    pub(crate) fn callback_finished(&mut self, failed: bool) {
410        self.callbacks_pending = self.callbacks_pending.saturating_sub(1);
411        if failed {
412            self.callbacks_failed += 1;
413        }
414    }
415
416    /// Cancels the batch at `now` unless it finished or was cancelled;
417    /// whether it changed.
418    pub(crate) fn cancel(&mut self, now: i64) -> bool {
419        if self.cancelled_at.is_some() || self.finished_at.is_some() {
420            return false;
421        }
422        self.cancelled_at = Some(now);
423        true
424    }
425
426    /// Whether the batch and the callbacks it dispatched have all finished.
427    pub(crate) fn settled(&self) -> bool {
428        self.finished_at.is_some() && self.callbacks_pending == 0
429    }
430
431    /// Marks the batch finished; returns `then` (when it applies) and
432    /// `finally`, counted as pending callbacks.
433    fn finish(&mut self, now: i64) -> Vec<JobEnvelope> {
434        let mut due = Vec::new();
435        if self.finished_at.is_none() {
436            self.finished_at = Some(now);
437            if self.failed_jobs == 0
438                && self.cancelled_at.is_none()
439                && let Some(then) = &self.callbacks.then
440            {
441                due.push(then.clone());
442            }
443            if let Some(finally) = &self.callbacks.finally {
444                due.push(finally.clone());
445            }
446        }
447        self.callbacks_pending += due.len() as u64;
448        due
449    }
450
451    /// The public view.
452    pub(crate) fn to_batch(&self) -> JobBatch {
453        JobBatch {
454            id: self.id.clone(),
455            name: self.name.clone(),
456            total_jobs: self.total_jobs,
457            pending_jobs: self.pending_jobs,
458            failed_jobs: self.failed_jobs,
459            failed_job_ids: self.failed_job_ids.clone(),
460            allow_failures: self.allow_failures,
461            operation_id: self
462                .operation_id
463                .as_deref()
464                .and_then(|id| Uuid::parse_str(id).ok()),
465            created_at: from_millis(self.created_at),
466            cancelled_at: self.cancelled_at.map(from_millis),
467            finished_at: self.finished_at.map(from_millis),
468        }
469    }
470}
471
472#[cfg(test)]
473mod tests {
474    use navree_contracts::{BoxError, JobContext};
475
476    use super::*;
477
478    #[derive(Serialize, Deserialize)]
479    struct Ping;
480
481    impl Job for Ping {
482        const NAME: &'static str = "test.ping";
483
484        async fn handle(self, _ctx: JobContext) -> Result<(), BoxError> {
485            Ok(())
486        }
487    }
488
489    #[test]
490    fn on_queue_moves_every_job_and_callback() {
491        let batch = Batch::new("pings")
492            .push(Ping)
493            .then(Ping)
494            .on_queue("media")
495            .push(Ping)
496            .finally(Ping);
497        assert_eq!(batch.len(), 2);
498        assert!(batch.jobs.iter().all(|job| job.options.queue == "media"));
499        let callbacks = [&batch.callbacks.then, &batch.callbacks.finally];
500        assert!(
501            callbacks
502                .iter()
503                .all(|job| job.as_ref().is_some_and(|job| job.options.queue == "media"))
504        );
505        assert_eq!(
506            Batch::new("plain").push(Ping).jobs[0].options.queue,
507            "default"
508        );
509    }
510}