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 /// All steps of a previous execution of the *same* attempt, keyed by
110 /// `(position, step name)`. A `parallel` wave shares one position across
111 /// several steps, which `replay_steps` cannot represent -- this index lets
112 /// `parallel()` check that every step of a wave already completed before
113 /// replaying the whole wave from the store, without re-running any item.
114 replay_wave_steps: HashMap<(u32, String), Step>,
115 /// Approvals granted in an *earlier* attempt, keyed by position, holding the
116 /// attempt that granted them. An approval is carried by the run, not by the
117 /// attempt, so a retry never asks a human to approve the same gate twice.
118 granted_approvals: HashMap<u32, u32>,
119 /// Human inputs answered in an *earlier* attempt, keyed by position:
120 /// (attempt, answer). Like an approval, an answer is carried by the run, so
121 /// a retry never asks a human to answer the same input twice.
122 answered_inputs: HashMap<u32, (u32, Value)>,
123 /// Which run attempt this context is executing (1-based).
124 attempt: u32,
125 /// Wall-clock duration already recorded on the run by previous attempts.
126 /// Added to this attempt's duration when the run is finalized.
127 carried_duration_ms: u64,
128 /// Optional sender for real-time log streaming.
129 log_sender: Option<LogSender>,
130 /// Where artifact bytes are read and written. `None` when no artifact
131 /// storage is configured: steps that declare artifacts then fail explicitly
132 /// instead of silently dropping their files.
133 artifact_sink: Option<Arc<dyn ArtifactSink>>,
134 /// Set to `true` when at least one `allow_failure` step failed.
135 has_allowed_failure: bool,
136 /// Error handlers registered via [`on_error`](Self::on_error).
137 error_handlers: Vec<OnErrorHandler>,
138 /// Shared guard state for workflow execution limits.
139 guard_state: Option<SharedGuardState>,
140 /// Guard configuration for this workflow run.
141 guard_config: Option<WorkflowGuardConfig>,
142 /// Accumulated step results for post-execution inspection.
143 step_results: Vec<StepResult>,
144 /// Optional event bus for per-run real-time monitoring.
145 event_bus: Option<WorkflowEventBus>,
146 /// Optional hook that resolves steps without executing them. `None` in
147 /// production; set by [`crate::testing::TestEngine`].
148 interceptor: Option<Arc<dyn StepInterceptor>>,
149 /// W3C trace context for distributed tracing propagation.
150 trace_context: WorkflowTraceContext,
151 /// Shared operation context for custom operations.
152 operation_ctx: Option<OperationContext>,
153 /// Set when the context is recording an execution plan instead of running.
154 /// Every step method checks this first and records intent without executing.
155 plan: Option<SharedPlanRecorder>,
156}
157
158/// A registered error handler that fires when a subsequent step fails.
159struct OnErrorHandler {
160 name: String,
161 config: StepConfig,
162}
163
164impl fmt::Debug for WorkflowContext {
165 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166 f.debug_struct("WorkflowContext")
167 .field("run_id", &self.run_id)
168 .field("position", &self.position)
169 .field("total_cost_usd", &self.total_cost_usd)
170 .field("inherited_cost_usd", &self.inherited_cost_usd)
171 .field("max_cost_usd", &self.max_cost_usd)
172 .field("planning", &self.plan.is_some())
173 .finish_non_exhaustive()
174 }
175}