Skip to main content

JobContext

Struct JobContext 

Source
#[non_exhaustive]
pub struct JobContext { pub job_id: Uuid, pub job_type: String, pub attempt: u32, pub max_attempts: u32, pub auth: AuthContext, /* private fields */ }
Expand description

Context available to job handlers.

Fields (Non-exhaustive)§

This struct is marked as non-exhaustive
Non-exhaustive structs could have additional fields added in future. Therefore, non-exhaustive structs cannot be constructed in external crates using the traditional Struct { .. } syntax; cannot be matched against without a wildcard ..; and struct update syntax will not work.
§job_id: Uuid

Current attempt (1-based).

§job_type: String§attempt: u32§max_attempts: u32§auth: AuthContext

Implementations§

Source§

impl JobContext

Source

pub fn new( job_id: Uuid, job_type: String, attempt: u32, max_attempts: u32, db_pool: PgPool, http_client: CircuitBreakerClient, ) -> Self

Create a new job context.

Source

pub fn with_kv(self, kv: Arc<dyn KvHandle>) -> Self

Attach a KV store handle. Called by the runtime before handing the context to the handler.

Source

pub fn with_job_dispatch(self, dispatcher: Arc<dyn JobDispatch>) -> Self

Attach a job dispatcher so dispatch_job routes through the JobDispatch trait (the only path that resolves registered job metadata).

Source

pub fn with_workflow_dispatch( self, dispatcher: Arc<dyn WorkflowDispatch>, ) -> Self

Attach a workflow dispatcher so start_workflow routes through the WorkflowDispatch trait, which writes the active version + signature. Without this, dispatched workflows would resume as BlockedSignatureMismatch on first attempt.

Source

pub fn kv(&self) -> Result<&dyn KvHandle>

Access the KV store.

Source

pub fn with_saved(self, data: Value) -> Self

Create a new job context with persisted saved data.

Source

pub fn with_auth(self, auth: AuthContext) -> Self

Set authentication context.

Source

pub fn with_tenant_id(self, tenant_id: Uuid) -> Self

Inject a tenant ID into the auth context claims.

Merges the tenant_id claim into the existing auth context so that ctx.auth.tenant_id() returns the value for the duration of this job. Used by the executor when the job record carries a tenant ID.

Source

pub fn with_progress(self, tx: Sender<ProgressUpdate>) -> Self

Set progress channel.

Source

pub fn with_env_provider(self, provider: Arc<dyn EnvProvider>) -> Self

Set environment provider.

Source

pub fn db(&self) -> ForgeDb

Get database pool.

Source

pub fn db_conn(&self) -> DbConn<'_>

Get a DbConn for use in shared helper functions.

Source

pub async fn conn(&self) -> Result<ForgeConn<'static>>

Acquire a connection compatible with sqlx compile-time checked macros.

Source

pub fn http(&self) -> HttpClient

Get the HTTP client for external requests.

Source

pub fn raw_http(&self) -> &Client

Get the raw reqwest client, bypassing circuit breaker execution.

Source

pub fn set_http_timeout(&mut self, timeout: Option<Duration>)

Source

pub fn progress(&self, percentage: u8, message: impl Into<String>) -> Result<()>

Report job progress.

Source

pub async fn saved(&self) -> Value

Get all saved job data.

Returns data that was saved during job execution via save(). This data persists across retries and is accessible in compensation handlers.

Source

pub async fn save(&self, key: &str, value: Value) -> Result<()>

Save a key-value pair to persistent job data.

Merges key into the saved data object and persists the result to the database. Saved data survives retries and is accessible in compensation handlers. Use this to store information needed for rollback (e.g., transaction IDs, resource handles, progress markers).

Read saved data back with saved().

§Example
ctx.save("charge_id", json!(charge.id)).await?;
ctx.save("refund_amount", json!(amount)).await?;
Source

pub async fn dispatch_job<T: Serialize>( &self, job_type: &str, args: &T, ) -> Result<Uuid>

Dispatch a sub-job directly.

Routes through the JobDispatch trait so registered job metadata (queue/capability, priority, retry policy) is honoured. The dispatch is non-transactional: once the parent job returns, the child remains enqueued regardless of success. Use the transactional dispatch on MutationContext for commit-dependent fan-out.

Source

pub async fn dispatch<J: ForgeJob>(&self, args: &J::Args) -> Result<Uuid>

Type-safe dispatch: resolves the job name from the type’s ForgeJob impl and serializes the args at the call site.

Source

pub async fn start_workflow<T: Serialize>( &self, workflow_name: &str, args: &T, ) -> Result<Uuid>

Start a workflow directly.

Routes through the WorkflowDispatch trait, which writes the active version + signature onto the run row and enqueues the $workflow_resume job. Calling raw SQL here would leave both columns blank and the executor would immediately mark the run as BlockedSignatureMismatch.

Source

pub async fn is_cancel_requested(&self) -> Result<bool>

Check if cancellation has been requested for this job.

Source

pub async fn check_cancelled(&self) -> Result<()>

Return an error if cancellation has been requested.

Source

pub async fn heartbeat(&self) -> Result<()>

Send heartbeat to keep job alive (async).

Source

pub fn is_retry(&self) -> bool

Check if this is a retry attempt.

Source

pub fn is_last_attempt(&self) -> bool

Check if this is the last attempt.

Trait Implementations§

Source§

impl EnvAccess for JobContext

Source§

fn env_provider(&self) -> &dyn EnvProvider

Source§

fn env(&self, key: &str) -> Option<String>

Source§

fn env_or(&self, key: &str, default: &str) -> String

Source§

fn env_require(&self, key: &str) -> Result<String>

Source§

fn env_parse<T: FromStr>(&self, key: &str) -> Result<T>
where T::Err: Display,

Source§

fn env_parse_or<T: FromStr>(&self, key: &str, default: T) -> Result<T>
where T::Err: Display,

Returns the default when unset; errors only if the variable is set but unparseable.
Source§

fn env_contains(&self, key: &str) -> bool

Source§

impl HandlerContext for JobContext

Source§

fn db(&self) -> ForgeDb

Database handle with automatic db.query tracing spans. Read more
Source§

fn db_conn(&self) -> DbConn<'_>

Unified connection handle for shared helper functions. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more