use chrono::{DateTime, Utc};
use navree_contracts::{Job, JobEnvelope};
use navree_db::Uow;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::record::from_millis;
use crate::{Queue, QueueError};
#[derive(Clone, Debug)]
pub struct Batch {
pub(crate) name: String,
pub(crate) jobs: Vec<JobEnvelope>,
pub(crate) callbacks: Callbacks,
pub(crate) allow_failures: bool,
pub(crate) operation_id: Option<Uuid>,
pub(crate) error: Option<String>,
pub(crate) queue: Option<String>,
}
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub(crate) struct Callbacks {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) then: Option<JobEnvelope>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) catch: Option<JobEnvelope>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub(crate) finally: Option<JobEnvelope>,
}
impl Batch {
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
jobs: Vec::new(),
callbacks: Callbacks::default(),
allow_failures: false,
operation_id: None,
error: None,
queue: None,
}
}
pub fn on_queue(mut self, queue: impl Into<String>) -> Self {
let queue = queue.into();
let callbacks = [
&mut self.callbacks.then,
&mut self.callbacks.catch,
&mut self.callbacks.finally,
];
for envelope in self.jobs.iter_mut().chain(callbacks.into_iter().flatten()) {
envelope.options.queue = queue.clone();
}
self.queue = Some(queue);
self
}
#[allow(clippy::should_implement_trait)]
pub fn add<J: Job>(mut self, jobs: impl IntoIterator<Item = J>) -> Self {
for job in jobs {
if let Some(envelope) = self.envelope(&job) {
self.jobs.push(envelope);
}
}
self
}
pub fn push<J: Job>(self, job: J) -> Self {
self.add([job])
}
pub fn then<J: Job>(mut self, job: J) -> Self {
self.callbacks.then = self.envelope(&job);
self
}
pub fn catch<J: Job>(mut self, job: J) -> Self {
self.callbacks.catch = self.envelope(&job);
self
}
pub fn finally<J: Job>(mut self, job: J) -> Self {
self.callbacks.finally = self.envelope(&job);
self
}
pub fn allow_failures(mut self) -> Self {
self.allow_failures = true;
self
}
pub fn operation(mut self, id: Uuid) -> Self {
self.operation_id = Some(id);
self
}
pub fn len(&self) -> usize {
self.jobs.len()
}
pub fn is_empty(&self) -> bool {
self.jobs.is_empty()
}
pub fn name(&self) -> &str {
&self.name
}
pub async fn dispatch(self, queue: &Queue) -> Result<JobBatch, QueueError> {
queue.dispatch_batch(self).await
}
pub async fn dispatch_in(self, queue: &Queue, uow: &Uow) -> Result<JobBatch, QueueError> {
queue.dispatch_batch_in(uow, self).await
}
fn envelope<J: Job>(&mut self, job: &J) -> Option<JobEnvelope> {
match serde_json::to_value(job) {
Ok(payload) => {
let mut options = J::options();
if let Some(queue) = &self.queue {
options.queue = queue.clone();
}
Some(JobEnvelope {
job_type: J::NAME.to_owned(),
payload,
options,
delay_secs: None,
unique_key: None,
})
}
Err(error) => {
self.error
.get_or_insert_with(|| format!("job `{}`: {error}", J::NAME));
None
}
}
}
pub(crate) fn check(&self) -> Result<(), QueueError> {
match &self.error {
Some(error) => Err(QueueError::Payload(serde::de::Error::custom(error))),
None => Ok(()),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct JobBatch {
pub id: String,
pub name: String,
pub total_jobs: u64,
pub pending_jobs: u64,
pub failed_jobs: u64,
pub failed_job_ids: Vec<String>,
pub allow_failures: bool,
pub operation_id: Option<Uuid>,
pub created_at: DateTime<Utc>,
pub cancelled_at: Option<DateTime<Utc>>,
pub finished_at: Option<DateTime<Utc>>,
}
impl JobBatch {
pub fn processed_jobs(&self) -> u64 {
self.total_jobs.saturating_sub(self.pending_jobs)
}
pub fn progress(&self) -> u8 {
if self.total_jobs == 0 {
return 100;
}
let percent = u128::from(self.processed_jobs()) * 100 / u128::from(self.total_jobs);
u8::try_from(percent).unwrap_or(100)
}
pub fn finished(&self) -> bool {
self.finished_at.is_some()
}
pub fn cancelled(&self) -> bool {
self.cancelled_at.is_some()
}
pub fn has_failures(&self) -> bool {
self.failed_jobs > 0
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Finish {
Succeeded,
Skipped,
Failed,
}
#[derive(Clone, Debug)]
pub(crate) struct BatchRow {
pub(crate) id: String,
pub(crate) name: String,
pub(crate) total_jobs: u64,
pub(crate) pending_jobs: u64,
pub(crate) failed_jobs: u64,
pub(crate) failed_job_ids: Vec<String>,
pub(crate) callbacks: Callbacks,
pub(crate) callbacks_pending: u64,
pub(crate) callbacks_failed: u64,
pub(crate) allow_failures: bool,
pub(crate) operation_id: Option<String>,
pub(crate) created_at: i64,
pub(crate) cancelled_at: Option<i64>,
pub(crate) finished_at: Option<i64>,
}
#[derive(Clone, Debug)]
pub(crate) enum Finished {
Lost,
Done(Option<Box<BatchStep>>),
}
#[derive(Clone, Debug)]
pub(crate) struct BatchStep {
pub(crate) batch: BatchRow,
pub(crate) settled_now: bool,
}
impl BatchRow {
pub(crate) fn new(id: String, batch: &Batch, now: i64) -> Self {
let total = batch.jobs.len() as u64;
Self {
id,
name: batch.name.clone(),
total_jobs: total,
pending_jobs: total,
failed_jobs: 0,
failed_job_ids: Vec::new(),
callbacks: batch.callbacks.clone(),
callbacks_pending: 0,
callbacks_failed: 0,
allow_failures: batch.allow_failures,
operation_id: batch.operation_id.map(|id| id.to_string()),
created_at: now,
cancelled_at: None,
finished_at: None,
}
}
pub(crate) fn start_empty(&mut self, now: i64) -> Vec<JobEnvelope> {
if self.total_jobs == 0 {
self.finish(now)
} else {
Vec::new()
}
}
pub(crate) fn job_finished(
&mut self,
job_id: &str,
finish: Finish,
now: i64,
) -> Vec<JobEnvelope> {
if self.pending_jobs == 0 {
return Vec::new();
}
self.pending_jobs -= 1;
let mut due = Vec::new();
if finish == Finish::Failed {
self.failed_jobs += 1;
self.failed_job_ids.push(job_id.to_owned());
if self.failed_jobs == 1
&& let Some(catch) = &self.callbacks.catch
{
due.push(catch.clone());
}
if !self.allow_failures && self.cancelled_at.is_none() {
self.cancelled_at = Some(now);
}
}
self.callbacks_pending += due.len() as u64;
if self.pending_jobs == 0 {
due.extend(self.finish(now));
}
due
}
pub(crate) fn callback_finished(&mut self, failed: bool) {
self.callbacks_pending = self.callbacks_pending.saturating_sub(1);
if failed {
self.callbacks_failed += 1;
}
}
pub(crate) fn cancel(&mut self, now: i64) -> bool {
if self.cancelled_at.is_some() || self.finished_at.is_some() {
return false;
}
self.cancelled_at = Some(now);
true
}
pub(crate) fn settled(&self) -> bool {
self.finished_at.is_some() && self.callbacks_pending == 0
}
fn finish(&mut self, now: i64) -> Vec<JobEnvelope> {
let mut due = Vec::new();
if self.finished_at.is_none() {
self.finished_at = Some(now);
if self.failed_jobs == 0
&& self.cancelled_at.is_none()
&& let Some(then) = &self.callbacks.then
{
due.push(then.clone());
}
if let Some(finally) = &self.callbacks.finally {
due.push(finally.clone());
}
}
self.callbacks_pending += due.len() as u64;
due
}
pub(crate) fn to_batch(&self) -> JobBatch {
JobBatch {
id: self.id.clone(),
name: self.name.clone(),
total_jobs: self.total_jobs,
pending_jobs: self.pending_jobs,
failed_jobs: self.failed_jobs,
failed_job_ids: self.failed_job_ids.clone(),
allow_failures: self.allow_failures,
operation_id: self
.operation_id
.as_deref()
.and_then(|id| Uuid::parse_str(id).ok()),
created_at: from_millis(self.created_at),
cancelled_at: self.cancelled_at.map(from_millis),
finished_at: self.finished_at.map(from_millis),
}
}
}
#[cfg(test)]
mod tests {
use navree_contracts::{BoxError, JobContext};
use super::*;
#[derive(Serialize, Deserialize)]
struct Ping;
impl Job for Ping {
const NAME: &'static str = "test.ping";
async fn handle(self, _ctx: JobContext) -> Result<(), BoxError> {
Ok(())
}
}
#[test]
fn on_queue_moves_every_job_and_callback() {
let batch = Batch::new("pings")
.push(Ping)
.then(Ping)
.on_queue("media")
.push(Ping)
.finally(Ping);
assert_eq!(batch.len(), 2);
assert!(batch.jobs.iter().all(|job| job.options.queue == "media"));
let callbacks = [&batch.callbacks.then, &batch.callbacks.finally];
assert!(
callbacks
.iter()
.all(|job| job.as_ref().is_some_and(|job| job.options.queue == "media"))
);
assert_eq!(
Batch::new("plain").push(Ping).jobs[0].options.queue,
"default"
);
}
}