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