Skip to main content

ironflow_engine/
context.rs

1//! [`WorkflowContext`] — execution context for dynamic workflows.
2//!
3//! Provides step execution methods that automatically persist results to the
4//! store. Each call to [`shell`](WorkflowContext::shell),
5//! [`http`](WorkflowContext::http), [`agent`](WorkflowContext::agent), or
6//! [`workflow`](WorkflowContext::workflow) creates a step record, executes the
7//! operation, captures the output, and returns a
8//! [`StepOutput`](crate::executor::StepOutput) that the next step can
9//! reference.
10//!
11//! # Examples
12//!
13//! ```no_run
14//! use ironflow_engine::context::WorkflowContext;
15//! use ironflow_engine::config::{ShellConfig, AgentStepConfig};
16//! use ironflow_engine::error::EngineError;
17//!
18//! # async fn example(ctx: &mut WorkflowContext) -> Result<(), EngineError> {
19//! let build = ctx.shell("build", ShellConfig::new("cargo build")).await?;
20//! let review = ctx.agent("review", AgentStepConfig::new(
21//!     &format!("Build output:\n{}", build.stdout())
22//! )).await?;
23//! # Ok(())
24//! # }
25//! ```
26
27mod accessors;
28mod artifacts;
29mod error_handlers;
30mod failure;
31mod guard;
32mod lifecycle;
33mod steps;
34
35#[cfg(test)]
36mod tests;
37
38use std::collections::HashMap;
39use std::fmt;
40use std::sync::Arc;
41
42use rust_decimal::Decimal;
43use serde_json::Value;
44use uuid::Uuid;
45
46use ironflow_core::decision::DecisionProvider;
47use ironflow_core::provider::AgentProvider;
48use ironflow_core::trace_context::WorkflowTraceContext;
49use ironflow_store::models::Step;
50use ironflow_store::store::Store;
51
52use crate::artifact::ArtifactSink;
53use crate::config::StepConfig;
54use crate::executor::{StepInterceptor, StepResult};
55use crate::guard::{SharedGuardState, WorkflowGuardConfig};
56use crate::handler::WorkflowHandler;
57use crate::log_sender::LogSender;
58use crate::notify::WorkflowEventBus;
59use crate::operation::OperationContext;
60use crate::plan::SharedPlanRecorder;
61
62/// Callback type for resolving workflow handlers by name.
63pub(crate) type HandlerResolver =
64    Arc<dyn Fn(&str) -> Option<Arc<dyn WorkflowHandler>> + Send + Sync>;
65
66/// Execution context for a single workflow run.
67///
68/// Tracks the current step position and provides convenience methods
69/// for executing operations with automatic persistence.
70///
71/// # Examples
72///
73/// ```no_run
74/// use ironflow_engine::context::WorkflowContext;
75/// use ironflow_engine::config::ShellConfig;
76/// use ironflow_engine::error::EngineError;
77///
78/// # async fn example(ctx: &mut WorkflowContext) -> Result<(), EngineError> {
79/// let result = ctx.shell("greet", ShellConfig::new("echo hello")).await?;
80/// assert!(result.stdout().contains("hello"));
81/// # Ok(())
82/// # }
83/// ```
84pub struct WorkflowContext {
85    run_id: Uuid,
86    workflow_name: String,
87    store: Arc<dyn Store>,
88    provider: Arc<dyn AgentProvider>,
89    /// Optional decision backend (System One / Jev) for `ctx.decision(...)`.
90    /// `None` when no decision provider was wired: a decision step then fails
91    /// explicitly instead of silently doing nothing.
92    decision_provider: Option<Arc<dyn DecisionProvider>>,
93    handler_resolver: Option<HandlerResolver>,
94    position: u32,
95    /// IDs of the last executed step(s) -- used to record DAG dependencies.
96    last_step_ids: Vec<Uuid>,
97    /// Accumulated cost across all steps in this run.
98    total_cost_usd: Decimal,
99    /// Accumulated duration across all steps.
100    total_duration_ms: u64,
101    /// Cumulative cost cap for this run, resolved at creation. `None` = no cap.
102    max_cost_usd: Option<Decimal>,
103    /// Cost already spent by ancestor runs when this context belongs to a
104    /// sub-workflow. Zero for a top-level run.
105    inherited_cost_usd: Decimal,
106    /// Steps from a previous execution of the *same* attempt, keyed by position.
107    /// Used when resuming after approval to replay completed steps.
108    replay_steps: HashMap<u32, Step>,
109    /// Approvals granted in an *earlier* attempt, keyed by position, holding the
110    /// attempt that granted them. An approval is carried by the run, not by the
111    /// attempt, so a retry never asks a human to approve the same gate twice.
112    granted_approvals: HashMap<u32, u32>,
113    /// Human inputs answered in an *earlier* attempt, keyed by position:
114    /// (attempt, answer). Like an approval, an answer is carried by the run, so
115    /// a retry never asks a human to answer the same input twice.
116    answered_inputs: HashMap<u32, (u32, Value)>,
117    /// Which run attempt this context is executing (1-based).
118    attempt: u32,
119    /// Wall-clock duration already recorded on the run by previous attempts.
120    /// Added to this attempt's duration when the run is finalized.
121    carried_duration_ms: u64,
122    /// Optional sender for real-time log streaming.
123    log_sender: Option<LogSender>,
124    /// Where artifact bytes are read and written. `None` when no artifact
125    /// storage is configured: steps that declare artifacts then fail explicitly
126    /// instead of silently dropping their files.
127    artifact_sink: Option<Arc<dyn ArtifactSink>>,
128    /// Set to `true` when at least one `allow_failure` step failed.
129    has_allowed_failure: bool,
130    /// Error handlers registered via [`on_error`](Self::on_error).
131    error_handlers: Vec<OnErrorHandler>,
132    /// Shared guard state for workflow execution limits.
133    guard_state: Option<SharedGuardState>,
134    /// Guard configuration for this workflow run.
135    guard_config: Option<WorkflowGuardConfig>,
136    /// Accumulated step results for post-execution inspection.
137    step_results: Vec<StepResult>,
138    /// Optional event bus for per-run real-time monitoring.
139    event_bus: Option<WorkflowEventBus>,
140    /// Optional hook that resolves steps without executing them. `None` in
141    /// production; set by [`crate::testing::TestEngine`].
142    interceptor: Option<Arc<dyn StepInterceptor>>,
143    /// W3C trace context for distributed tracing propagation.
144    trace_context: WorkflowTraceContext,
145    /// Shared operation context for custom operations.
146    operation_ctx: Option<OperationContext>,
147    /// Set when the context is recording an execution plan instead of running.
148    /// Every step method checks this first and records intent without executing.
149    plan: Option<SharedPlanRecorder>,
150}
151
152/// A registered error handler that fires when a subsequent step fails.
153struct OnErrorHandler {
154    name: String,
155    config: StepConfig,
156}
157
158impl fmt::Debug for WorkflowContext {
159    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160        f.debug_struct("WorkflowContext")
161            .field("run_id", &self.run_id)
162            .field("position", &self.position)
163            .field("total_cost_usd", &self.total_cost_usd)
164            .field("inherited_cost_usd", &self.inherited_cost_usd)
165            .field("max_cost_usd", &self.max_cost_usd)
166            .field("planning", &self.plan.is_some())
167            .finish_non_exhaustive()
168    }
169}