ironflow-core 2.8.0

Rust workflow engine with Claude Code native agent support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//! Parallel step execution utilities.
//!
//! Run independent workflow steps concurrently to reduce total wall-clock time.
//! Two patterns are supported:
//!
//! # Static parallelism (known number of steps)
//!
//! Use [`tokio::try_join!`] when you know at compile time how many steps
//! to run in parallel:
//!
//! ```no_run
//! use ironflow_core::prelude::*;
//!
//! # async fn example() -> Result<(), OperationError> {
//! let (files, status) = tokio::try_join!(
//!     Shell::new("ls -la"),
//!     Shell::new("git status"),
//! )?;
//!
//! println!("files:\n{}", files.stdout());
//! println!("status:\n{}", status.stdout());
//! # Ok(())
//! # }
//! ```
//!
//! # Dynamic parallelism (runtime-determined number of steps)
//!
//! Use [`try_join_all`] when the number of steps is determined at runtime:
//!
//! ```no_run
//! use ironflow_core::prelude::*;
//!
//! # async fn example() -> Result<(), OperationError> {
//! let commands = vec!["ls -la", "git status", "df -h"];
//! let results = try_join_all(
//!     commands.iter().map(|cmd| Shell::new(cmd).run())
//! ).await?;
//!
//! for (cmd, output) in commands.iter().zip(&results) {
//!     println!("{cmd}: {}", output.stdout());
//! }
//! # Ok(())
//! # }
//! ```
//!
//! # Concurrency-limited parallelism
//!
//! Use [`try_join_all_limited`] to cap the number of steps running
//! simultaneously (useful when launching many agent calls):
//!
//! ```no_run
//! use ironflow_core::prelude::*;
//!
//! # async fn example() -> Result<(), OperationError> {
//! let provider = ClaudeCodeProvider::new();
//! let prompts = vec!["Summarize file A", "Summarize file B", "Summarize file C"];
//!
//! let results = try_join_all_limited(
//!     prompts.iter().map(|p| {
//!         Agent::new()
//!             .prompt(p)
//!             .model(Model::HAIKU)
//!             .max_budget_usd(0.10)
//!             .run(&provider)
//!     }),
//!     2, // at most 2 agent calls at a time
//! ).await?;
//! # Ok(())
//! # }
//! ```

use std::future::Future;
use std::sync::Arc;

use futures_util::future;
use tokio::sync::Semaphore;

use crate::error::OperationError;

/// Run a collection of futures concurrently and collect their results.
///
/// All futures start executing immediately. Returns a [`Vec<T>`] in the same
/// order as the input iterator, or the first [`OperationError`] encountered
/// (remaining futures are dropped on error).
///
/// # Examples
///
/// ```no_run
/// use ironflow_core::prelude::*;
///
/// # async fn example() -> Result<(), OperationError> {
/// let outputs = try_join_all(vec![
///     Shell::new("echo one").run(),
///     Shell::new("echo two").run(),
///     Shell::new("echo three").run(),
/// ]).await?;
///
/// assert_eq!(outputs.len(), 3);
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns the first [`OperationError`] produced by any future. When an error
/// occurs, all other in-flight futures are cancelled.
pub async fn try_join_all<I, F, T>(futures: I) -> Result<Vec<T>, OperationError>
where
    I: IntoIterator<Item = F>,
    F: Future<Output = Result<T, OperationError>>,
{
    future::try_join_all(futures).await
}

