1use azums::{quickstart, QuickstartFlow};
6pub use azums_core::{Job, JobListItem, JobStatus};
7use azums_core::{NewJob, StorageBackend};
8use chrono::{DateTime, Utc};
9use rocket::request::{FromRequest, Outcome, Request};
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
118#[rocket::async_trait]
119impl<'r> FromRequest<'r> for JobQueue {
120 type Error = ();
121
122 async fn from_request(req: &'r Request<'_>) -> Outcome<Self, Self::Error> {
123 if let Some(jobs) = req.rocket().state::<BackgroundJobs>() {
124 Outcome::Success(jobs.queue())
125 } else if let Some(queue) = req.rocket().state::<JobQueue>() {
126 Outcome::Success(queue.clone())
127 } else {
128 Outcome::Error((rocket::http::Status::InternalServerError, ()))
129 }
130 }
131}
132
133#[derive(Clone)]
135pub struct BackgroundJobs {
136 backend: Arc<dyn StorageBackend>,
137 flow: Arc<QuickstartFlow>,
138}
139
140impl BackgroundJobs {
141 pub async fn from_url(url: impl AsRef<str>) -> anyhow::Result<Self> {
143 let flow = quickstart(url).await?;
144 let flow = Arc::new(flow);
145 Ok(Self {
146 backend: flow.backend().clone(),
147 flow,
148 })
149 }
150
151 pub fn from_flow(flow: QuickstartFlow) -> Self {
153 let flow = Arc::new(flow);
154 Self {
155 backend: flow.backend().clone(),
156 flow,
157 }
158 }
159
160 pub fn from_backend(backend: Arc<dyn StorageBackend>) -> Self {
162 let flow = QuickstartFlow::new(backend.clone());
163 let flow = Arc::new(flow);
164 Self { backend, flow }
165 }
166
167 pub fn backend(&self) -> Arc<dyn StorageBackend> {
169 self.backend.clone()
170 }
171
172 pub fn queue(&self) -> JobQueue {
174 JobQueue(self.backend.clone())
175 }
176
177 pub async fn register_handler<F, Fut>(&self, job_type: impl Into<String>, handler: F)
179 where
180 F: Fn(azums_core::Job) -> Fut + Send + Sync + 'static,
181 Fut: std::future::Future<Output = anyhow::Result<()>> + Send + 'static,
182 {
183 self.flow.register_handler(job_type, handler).await;
184 }
185
186 pub async fn register_processor<P>(&self, job_type: impl Into<String>, processor: P)
188 where
189 P: azums_core::JobProcessor + 'static,
190 {
191 self.flow.register_processor(job_type, processor).await;
192 }
193
194 pub fn spawn_worker(&self) -> JoinHandle<anyhow::Result<()>> {
196 let flow = self.flow.clone();
197 tokio::spawn(async move { flow.run().await })
198 }
199}