Skip to main content

azums_rocket/
lib.rs

1//! # Azums Rocket
2//!
3//! Native Rocket request guard (`JobQueue`) and state service integration (`BackgroundJobs`) for `azums`.
4
5use 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/// Rocket request guard for enqueueing background jobs from HTTP handlers.
16///
17/// # Examples
18///
19/// ```rust,no_run
20/// use azums_rocket::{BackgroundJobs, JobQueue};
21/// use rocket::{post, routes, serde::json::Json};
22/// use serde_json::json;
23///
24/// #[post("/orders")]
25/// async fn create_order(queue: JobQueue) -> Json<serde_json::Value> {
26///     let job_id = queue
27///         .enqueue_now("default", "process_order", json!({"item": "phone"}))
28///         .await
29///         .unwrap();
30///     Json(json!({ "status": "queued", "id": job_id }))
31/// }
32/// ```
33#[derive(Clone)]
34pub struct JobQueue(pub Arc<dyn StorageBackend>);
35
36impl JobQueue {
37    /// Creates a `JobQueue` wrapping a [`StorageBackend`].
38    pub fn new(backend: Arc<dyn StorageBackend>) -> Self {
39        Self(backend)
40    }
41
42    /// Returns reference to the underlying [`StorageBackend`].
43    pub fn backend(&self) -> &Arc<dyn StorageBackend> {
44        &self.0
45    }
46
47    /// Enqueues a [`NewJob`] or [`Job`] into the queue.
48    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    /// Enqueues a job immediately with default queue `"default"`, priority `0`, and `25` max attempts.
54    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    /// Enqueues a job delayed by `delay_secs` seconds.
77    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    /// Enqueues a job scheduled for a specific UTC timestamp (`run_at`).
94    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/// Central background job service attaching runtime workers and storage backends to Rocket state.
134#[derive(Clone)]
135pub struct BackgroundJobs {
136    backend: Arc<dyn StorageBackend>,
137    flow: Arc<QuickstartFlow>,
138}
139
140impl BackgroundJobs {
141    /// Connects to database URL (PostgreSQL, SQLite, or In-Memory) and initializes `BackgroundJobs`.
142    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    /// Creates `BackgroundJobs` from a pre-configured [`QuickstartFlow`].
152    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    /// Creates `BackgroundJobs` from a custom [`StorageBackend`].
161    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    /// Returns reference to the underlying [`StorageBackend`].
168    pub fn backend(&self) -> Arc<dyn StorageBackend> {
169        self.backend.clone()
170    }
171
172    /// Returns a [`JobQueue`] extractor instance.
173    pub fn queue(&self) -> JobQueue {
174        JobQueue(self.backend.clone())
175    }
176
177    /// Registers an async handler closure for `job_type`.
178    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    /// Registers a trait-based [`JobProcessor`](azums_core::JobProcessor) for `job_type`.
187    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    /// Spawns the background worker polling loop as an asynchronous Tokio task.
195    pub fn spawn_worker(&self) -> JoinHandle<anyhow::Result<()>> {
196        let flow = self.flow.clone();
197        tokio::spawn(async move { flow.run().await })
198    }
199}