use std::any::TypeId;
use std::collections::{HashMap, HashSet};
use std::hash::Hash;
use crate::Context;
use crate::context::AccessSpec;
use crate::pipeline::{
BuildError, CompiledStep, NestedPipelineError, PipelineError, qualify_step_name, run_steps,
};
use crate::step::{Flow, Step, StepError};
pub struct Arm<Out> {
steps: Vec<CompiledStep<Out>>,
effective: EffectiveAccess,
}
impl<Out> Arm<Out> {
pub fn builder() -> ArmBuilder<Out> {
ArmBuilder { steps: Vec::new() }
}
pub(crate) fn effective_access(&self) -> &EffectiveAccess {
&self.effective
}
pub(crate) fn steps(&self) -> &[CompiledStep<Out>] {
&self.steps
}
}
pub(crate) struct EffectiveAccess {
pub(crate) reads: HashMap<TypeId, &'static str>,
pub(crate) writes: HashMap<TypeId, &'static str>,
pub(crate) consumes: HashMap<TypeId, &'static str>,
}
fn compute_effective_access<Out>(
steps: &[CompiledStep<Out>],
) -> Result<EffectiveAccess, BuildError> {
let mut written: HashMap<TypeId, &'static str> = HashMap::new();
let mut ever_produced: HashSet<TypeId> = HashSet::new();
let mut needed_reads: HashMap<TypeId, &'static str> = HashMap::new();
let mut all_consumed: HashMap<TypeId, &'static str> = HashMap::new();
for step in steps {
let mut lost: Vec<(TypeId, &'static str)> = Vec::new();
let mut first_time: Vec<(TypeId, &'static str)> = Vec::new();
for (id, name) in step.access.read_entries() {
if written.contains_key(&id) {
continue;
}
if ever_produced.contains(&id) {
lost.push((id, name));
} else {
first_time.push((id, name));
}
}
if !lost.is_empty() {
lost.sort_unstable_by_key(|(_, name)| *name);
let (_, entry) = lost[0];
return Err(BuildError::UnsatisfiedRead {
step: step.name.clone(),
entry,
});
}
for (id, name) in first_time {
needed_reads.insert(id, name);
}
for (id, name) in step.access.write_entries() {
written.insert(id, name);
ever_produced.insert(id);
}
for (id, name) in step.access.consume_entries() {
all_consumed.insert(id, name);
written.remove(&id);
}
}
Ok(EffectiveAccess {
reads: needed_reads,
writes: written,
consumes: all_consumed,
})
}
pub struct ArmBuilder<Out> {
steps: Vec<Box<dyn Step<Out>>>,
}
impl<Out> ArmBuilder<Out> {
pub fn step(mut self, step: impl Step<Out> + 'static) -> Self {
self.steps.push(Box::new(step));
self
}
pub fn build(self) -> Result<Arm<Out>, BuildError> {
let mut names = HashSet::new();
let mut steps = Vec::with_capacity(self.steps.len());
for step in self.steps {
let name = step.name().to_string();
if !names.insert(name.clone()) {
return Err(BuildError::DuplicateName { name });
}
let access = step.access();
steps.push(CompiledStep { name, access, step });
}
let effective = compute_effective_access(&steps)?;
Ok(Arm { steps, effective })
}
}
pub struct Branch<K, Out> {
name: String,
condition: Box<dyn Fn(&Context) -> K + Send + Sync>,
arms: HashMap<K, Arm<Out>>,
access: AccessSpec,
}
impl<K, Out> Branch<K, Out> {
pub fn builder(
name: impl Into<String>,
condition: impl Fn(&Context) -> K + Send + Sync + 'static,
) -> BranchBuilder<K, Out> {
BranchBuilder {
name: name.into(),
condition: Box::new(condition),
condition_access: AccessSpec::new(),
arms: HashMap::new(),
}
}
}
#[async_trait::async_trait]
impl<K, Out> Step<Out> for Branch<K, Out>
where
K: Eq + Hash + Send + Sync + 'static,
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> {
let key = (self.condition)(ctx);
let Some(arm) = self.arms.get(&key) else {
return Err(StepError::new(NestedPipelineError(
PipelineError::NoMatchingBranch {
step: self.name.clone(),
},
)));
};
run_steps(&arm.steps, ctx)
.await
.map_err(|err| StepError::new(NestedPipelineError(qualify_step_name(&self.name, err))))
}
}
pub struct BranchBuilder<K, Out> {
name: String,
condition: Box<dyn Fn(&Context) -> K + Send + Sync>,
condition_access: AccessSpec,
arms: HashMap<K, Arm<Out>>,
}
impl<K: Eq + Hash, Out> BranchBuilder<K, Out> {
pub fn reads<T: 'static>(mut self) -> Self {
self.condition_access = self.condition_access.reads::<T>();
self
}
pub fn arm(mut self, key: K, arm: Arm<Out>) -> Self {
self.arms.insert(key, arm);
self
}
pub fn build(self) -> Result<Branch<K, Out>, BuildError> {
if self.arms.is_empty() {
return Err(BuildError::EmptyBranch { step: self.name });
}
let mut reads_union: HashMap<TypeId, &'static str> = HashMap::new();
let mut consumes_union: HashMap<TypeId, &'static str> = HashMap::new();
let mut writes_intersection: Option<HashMap<TypeId, &'static str>> = None;
for arm in self.arms.values() {
let effective = arm.effective_access();
reads_union.extend(effective.reads.iter().map(|(id, name)| (*id, *name)));
consumes_union.extend(effective.consumes.iter().map(|(id, name)| (*id, *name)));
writes_intersection = Some(match writes_intersection {
None => effective.writes.clone(),
Some(acc) => acc
.into_iter()
.filter(|(id, _)| effective.writes.contains_key(id))
.collect(),
});
}
let writes_intersection = writes_intersection.unwrap_or_default();
let mut access = self.condition_access;
access.extend_reads(reads_union);
access.extend_consumes(
consumes_union
.into_iter()
.filter(|(id, _)| !writes_intersection.contains_key(id)),
);
access.extend_writes(writes_intersection);
Ok(Branch {
name: self.name,
condition: self.condition,
arms: self.arms,
access,
})
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::step::Flow;
use crate::test_support::block_on;
struct Alpha;
struct Beta;
struct FixedAccessStep {
access: AccessSpec,
}
#[async_trait::async_trait]
impl Step<i32> for FixedAccessStep {
fn name(&self) -> &str {
"fixed"
}
fn access(&self) -> AccessSpec {
self.access.clone()
}
async fn run(&self, _ctx: &mut Context) -> Result<Flow<i32>, StepError> {
Ok(Flow::Continue)
}
}
fn arm_with(access: AccessSpec) -> Arm<i32> {
Arm::builder()
.step(FixedAccessStep { access })
.build()
.unwrap()
}
#[test]
fn build_computes_reads_as_union_of_arms_needed_reads() {
let branch = Branch::<u8, i32>::builder("route", |_ctx: &Context| 0u8)
.arm(0, arm_with(AccessSpec::new().reads::<Alpha>()))
.arm(1, arm_with(AccessSpec::new().reads::<Beta>()))
.build()
.unwrap();
let access = branch.access();
assert!(access.can_read(TypeId::of::<Alpha>()));
assert!(access.can_read(TypeId::of::<Beta>()));
}
#[test]
fn build_folds_the_condition_functions_own_declared_reads_into_the_union() {
let branch = Branch::<u8, i32>::builder("route", |_ctx: &Context| 0u8)
.reads::<Alpha>()
.arm(0, arm_with(AccessSpec::new()))
.build()
.unwrap();
assert!(branch.access().can_read(TypeId::of::<Alpha>()));
}
#[test]
fn build_computes_writes_as_intersection_of_arms_writes() {
let branch = Branch::<u8, i32>::builder("route", |_ctx: &Context| 0u8)
.arm(
0,
arm_with(AccessSpec::new().writes::<Alpha>().writes::<Beta>()),
)
.arm(1, arm_with(AccessSpec::new().writes::<Alpha>()))
.build()
.unwrap();
let access = branch.access();
assert!(access.can_write(TypeId::of::<Alpha>()));
assert!(!access.can_write(TypeId::of::<Beta>()));
}
#[test]
fn build_computes_consumes_as_union_of_arms_consumes() {
let branch = Branch::<u8, i32>::builder("route", |_ctx: &Context| 0u8)
.arm(0, arm_with(AccessSpec::new().consumes::<Alpha>()))
.arm(1, arm_with(AccessSpec::new().consumes::<Beta>()))
.build()
.unwrap();
let access = branch.access();
assert!(access.can_consume(TypeId::of::<Alpha>()));
assert!(access.can_consume(TypeId::of::<Beta>()));
}
#[test]
fn arm_build_fails_when_a_later_step_reads_a_type_this_arm_already_consumed() {
struct ConsumeAlpha;
#[async_trait::async_trait]
impl Step<i32> for ConsumeAlpha {
fn name(&self) -> &str {
"consume_alpha"
}
fn access(&self) -> AccessSpec {
AccessSpec::new().consumes::<Alpha>()
}
async fn run(&self, ctx: &mut Context) -> Result<Flow<i32>, StepError> {
ctx.take::<Alpha>();
Ok(Flow::Continue)
}
}
struct ReadAlphaAgain;
#[async_trait::async_trait]
impl Step<i32> for ReadAlphaAgain {
fn name(&self) -> &str {
"read_alpha_again"
}
fn access(&self) -> AccessSpec {
AccessSpec::new().reads::<Alpha>()
}
async fn run(&self, _ctx: &mut Context) -> Result<Flow<i32>, StepError> {
Ok(Flow::Continue)
}
}
let result = Arm::<i32>::builder()
.step(ConsumeAlpha)
.step(ReadAlphaAgain)
.build();
assert!(matches!(
result,
Err(BuildError::UnsatisfiedRead { step, .. }) if step == "read_alpha_again"
));
}
#[test]
fn arm_build_succeeds_when_a_read_after_consume_is_needed_from_outside_the_arm() {
let result = Arm::<i32>::builder()
.step(FixedAccessStep {
access: AccessSpec::new().reads::<Alpha>(),
})
.build();
assert!(result.is_ok());
}
#[test]
fn arm_build_treats_a_read_as_satisfied_by_an_earlier_write_in_the_same_arm() {
struct WriteThenReadAlpha;
#[async_trait::async_trait]
impl Step<i32> for WriteThenReadAlpha {
fn name(&self) -> &str {
"write_alpha"
}
fn access(&self) -> AccessSpec {
AccessSpec::new().writes::<Alpha>()
}
async fn run(&self, _ctx: &mut Context) -> Result<Flow<i32>, StepError> {
Ok(Flow::Continue)
}
}
struct ReadAlpha;
#[async_trait::async_trait]
impl Step<i32> for ReadAlpha {
fn name(&self) -> &str {
"read_alpha"
}
fn access(&self) -> AccessSpec {
AccessSpec::new().reads::<Alpha>()
}
async fn run(&self, _ctx: &mut Context) -> Result<Flow<i32>, StepError> {
Ok(Flow::Continue)
}
}
let arm = Arm::<i32>::builder()
.step(WriteThenReadAlpha)
.step(ReadAlpha)
.build()
.unwrap();
let branch = Branch::<u8, i32>::builder("route", |_ctx: &Context| 0u8)
.arm(0, arm)
.build()
.unwrap();
assert!(!branch.access().can_read(TypeId::of::<Alpha>()));
}
#[test]
fn arm_build_fails_on_duplicate_step_names() {
let result = Arm::<i32>::builder()
.step(FixedAccessStep {
access: AccessSpec::new(),
})
.step(FixedAccessStep {
access: AccessSpec::new(),
})
.build();
assert!(matches!(result, Err(BuildError::DuplicateName { name }) if name == "fixed"));
}
#[test]
fn branch_build_fails_when_no_arms_registered() {
let result = Branch::<u8, i32>::builder("route", |_ctx: &Context| 0u8).build();
assert!(matches!(result, Err(BuildError::EmptyBranch { step }) if step == "route"));
}
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))
}
}
#[test]
fn run_dispatches_to_the_arm_matching_the_condition_key() {
let branch: Branch<u8, i32> = Branch::builder("route", |_ctx: &Context| 1u8)
.arm(0, Arm::builder().step(DoneStep(100)).build().unwrap())
.arm(1, Arm::builder().step(DoneStep(200)).build().unwrap())
.build()
.unwrap();
let mut ctx = Context::new();
match block_on(branch.run(&mut ctx)) {
Ok(Flow::Done(v)) => assert_eq!(v, 200),
Ok(Flow::Continue) => panic!("expected Done(200), got Continue"),
Err(err) => panic!("expected Done(200), got Err({err})"),
}
}
#[test]
fn run_returns_err_wrapping_no_matching_branch_when_key_has_no_arm() {
let branch: Branch<u8, i32> = Branch::builder("route", |_ctx: &Context| 9u8)
.arm(0, Arm::builder().step(DoneStep(1)).build().unwrap())
.build()
.unwrap();
let mut ctx = Context::new();
let err = match block_on(branch.run(&mut ctx)) {
Err(err) => err,
Ok(_) => panic!("expected Err: no arm matches key 9"),
};
let nested = err
.downcast::<NestedPipelineError>()
.unwrap_or_else(|_| panic!("expected a NestedPipelineError"));
match nested.0 {
PipelineError::NoMatchingBranch { step } => assert_eq!(step, "route"),
other => panic!("expected NoMatchingBranch, got {other}"),
}
}
#[test]
fn run_qualifies_a_step_error_from_within_an_arm_with_the_branch_name() {
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 branch: Branch<u8, i32> = Branch::builder("route", |_ctx: &Context| 0u8)
.arm(0, Arm::builder().step(Fail).build().unwrap())
.build()
.unwrap();
let mut ctx = Context::new();
let err = match block_on(branch.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, "route/fail"),
other => panic!("expected Step, got {other}"),
}
}
#[test]
fn run_qualifies_an_access_violation_from_within_an_arm_with_the_branch_name() {
struct RogueRead;
#[async_trait::async_trait]
impl Step<i32> for RogueRead {
fn name(&self) -> &str {
"rogue_read"
}
fn access(&self) -> AccessSpec {
AccessSpec::new()
}
async fn run(&self, ctx: &mut Context) -> Result<Flow<i32>, StepError> {
let _ = ctx.get::<Alpha>();
Ok(Flow::Continue)
}
}
let branch: Branch<u8, i32> = Branch::builder("route", |_ctx: &Context| 0u8)
.arm(0, Arm::builder().step(RogueRead).build().unwrap())
.build()
.unwrap();
let mut ctx = Context::new();
let err = match block_on(branch.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::AccessViolation(v) => assert_eq!(v.step, "route/rogue_read"),
other => panic!("expected AccessViolation, got {other}"),
}
}
#[test]
fn run_qualifies_a_nested_no_matching_branch_error_with_both_branch_names() {
let inner: Branch<u8, i32> = Branch::builder("inner", |_ctx: &Context| 9u8)
.arm(0, Arm::builder().step(DoneStep(1)).build().unwrap())
.build()
.unwrap();
let outer: Branch<u8, i32> = Branch::builder("outer", |_ctx: &Context| 0u8)
.arm(0, Arm::builder().step(inner).build().unwrap())
.build()
.unwrap();
let mut ctx = Context::new();
let err = match block_on(outer.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::NoMatchingBranch { step } => assert_eq!(step, "outer/inner"),
other => panic!("expected NoMatchingBranch, got {other}"),
}
}
}