Skip to main content

ironflow_engine/
error.rs

1//! Engine error types.
2
3use rust_decimal::Decimal;
4use thiserror::Error;
5
6use ironflow_artifacts::error::ArtifactError;
7use ironflow_core::error::OperationError;
8use ironflow_store::error::StoreError;
9
10use crate::guard::{WORKFLOW_GUARD_REJECTED_CODE, WorkflowRejection};
11
12/// Business error code carried by [`EngineError::RunBudgetExceeded`].
13pub const RUN_BUDGET_EXCEEDED_CODE: &str = "RUN_BUDGET_EXCEEDED";
14
15/// Business error code carried by [`EngineError::MonthlyBudgetExceeded`].
16pub const MONTHLY_BUDGET_EXCEEDED_CODE: &str = "MONTHLY_BUDGET_EXCEEDED";
17
18/// Business error code for handler-version mismatch on retry.
19pub const HANDLER_VERSION_MISMATCH_CODE: &str = "HANDLER_VERSION_MISMATCH";
20
21/// Errors produced by the workflow engine.
22#[derive(Debug, Error)]
23pub enum EngineError {
24    /// An operation (Shell, Http, Agent) failed during step execution.
25    #[error("operation failed: {0}")]
26    Operation(#[from] OperationError),
27
28    /// The backing store returned an error.
29    #[error("store error: {0}")]
30    Store(#[from] StoreError),
31
32    /// The workflow definition is invalid.
33    #[error("invalid workflow: {0}")]
34    InvalidWorkflow(String),
35
36    /// A step configuration could not be deserialized for execution.
37    #[error("step config error: {0}")]
38    StepConfig(String),
39
40    /// JSON serialization error.
41    #[error("serialization error: {0}")]
42    Serialization(#[from] serde_json::Error),
43
44    /// The run reached its cumulative cost cap before launching an agent step.
45    ///
46    /// Raised *before* the step is created, so no work and no spend happen.
47    /// The engine transitions the run to
48    /// [`Cancelled`](ironflow_store::entities::RunStatus::Cancelled).
49    #[error(
50        "{RUN_BUDGET_EXCEEDED_CODE}: run {run_id} would exceed its cost cap \
51         (spent {spent_usd} USD + next step {step_budget_usd} USD > cap {limit_usd} USD)"
52    )]
53    RunBudgetExceeded {
54        /// The run that hit its cap.
55        run_id: uuid::Uuid,
56        /// The configured cap, in USD.
57        limit_usd: Decimal,
58        /// Cost already accumulated by this run and its ancestors, in USD.
59        spent_usd: Decimal,
60        /// Declared budget of the step that was about to run, in USD.
61        step_budget_usd: Decimal,
62    },
63
64    /// The global monthly cost quota is exhausted; no new run may be created.
65    ///
66    /// Runs already in flight are never interrupted by this error.
67    #[error(
68        "{MONTHLY_BUDGET_EXCEEDED_CODE}: monthly cost quota exhausted \
69         ({spent_usd} USD spent of {limit_usd} USD)"
70    )]
71    MonthlyBudgetExceeded {
72        /// The configured monthly quota, in USD.
73        limit_usd: Decimal,
74        /// Cost already spent during the current calendar month, in USD.
75        spent_usd: Decimal,
76    },
77
78    /// A step declared an output that produced no file.
79    ///
80    /// Raised only when the step itself succeeded: a declared output that never
81    /// materialised is a broken contract, and failing here beats failing later
82    /// in whichever step tried to consume it.
83    #[error("step {step:?} declared output {pattern:?} but no file matched")]
84    MissingArtifact {
85        /// Name of the step that declared the output.
86        step: String,
87        /// The unmatched pattern.
88        pattern: String,
89    },
90
91    /// A step asked for an artifact that no earlier step produced.
92    #[error("no artifact {name:?} produced by step {step:?} before this point")]
93    ArtifactNotFound {
94        /// Name of the producing step that was searched for.
95        step: String,
96        /// Name of the artifact that was searched for.
97        name: String,
98    },
99
100    /// Artifacts were used but no storage backend is configured.
101    #[error("artifact storage is not configured: {0}")]
102    ArtifactsUnavailable(String),
103
104    /// The artifact storage backend failed.
105    #[error("artifact storage error: {0}")]
106    Artifact(#[from] ArtifactError),
107
108    /// The run requires human approval before continuing.
109    #[error("approval required for run {run_id}, step {step_id}: {message}")]
110    ApprovalRequired {
111        /// The run that is awaiting approval.
112        run_id: uuid::Uuid,
113        /// The approval step that triggered the pause.
114        step_id: uuid::Uuid,
115        /// The approval message.
116        message: String,
117    },
118
119    /// A workflow invocation was rejected by the [workflow guard](crate::guard).
120    ///
121    /// The run is transitioned to
122    /// [`Cancelled`](ironflow_store::entities::RunStatus::Cancelled) when this
123    /// error is raised.
124    #[error("{WORKFLOW_GUARD_REJECTED_CODE}: {0}")]
125    WorkflowGuardRejected(#[from] WorkflowRejection),
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131
132    #[test]
133    fn invalid_workflow_display() {
134        let err = EngineError::InvalidWorkflow("unknown-handler".to_string());
135        assert!(err.to_string().contains("invalid workflow"));
136        assert!(err.to_string().contains("unknown-handler"));
137    }
138
139    #[test]
140    fn step_config_display() {
141        let err = EngineError::StepConfig("bad shell config".to_string());
142        assert!(err.to_string().contains("step config error"));
143        assert!(err.to_string().contains("bad shell config"));
144    }
145
146    #[test]
147    fn store_error_from_conversion() {
148        let store_err = StoreError::RunNotFound(uuid::Uuid::nil());
149        let engine_err = EngineError::from(store_err);
150        assert!(engine_err.to_string().contains("store error"));
151    }
152
153    #[test]
154    fn run_budget_exceeded_display_carries_code_and_amounts() {
155        let err = EngineError::RunBudgetExceeded {
156            run_id: uuid::Uuid::nil(),
157            limit_usd: Decimal::new(200, 2),
158            spent_usd: Decimal::new(180, 2),
159            step_budget_usd: Decimal::new(50, 2),
160        };
161
162        let msg = err.to_string();
163        assert!(msg.contains(RUN_BUDGET_EXCEEDED_CODE));
164        assert!(msg.contains("2.00"));
165        assert!(msg.contains("1.80"));
166        assert!(msg.contains("0.50"));
167    }
168
169    #[test]
170    fn monthly_budget_exceeded_display_carries_code_and_amounts() {
171        let err = EngineError::MonthlyBudgetExceeded {
172            limit_usd: Decimal::new(10000, 2),
173            spent_usd: Decimal::new(10500, 2),
174        };
175
176        let msg = err.to_string();
177        assert!(msg.contains(MONTHLY_BUDGET_EXCEEDED_CODE));
178        assert!(msg.contains("100.00"));
179        assert!(msg.contains("105.00"));
180    }
181
182    #[test]
183    fn missing_artifact_display_names_the_step_and_pattern() {
184        let err = EngineError::MissingArtifact {
185            step: "build".to_string(),
186            pattern: "target/report.html".to_string(),
187        };
188
189        let msg = err.to_string();
190        assert!(msg.contains("\"build\""));
191        assert!(msg.contains("target/report.html"));
192    }
193
194    #[test]
195    fn artifact_not_found_display_names_the_producer() {
196        let err = EngineError::ArtifactNotFound {
197            step: "build".to_string(),
198            name: "report.html".to_string(),
199        };
200
201        let msg = err.to_string();
202        assert!(msg.contains("\"build\""));
203        assert!(msg.contains("report.html"));
204    }
205
206    #[test]
207    fn artifacts_unavailable_display() {
208        let err = EngineError::ArtifactsUnavailable("no blob store".to_string());
209        assert!(err.to_string().contains("not configured"));
210    }
211
212    #[test]
213    fn artifact_error_from_conversion() {
214        let engine_err = EngineError::from(ArtifactError::NotFound("a/b".to_string()));
215        assert!(engine_err.to_string().contains("artifact storage error"));
216    }
217
218    #[test]
219    fn serialization_error_from_conversion() {
220        let serde_err = serde_json::from_str::<String>("not json").unwrap_err();
221        let engine_err = EngineError::from(serde_err);
222        assert!(engine_err.to_string().contains("serialization error"));
223    }
224
225    #[test]
226    fn workflow_guard_rejected_display_carries_code_and_detail() {
227        use crate::guard::WorkflowRejection;
228
229        let rejection = WorkflowRejection::MaxDepthExceeded { depth: 6, max: 5 };
230        let err = EngineError::from(rejection);
231
232        let msg = err.to_string();
233        assert!(msg.contains(WORKFLOW_GUARD_REJECTED_CODE));
234        assert!(msg.contains("max call depth exceeded"));
235        assert!(msg.contains("6/5"));
236    }
237
238    #[test]
239    fn workflow_guard_rejected_from_conversion() {
240        use crate::guard::WorkflowRejection;
241
242        let rejection = WorkflowRejection::CycleDetected {
243            target: "wf-b".to_string(),
244            chain: vec!["wf-a".to_string(), "wf-b".to_string()],
245        };
246        let engine_err = EngineError::from(rejection);
247        assert!(engine_err.to_string().contains("cycle detected"));
248    }
249}