WorkflowContext

Struct WorkflowContext 

Source
pub struct WorkflowContext {
    pub run_id: Uuid,
    pub workflow_name: String,
    pub version: u32,
    pub started_at: DateTime<Utc>,
    pub auth: AuthContext,
    /* private fields */
}
Expand description

Context available to workflow handlers.

Fields§

§run_id: Uuid

Workflow run ID.

§workflow_name: String

Workflow name.

§version: u32

Workflow version.

§started_at: DateTime<Utc>

When the workflow started.

§auth: AuthContext

Authentication context.

Implementations§

Source§

impl WorkflowContext

Source

pub fn new( run_id: Uuid, workflow_name: String, version: u32, db_pool: Pool<Postgres>, http_client: Client, ) -> WorkflowContext

Create a new workflow context.

Source

pub fn resumed( run_id: Uuid, workflow_name: String, version: u32, started_at: DateTime<Utc>, db_pool: Pool<Postgres>, http_client: Client, ) -> WorkflowContext

Create a resumed workflow context.

Source

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

Set environment provider.

Source

pub fn with_resumed_from_sleep(self) -> WorkflowContext

Mark that this context resumed from a sleep (timer expired).

Source

pub fn with_suspend_channel(self, tx: Sender<SuspendReason>) -> WorkflowContext

Set the suspend channel.

Source

pub fn with_tenant(self, tenant_id: Uuid) -> WorkflowContext

Set the tenant ID.

Source

pub fn tenant_id(&self) -> Option<Uuid>

Get the tenant ID.

Source

pub fn is_resumed(&self) -> bool

Check if this is a resumed execution.

Source

pub fn workflow_time(&self) -> DateTime<Utc>

Get the deterministic workflow time.

Source

pub fn db(&self) -> &Pool<Postgres>

Get the database pool.

Source

pub fn http(&self) -> &Client

Get the HTTP client.

Source

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

Set authentication context.

Source

pub fn with_step_states( self, states: HashMap<String, StepState>, ) -> WorkflowContext

Restore step states from persisted data.

Source

pub fn get_step_state(&self, name: &str) -> Option<StepState>

Get step state by name.

Source

pub fn is_step_completed(&self, name: &str) -> bool

Check if a step is already completed.

Source

pub fn is_step_started(&self, name: &str) -> bool

Check if a step has been started (running, completed, or failed).

Use this to guard steps that should only execute once, even across workflow suspension and resumption.

Source

pub fn get_step_result<T>(&self, name: &str) -> Option<T>

Get the result of a completed step.

Source

pub fn record_step_start(&self, name: &str)

Record step start.

If the step is already running or beyond (completed/failed), this is a no-op. This prevents race conditions when resuming workflows.

Source

pub fn record_step_complete(&self, name: &str, result: Value)

Record step completion (fire-and-forget database update). Use record_step_complete_async if you need to ensure persistence before continuing.

Source

pub async fn record_step_complete_async(&self, name: &str, result: Value)

Record step completion and wait for database persistence.

Source

pub fn record_step_failure(&self, name: &str, error: impl Into<String>)

Record step failure.

Source

pub fn record_step_compensated(&self, name: &str)

Record step compensation.

Source

pub fn completed_steps_reversed(&self) -> Vec<String>

Get completed steps in reverse order (for compensation).

Source

pub fn all_step_states(&self) -> HashMap<String, StepState>

Get all step states.

Source

pub fn elapsed(&self) -> TimeDelta

Get elapsed time since workflow started.

Source

pub fn register_compensation( &self, step_name: &str, handler: Arc<dyn Fn(Value) -> Pin<Box<dyn Future<Output = Result<(), ForgeError>> + Send>> + Send + Sync>, )

Register a compensation handler for a step.

Source

pub fn get_compensation_handler( &self, step_name: &str, ) -> Option<Arc<dyn Fn(Value) -> Pin<Box<dyn Future<Output = Result<(), ForgeError>> + Send>> + Send + Sync>>

Get compensation handler for a step.

Source

pub fn has_compensation(&self, step_name: &str) -> bool

