1use actix_web::{dev::Payload, web, FromRequest, HttpRequest};
6use azums::{quickstart, QuickstartFlow};
7pub use azums_core::{Job, JobListItem, JobStatus};
8use azums_core::{NewJob, StorageBackend};
9use chrono::{DateTime, Utc};
10use futures_util::future::{ready, Ready};
11use serde_json::Value;
12use std::sync::Arc;
13use tokio::task::JoinHandle;
14use uuid::Uuid;
15
16#[derive(Clone)]
35pub struct JobQueue(pub Arc<dyn StorageBackend>);
36
37impl JobQueue {
38 pub fn new(backend: Arc<dyn StorageBackend>) -> Self {
40 Self(backend)
41 }
42
43 pub fn backend(&self) -> &Arc<dyn StorageBackend> {
45 &self.0
46 }
47
48 pub async fn enqueue(&self, job: impl Into<NewJob>) -> anyhow::Result<Uuid> {
50 let new_job: NewJob = job.into();
51 self.0.enqueue(new_job).await
52 }
53
54 pub async fn enqueue_now(
56 &self,
57 queue: &str,
58 job_type: &str,
59 payload_json: Value,
60 ) -> anyhow::Result<Uuid> {
61 self.0
62 .enqueue(NewJob {
63 queue: queue.to_string(),
64 job_type: job_type.to_string(),
65 payload_json,
66 idempotency_key: None,
67 run_at: Utc::now(),
68 deadline_at: None,
69 timeout_seconds: None,
70 recurring_interval_seconds: None,
71 priority: 0,
72 max_attempts: 25,
73 })
74 .await
75 }
76
77 pub async fn enqueue_in(
79 &self,
80 queue: &str,
81 job_type: &str,
82 payload_json: Value,
83 delay_secs: i64,
84 ) -> anyhow::Result<Uuid> {
85 self.enqueue_at(
86 queue,
87 job_type,
88 payload_json,
89 Utc::now() + chrono::Duration::seconds(delay_secs),
90 )
91 .await
92 }
93
94 pub async fn enqueue_at(
96 &self,
97 queue: &str,
98 job_type: &str,
99 payload_json: Value,
100 run_at: DateTime<Utc>,
101 ) -> anyhow::Result<Uuid> {
102 self.0
103 .enqueue(NewJob {
104 queue: queue.to_string(),
105 job_type: job_type.to_string(),
106 payload_json,
107 idempotency_key: None,
108 run_at,
109 deadline_at: None,
110 timeout_seconds: None,
111 recurring_interval_seconds: None,
112 priority: 0,
113 max_attempts: 25,
114 })
115 .await
116 }
117}
118
119impl FromRequest for JobQueue {
120 type Error = actix_web::Error;
121 type Future = Ready<Result<Self, Self::Error>>;
122
123 fn from_request(req: &HttpRequest, _payload: &mut Payload) -> Self::Future {
124 if let Some(jobs) = req.app_data::<web::Data<BackgroundJobs>>() {
125 ready(Ok(jobs.queue()))
126 } else if let Some(queue) = req.app_data::<web::Data<JobQueue>>() {
127 ready(Ok(queue.get_ref().clone()))
128 } else {
129 ready(Err(actix_web::error::ErrorInternalServerError(
130 "BackgroundJobs or JobQueue app_data missing in Actix Web request",
131 )))
132 }
133 }
134}
135
136#[derive(Clone)]
138pub struct BackgroundJobs {
139 backend: Arc<dyn StorageBackend>,
140 flow: Arc<QuickstartFlow>,
141}
142
143impl BackgroundJobs {
144 pub async fn from_url(url: impl AsRef<str>) -> anyhow::Result<Self> {
146 let flow = quickstart(url).await?;
147 let flow = Arc::new(flow);
148 Ok(Self {
149 backend: flow.backend().clone(),
150 flow,
151 })
152 }
153
154 pub fn from_flow(flow: QuickstartFlow) -> Self {
156 let flow = Arc::new(flow);
157 Self {
158 backend: flow.backend().clone(),
159 flow,
160 }
161 }
162
163 pub fn from_backend(backend: Arc<dyn StorageBackend>) -> Self {
165 let flow = QuickstartFlow::new(backend.clone());
166 let flow = Arc::new(flow);
167 Self { backend, flow }
168 }
169
170 pub fn backend(&self) -> Arc<dyn StorageBackend> {
172 self.backend.clone()
173 }
174
175 pub fn queue(&self) -> JobQueue {
177 JobQueue(self.backend.clone())
178 }
179
180 pub async fn register_handler<F, Fut>(&self, job_type: impl Into<String>, handler: F)
182 where
183 F: Fn(azums_core::Job) -> Fut + Send + Sync + 'static,
184 Fut: std::future::Future<Output = anyhow::Result<()>> + Send + 'static,
185 {
186 self.flow.register_handler(job_type, handler).await;
187 }
188
189 pub async fn register_processor<P>(&self, job_type: impl Into<String>, processor: P)
191 where
192 P: azums_core::JobProcessor + 'static,
193 {
194 self.flow.register_processor(job_type, processor).await;
195 }
196
197 pub fn spawn_worker(&self) -> JoinHandle<anyhow::Result<()>> {
199 let flow = self.flow.clone();
200 tokio::spawn(async move { flow.run().await })
201 }
202}