1use 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#[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 pub(crate) error: Option<String>,
65 pub(crate) queue: Option<String>,
67}
68
69#[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 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 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 #[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 pub fn push<J: Job>(self, job: J) -> Self {
127 self.add([job])
128 }
129
130 pub fn then<J: Job>(mut self, job: J) -> Self {
133 self.callbacks.then = self.envelope(&job);
134 self
135 }
136
137 pub fn catch<J: Job>(mut self, job: J) -> Self {
139 self.callbacks.catch = self.envelope(&job);
140 self
141 }
142
143 pub fn finally<J: Job>(mut self, job: J) -> Self {
145 self.callbacks.finally = self.envelope(&job);
146 self
147 }
148
149 pub fn allow_failures(mut self) -> Self {
153 self.allow_failures = true;
154 self
155 }
156
157 pub fn operation(mut self, id: Uuid) -> Self {
164 self.operation_id = Some(id);
165 self
166 }
167
168 pub fn len(&self) -> usize {
170 self.jobs.len()
171 }
172
173 pub fn is_empty(&self) -> bool {
176 self.jobs.is_empty()
177 }
178
179 pub fn name(&self) -> &str {
181 &self.name
182 }
183
184 pub async fn dispatch(self, queue: &Queue) -> Result<JobBatch, QueueError> {
188 queue.dispatch_batch(self).await
189 }
190
191 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 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#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
233pub struct JobBatch {
234 pub id: String,
236 pub name: String,
238 pub total_jobs: u64,
240 pub pending_jobs: u64,
242 pub failed_jobs: u64,
244 pub failed_job_ids: Vec<String>,
246 pub allow_failures: bool,
248 pub operation_id: Option<Uuid>,
250 pub created_at: DateTime<Utc>,
252 pub cancelled_at: Option<DateTime<Utc>>,
254 pub finished_at: Option<DateTime<Utc>>,
256}
257
258impl JobBatch {
259 pub fn processed_jobs(&self) -> u64 {
261 self.total_jobs.saturating_sub(self.pending_jobs)
262 }
263
264 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 pub fn finished(&self) -> bool {
276 self.finished_at.is_some()
277 }
278
279 pub fn cancelled(&self) -> bool {
281 self.cancelled_at.is_some()
282 }
283
284 pub fn has_failures(&self) -> bool {
286 self.failed_jobs > 0
287 }
288}
289
290#[derive(Clone, Copy, Debug, PartialEq, Eq)]
292pub(crate) enum Finish {
293 Succeeded,
295 Skipped,
298 Failed,
300}
301
302#[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 pub(crate) callbacks_pending: u64,
314 pub(crate) callbacks_failed: u64,
316 pub(crate) allow_failures: bool,
317 pub(crate) operation_id: Option<String>,
318 pub(crate) created_at: i64,
320 pub(crate) cancelled_at: Option<i64>,
321 pub(crate) finished_at: Option<i64>,
322}
323
324#[derive(Clone, Debug)]
326pub(crate) enum Finished {
327 Lost,
329 Done(Option<Box<BatchStep>>),
332}
333
334#[derive(Clone, Debug)]
336pub(crate) struct BatchStep {
337 pub(crate) batch: BatchRow,
339 pub(crate) settled_now: bool,
342}
343
344impl BatchRow {
345 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 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 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 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 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 pub(crate) fn settled(&self) -> bool {
428 self.finished_at.is_some() && self.callbacks_pending == 0
429 }
430
431 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 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}