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    /// The top-level run: `run_id` itself, or the parent's root for a
87    /// sub-workflow. Stamped on agent pods so a retry releases the children.
88    root_run_id: Uuid,
89    workflow_name: String,
90    store: Arc<dyn Store>,
91    provider: Arc<dyn AgentProvider>,
92    /// Optional decision backend (System One / Jev) for `ctx.decision(...)`.
93    /// `None` when no decision provider was wired: a decision step then fails
94    /// explicitly instead of silently doing nothing.
95    decision_provider: Option<Arc<dyn DecisionProvider>>,
96    handler_resolver: Option<HandlerResolver>,
97    position: u32,
98    /// IDs of the last executed step(s) -- used to record DAG dependencies.
99    last_step_ids: Vec<Uuid>,
100    /// Accumulated cost across all steps in this run.
101    total_cost_usd: Decimal,
102    /// Accumulated duration across all steps.
103    total_duration_ms: u64,
104    /// Cumulative cost cap for this run, resolved at creation. `None` = no cap.
105    max_cost_usd: Option<Decimal>,
106    /// Cost already spent by ancestor runs when this context belongs to a
107    /// sub-workflow. Zero for a top-level run.
108    inherited_cost_usd: Decimal,
109    /// Steps from a previous execution of the *same* attempt, keyed by position.
110    /// Used when resuming after approval to replay completed steps.
111    replay_steps: HashMap<u32, Step>,
112    /// All steps of a previous execution of the *same* attempt, keyed by
113    /// `(position, step name)`. A `parallel` wave shares one position across
114    /// several steps, which `replay_steps` cannot represent -- this index lets
115    /// `parallel()` check that every step of a wave already completed before
116    /// replaying the whole wave from the store, without re-running any item.
117    replay_wave_steps: HashMap<(u32, String), Step>,
118    /// Approvals granted in an *earlier* attempt, keyed by position, holding the
119    /// attempt that granted them. An approval is carried by the run, not by the
120    /// attempt, so a retry never asks a human to approve the same gate twice.
121    granted_approvals: HashMap<u32, u32>,
122    /// Human inputs answered in an *earlier* attempt, keyed by position:
123    /// (attempt, answer). Like an approval, an answer is carried by the run, so
124    /// a retry never asks a human to answer the same input twice.
125    answered_inputs: HashMap<u32, (u32, Value)>,
126    /// Which run attempt this context is executing (1-based).
127    attempt: u32,
128    /// Wall-clock duration already recorded on the run by previous attempts.
129    /// Added to this attempt's duration when the run is finalized.
130    carried_duration_ms: u64,
131    /// Optional sender for real-time log streaming.
132    log_sender: Option<LogSender>,
133    /// Where artifact bytes are read and written. `None` when no artifact
134    /// storage is configured: steps that declare artifacts then fail explicitly
135    /// instead of silently dropping their files.
136    artifact_sink: Option<Arc<dyn ArtifactSink>>,
137    /// Set to `true` when at least one `allow_failure` step failed.
138    has_allowed_failure: bool,
139    /// Error handlers registered via [`on_error`](Self::on_error).
140    error_handlers: Vec<OnErrorHandler>,
141    /// Shared guard state for workflow execution limits.
142    guard_state: Option<SharedGuardState>,
143    /// Guard configuration for this workflow run.
144    guard_config: Option<WorkflowGuardConfig>,
145    /// Accumulated step results for post-execution inspection.
146    step_results: Vec<StepResult>,
147    /// Optional event bus for per-run real-time monitoring.
148    event_bus: Option<WorkflowEventBus>,
149    /// Optional hook that resolves steps without executing them. `None` in
150    /// production; set by [`crate::testing::TestEngine`].
151    interceptor: Option<Arc<dyn StepInterceptor>>,
152    /// W3C trace context for distributed tracing propagation.
153    trace_context: WorkflowTraceContext,
154    /// Shared operation context for custom operations.
155    operation_ctx: Option<OperationContext>,
156    /// Set when the context is recording an execution plan instead of running.
157    /// Every step method checks this first and records intent without executing.
158    plan: Option<SharedPlanRecorder>,
159}
160
161/// A registered error handler that fires when a subsequent step fails.
162struct OnErrorHandler {
163    name: String,
164    config: StepConfig,
165}
166
167impl fmt::Debug for WorkflowContext {
168    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
169        f.debug_struct("WorkflowContext")
170            .field("run_id", &self.run_id)
171            .field("position", &self.position)
172            .field("total_cost_usd", &self.total_cost_usd)
173            .field("inherited_cost_usd", &self.inherited_cost_usd)
174            .field("max_cost_usd", &self.max_cost_usd)
175            .field("planning", &self.plan.is_some())
176            .finish_non_exhaustive()
177    }
178}