Skip to main content

asyncq/
context.rs

1use std::sync::Arc;
2use std::any::Any;
3use chrono::{DateTime, Utc};
4use uuid::Uuid;
5
6/// Injected into every job execution. Provides job metadata and shared app state.
7///
8/// # Accessing shared state
9///
10/// State is injected via [`Queue::with_state`](crate::Queue::with_state) and
11/// accessed with `ctx.state::<T>()` — the same mental model as axum's `State<T>`:
12///
13/// ```rust,ignore
14/// // Set up — pass your app state once when building the queue
15/// let queue = Queue::new(backend).with_state(Arc::new(db_pool));
16///
17/// // Inside a job — retrieve it by type
18/// impl Perform for MyJob {
19///     async fn perform(self, ctx: JobContext) -> JobResult {
20///         let db = ctx.state::<Arc<PgPool>>().expect("db not in state");
21///         // use db ...
22///         Ok(())
23///     }
24/// }
25/// ```
26#[derive(Clone)]
27pub struct JobContext {
28    /// Unique ID of this job instance.
29    pub job_id: Uuid,
30    /// Name of the queue this job was claimed from.
31    pub queue: String,
32    /// Delivery attempt number (1 = first attempt).
33    pub attempt: u32,
34    /// When this job was originally enqueued.
35    pub enqueued_at: DateTime<Utc>,
36    /// Shared application state set via `Queue::with_state`.
37    state: Arc<dyn Any + Send + Sync>,
38}
39
40impl JobContext {
41    pub(crate) fn new(
42        job_id: Uuid,
43        queue: String,
44        attempt: u32,
45        enqueued_at: DateTime<Utc>,
46        state: Arc<dyn Any + Send + Sync>,
47    ) -> Self {
48        Self { job_id, queue, attempt, enqueued_at, state }
49    }
50
51    /// Retrieve shared state by type.
52    ///
53    /// Returns `None` if no state of type `T` was set on the queue.
54    ///
55    /// ```rust,ignore
56    /// let pool = ctx.state::<Arc<PgPool>>().expect("PgPool not in state");
57    /// ```
58    pub fn state<T: Send + Sync + 'static>(&self) -> Option<&T> {
59        self.state.downcast_ref::<T>()
60    }
61
62    /// Whether this is the first attempt (attempt == 1).
63    pub fn is_first_attempt(&self) -> bool {
64        self.attempt == 1
65    }
66
67    /// Whether this is a retry (attempt > 1).
68    pub fn is_retry(&self) -> bool {
69        self.attempt > 1
70    }
71}