use std::sync::Arc;
use std::any::Any;
use std::time::Duration;
use chrono::{DateTime, Utc};
use crate::{
backend::Backend,
error::Result,
job::{Job, JobId, JobRecord, Perform, QueueStats},
};
#[derive(Clone)]
pub struct Queue<B: Backend> {
pub(crate) backend: Arc<B>,
pub(crate) state: Arc<dyn Any + Send + Sync>,
}
impl<B: Backend> Queue<B> {
pub fn new(backend: B) -> Self {
Self {
backend: Arc::new(backend),
state: Arc::new(()),
}
}
pub fn with_state<S: Send + Sync + 'static>(mut self, state: S) -> Self {
self.state = Arc::new(state);
self
}
pub async fn enqueue<J: Perform>(&self, job: J) -> Result<JobId> {
let record = self.build_record(&job, Utc::now())?;
self.backend.enqueue(record).await
}
pub async fn enqueue_in<J: Perform>(&self, job: J, delay: Duration) -> Result<JobId> {
let at = Utc::now() + chrono::Duration::from_std(delay).unwrap_or_default();
let record = self.build_record(&job, at)?;
self.backend.enqueue(record).await
}
pub async fn enqueue_at<J: Perform>(&self, job: J, at: DateTime<Utc>) -> Result<JobId> {
let record = self.build_record(&job, at)?;
self.backend.enqueue(record).await
}
pub async fn enqueue_record(&self, record: crate::job::JobRecord) -> Result<JobId> {
self.backend.enqueue(record).await
}
pub async fn stats(&self, queue: &str) -> Result<QueueStats> {
self.backend.stats(queue).await
}
pub async fn dead_jobs(
&self,
queue: &str,
limit: i64,
offset: i64,
) -> Result<Vec<JobRecord>> {
self.backend.dead_jobs(queue, limit, offset).await
}
pub async fn retry_dead(&self, id: JobId) -> Result<()> {
self.backend.retry_dead(id).await
}
pub async fn retry_all_dead(&self, queue: &str) -> Result<u64> {
self.backend.retry_all_dead(queue).await
}
fn build_record<J: Job>(&self, job: &J, scheduled_at: DateTime<Utc>) -> Result<JobRecord> {
let payload = serde_json::to_vec(job)?;
Ok(JobRecord::new(J::KIND, J::QUEUE, payload, J::MAX_RETRIES)
.with_scheduled_at(scheduled_at))
}
}