Skip to main content

awa_worker/
context.rs

1use awa_model::JobRow;
2use std::any::Any;
3use std::collections::HashMap;
4use std::sync::atomic::{AtomicBool, Ordering};
5use std::sync::Arc;
6
7/// Context passed to worker handlers during job execution.
8///
9/// Provides access to the job metadata and shared state (e.g., service dependencies).
10pub struct JobContext {
11    /// The raw job row from the database.
12    pub job: JobRow,
13    /// Cancellation flag — set to true when shutdown or deadline is signalled.
14    cancelled: Arc<AtomicBool>,
15    /// Shared state map for dependency injection.
16    state: Arc<HashMap<std::any::TypeId, Box<dyn Any + Send + Sync>>>,
17}
18
19impl JobContext {
20    pub fn new(
21        job: JobRow,
22        cancelled: Arc<AtomicBool>,
23        state: Arc<HashMap<std::any::TypeId, Box<dyn Any + Send + Sync>>>,
24    ) -> Self {
25        Self {
26            job,
27            cancelled,
28            state,
29        }
30    }
31
32    /// Check if this job's execution has been cancelled (shutdown or deadline).
33    pub fn is_cancelled(&self) -> bool {
34        self.cancelled.load(Ordering::SeqCst)
35    }
36
37    /// Clone the shared cancellation flag for language bridges.
38    pub fn cancellation_flag(&self) -> Arc<AtomicBool> {
39        self.cancelled.clone()
40    }
41
42    /// Signal cancellation for this job.
43    pub fn cancel(&self) {
44        self.cancelled.store(true, Ordering::SeqCst);
45    }
46
47    /// Extract a shared state value by type.
48    ///
49    /// State values are registered via `Client::builder().state(value)`.
50    pub fn extract<T: Any + Send + Sync + Clone>(&self) -> Option<T> {
51        self.state
52            .get(&std::any::TypeId::of::<T>())
53            .and_then(|v| v.downcast_ref::<T>())
54            .cloned()
55    }
56}