pipeline-toolkit 0.2.0

A small toolkit for building linear, async processing pipelines out of independently testable steps that communicate through a shared, type-keyed Context.
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
use std::any::TypeId;

use crate::Context;
use crate::branch::Arm;
use crate::context::AccessSpec;
use crate::pipeline::{
    BuildError, NestedPipelineError, PipelineError, qualify_step_name, run_steps,
};
use crate::step::{Flow, Step, StepError};

/// A `Loop`'s condition function, boxed so [`Loop`]/[`LoopBuilder`] don't
/// need to be generic over it.
type Condition = Box<dyn Fn(&Context, u32) -> bool + Send + Sync>;

/// A framework-provided [`Step`] that runs the same [`Arm`] body repeatedly,
/// do-while style, until a condition function says to stop or
/// `max_iterations` is reached.
///
/// Build one via [`Self::builder`]. Unlike [`Branch`](crate::Branch), which
/// picks one of several arms, `Loop` has exactly one body arm and runs it
/// one or more times against the same [`Context`].
///
/// # Evaluation order
///
/// The body always runs at least once. After each run, if the body returned
/// [`Flow::Done`], that value is produced immediately, short-circuiting the
/// loop (and the whole pipeline) just like a top-level step would. If the
/// body returned [`Flow::Continue`], the condition function is called with
/// the [`Context`] and the 1-based iteration number just completed; a
/// `false` result stops the loop (`Loop::run` itself then returns
/// [`Flow::Continue`], handing off to whatever follows the loop in the
/// enclosing pipeline), while `true` runs the body again. If the condition
/// never returns `false` within `max_iterations` runs,
/// [`PipelineError::MaxIterationsExceeded`](crate::PipelineError::MaxIterationsExceeded)
/// is returned instead.
///
/// A body `Err` is never passed to the condition function — it propagates
/// immediately as an ordinary step failure, the same as any other step's
/// error. See the [design doc](https://github.com/ryoshrimp/pipeline-toolkit/blob/main/docs/design/iteration.md)
/// for the rationale (in particular, why retry-worthy failures must be
/// signalled through the `Context` rather than through `Err`).
///
/// # Access declaration
///
/// A `Loop`'s [`Step::access`] is computed automatically from its body (plus
/// the condition function's own declared reads, via
/// [`LoopBuilder::reads`]) — unlike [`Branch`](crate::Branch), no
/// union/intersection is needed, since a `Loop` has only one body and that
/// body is guaranteed (see [`Self::builder`]) to leave its own effective
/// access stable across repeated runs:
///
/// - **reads** = the body's effective reads + the condition's declared reads
/// - **writes** = the body's effective writes
/// - **consumes** = the body's effective consumes
///
/// # Examples
///
/// ```
/// use pipeline_toolkit::{AccessSpec, Arm, Context, Flow, Loop, Pipeline, Step, StepError};
///
/// struct Counter(i32);
///
/// struct Increment;
///
/// #[async_trait::async_trait]
/// impl Step<i32> for Increment {
///     fn name(&self) -> &str {
///         "increment"
///     }
///     fn access(&self) -> AccessSpec {
///         AccessSpec::new().reads_writes::<Counter>()
///     }
///     async fn run(&self, ctx: &mut Context) -> Result<Flow<i32>, StepError> {
///         ctx.get_mut::<Counter>().expect("declared as reads_writes").0 += 1;
///         Ok(Flow::Continue)
///     }
/// }
///
/// let body = Arm::builder().step(Increment).build()?;
/// let count_to_three = Loop::builder(
///     "count_to_three",
///     body,
///     |ctx: &Context, _iteration: u32| ctx.get::<Counter>().expect("declared as read").0 < 3,
///     10,
/// )
/// .reads::<Counter>()
/// .build()?;
///
/// struct Init;
/// #[async_trait::async_trait]
/// impl Step<i32> for Init {
///     fn name(&self) -> &str {
///         "init"
///     }
///     fn access(&self) -> AccessSpec {
///         AccessSpec::new().writes::<Counter>()
///     }
///     async fn run(&self, ctx: &mut Context) -> Result<Flow<i32>, StepError> {
///         ctx.insert(Counter(0));
///         Ok(Flow::Continue)
///     }
/// }
///
/// struct Finish;
/// #[async_trait::async_trait]
/// impl Step<i32> for Finish {
///     fn name(&self) -> &str {
///         "finish"
///     }
///     fn access(&self) -> AccessSpec {
///         AccessSpec::new().reads::<Counter>()
///     }
///     async fn run(&self, ctx: &mut Context) -> Result<Flow<i32>, StepError> {
///         Ok(Flow::Done(ctx.get::<Counter>().expect("declared as read").0))
///     }
/// }
///
/// let pipeline = Pipeline::<(), i32>::builder()
///     .step(Init)
///     .step(count_to_three)
///     .step(Finish)
///     .build()?;
///
/// # fn block_on<F: std::future::Future>(fut: F) -> F::Output {
/// #     use std::task::{Context as TaskContext, Poll, Waker};
/// #     let mut fut = std::pin::pin!(fut);
/// #     let mut cx = TaskContext::from_waker(Waker::noop());
/// #     loop {
/// #         if let Poll::Ready(val) = fut.as_mut().poll(&mut cx) {
/// #             return val;
/// #         }
/// #     }
/// # }
/// #
/// assert_eq!(block_on(pipeline.run(()))?, 3);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub struct Loop<Out> {
    name: String,
    body: Arm<Out>,
    condition: Condition,
    max_iterations: u32,
    access: AccessSpec,
}

