Skip to main content

Loop

Struct Loop 

Source
pub struct Loop<Out> { /* private fields */ }
Expand description

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, 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 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 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, 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()?;

assert_eq!(block_on(pipeline.run(()))?, 3);

Implementations§

Source§

impl<Out> Loop<Out>

Source

pub fn builder( name: impl Into<String>, body: Arm<Out>, condition: impl Fn(&Context, u32) -> bool + Send + Sync + 'static, max_iterations: u32, ) -> LoopBuilder<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. 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.

Trait Implementations§

Source§

impl<Out> Step<Out> for Loop<Out>
where Out: Send + Sync + 'static,

Source§

fn name(&self) -> &str

Must consistently return the same value for the lifetime of the step. PipelineBuilder::build calls this once and reuses the result for the rest of the pipeline’s life instead of calling it again at run time.
Source§

fn access(&self) -> AccessSpec

Must consistently return an equivalent AccessSpec for the lifetime of the step, for the same reason as Self::name.
Source§

fn run<'life0, 'life1, 'async_trait>( &'life0 self, ctx: &'life1 mut Context, ) -> Pin<Box<dyn Future<Output = Result<Flow<Out>, StepError>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait,

Performs this step’s work against the shared context. Read more

Auto Trait Implementations§

§

impl<Out> !RefUnwindSafe for Loop<Out>

§

impl<Out> !UnwindSafe for Loop<Out>

§

impl<Out> Freeze for Loop<Out>
where Arm<Out>: Freeze,

§

impl<Out> Send for Loop<Out>
where Arm<Out>: Send,

§

impl<Out> Sync for Loop<Out>
where Arm<Out>: Sync,

§

impl<Out> Unpin for Loop<Out>
where Arm<Out>: Unpin,

§

impl<Out> UnsafeUnpin for Loop<Out>
where Arm<Out>: UnsafeUnpin,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.