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