/// Run a collection of futures with a concurrency limit.
///
/// At most `limit` futures execute simultaneously. Results are returned in
/// the same order as the input iterator. Useful when running many agent
/// calls to avoid overwhelming the system or exceeding rate limits.
///
/// # Examples
///
/// ```no_run
/// use ironflow_core::prelude::*;
///
/// # async fn example() -> Result<(), OperationError> {
/// let commands: Vec<&str> = (0..20)
///     .map(|_| "echo hello")
///     .collect();
///
/// let outputs = try_join_all_limited(
///     commands.iter().map(|cmd| Shell::new(cmd).run()),
///     5, // run at most 5 in parallel
/// ).await?;
///
/// assert_eq!(outputs.len(), 20);
/// # Ok(())
/// # }
/// ```
///
/// # Errors
///
/// Returns the first [`OperationError`] produced by any future. When an error
/// occurs, all other in-flight futures are cancelled.
///
/// # Panics
///
/// Panics if `limit` is `0`.
pub async fn try_join_all_limited<I, F, T>(
    futures: I,
    limit: usize,
) -> Result<Vec<T>, OperationError>
where
    I: IntoIterator<Item = F>,
    F: Future<Output = Result<T, OperationError>>,
{
    assert!(limit > 0, "concurrency limit must be greater than 0");

    let sem = Arc::new(Semaphore::new(limit));
    let guarded = futures.into_iter().map(|f| {
        let sem = sem.clone();
        async move {
            let _permit = sem.acquire().await.expect("semaphore closed unexpectedly");
            f.await
        }
    });

    future::try_join_all(guarded).await
}

#[cfg(test)]
mod tests {
    use std::pin::Pin;
    use std::sync::atomic::{AtomicUsize, Ordering};

    use super::*;
    use crate::operations::shell::Shell;

    #[tokio::test]
    async fn try_join_all_empty_returns_empty_vec() {
        let result: Result<Vec<()>, OperationError> = try_join_all(Vec::<
            Pin<Box<dyn Future<Output = Result<(), OperationError>> + Send>>,
        >::new())
        .await;
        assert!(result.unwrap().is_empty());
    }

