use chrono::{DateTime, Utc};
use serde::{de::DeserializeOwned, Serialize};
use uuid::Uuid;
use crate::{context::JobContext, error::JobResult};
pub type JobId = Uuid;
#[derive(Debug, Clone)]
pub struct JobRecord {
pub id: JobId,
pub kind: String,
pub queue: String,
pub payload: Vec<u8>,
pub attempt: u32,
pub max_attempts: u32,
pub scheduled_at: DateTime<Utc>,
pub created_at: DateTime<Utc>,
pub last_error: Option<String>,
}
impl JobRecord {
pub fn new(kind: &str, queue: &str, payload: Vec<u8>, max_attempts: u32) -> Self {
Self {
id: Uuid::new_v4(),
kind: kind.to_owned(),
queue: queue.to_owned(),
payload,
attempt: 0,
max_attempts,
scheduled_at: Utc::now(),
created_at: Utc::now(),
last_error: None,
}
}
pub fn with_scheduled_at(mut self, at: DateTime<Utc>) -> Self {
self.scheduled_at = at;
self
}
}
#[derive(Debug, Clone, Default)]
pub struct QueueStats {
pub queue: String,
pub pending: u64,
pub running: u64,
pub completed: u64,
pub failed: u64,
pub dead: u64,
}
pub trait Job: Serialize + DeserializeOwned + Send + Sync + 'static {
const KIND: &'static str;
const QUEUE: &'static str;
const MAX_RETRIES: u32;
const TIMEOUT_SECS: Option<u64>;
fn kind(&self) -> &'static str {
Self::KIND
}
fn queue(&self) -> &'static str {
Self::QUEUE
}
fn max_retries(&self) -> u32 {
Self::MAX_RETRIES
}
}
pub trait Perform: Job {
fn perform(self, ctx: JobContext) -> impl std::future::Future<Output = JobResult> + Send;
}
pub(crate) type BoxedHandler = Box<
dyn Fn(JobRecord, JobContext) -> std::pin::Pin<Box<dyn std::future::Future<Output = JobResult> + Send>>
+ Send
+ Sync,
>;
pub(crate) fn make_handler<J: Perform>() -> BoxedHandler {
Box::new(|record: JobRecord, ctx: JobContext| {
Box::pin(async move {
let job: J = serde_json::from_slice(&record.payload)
.map_err(|e| crate::error::JobError::discard(format!("deserialization failed: {e}")))?;
job.perform(ctx).await
})
})
}