Skip to main content

azums_actix/
lib.rs

1//! # Azums Actix
2//!
3//! Native Actix Web extractor (`JobQueue`) and state service integration (`BackgroundJobs`) for `azums`.
4
5use 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/// Actix Web request extractor for enqueueing background jobs from HTTP handlers.
17///
18/// # Examples
19///
20/// ```rust,no_run
21/// use actix_web::{post, web, App, HttpResponse, HttpServer, Responder};
22/// use azums_actix::{BackgroundJobs, JobQueue};
23/// use serde_json::json;
24///
25/// #[post("/orders")]
26/// async fn create_order(queue: JobQueue) -> impl Responder {
27///     let job_id = queue
28///         .enqueue_now("default", "process_order", json!({"item": "book"}))
29///         .await
30///         .unwrap();
31///     HttpResponse::Ok().json(json!({ "status": "queued", "id": job_id }))
32/// }
33/// ```
34#[derive(Clone)]
35pub struct JobQueue(pub Arc<dyn StorageBackend>);
36
37impl JobQueue {
38    /// Creates a `JobQueue` wrapping a [`StorageBackend`].
39    pub fn new(backend: Arc<dyn StorageBackend>) -> Self {
40        Self(backend)
41    }
42
43    /// Returns reference to the underlying [`StorageBackend`].
44    pub fn backend(&self) -> &Arc<dyn StorageBackend> {
45        &self.0
46    }
47
48    /// Enqueues a [`NewJob`] or [`Job`] into the queue.
49    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    /// Enqueues a job immediately with default queue `"default"`, priority `0`, and `25` max attempts.
55    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    /// Enqueues a job delayed by `delay_secs` seconds.
78    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    /// Enqueues a job scheduled for a specific UTC timestamp (`run_at`).
95    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/// Central background job service attaching runtime workers and storage backends to Actix Web app data.
137#[derive(Clone)]
138pub struct BackgroundJobs {
139    backend: Arc<dyn StorageBackend>,
140    flow: Arc<QuickstartFlow>,
141}
142
143impl BackgroundJobs {
144    /// Connects to database URL (PostgreSQL, SQLite, or In-Memory) and initializes `BackgroundJobs`.
145    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    /// Creates `BackgroundJobs` from a pre-configured [`QuickstartFlow`].
155    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    /// Creates `BackgroundJobs` from a custom [`StorageBackend`].
164    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    /// Returns reference to the underlying [`StorageBackend`].
171    pub fn backend(&self) -> Arc<dyn StorageBackend> {
172        self.backend.clone()
173    }
174
175    /// Returns a [`JobQueue`] extractor instance.
176    pub fn queue(&self) -> JobQueue {
177        JobQueue(self.backend.clone())
178    }
179
180    /// Registers an async handler closure for `job_type`.
181    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    /// Registers a trait-based [`JobProcessor`](azums_core::JobProcessor) for `job_type`.
190    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    /// Spawns the background worker polling loop as an asynchronous Tokio task.
198    pub fn spawn_worker(&self) -> JoinHandle<anyhow::Result<()>> {
199        let flow = self.flow.clone();
200        tokio::spawn(async move { flow.run().await })
201    }
202}