impl<Out> Loop<Out> {
    /// Starts building a `Loop` named `name`, whose body is `body` and whose
    /// continuation is decided by calling `condition` against the shared
    /// [`Context`] and the 1-based number of the iteration just completed,
    /// after every run of `body` that returns [`Flow::Continue`].
    ///
    /// `max_iterations` is the upper bound on how many times `body` may run
    /// before [`Loop::run`] gives up with
    /// [`PipelineError::MaxIterationsExceeded`](crate::PipelineError::MaxIterationsExceeded).
    /// It's a required constructor argument rather than a builder default,
    /// since an unbounded loop is a production hazard (hang, resource leak)
    /// that's cheap to guard against statically.
    ///
    /// If `condition` itself reads from the [`Context`], declare that via
    /// [`LoopBuilder::reads`] — it is not inferred automatically, since a
    /// closure's body can't be introspected.
    pub fn builder(
        name: impl Into<String>,
        body: Arm<Out>,
        condition: impl Fn(&Context, u32) -> bool + Send + Sync + 'static,
        max_iterations: u32,
    ) -> LoopBuilder<Out> {
        LoopBuilder {
            name: name.into(),
            body,
            condition: Box::new(condition),
            condition_access: AccessSpec::new(),
            max_iterations,
        }
    }
}

#[async_trait::async_trait]
impl<Out> Step<Out> for Loop<Out>
where
    Out: Send + Sync + 'static,
{
    fn name(&self) -> &str {
        &self.name
    }

    fn access(&self) -> AccessSpec {
        self.access.clone()
    }

    async fn run(&self, ctx: &mut Context) -> Result<Flow<Out>, StepError> {
        for iteration in 1..=self.max_iterations {
            match run_steps(self.body.steps(), ctx).await {
                Ok(Flow::Done(out)) => return Ok(Flow::Done(out)),
                Ok(Flow::Continue) => {
                    if !(self.condition)(ctx, iteration) {
                        return Ok(Flow::Continue);
                    }
                }
                Err(err) => {
                    return Err(StepError::new(NestedPipelineError(qualify_step_name(
                        &self.name, err,
                    ))));
                }
            }
        }
        Err(StepError::new(NestedPipelineError(
            PipelineError::MaxIterationsExceeded {
                step: self.name.clone(),
                max_iterations: self.max_iterations,
            },
        )))
    }
}

/// Incrementally assembles a [`Loop`], returned by [`Loop::builder`].
pub struct LoopBuilder<Out> {
    name: String,
    body: Arm<Out>,
    condition: Condition,
    condition_access: AccessSpec,
    max_iterations: u32,
}

