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