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