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};
type Condition = Box<dyn Fn(&Context, u32) -> bool + Send + Sync>;
pub struct Loop<Out> {
name: String,
body: Arm<Out>,
condition: Condition,
max_iterations: u32,
access: AccessSpec,
}
impl<Out> Loop<Out> {
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,
},
)))
}
}
pub struct LoopBuilder<Out> {
name: String,
body: Arm<Out>,
condition: Condition,
condition_access: AccessSpec,
max_iterations: u32,
}
impl<Out> LoopBuilder<Out> {
pub fn reads<T: 'static>(mut self) -> Self {
self.condition_access = self.condition_access.reads::<T>();
self
}
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)));
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() {
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>()));
}
}