Skip to main content

azums_poem/
lib.rs

1//! # Azums Poem
2//!
3//! Native Poem extractor (`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 poem::{FromRequest, Request, RequestBody};
10use serde_json::Value;
11use std::sync::Arc;
12use tokio::task::JoinHandle;
13use uuid::Uuid;
14
15/// Poem request extractor for enqueueing background jobs from HTTP handlers.
16///
17/// # Examples
18///
19/// ```rust,no_run
20/// use poem::{handler, web::Json, Route, Server};
21/// use azums_poem::{BackgroundJobs, JobQueue};
22/// use serde_json::json;
23///
24/// #[handler]
25/// async fn create_order(queue: JobQueue) -> Json<serde_json::Value> {
26///     let job_id = queue
27///         .enqueue_now("default", "process_order", json!({"item": "laptop"}))
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
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/// Central background job service attaching runtime workers and storage backends to Poem state.
138#[derive(Clone)]
139pub struct BackgroundJobs {
140    backend: Arc<dyn StorageBackend>,
141    flow: Arc<QuickstartFlow>,
142}
143
144impl BackgroundJobs {
145    /// Connects to database URL (PostgreSQL, SQLite, or In-Memory) and initializes `BackgroundJobs`.
146    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    /// Creates `BackgroundJobs` from a pre-configured [`QuickstartFlow`].
156    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    /// Creates `BackgroundJobs` from a custom [`StorageBackend`].
165    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    /// Returns reference to the underlying [`StorageBackend`].
172    pub fn backend(&self) -> Arc<dyn StorageBackend> {
173        self.backend.clone()
174    }
175
176    /// Returns a [`JobQueue`] extractor instance.
177    pub fn queue(&self) -> JobQueue {
178        JobQueue(self.backend.clone())
179    }
180
181    /// Registers an async handler closure for `job_type`.
182    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    /// Registers a trait-based [`JobProcessor`](azums_core::JobProcessor) for `job_type`.
191    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    /// Spawns the background worker polling loop as an asynchronous Tokio task.
199    pub fn spawn_worker(&self) -> JoinHandle<anyhow::Result<()>> {
200        let flow = self.flow.clone();
201        tokio::spawn(async move { flow.run().await })
202    }
203}