    #[tokio::test]
    async fn try_join_all_single_future() {
        let results = try_join_all(vec![Shell::new("echo hello").dry_run(false).run()])
            .await
            .unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].stdout().trim(), "hello");
    }

    #[tokio::test]
    async fn try_join_all_multiple_futures_preserves_order() {
        let results = try_join_all(vec![
            Shell::new("echo one").dry_run(false).run(),
            Shell::new("echo two").dry_run(false).run(),
            Shell::new("echo three").dry_run(false).run(),
        ])
        .await
        .unwrap();

        assert_eq!(results.len(), 3);
        assert_eq!(results[0].stdout().trim(), "one");
        assert_eq!(results[1].stdout().trim(), "two");
        assert_eq!(results[2].stdout().trim(), "three");
    }

    #[tokio::test]
    async fn try_join_all_runs_concurrently() {
        let concurrent = Arc::new(AtomicUsize::new(0));
        let max_concurrent = Arc::new(AtomicUsize::new(0));

        let futs: Vec<_> = (0..3)
            .map(|i| {
                let concurrent = concurrent.clone();
                let max_concurrent = max_concurrent.clone();
                async move {
                    let current = concurrent.fetch_add(1, Ordering::SeqCst) + 1;
                    max_concurrent.fetch_max(current, Ordering::SeqCst);
                    let result = Shell::new(&format!("sleep 0.05 && echo {i}"))
                        .dry_run(false)
                        .run()
                        .await;
                    concurrent.fetch_sub(1, Ordering::SeqCst);
                    result
                }
            })
            .collect();

        let results = try_join_all(futs).await.unwrap();
        assert_eq!(results.len(), 3);
        // All 3 should run concurrently (no limit)
        assert!(
            max_concurrent.load(Ordering::SeqCst) >= 2,
            "expected concurrent execution, max concurrency was {}",
            max_concurrent.load(Ordering::SeqCst)
        );
    }

    #[tokio::test]
    async fn try_join_all_returns_first_error() {
        let result = try_join_all(vec![
            Shell::new("echo ok").dry_run(false).run(),
            Shell::new("exit 1").dry_run(false).run(),
            Shell::new("echo also ok").dry_run(false).run(),
        ])
        .await;

        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(matches!(err, OperationError::Shell { exit_code: 1, .. }));
    }

    #[tokio::test]
    async fn try_join_all_from_iterator() {
        let commands = ["echo alpha", "echo beta"];
        let results = try_join_all(commands.iter().map(|c| Shell::new(c).dry_run(false).run()))
            .await
            .unwrap();

        assert_eq!(results[0].stdout().trim(), "alpha");
        assert_eq!(results[1].stdout().trim(), "beta");
    }

    // --- try_join_all_limited ---

    #[tokio::test]
    async fn limited_empty_returns_empty_vec() {
        let result: Result<Vec<()>, OperationError> = try_join_all_limited(
            Vec::<Pin<Box<dyn Future<Output = Result<(), OperationError>> + Send>>>::new(),
            3,
        )
        .await;
        assert!(result.unwrap().is_empty());
    }

    #[tokio::test]
    async fn limited_preserves_order() {
        let results = try_join_all_limited(
            vec![
                Shell::new("echo one").dry_run(false).run(),
                Shell::new("echo two").dry_run(false).run(),
                Shell::new("echo three").dry_run(false).run(),
            ],
            2,
        )
        .await
        .unwrap();

        assert_eq!(results[0].stdout().trim(), "one");
        assert_eq!(results[1].stdout().trim(), "two");
        assert_eq!(results[2].stdout().trim(), "three");
    }

    #[tokio::test]
    async fn limited_respects_concurrency_limit() {
        let concurrent = Arc::new(AtomicUsize::new(0));
        let max_concurrent = Arc::new(AtomicUsize::new(0));

        let futs: Vec<_> = (0..6)
            .map(|i| {
                let concurrent = concurrent.clone();
                let max_concurrent = max_concurrent.clone();
                async move {
                    let current = concurrent.fetch_add(1, Ordering::SeqCst) + 1;
                    max_concurrent.fetch_max(current, Ordering::SeqCst);
                    let result = Shell::new(&format!("sleep 0.05 && echo {i}"))
                        .dry_run(false)
                        .run()
                        .await;
                    concurrent.fetch_sub(1, Ordering::SeqCst);
                    result
                }
            })
            .collect();

        let results = try_join_all_limited(futs, 2).await.unwrap();
        assert_eq!(results.len(), 6);
        assert!(
            max_concurrent.load(Ordering::SeqCst) <= 2,
            "max concurrency was {}, expected <= 2",
            max_concurrent.load(Ordering::SeqCst)
        );
    }

    #[tokio::test]
    async fn limited_returns_first_error() {
        let result = try_join_all_limited(
            vec![
                Shell::new("echo ok").dry_run(false).run(),
                Shell::new("exit 42").dry_run(false).run(),
                Shell::new("echo also ok").dry_run(false).run(),
            ],
            2,
        )
        .await;

        assert!(result.is_err());
    }

    #[tokio::test]
    #[should_panic(expected = "concurrency limit must be greater than 0")]
    async fn limited_zero_limit_panics() {
        let _: Result<Vec<()>, _> = try_join_all_limited(
            Vec::<Pin<Box<dyn Future<Output = Result<(), OperationError>> + Send>>>::new(),
            0,
        )
        .await;
    }

    #[tokio::test]
    async fn limited_with_limit_one_runs_sequentially() {
        let concurrent = Arc::new(AtomicUsize::new(0));
        let max_concurrent = Arc::new(AtomicUsize::new(0));

        let futs: Vec<_> = (0..3)
            .map(|i| {
                let concurrent = concurrent.clone();
                let max_concurrent = max_concurrent.clone();
                async move {
                    let current = concurrent.fetch_add(1, Ordering::SeqCst) + 1;
                    max_concurrent.fetch_max(current, Ordering::SeqCst);
                    let result = Shell::new(&format!("sleep 0.05 && echo {i}"))
                        .dry_run(false)
                        .run()
                        .await;
                    concurrent.fetch_sub(1, Ordering::SeqCst);
                    result
                }
            })
            .collect();

        let results = try_join_all_limited(futs, 1).await.unwrap();
        assert_eq!(results.len(), 3);
        // With limit=1, only 1 should run at a time
        assert_eq!(
            max_concurrent.load(Ordering::SeqCst),
            1,
            "expected max concurrency of 1, got {}",
            max_concurrent.load(Ordering::SeqCst)
        );
    }

    #[tokio::test]
    async fn limited_with_limit_greater_than_count() {
        let results = try_join_all_limited(
            vec![
                Shell::new("echo x").dry_run(false).run(),
                Shell::new("echo y").dry_run(false).run(),
            ],
            100,
        )
        .await
        .unwrap();

        assert_eq!(results.len(), 2);
        assert_eq!(results[0].stdout().trim(), "x");
        assert_eq!(results[1].stdout().trim(), "y");
    }
}