use azums::{quickstart, QuickstartFlow};
pub use azums_core::{Job, JobListItem, JobStatus};
use azums_core::{NewJob, StorageBackend};
use chrono::{DateTime, Utc};
use rocket::request::{FromRequest, Outcome, Request};
use serde_json::Value;
use std::sync::Arc;
use tokio::task::JoinHandle;
use uuid::Uuid;
#[derive(Clone)]
pub struct JobQueue(pub Arc<dyn StorageBackend>);
impl JobQueue {
pub fn new(backend: Arc<dyn StorageBackend>) -> Self {
Self(backend)
}
pub fn backend(&self) -> &Arc<dyn StorageBackend> {
&self.0
}
pub async fn enqueue(&self, job: impl Into<NewJob>) -> anyhow::Result<Uuid> {
let new_job: NewJob = job.into();
self.0.enqueue(new_job).await
}
pub async fn enqueue_now(
&self,
queue: &str,
job_type: &str,
payload_json: Value,
) -> anyhow::Result<Uuid> {
self.0
.enqueue(NewJob {
queue: queue.to_string(),
job_type: job_type.to_string(),
payload_json,
idempotency_key: None,
run_at: Utc::now(),
deadline_at: None,
timeout_seconds: None,
recurring_interval_seconds: None,
priority: 0,
max_attempts: 25,
})
.await
}
pub async fn enqueue_in(
&self,
queue: &str,
job_type: &str,
payload_json: Value,
delay_secs: i64,
) -> anyhow::Result<Uuid> {
self.enqueue_at(
queue,
job_type,
payload_json,
Utc::now() + chrono::Duration::seconds(delay_secs),
)
.await
}
pub async fn enqueue_at(
&self,
queue: &str,
job_type: &str,
payload_json: Value,
run_at: DateTime<Utc>,
) -> anyhow::Result<Uuid> {
self.0
.enqueue(NewJob {
queue: queue.to_string(),
job_type: job_type.to_string(),
payload_json,
idempotency_key: None,
run_at,
deadline_at: None,
timeout_seconds: None,
recurring_interval_seconds: None,
priority: 0,
max_attempts: 25,
})
.await
}
}
#[rocket::async_trait]
impl<'r> FromRequest<'r> for JobQueue {
type Error = ();
async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> {
if let Some(jobs) = req.rocket().state::<BackgroundJobs>() {
Outcome::Success(jobs.queue())
} else if let Some(queue) = req.rocket().state::<JobQueue>() {
Outcome::Success(queue.clone())
} else {
Outcome::Error((rocket::http::Status::InternalServerError, ()))
}
}
}
#[derive(Clone)]
pub struct BackgroundJobs {
backend: Arc<dyn StorageBackend>,
flow: Arc<QuickstartFlow>,
}
impl BackgroundJobs {
pub async fn from_url(url: impl AsRef<str>) -> anyhow::Result<Self> {
let flow = quickstart(url).await?;
let flow = Arc::new(flow);
Ok(Self {
backend: flow.backend().clone(),
flow,
})
}
pub fn from_flow(flow: QuickstartFlow) -> Self {
let flow = Arc::new(flow);
Self {
backend: flow.backend().clone(),
flow,
}
}
pub fn from_backend(backend: Arc<dyn StorageBackend>) -> Self {
let flow = QuickstartFlow::new(backend.clone());
let flow = Arc::new(flow);
Self { backend, flow }
}
pub fn backend(&self) -> Arc<dyn StorageBackend> {
self.backend.clone()
}
pub fn queue(&self) -> JobQueue {
JobQueue(self.backend.clone())
}
pub async fn register_handler<F, Fut>(&self, job_type: impl Into<String>, handler: F)
where
F: Fn(azums_core::Job) -> Fut + Send + Sync + 'static,
Fut: std::future::Future<Output = anyhow::Result<()>> + Send + 'static,
{
self.flow.register_handler(job_type, handler).await;
}
pub async fn register_processor<P>(&self, job_type: impl Into<String>, processor: P)
where
P: azums_core::JobProcessor + 'static,
{
self.flow.register_processor(job_type, processor).await;
}
pub fn spawn_worker(&self) -> JoinHandle<anyhow::Result<()>> {
let flow = self.flow.clone();
tokio::spawn(async move { flow.run().await })
}
}