turnkeeper/job/
context.rs

1use super::{InstanceId, TKJobId};
2
3/// Contextual information available to a running job instance via task-locals.
4/// Accessible within a `BoxedExecFn` using `try_get_current_job_context()`
5/// or the `job_context!()` macro when the `job_context` feature is enabled.
6#[derive(Clone, Copy, Debug)]
7pub struct JobContext {
8  /// The unique lineage ID of the TurnKeeper job definition.
9  pub tk_job_id: TKJobId,
10  /// The unique ID of this specific execution instance.
11  pub instance_id: InstanceId,
12}
13
14tokio::task_local! {
15    /// Provides access to the current `JobContext` within a job's execution scope.
16    /// Set by the TurnKeeper worker if the `job_context` feature is enabled.
17    pub static CURRENT_JOB_CONTEXT: JobContext; // Make the static crate-public
18}
19
20/// Attempts to retrieve the current `JobContext` for the executing job.
21///
22/// Requires the `job_context` feature to be enabled.
23///
24/// Returns `Some(JobContext)` if the job is running within the context set by
25/// the TurnKeeper worker, `None` otherwise.
26pub fn try_get_current_job_context() -> Option<JobContext> {
27  CURRENT_JOB_CONTEXT.try_with(|ctx| *ctx).ok()
28}
29
30/// Retrieves the current `JobContext`, panicking if called outside a
31/// TurnKeeper-managed job task where the context has not been set.
32///
33/// Requires the `job_context` feature to be enabled.
34/// Use `try_get_current_job_context()` for safe, optional access.
35///
36/// # Panics
37/// Panics if the `CURRENT_JOB_CONTEXT` task local has not been set.
38#[macro_export] // Needs to be exported from the crate root effectively
39macro_rules! job_context {
40  () => {
41    // Path assumes the macro is invoked from outside the crate
42    $crate::job::context::CURRENT_JOB_CONTEXT.with(|ctx| *ctx)
43  };
44}