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 cost;
30mod error_handlers;
31mod failure;
32mod guard;
33mod lifecycle;
34mod session;
35mod steps;
36
37#[cfg(test)]
38mod tests;
39
40pub(crate) use lifecycle::interrupt_running_steps;
41pub(crate) use steps::approval::required_votes;
42pub(crate) use steps::sub_workflow::recorded_child_run_id;
43
44use std::collections::HashMap;
45use std::fmt;
46use std::sync::Arc;
47
48use chrono::{DateTime, Utc};
49use rust_decimal::Decimal;
50use serde_json::Value;
51use uuid::Uuid;
52
53use ironflow_core::decision::DecisionProvider;
54use ironflow_core::provider::AgentProvider;
55use ironflow_core::trace_context::WorkflowTraceContext;
56use ironflow_store::models::Step;
57use ironflow_store::store::Store;
58
59use crate::artifact::ArtifactSink;
60use crate::config::StepConfig;
61use crate::error::EngineError;
62use crate::executor::{StepInterceptor, StepResult};
63use crate::guard::{SharedGuardState, WorkflowGuardConfig};
64use crate::handler::WorkflowHandler;
65use crate::log_sender::LogSender;
66use crate::notify::WorkflowEventBus;
67use crate::operation::OperationContext;
68use crate::plan::SharedPlanRecorder;
69
70use cost::SharedCost;
71
72/// Label set on every child run of a sub-workflow step, holding the id of the
73/// run that started it. Defined by the store, which follows it to list the
74/// descendants of a run; re-exported here where workflow code looks for it.
75///
76/// The root of the chain is recorded under
77/// [`LABEL_ROOT_RUN_ID`](ironflow_core::provider::LABEL_ROOT_RUN_ID).
78///
79/// # Examples
80///
81/// ```no_run
82/// use std::collections::HashMap;
83/// use ironflow_engine::context::PARENT_RUN_ID_LABEL;
84/// use ironflow_store::models::RunFilter;
85/// use uuid::Uuid;
86///
87/// # fn example(parent: Uuid) {
88/// let children = RunFilter {
89/// labels: Some(HashMap::from([(PARENT_RUN_ID_LABEL.to_string(), parent.to_string())])),
90/// ..RunFilter::default()
91/// };
92/// # }
93/// ```
94pub use ironflow_store::entities::PARENT_RUN_ID_LABEL;
95
96pub use steps::agent::AgentReply;
97
98/// Callback type for resolving workflow handlers by name.
99pub(crate) type HandlerResolver =
100 Arc<dyn Fn(&str) -> Option<Arc<dyn WorkflowHandler>> + Send + Sync>;
101
102/// Execution context for a single workflow run.
103///
104/// Tracks the current step position and provides convenience methods
105/// for executing operations with automatic persistence.
106///
107/// # Examples
108///
109/// ```no_run
110/// use ironflow_engine::context::WorkflowContext;
111/// use ironflow_engine::config::ShellConfig;
112/// use ironflow_engine::error::EngineError;
113///
114/// # async fn example(ctx: &mut WorkflowContext) -> Result<(), EngineError> {
115/// let result = ctx.shell("greet", ShellConfig::new("echo hello")).await?;
116/// assert!(result.stdout().contains("hello"));
117/// # Ok(())
118/// # }
119/// ```
120pub struct WorkflowContext {
121 run_id: Uuid,
122 /// The top-level run: `run_id` itself, or the parent's root for a
123 /// sub-workflow. Stamped on agent pods so a retry releases the children.
124 root_run_id: Uuid,
125 workflow_name: String,
126 store: Arc<dyn Store>,
127 provider: Arc<dyn AgentProvider>,
128 /// Optional decision backend (System One / Jev) for `ctx.decision(...)`.
129 /// `None` when no decision provider was wired: a decision step then fails
130 /// explicitly instead of silently doing nothing.
131 decision_provider: Option<Arc<dyn DecisionProvider>>,
132 handler_resolver: Option<HandlerResolver>,
133 position: u32,
134 /// IDs of the last executed step(s) -- used to record DAG dependencies.
135 last_step_ids: Vec<Uuid>,
136 /// Accumulated cost across all steps in this run.
137 total_cost_usd: Decimal,
138 /// Accumulated duration across all steps.
139 total_duration_ms: u64,
140 /// Cumulative cost cap for this run, resolved at creation. `None` = no cap.
141 max_cost_usd: Option<Decimal>,
142 /// Cost already spent by ancestor runs when this context belongs to a
143 /// sub-workflow. Zero for a top-level run.
144 inherited_cost_usd: Decimal,
145 /// Live cost of the run tree, set when this run belongs to a
146 /// [`workflows_with`](Self::workflows_with) wave or descends from one:
147 /// siblings run at the same time, so the cap is checked against what the
148 /// whole tree spends and reserves, not against a snapshot.
149 shared_cost: Option<SharedCost>,
150 /// Steps from a previous execution of the *same* attempt, keyed by position.
151 /// Used when resuming after approval to replay completed steps.
152 replay_steps: HashMap<u32, Step>,
153 /// All steps of a previous execution of the *same* attempt, keyed by
154 /// `(position, step name)`. A `parallel` wave shares one position across
155 /// several steps, which `replay_steps` cannot represent -- this index lets
156 /// `parallel()` check that every step of a wave already completed before
157 /// replaying the whole wave from the store, without re-running any item.
158 replay_wave_steps: HashMap<(u32, String), Step>,
159 /// Approvals granted in an *earlier* attempt, keyed by position, holding the
160 /// attempt that granted them. An approval is carried by the run, not by the
161 /// attempt, so a retry never asks a human to approve the same gate twice.
162 granted_approvals: HashMap<u32, u32>,
163 /// Human inputs answered in an *earlier* attempt, keyed by position:
164 /// (attempt, answer). Like an approval, an answer is carried by the run, so
165 /// a retry never asks a human to answer the same input twice.
166 answered_inputs: HashMap<u32, (u32, Value)>,
167 /// `Workflow` steps of the current attempt interrupted by a lost worker
168 /// lease, keyed by `(position, step name)`: the children of a
169 /// [`workflows_with`](Self::workflows_with) wave share one position. The
170 /// step executed again there re-enters the child run they recorded
171 /// instead of starting a new one.
172 interrupted_children: HashMap<(u32, String), Step>,
173 /// Which run attempt this context is executing (1-based).
174 attempt: u32,
175 /// Wall-clock duration already recorded on the run by previous attempts.
176 /// Added to this attempt's duration when the run is finalized.
177 carried_duration_ms: u64,
178 /// Optional sender for real-time log streaming.
179 log_sender: Option<LogSender>,
180 /// Where artifact bytes are read and written. `None` when no artifact
181 /// storage is configured: steps that declare artifacts then fail explicitly
182 /// instead of silently dropping their files.
183 artifact_sink: Option<Arc<dyn ArtifactSink>>,
184 /// Set to `true` when at least one `allow_failure` step failed.
185 has_allowed_failure: bool,
186 /// Error handlers registered via [`on_error`](Self::on_error).
187 error_handlers: Vec<OnErrorHandler>,
188 /// Shared guard state for workflow execution limits.
189 guard_state: Option<SharedGuardState>,
190 /// Guard configuration for this workflow run.
191 guard_config: Option<WorkflowGuardConfig>,
192 /// Accumulated step results for post-execution inspection.
193 step_results: Vec<StepResult>,
194 /// Optional event bus for per-run real-time monitoring.
195 event_bus: Option<WorkflowEventBus>,
196 /// Optional hook that resolves steps without executing them. `None` in
197 /// production; set by [`crate::testing::TestEngine`].
198 interceptor: Option<Arc<dyn StepInterceptor>>,
199 /// W3C trace context for distributed tracing propagation.
200 trace_context: WorkflowTraceContext,
201 /// Shared operation context for custom operations.
202 operation_ctx: Option<OperationContext>,
203 /// When the run was created, set by the engine. Bounds the signals a wait
204 /// step accepts: a signal received before the run existed is not for it.
205 /// `None` falls back to reading the run from the store.
206 run_created_at: Option<DateTime<Utc>>,
207 /// Set when the context is recording an execution plan instead of running.
208 /// Every step method checks this first and records intent without executing.
209 plan: Option<SharedPlanRecorder>,
210 /// Output set by the handler with [`set_output`](Self::set_output),
211 /// persisted on the run when the execution ends.
212 output: Option<Value>,
213 /// Worker tags carried by the process running this context, set by the
214 /// engine of a tagged worker. A sub-workflow requiring a tag missing from
215 /// this list is refused. `None` outside a worker: no check.
216 worker_tags: Option<Arc<Vec<String>>>,
217 /// Suspensions of wave children that the error this run returns does not
218 /// carry: a wave reports its first suspended child, the engine publishes
219 /// the event of every other one from here.
220 sibling_suspensions: Vec<EngineError>,
221}
222
223/// A registered error handler that fires when a subsequent step fails.
224struct OnErrorHandler {
225 name: String,
226 config: StepConfig,
227}
228
229impl fmt::Debug for WorkflowContext {
230 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
231 f.debug_struct("WorkflowContext")
232 .field("run_id", &self.run_id)
233 .field("position", &self.position)
234 .field("total_cost_usd", &self.total_cost_usd)
235 .field("inherited_cost_usd", &self.inherited_cost_usd)
236 .field("max_cost_usd", &self.max_cost_usd)
237 .field("planning", &self.plan.is_some())
238 .finish_non_exhaustive()
239 }
240}