use std::time::Duration;
use async_trait::async_trait;
use uuid::Uuid;
use crate::{error::JobError, job::Job};
#[derive(Debug, Clone)]
pub struct JobContext {
pub job_id: Uuid,
pub job_type: &'static str,
pub queue: &'static str,
pub attempt: u32,
pub max_attempts: u32,
pub deferrals: u32,
pub priority: u8,
pub age: Duration,
}
impl JobContext {
pub fn is_last_attempt(&self) -> bool {
self.attempt >= self.max_attempts
}
}
#[async_trait]
pub trait JobHandler: Send + Sync + 'static {
type Job: Job;
async fn handle(&self, job: Self::Job, ctx: JobContext) -> Result<(), JobError>;
}
pub struct FnHandler<J, F> {
f: F,
_job: std::marker::PhantomData<fn(J)>,
}
impl<J, F> FnHandler<J, F> {
pub fn new(f: F) -> Self {
Self {
f,
_job: std::marker::PhantomData,
}
}
}
#[async_trait]
impl<J, F, Fut> JobHandler for FnHandler<J, F>
where
J: Job,
F: Fn(J, JobContext) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = Result<(), JobError>> + Send + 'static,
{
type Job = J;
async fn handle(&self, job: J, ctx: JobContext) -> Result<(), JobError> {
(self.f)(job, ctx).await
}
}