Skip to main content

ironflow_engine/executor/
stored.rs

1//! Read a persisted step back as a [`StepOutput`].
2
3use serde_json::Value;
4
5use ironflow_store::entities::Step;
6
7use super::{StepArtifacts, StepOutput};
8
9/// View a persisted step through the typed [`StepOutput`] accessors.
10///
11/// Useful to read the steps of a sub-workflow run, listed from the store by
12/// [`SubWorkflowOutput::run_id`](super::SubWorkflowOutput::run_id). A step
13/// without output (still running, failed, skipped) reads as an empty output.
14/// The model and the debug conversation are not carried over.
15///
16/// # Examples
17///
18/// ```no_run
19/// use ironflow_engine::context::WorkflowContext;
20/// use ironflow_engine::error::EngineError;
21/// use ironflow_engine::executor::{StepOutput, SubWorkflowOutput};
22///
23/// # async fn example(ctx: &WorkflowContext, child: &SubWorkflowOutput) -> Result<(), EngineError> {
24/// for step in ctx.store().list_steps(child.run_id()).await? {
25///     println!("{}: {}", step.name, StepOutput::from(&step).stdout());
26/// }
27/// # Ok(())
28/// # }
29/// ```
30impl From<&Step> for StepOutput {
31    fn from(step: &Step) -> Self {
32        Self {
33            output: step.output.clone().unwrap_or(Value::Null),
34            duration_ms: step.duration_ms,
35            cost_usd: step.cost_usd,
36            input_tokens: step.input_tokens,
37            cache_read_input_tokens: step.cache_read_input_tokens,
38            cache_creation_input_tokens: step.cache_creation_input_tokens,
39            output_tokens: step.output_tokens,
40            model: None,
41            debug_messages: None,
42            artifacts: StepArtifacts::default(),
43            account_id: step.account_id,
44            environment_id: step.environment_id.clone(),
45        }
46    }
47}
48
49#[cfg(test)]
50mod tests {
51    use std::collections::HashMap;
52
53    use ironflow_store::entities::{
54        NewRun, NewStep, StepKind, StepStatus, StepUpdate, TriggerKind,
55    };
56    use ironflow_store::memory::InMemoryStore;
57    use ironflow_store::store::RunStore;
58    use rust_decimal::Decimal;
59    use serde_json::json;
60    use uuid::Uuid;
61
62    use super::*;
63
64    /// A shell step of a fresh run, completed with `output` when given.
65    async fn stored_step(output: Option<Value>) -> Step {
66        let store = InMemoryStore::new();
67        let run = store
68            .create_run(NewRun {
69                created_by: None,
70                workflow_name: "collect".to_string(),
71                trigger: TriggerKind::Manual,
72                payload: json!({}),
73                max_retries: 0,
74                handler_version: None,
75                labels: HashMap::new(),
76                scheduled_at: None,
77                idempotency_key: None,
78                concurrency_key: None,
79                concurrency_limits: Vec::new(),
80                max_cost_usd: None,
81            })
82            .await
83            .expect("create run")
84            .into_run();
85        let step = store
86            .create_step(NewStep {
87                run_id: run.id,
88                trace_id: Uuid::now_v7(),
89                name: "disk".to_string(),
90                kind: StepKind::Shell,
91                position: 0,
92                input: None,
93                is_error_handler: false,
94            })
95            .await
96            .expect("create step");
97        store
98            .update_step(
99                step.id,
100                StepUpdate {
101                    status: Some(StepStatus::Running),
102                    ..StepUpdate::default()
103                },
104            )
105            .await
106            .expect("to running");
107        if output.is_some() {
108            store
109                .update_step(
110                    step.id,
111                    StepUpdate {
112                        status: Some(StepStatus::Completed),
113                        output,
114                        duration_ms: Some(12),
115                        cost_usd: Some(Decimal::new(3, 2)),
116                        ..StepUpdate::default()
117                    },
118                )
119                .await
120                .expect("to completed");
121        }
122        store.get_step(step.id).await.expect("get").expect("exists")
123    }
124
125    #[tokio::test]
126    async fn a_stored_shell_step_reads_through_the_accessors() {
127        let step = stored_step(Some(
128            json!({"stdout": "42%\n", "stderr": "", "exit_code": 0}),
129        ))
130        .await;
131
132        let output = StepOutput::from(&step);
133
134        assert_eq!(output.stdout(), "42%\n");
135        assert_eq!(output.exit_code(), Some(0));
136        assert!(output.is_success());
137        assert_eq!(output.duration_ms, 12);
138        assert_eq!(output.cost_usd, Decimal::new(3, 2));
139    }
140
141    #[tokio::test]
142    async fn step_output_error_reads_from_stored_step() {
143        let step = stored_step(Some(json!({"error": "x"}))).await;
144        assert_eq!(StepOutput::from(&step).error(), Some("x"));
145
146        let step = stored_step(None).await;
147        assert_eq!(StepOutput::from(&step).error(), None);
148    }
149
150    #[tokio::test]
151    async fn a_step_without_output_reads_as_empty() {
152        let step = stored_step(None).await;
153
154        let output = StepOutput::from(&step);
155
156        assert_eq!(output.output, Value::Null);
157        assert_eq!(output.stdout(), "");
158        assert_eq!(output.exit_code(), None);
159        assert!(!output.is_success());
160    }
161
162    #[tokio::test]
163    async fn a_stored_step_carries_its_environment_id() {
164        let mut step = stored_step(None).await;
165        assert_eq!(StepOutput::from(&step).environment_id, None);
166
167        step.environment_id = Some("ironflow-env-0a1b2c".to_string());
168        assert_eq!(
169            StepOutput::from(&step).environment_id.as_deref(),
170            Some("ironflow-env-0a1b2c")
171        );
172    }
173}