impl<Out> LoopBuilder<Out> {
    /// Declares that the condition function reads `T` from the [`Context`]
    /// when it runs, folding it into the reads computed for
    /// [`Step::access`]. Chainable across multiple types, like
    /// [`AccessSpec::reads`].
    pub fn reads<T: 'static>(mut self) -> Self {
        self.condition_access = self.condition_access.reads::<T>();
        self
    }

    /// Finishes this `Loop`, computing its [`Step::access`] from the body's
    /// effective access plus the condition's own declared reads.
    ///
    /// # Errors
    ///
    /// - [`BuildError::UnrepeatableConsume`] if the body consumes (via
    ///   [`AccessSpec::consumes`]) a type it doesn't also write again by the
    ///   time it finishes — such a body would work on the first iteration
    ///   but find that type gone on the second, since the same body runs
    ///   more than once.
    pub fn build(self) -> Result<Loop<Out>, BuildError> {
        let effective = self.body.effective_access();
        let mut missing: Vec<(TypeId, &'static str)> = effective
            .consumes
            .iter()
            .filter(|(id, _)| !effective.writes.contains_key(id))
            .map(|(id, name)| (*id, *name))
            .collect();
        if !missing.is_empty() {
            missing.sort_unstable_by_key(|(_, name)| *name);
            let (_, entry) = missing[0];
            return Err(BuildError::UnrepeatableConsume {
                step: self.name,
                entry,
            });
        }

        let mut access = self.condition_access;
        access.extend_reads(effective.reads.iter().map(|(id, name)| (*id, *name)));
        access.extend_writes(effective.writes.iter().map(|(id, name)| (*id, *name)));
        // A type that's also in `effective.writes` is guaranteed present
        // once the body finishes (the `UnrepeatableConsume` check above
        // ensures every consumed type meets this), so it must not be
        // declared as consumed here too: PipelineBuilder::build applies a
        // step's declared writes before its declared consumes, so a type
        // present in both would have its guaranteed write immediately
        // undone by the same step's own consume, making the outer pipeline
        // wrongly see it as unavailable to a step downstream of this Loop.
        access.extend_consumes(
            effective
                .consumes
                .iter()
                .filter(|(id, _)| !effective.writes.contains_key(id))
                .map(|(id, name)| (*id, *name)),
        );

        Ok(Loop {
            name: self.name,
            body: self.body,
            condition: self.condition,
            max_iterations: self.max_iterations,
            access,
        })
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::step::Flow;
    use crate::test_support::block_on;

    struct Counter(i32);

    struct Increment;

    #[async_trait::async_trait]
    impl Step<i32> for Increment {
        fn name(&self) -> &str {
            "increment"
        }
        fn access(&self) -> AccessSpec {
            AccessSpec::new().reads_writes::<Counter>()
        }
        async fn run(&self, ctx: &mut Context) -> Result<Flow<i32>, StepError> {
            ctx.get_mut::<Counter>()
                .expect("declared as reads_writes")
                .0 += 1;
            Ok(Flow::Continue)
        }
    }

    fn increment_body() -> Arm<i32> {
        Arm::builder().step(Increment).build().unwrap()
    }

    fn less_than(limit: i32) -> impl Fn(&Context, u32) -> bool + Send + Sync + 'static {
        move |ctx: &Context, _iteration: u32| {
            ctx.get::<Counter>().expect("declared as read").0 < limit
        }
    }

    #[test]
    fn build_fails_when_body_consumes_a_type_it_never_rewrites() {
        struct Token;

        struct ConsumeToken;
        #[async_trait::async_trait]
        impl Step<i32> for ConsumeToken {
            fn name(&self) -> &str {
                "consume_token"
            }
            fn access(&self) -> AccessSpec {
                AccessSpec::new().consumes::<Token>()
            }
            async fn run(&self, ctx: &mut Context) -> Result<Flow<i32>, StepError> {
                ctx.take::<Token>();
                Ok(Flow::Continue)
            }
        }

        let body = Arm::<i32>::builder().step(ConsumeToken).build().unwrap();
        let result = Loop::builder("loop", body, |_ctx: &Context, _i: u32| false, 5).build();
        assert!(matches!(
            result,
            Err(BuildError::UnrepeatableConsume { step, .. }) if step == "loop"
        ));
    }

    #[test]
    fn build_succeeds_when_body_rewrites_a_type_it_consumed() {
        struct Token;

        struct ConsumeToken;
        #[async_trait::async_trait]
        impl Step<i32> for ConsumeToken {
            fn name(&self) -> &str {
                "consume_token"
            }
            fn access(&self) -> AccessSpec {
                AccessSpec::new().consumes::<Token>()
            }
            async fn run(&self, ctx: &mut Context) -> Result<Flow<i32>, StepError> {
                ctx.take::<Token>();
                Ok(Flow::Continue)
            }
        }

        struct RewriteToken;
        #[async_trait::async_trait]
        impl Step<i32> for RewriteToken {
            fn name(&self) -> &str {
                "rewrite_token"
            }
            fn access(&self) -> AccessSpec {
                AccessSpec::new().writes::<Token>()
            }
            async fn run(&self, ctx: &mut Context) -> Result<Flow<i32>, StepError> {
                ctx.insert(Token);
                Ok(Flow::Continue)
            }
        }

        let body = Arm::<i32>::builder()
            .step(ConsumeToken)
            .step(RewriteToken)
            .build()
            .unwrap();
        let result = Loop::builder("loop", body, |_ctx: &Context, _i: u32| false, 5).build();
        assert!(result.is_ok());
    }

    #[test]
    fn run_executes_body_the_correct_number_of_times_until_condition_is_false() {
        let body = increment_body();
        let looped = Loop::builder("loop", body, less_than(3), 10)
            .reads::<Counter>()
            .build()
            .unwrap();

        let mut ctx = Context::new();
        ctx.insert(Counter(0));
        let result = block_on(looped.run(&mut ctx));
        assert!(matches!(result, Ok(Flow::Continue)));
        assert_eq!(ctx.get::<Counter>().unwrap().0, 3);
    }

    #[test]
    fn run_fails_with_max_iterations_exceeded_when_condition_never_becomes_false() {
        let body = increment_body();
        let looped = Loop::builder("loop", body, |_ctx: &Context, _i: u32| true, 3)
            .build()
            .unwrap();

        let mut ctx = Context::new();
        ctx.insert(Counter(0));
        let err = match block_on(looped.run(&mut ctx)) {
            Err(err) => err,
            Ok(_) => panic!("expected Err"),
        };
        let nested = err
            .downcast::<NestedPipelineError>()
            .unwrap_or_else(|_| panic!("expected a NestedPipelineError"));
        match nested.0 {
            PipelineError::MaxIterationsExceeded {
                step,
                max_iterations,
            } => {
                assert_eq!(step, "loop");
                assert_eq!(max_iterations, 3);
            }
            other => panic!("expected MaxIterationsExceeded, got {other}"),
        }
        assert_eq!(ctx.get::<Counter>().unwrap().0, 3);
    }

    #[test]
    fn run_propagates_a_body_err_immediately_without_consulting_the_condition() {
        struct Fail;
        #[async_trait::async_trait]
        impl Step<i32> for Fail {
            fn name(&self) -> &str {
                "fail"
            }
            fn access(&self) -> AccessSpec {
                AccessSpec::new()
            }
            async fn run(&self, _ctx: &mut Context) -> Result<Flow<i32>, StepError> {
                Err(StepError::new("boom"))
            }
        }

        let body = Arm::<i32>::builder().step(Fail).build().unwrap();
        let looped = Loop::builder(
            "loop",
            body,
            |_ctx: &Context, _i: u32| {
                panic!("condition must not be consulted when the body errors")
            },
            5,
        )
        .build()
        .unwrap();

        let mut ctx = Context::new();
        let err = match block_on(looped.run(&mut ctx)) {
            Err(err) => err,
            Ok(_) => panic!("expected Err"),
        };
        let nested = err
            .downcast::<NestedPipelineError>()
            .unwrap_or_else(|_| panic!("expected a NestedPipelineError"));
        match nested.0 {
            PipelineError::Step { step, .. } => assert_eq!(step, "loop/fail"),
            other => panic!("expected Step, got {other}"),
        }
    }

    #[test]
    fn run_propagates_a_body_done_to_the_outer_caller() {
        struct DoneStep(i32);
        #[async_trait::async_trait]
        impl Step<i32> for DoneStep {
            fn name(&self) -> &str {
                "done"
            }
            fn access(&self) -> AccessSpec {
                AccessSpec::new()
            }
            async fn run(&self, _ctx: &mut Context) -> Result<Flow<i32>, StepError> {
                Ok(Flow::Done(self.0))
            }
        }

        let body = Arm::<i32>::builder().step(DoneStep(99)).build().unwrap();
        let looped = Loop::builder(
            "loop",
            body,
            |_ctx: &Context, _i: u32| {
                panic!("condition must not be consulted when the body is Done")
            },
            5,
        )
        .build()
        .unwrap();

        let mut ctx = Context::new();
        match block_on(looped.run(&mut ctx)) {
            Ok(Flow::Done(v)) => assert_eq!(v, 99),
            Ok(Flow::Continue) => panic!("expected Done(99), got Continue"),
            Err(err) => panic!("expected Done(99), got Err({err})"),
        }
    }

    #[test]
    fn run_passes_the_1_based_iteration_number_to_the_condition() {
        use std::sync::{Arc, Mutex};

        let seen = Arc::new(Mutex::new(Vec::new()));
        let seen_in_condition = seen.clone();

        let body = increment_body();
        let looped = Loop::builder(
            "loop",
            body,
            move |_ctx: &Context, iteration: u32| {
                seen_in_condition.lock().unwrap().push(iteration);
                iteration < 3
            },
            10,
        )
        .build()
        .unwrap();

        let mut ctx = Context::new();
        ctx.insert(Counter(0));
        block_on(looped.run(&mut ctx)).unwrap();
        assert_eq!(*seen.lock().unwrap(), vec![1, 2, 3]);
    }

    #[test]
    fn access_reads_is_union_of_body_needed_reads_and_condition_declared_reads() {
        struct Other;
        struct ReadsOther;
        #[async_trait::async_trait]
        impl Step<i32> for ReadsOther {
            fn name(&self) -> &str {
                "reads_other"
            }
            fn access(&self) -> AccessSpec {
                AccessSpec::new().reads::<Other>()
            }
            async fn run(&self, _ctx: &mut Context) -> Result<Flow<i32>, StepError> {
                Ok(Flow::Continue)
            }
        }

        let body = Arm::<i32>::builder().step(ReadsOther).build().unwrap();
        let looped = Loop::builder("loop", body, |_ctx: &Context, _i: u32| false, 5)
            .reads::<Counter>()
            .build()
            .unwrap();

        let access = looped.access();
        assert!(access.can_read(TypeId::of::<Other>()));
        assert!(access.can_read(TypeId::of::<Counter>()));
    }

    #[test]
    fn access_does_not_declare_consumed_when_the_body_also_rewrites_it() {
        // LoopBuilder::build's UnrepeatableConsume check (see the
        // build_fails/build_succeeds tests above) means any type that
        // survives in the body's effective consumes is, by construction,
        // also in its effective writes. Declaring it as consumed on the
        // Loop's own access anyway would be actively wrong, not just
        // redundant: PipelineBuilder::build applies a step's declared
        // writes before its declared consumes, so a type present in both
        // would have its guaranteed write immediately undone by the same
        // step's own consume - making a step downstream of this Loop that
        // reads Consumed fail to build even though the Loop always leaves
        // Consumed behind.
        struct Written;
        struct Consumed;

        struct WriteAndConsume;
        #[async_trait::async_trait]
        impl Step<i32> for WriteAndConsume {
            fn name(&self) -> &str {
                "write_and_consume"
            }
            fn access(&self) -> AccessSpec {
                AccessSpec::new().writes::<Written>().consumes::<Consumed>()
            }
            async fn run(&self, _ctx: &mut Context) -> Result<Flow<i32>, StepError> {
                Ok(Flow::Continue)
            }
        }
        struct RewriteConsumed;
        #[async_trait::async_trait]
        impl Step<i32> for RewriteConsumed {
            fn name(&self) -> &str {
                "rewrite_consumed"
            }
            fn access(&self) -> AccessSpec {
                AccessSpec::new().writes::<Consumed>()
            }
            async fn run(&self, _ctx: &mut Context) -> Result<Flow<i32>, StepError> {
                Ok(Flow::Continue)
            }
        }

        let body = Arm::<i32>::builder()
            .step(WriteAndConsume)
            .step(RewriteConsumed)
            .build()
            .unwrap();
        let looped = Loop::builder("loop", body, |_ctx: &Context, _i: u32| false, 5)
            .build()
            .unwrap();

        let access = looped.access();
        assert!(access.can_write(TypeId::of::<Written>()));
        assert!(access.can_write(TypeId::of::<Consumed>()));
        assert!(!access.can_consume(TypeId::of::<Consumed>()));
    }
}