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                max_cost_usd: None,
80            })
81            .await
82            .expect("create run")
83            .into_run();
84        let step = store
85            .create_step(NewStep {
86                run_id: run.id,
87                trace_id: Uuid::now_v7(),
88                name: "disk".to_string(),
89                kind: StepKind::Shell,
90                position: 0,
91                input: None,
92                is_error_handler: false,
93            })
94            .await
95            .expect("create step");
96        store
97            .update_step(
98                step.id,
99                StepUpdate {
100                    status: Some(StepStatus::Running),
101                    ..StepUpdate::default()
102                },
103            )
104            .await
105            .expect("to running");
106        if output.is_some() {
107            store
108                .update_step(
109                    step.id,
110                    StepUpdate {
111                        status: Some(StepStatus::Completed),
112                        output,
113                        duration_ms: Some(12),
114                        cost_usd: Some(Decimal::new(3, 2)),
115                        ..StepUpdate::default()
116                    },
117                )
118                .await
119                .expect("to completed");
120        }
121        store.get_step(step.id).await.expect("get").expect("exists")
122    }
123
124    #[tokio::test]
125    async fn a_stored_shell_step_reads_through_the_accessors() {
126        let step = stored_step(Some(
127            json!({"stdout": "42%\n", "stderr": "", "exit_code": 0}),
128        ))
129        .await;
130
131        let output = StepOutput::from(&step);
132
133        assert_eq!(output.stdout(), "42%\n");
134        assert_eq!(output.exit_code(), Some(0));
135        assert!(output.is_success());
136        assert_eq!(output.duration_ms, 12);
137        assert_eq!(output.cost_usd, Decimal::new(3, 2));
138    }
139
140    #[tokio::test]
141    async fn step_output_error_reads_from_stored_step() {
142        let step = stored_step(Some(json!({"error": "x"}))).await;
143        assert_eq!(StepOutput::from(&step).error(), Some("x"));
144
145        let step = stored_step(None).await;
146        assert_eq!(StepOutput::from(&step).error(), None);
147    }
148
149    #[tokio::test]
150    async fn a_step_without_output_reads_as_empty() {
151        let step = stored_step(None).await;
152
153        let output = StepOutput::from(&step);
154
155        assert_eq!(output.output, Value::Null);
156        assert_eq!(output.stdout(), "");
157        assert_eq!(output.exit_code(), None);
158        assert!(!output.is_success());
159    }
160
161    #[tokio::test]
162    async fn a_stored_step_carries_its_environment_id() {
163        let mut step = stored_step(None).await;
164        assert_eq!(StepOutput::from(&step).environment_id, None);
165
166        step.environment_id = Some("ironflow-env-0a1b2c".to_string());
167        assert_eq!(
168            StepOutput::from(&step).environment_id.as_deref(),
169            Some("ironflow-env-0a1b2c")
170        );
171    }
172}