Check if a step has a compensation handler.

Source

pub async fn run_compensation(&self) -> Vec<(String, bool)>

Run compensation for all completed steps in reverse order. Returns a list of (step_name, success) tuples.

Source

pub fn compensation_handlers( &self, ) -> HashMap<String, Arc<dyn Fn(Value) -> Pin<Box<dyn Future<Output = Result<(), ForgeError>> + Send>> + Send + Sync>>

Get compensation handlers (for cloning to executor).

Source

pub async fn sleep(&self, duration: Duration) -> Result<(), ForgeError>

Sleep for a duration.

This suspends the workflow and persists the wake time to the database. The workflow scheduler will resume the workflow when the time arrives.

§Example
// Sleep for 30 days
ctx.sleep(Duration::from_secs(30 * 24 * 60 * 60)).await?;
Source

pub async fn sleep_until( &self, wake_at: DateTime<Utc>, ) -> Result<(), ForgeError>

Sleep until a specific time.

If the wake time has already passed, returns immediately.

§Example
use chrono::{Utc, Duration};
let renewal_date = Utc::now() + Duration::days(30);
ctx.sleep_until(renewal_date).await?;
Source

pub async fn wait_for_event<T>( &self, event_name: &str, timeout: Option<Duration>, ) -> Result<T, ForgeError>

Wait for an external event with optional timeout.

The workflow suspends until the event arrives or the timeout expires. Events are correlated by the workflow run ID.

§Example
let payment: PaymentConfirmation = ctx.wait_for_event(
    "payment_confirmed",
    Some(Duration::from_secs(7 * 24 * 60 * 60)), // 7 days
).await?;
Source

pub fn parallel(&self) -> ParallelBuilder<'_>

Create a parallel builder for executing steps concurrently.

§Example
let results = ctx.parallel()
    .step("fetch_user", || async { get_user(id).await })
    .step("fetch_orders", || async { get_orders(id).await })
    .step_with_compensate("charge_card",
        || async { charge_card(amount).await },
        |charge| async move { refund(charge.id).await })
    .run().await?;

let user: User = results.get("fetch_user")?;
let orders: Vec<Order> = results.get("fetch_orders")?;
Source

pub fn step<T, F, Fut>( &self, name: impl Into<String>, f: F, ) -> StepRunner<'_, T>
where T: Serialize + DeserializeOwned + Clone + Send + Sync + 'static, F: FnOnce() -> Fut + Send + 'static, Fut: Future<Output = Result<T, ForgeError>> + Send + 'static,

Create a step runner for executing a workflow step.

This provides a fluent API for defining steps with retry, compensation, timeout, and optional behavior.

§Examples
use std::time::Duration;

// Simple step
let data = ctx.step("fetch_data", || async {
    Ok(fetch_from_api().await?)
}).run().await?;

// Step with retry (3 attempts, 2 second delay)
ctx.step("send_email", || async {
    send_verification_email(&user.email).await
})
.retry(3, Duration::from_secs(2))
.run()
.await?;

// Step with compensation (rollback on later failure)
let charge = ctx.step("charge_card", || async {
    charge_credit_card(&card).await
})
.compensate(|charge_result| async move {
    refund_charge(&charge_result.charge_id).await
})
.run()
.await?;

// Optional step (failure won't trigger compensation)
ctx.step("notify_slack", || async {
    post_to_slack("User signed up!").await
})
.optional()
.run()
.await?;

// Step with timeout
ctx.step("slow_operation", || async {
    process_large_file().await
})
.timeout(Duration::from_secs(60))
.run()
.await?;

Trait Implementations§

Source§

impl EnvAccess for WorkflowContext

Source§

fn env_provider(&self) -> &dyn EnvProvider

Get the environment provider.
Source§

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

Get an environment variable. Read more
Source§

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

Get an environment variable with a default value. Read more
Source§

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

Get a required environment variable. Read more
Source§

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

Get an environment variable and parse it to the specified type. Read more
Source§

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

Get an environment variable and parse it, with a default. Read more
Source§

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

Check if an environment variable is set.

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