#[cfg(test)]
use crate::context::AccessKind;
use crate::context::{AccessSpec, AccessViolation, Context};
use crate::step::{Flow, Step, StepError};
use std::any::TypeId;
use std::collections::{HashMap, HashSet};
#[derive(Debug, thiserror::Error)]
pub enum BuildError {
#[error("duplicate step name: `{name}`")]
DuplicateName {
name: String,
},
#[error("anchor step not found: `{anchor}`")]
AnchorNotFound {
anchor: String,
},
#[error(
"step `{step}` reads `{entry}`, but no upstream step (nor the pipeline input) writes it"
)]
UnsatisfiedRead {
step: String,
entry: &'static str,
},
#[error("branch `{step}` has no arms")]
EmptyBranch {
step: String,
},
#[error(
"loop `{step}` body consumes `{entry}` without rewriting it, which would fail every iteration after the first"
)]
UnrepeatableConsume {
step: String,
entry: &'static str,
},
}
#[derive(Debug, thiserror::Error)]
pub enum PipelineError {
#[error("step `{step}` failed: {source}")]
Step {
step: String,
#[source]
source: StepError,
},
#[error("step `{}` {} `{}` without declaring it", .0.step, .0.verb(), .0.entry)]
AccessViolation(AccessViolation),
#[error("pipeline exhausted: no step produced an outcome")]
Exhausted,
#[error("step `{step}` had no matching branch arm")]
NoMatchingBranch {
step: String,
},
#[error("step `{step}` exceeded its max_iterations limit of {max_iterations}")]
MaxIterationsExceeded {
step: String,
max_iterations: u32,
},
}
#[derive(Debug, thiserror::Error)]
#[error("{0}")]
pub(crate) struct NestedPipelineError(pub(crate) PipelineError);
struct Pending<Out> {
anchor: String,
step: Box<dyn Step<Out>>,
after: bool,
}
pub struct PipelineBuilder<In, Out> {
steps: Vec<Box<dyn Step<Out>>>,
pending: Vec<Pending<Out>>,
_in: std::marker::PhantomData<fn(In)>,
}
impl<In: Send + Sync + 'static, Out> PipelineBuilder<In, Out> {
pub fn step(mut self, step: impl Step<Out> + 'static) -> Self {
self.steps.push(Box::new(step));
self
}
pub fn insert_before(
mut self,
anchor: impl Into<String>,
step: impl Step<Out> + 'static,
) -> Self {
self.pending.push(Pending {
anchor: anchor.into(),
step: Box::new(step),
after: false,
});
self
}
pub fn insert_after(
mut self,
anchor: impl Into<String>,
step: impl Step<Out> + 'static,
) -> Self {
self.pending.push(Pending {
anchor: anchor.into(),
step: Box::new(step),
after: true,
});
self
}
pub fn build(mut self) -> Result<Pipeline<In, Out>, BuildError> {
let mut pending = self.pending;
let mut after_offset: HashMap<String, usize> = HashMap::new();
while !pending.is_empty() {
let mut still_pending = Vec::with_capacity(pending.len());
let mut progressed = false;
for item in pending {
match self.steps.iter().position(|s| s.name() == item.anchor) {
Some(index) => {
progressed = true;
if item.after {
let offset = after_offset.entry(item.anchor).or_insert(0);
*offset += 1;
self.steps.insert(index + *offset, item.step);
} else {
self.steps.insert(index, item.step);
}
}
None => still_pending.push(item),
}
}
if !progressed {
return Err(BuildError::AnchorNotFound {
anchor: still_pending[0].anchor.clone(),
});
}
pending = still_pending;
}
let mut names = HashSet::new();
let mut compiled = 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();
compiled.push(CompiledStep { name, access, step });
}
let mut written: HashSet<TypeId> = HashSet::from([TypeId::of::<In>()]);
for compiled_step in &compiled {
let mut unsatisfied: Vec<(TypeId, &'static str)> = compiled_step
.access
.read_entries()
.filter(|(id, _)| !written.contains(id))
.collect();
unsatisfied.sort_unstable_by_key(|(_, entry)| *entry);
if let Some((_, entry)) = unsatisfied.into_iter().next() {
return Err(BuildError::UnsatisfiedRead {
step: compiled_step.name.clone(),
entry,
});
}
written.extend(compiled_step.access.write_entries().map(|(id, _)| id));
for (id, _) in compiled_step.access.consume_entries() {
written.remove(&id);
}
}
Ok(Pipeline {
steps: compiled,
_in: std::marker::PhantomData,
})
}
}
pub(crate) fn qualify_step_name(qualifier: &str, err: PipelineError) -> PipelineError {
match err {
PipelineError::Step { step, source } => PipelineError::Step {
step: format!("{qualifier}/{step}"),
source,
},
PipelineError::AccessViolation(violation) => {
PipelineError::AccessViolation(AccessViolation {
step: format!("{qualifier}/{}", violation.step),
..violation
})
}
PipelineError::NoMatchingBranch { step } => PipelineError::NoMatchingBranch {
step: format!("{qualifier}/{step}"),
},
PipelineError::MaxIterationsExceeded {
step,
max_iterations,
} => PipelineError::MaxIterationsExceeded {
step: format!("{qualifier}/{step}"),
max_iterations,
},
PipelineError::Exhausted => unreachable!(
"Branch's arm dispatch and Loop's body dispatch never produce PipelineError::Exhausted, only Pipeline::run does"
),
}
}
pub(crate) struct CompiledStep<Out> {
pub(crate) name: String,
pub(crate) access: AccessSpec,
pub(crate) step: Box<dyn Step<Out>>,
}
pub(crate) async fn run_steps<Out>(
steps: &[CompiledStep<Out>],
ctx: &mut Context,
) -> Result<Flow<Out>, PipelineError> {
for compiled_step in steps {
ctx.set_active(compiled_step.name.clone(), compiled_step.access.clone());
let result = compiled_step.step.run(ctx).await;
ctx.clear_active();
if let Some(v) = ctx.take_violation() {
return Err(PipelineError::AccessViolation(v));
}
match result {
Ok(Flow::Continue) => continue,
Ok(Flow::Done(out)) => return Ok(Flow::Done(out)),
Err(source) => {
return match source.downcast::<NestedPipelineError>() {
Ok(NestedPipelineError(err)) => Err(err),
Err(source) => Err(PipelineError::Step {
step: compiled_step.name.clone(),
source,
}),
};
}
}
}
Ok(Flow::Continue)
}
pub struct Pipeline<In, Out> {
steps: Vec<CompiledStep<Out>>,
_in: std::marker::PhantomData<fn(In)>,
}
impl<In, Out> std::fmt::Debug for Pipeline<In, Out> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Pipeline")
.field(
"steps",
&self
.steps
.iter()
.map(|s| s.name.as_str())
.collect::<Vec<_>>(),
)
.finish()
}
}
impl<In: Send + Sync + 'static, Out> Pipeline<In, Out> {
pub fn builder() -> PipelineBuilder<In, Out> {
PipelineBuilder {
steps: Vec::new(),
pending: Vec::new(),
_in: std::marker::PhantomData,
}
}
pub async fn run(&self, input: In) -> Result<Out, PipelineError> {
let mut ctx = Context::new();
ctx.insert(input);
match run_steps(&self.steps, &mut ctx).await? {
Flow::Done(out) => Ok(out),
Flow::Continue => Err(PipelineError::Exhausted),
}
}
pub fn step_names(&self) -> Vec<&str> {
self.steps.iter().map(|s| s.name.as_str()).collect()
}
}
#[cfg(test)]
mod test {
use std::error::Error;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use super::*;
use crate::test_support::block_on;
#[test]
fn display_formats_duplicate_name() {
let err = BuildError::DuplicateName {
name: "load".to_string(),
};
assert_eq!(err.to_string(), "duplicate step name: `load`");
}
#[test]
fn display_formats_anchor_not_found() {
let err = BuildError::AnchorNotFound {
anchor: "load".to_string(),
};
assert_eq!(err.to_string(), "anchor step not found: `load`");
}
#[test]
fn display_formats_unsatisfied_read() {
let err = BuildError::UnsatisfiedRead {
step: "load".to_string(),
entry: "Marker",
};
assert_eq!(
err.to_string(),
"step `load` reads `Marker`, but no upstream step (nor the pipeline input) writes it"
);
}
#[test]
fn display_formats_empty_branch() {
let err = BuildError::EmptyBranch {
step: "route".to_string(),
};
assert_eq!(err.to_string(), "branch `route` has no arms");
}
#[test]
fn implements_std_error_trait_with_none_source() {
let err = BuildError::DuplicateName {
name: "load".to_string(),
};
let as_dyn: &dyn Error = &err;
assert!(as_dyn.source().is_none());
}
#[test]
fn display_formats_step_variant() {
let err = PipelineError::Step {
step: "load".to_string(),
source: StepError::new("boom"),
};
assert_eq!(err.to_string(), "step `load` failed: boom");
}
#[test]
fn display_formats_access_violation_variant_for_read() {
let err = PipelineError::AccessViolation(AccessViolation {
step: "load".to_string(),
entry: "Marker",
kind: AccessKind::Read,
});
assert_eq!(
err.to_string(),
"step `load` read `Marker` without declaring it"
);
}
#[test]
fn display_formats_access_violation_variant_for_write() {
let err = PipelineError::AccessViolation(AccessViolation {
step: "load".to_string(),
entry: "Marker",
kind: AccessKind::Write,
});
assert_eq!(
err.to_string(),
"step `load` wrote `Marker` without declaring it"
);
}
#[test]
fn display_formats_exhausted_variant() {
let err = PipelineError::Exhausted;
assert_eq!(
err.to_string(),
"pipeline exhausted: no step produced an outcome"
);
}
#[test]
fn display_formats_no_matching_branch_variant() {
let err = PipelineError::NoMatchingBranch {
step: "route".to_string(),
};
assert_eq!(err.to_string(), "step `route` had no matching branch arm");
}
#[test]
fn source_returns_some_for_step_variant() {
let err = PipelineError::Step {
step: "load".to_string(),
source: StepError::new("boom"),
};
let source = err.source().expect("source should be present");
assert_eq!(source.to_string(), "boom");
}
#[test]
fn source_returns_none_for_access_violation_variant() {
let err = PipelineError::AccessViolation(AccessViolation {
step: "load".to_string(),
entry: "Marker",
kind: AccessKind::Read,
});
assert!(err.source().is_none());
}
#[test]
fn source_returns_none_for_exhausted_variant() {
let err = PipelineError::Exhausted;
assert!(err.source().is_none());
}
struct Input(i32);
struct Marker(i32);
enum Action {
Continue,
Done(i32),
Fail(&'static str),
WriteMarker(i32),
WriteMarkerThenFail(i32, &'static str),
ReadMarkerAsDone,
ReadInputAsDone,
}
struct ScriptedStep {
name: &'static str,
access: AccessSpec,
action: Action,
}
#[async_trait::async_trait]
impl Step<i32> for ScriptedStep {
fn name(&self) -> &str {
self.name
}
fn access(&self) -> AccessSpec {
self.access.clone()
}
async fn run(&self, ctx: &mut Context) -> Result<Flow<i32>, StepError> {
match &self.action {
Action::Continue => Ok(Flow::Continue),
Action::Done(v) => Ok(Flow::Done(*v)),
Action::Fail(msg) => Err(StepError::new(*msg)),
Action::WriteMarker(v) => {
ctx.insert(Marker(*v));
Ok(Flow::Continue)
}
Action::WriteMarkerThenFail(v, msg) => {
ctx.insert(Marker(*v));
Err(StepError::new(*msg))
}
Action::ReadMarkerAsDone => {
let doubled = ctx.get::<Marker>().map(|m| m.0 * 2).unwrap_or(-1);
Ok(Flow::Done(doubled))
}
Action::ReadInputAsDone => {
let v = ctx.get::<Input>().map(|i| i.0).unwrap_or(-1);
Ok(Flow::Done(v))
}
}
}
}
struct CountingStep {
access_calls: Arc<AtomicUsize>,
name_calls: Arc<AtomicUsize>,
}
#[async_trait::async_trait]
impl Step<i32> for CountingStep {
fn name(&self) -> &str {
self.name_calls.fetch_add(1, Ordering::SeqCst);
"counting"
}
fn access(&self) -> AccessSpec {
self.access_calls.fetch_add(1, Ordering::SeqCst);
AccessSpec::new()
}
async fn run(&self, _ctx: &mut Context) -> Result<Flow<i32>, StepError> {
Ok(Flow::Done(1))
}
}
fn step(name: &'static str, access: AccessSpec) -> ScriptedStep {
ScriptedStep {
name,
access,
action: Action::Continue,
}
}
fn scripted(name: &'static str, access: AccessSpec, action: Action) -> ScriptedStep {
ScriptedStep {
name,
access,
action,
}
}
#[test]
fn build_preserves_step_call_order_when_no_pending_insertions() {
let pipeline = Pipeline::<Input, i32>::builder()
.step(step("a", AccessSpec::new()))
.step(step("b", AccessSpec::new()))
.step(step("c", AccessSpec::new()))
.build()
.unwrap();
assert_eq!(pipeline.step_names(), vec!["a", "b", "c"]);
}
#[test]
fn insert_before_places_step_immediately_before_anchor() {
let pipeline = Pipeline::<Input, i32>::builder()
.step(step("a", AccessSpec::new()))
.step(step("b", AccessSpec::new()))
.insert_before("b", step("x", AccessSpec::new()))
.build()
.unwrap();
assert_eq!(pipeline.step_names(), vec!["a", "x", "b"]);
}
#[test]
fn insert_after_places_step_immediately_after_anchor() {
let pipeline = Pipeline::<Input, i32>::builder()
.step(step("a", AccessSpec::new()))
.step(step("b", AccessSpec::new()))
.insert_after("a", step("x", AccessSpec::new()))
.build()
.unwrap();
assert_eq!(pipeline.step_names(), vec!["a", "x", "b"]);
}
#[test]
fn repeated_insert_before_on_the_same_anchor_preserves_registration_order() {
let pipeline = Pipeline::<Input, i32>::builder()
.step(step("a", AccessSpec::new()))
.insert_before("a", step("x", AccessSpec::new()))
.insert_before("a", step("y", AccessSpec::new()))
.build()
.unwrap();
assert_eq!(pipeline.step_names(), vec!["x", "y", "a"]);
}
#[test]
fn repeated_insert_after_on_the_same_anchor_preserves_registration_order() {
let pipeline = Pipeline::<Input, i32>::builder()
.step(step("a", AccessSpec::new()))
.insert_after("a", step("x", AccessSpec::new()))
.insert_after("a", step("y", AccessSpec::new()))
.build()
.unwrap();
assert_eq!(pipeline.step_names(), vec!["a", "x", "y"]);
}
#[test]
fn pending_insert_can_anchor_onto_a_previously_resolved_pending_step() {
let pipeline = Pipeline::<Input, i32>::builder()
.step(step("a", AccessSpec::new()))
.insert_after("a", step("b", AccessSpec::new()))
.insert_before("b", step("c", AccessSpec::new()))
.build()
.unwrap();
assert_eq!(pipeline.step_names(), vec!["a", "c", "b"]);
}
#[test]
fn pending_insert_resolution_does_not_depend_on_registration_order() {
let pipeline = Pipeline::<Input, i32>::builder()
.step(step("a", AccessSpec::new()))
.insert_before("b", step("c", AccessSpec::new()))
.insert_after("a", step("b", AccessSpec::new()))
.build()
.unwrap();
assert_eq!(pipeline.step_names(), vec!["a", "c", "b"]);
}
#[test]
fn builder_creates_pipeline_with_zero_steps_when_none_added() {
let pipeline = Pipeline::<Input, i32>::builder().build().unwrap();
assert!(pipeline.step_names().is_empty());
}
#[test]
fn build_returns_anchor_not_found_when_insert_before_anchor_missing() {
let result = Pipeline::<Input, i32>::builder()
.insert_before("missing", step("x", AccessSpec::new()))
.build();
assert!(
matches!(result, Err(BuildError::AnchorNotFound { anchor }) if anchor == "missing")
);
}
#[test]
fn build_returns_anchor_not_found_when_insert_after_anchor_missing() {
let result = Pipeline::<Input, i32>::builder()
.insert_after("missing", step("x", AccessSpec::new()))
.build();
assert!(
matches!(result, Err(BuildError::AnchorNotFound { anchor }) if anchor == "missing")
);
}
#[test]
fn build_returns_duplicate_name_when_two_added_steps_share_a_name() {
let result = Pipeline::<Input, i32>::builder()
.step(step("a", AccessSpec::new()))
.step(step("a", AccessSpec::new()))
.build();
assert!(matches!(result, Err(BuildError::DuplicateName { name }) if name == "a"));
}
#[test]
fn build_returns_duplicate_name_when_a_pending_insert_introduces_a_duplicate() {
let result = Pipeline::<Input, i32>::builder()
.step(step("a", AccessSpec::new()))
.step(step("b", AccessSpec::new()))
.insert_after("a", step("b", AccessSpec::new()))
.build();
assert!(matches!(result, Err(BuildError::DuplicateName { name }) if name == "b"));
}
#[test]
fn build_succeeds_when_step_reads_the_pipeline_input_type() {
let result = Pipeline::<Input, i32>::builder()
.step(step("a", AccessSpec::new().reads::<Input>()))
.build();
assert!(result.is_ok());
}
#[test]
fn build_succeeds_when_a_read_is_satisfied_by_an_earlier_steps_write() {
let result = Pipeline::<Input, i32>::builder()
.step(step("a", AccessSpec::new().writes::<Marker>()))
.step(step("b", AccessSpec::new().reads::<Marker>()))
.build();
assert!(result.is_ok());
}
#[test]
fn build_succeeds_when_step_declares_no_access_requirements() {
let result = Pipeline::<Input, i32>::builder()
.step(step("a", AccessSpec::new()))
.build();
assert!(result.is_ok());
}
#[test]
fn build_returns_unsatisfied_read_when_nothing_writes_the_entry() {
let result = Pipeline::<Input, i32>::builder()
.step(step("a", AccessSpec::new().reads::<Marker>()))
.build();
assert!(matches!(
result,
Err(BuildError::UnsatisfiedRead { step, .. }) if step == "a"
));
}
#[test]
fn build_returns_unsatisfied_read_when_a_step_consumes_the_entry_before_a_later_reader() {
let result = Pipeline::<Input, i32>::builder()
.step(step("a", AccessSpec::new().writes::<Marker>()))
.step(step("b", AccessSpec::new().consumes::<Marker>()))
.step(step("c", AccessSpec::new().reads::<Marker>()))
.build();
assert!(matches!(
result,
Err(BuildError::UnsatisfiedRead { step, .. }) if step == "c"
));
}
#[test]
fn build_succeeds_when_a_later_step_rewrites_a_consumed_entry() {
let result = Pipeline::<Input, i32>::builder()
.step(step("a", AccessSpec::new().writes::<Marker>()))
.step(step("b", AccessSpec::new().consumes::<Marker>()))
.step(step("c", AccessSpec::new().writes::<Marker>()))
.step(step("d", AccessSpec::new().reads::<Marker>()))
.build();
assert!(result.is_ok());
}
#[test]
fn build_succeeds_when_reads_writes_is_used_for_in_place_mutation() {
let result = Pipeline::<Input, i32>::builder()
.step(step("a", AccessSpec::new().writes::<Marker>()))
.step(step("b", AccessSpec::new().reads_writes::<Marker>()))
.step(step("c", AccessSpec::new().reads::<Marker>()))
.build();
assert!(result.is_ok());
}
#[test]
fn build_reports_deterministic_entry_when_step_has_multiple_unsatisfied_reads() {
struct OtherMarker;
let access = AccessSpec::new().reads::<Marker>().reads::<OtherMarker>();
let expected = [
std::any::type_name::<Marker>(),
std::any::type_name::<OtherMarker>(),
]
.into_iter()
.min()
.unwrap();
for _ in 0..20 {
let result = Pipeline::<Input, i32>::builder()
.step(step("a", access.clone()))
.build();
assert!(matches!(
result,
Err(BuildError::UnsatisfiedRead { entry, .. }) if entry == expected
));
}
}
#[test]
fn build_returns_unsatisfied_read_when_only_a_later_step_writes_the_entry() {
let result = Pipeline::<Input, i32>::builder()
.step(step("a", AccessSpec::new().reads::<Marker>()))
.step(step("b", AccessSpec::new().writes::<Marker>()))
.build();
assert!(matches!(
result,
Err(BuildError::UnsatisfiedRead { step, .. }) if step == "a"
));
}
#[test]
fn run_returns_done_value_from_a_single_step() {
let pipeline = Pipeline::<Input, i32>::builder()
.step(scripted("a", AccessSpec::new(), Action::Done(42)))
.build()
.unwrap();
let result = block_on(pipeline.run(Input(0)));
assert!(matches!(result, Ok(42)));
}
#[test]
fn run_continues_to_next_step_when_flow_is_continue() {
let pipeline = Pipeline::<Input, i32>::builder()
.step(scripted("a", AccessSpec::new(), Action::Continue))
.step(scripted("b", AccessSpec::new(), Action::Done(7)))
.build()
.unwrap();
let result = block_on(pipeline.run(Input(0)));
assert!(matches!(result, Ok(7)));
}
#[test]
fn run_provides_pipeline_input_via_context() {
let pipeline = Pipeline::<Input, i32>::builder()
.step(scripted(
"a",
AccessSpec::new().reads::<Input>(),
Action::ReadInputAsDone,
))
.build()
.unwrap();
let result = block_on(pipeline.run(Input(9)));
assert!(matches!(result, Ok(9)));
}
#[test]
fn run_threads_a_value_written_by_an_earlier_step_to_a_later_step() {
let pipeline = Pipeline::<Input, i32>::builder()
.step(scripted(
"a",
AccessSpec::new().writes::<Marker>(),
Action::WriteMarker(5),
))
.step(scripted(
"b",
AccessSpec::new().reads::<Marker>(),
Action::ReadMarkerAsDone,
))
.build()
.unwrap();
let result = block_on(pipeline.run(Input(0)));
assert!(matches!(result, Ok(10)));
}
#[test]
fn run_returns_exhausted_for_pipeline_with_zero_steps() {
let pipeline = Pipeline::<Input, i32>::builder().build().unwrap();
let result = block_on(pipeline.run(Input(0)));
assert!(matches!(result, Err(PipelineError::Exhausted)));
}
#[test]
fn run_returns_step_error_when_a_step_returns_err() {
let pipeline = Pipeline::<Input, i32>::builder()
.step(scripted("a", AccessSpec::new(), Action::Fail("boom")))
.build()
.unwrap();
match block_on(pipeline.run(Input(0))) {
Err(PipelineError::Step { step, source }) => {
assert_eq!(step, "a");
assert_eq!(source.to_string(), "boom");
}
other => panic!("expected Step error, got {other:?}"),
}
}
#[test]
fn run_returns_access_violation_when_step_reads_undeclared_entry() {
let pipeline = Pipeline::<Input, i32>::builder()
.step(scripted("a", AccessSpec::new(), Action::ReadMarkerAsDone))
.build()
.unwrap();
match block_on(pipeline.run(Input(0))) {
Err(PipelineError::AccessViolation(AccessViolation { step, kind, .. })) => {
assert_eq!(step, "a");
assert_eq!(kind, AccessKind::Read);
}
other => panic!("expected AccessViolation, got {other:?}"),
}
}
#[test]
fn run_returns_access_violation_when_step_writes_undeclared_entry() {
let pipeline = Pipeline::<Input, i32>::builder()
.step(scripted("a", AccessSpec::new(), Action::WriteMarker(1)))
.build()
.unwrap();
match block_on(pipeline.run(Input(0))) {
Err(PipelineError::AccessViolation(AccessViolation { step, kind, .. })) => {
assert_eq!(step, "a");
assert_eq!(kind, AccessKind::Write);
}
other => panic!("expected AccessViolation, got {other:?}"),
}
}
#[test]
fn run_returns_access_violation_instead_of_step_error_when_both_occur() {
let pipeline = Pipeline::<Input, i32>::builder()
.step(scripted(
"a",
AccessSpec::new(),
Action::WriteMarkerThenFail(1, "boom"),
))
.build()
.unwrap();
match block_on(pipeline.run(Input(0))) {
Err(PipelineError::AccessViolation(AccessViolation { step, kind, .. })) => {
assert_eq!(step, "a");
assert_eq!(kind, AccessKind::Write);
}
other => panic!("expected AccessViolation, got {other:?}"),
}
}
#[test]
fn run_never_calls_access_or_name_again_after_build_cached_them() {
let access_calls = Arc::new(AtomicUsize::new(0));
let name_calls = Arc::new(AtomicUsize::new(0));
let pipeline = Pipeline::<Input, i32>::builder()
.step(CountingStep {
access_calls: access_calls.clone(),
name_calls: name_calls.clone(),
})
.build()
.unwrap();
let access_calls_after_build = access_calls.load(Ordering::SeqCst);
let name_calls_after_build = name_calls.load(Ordering::SeqCst);
assert!(access_calls_after_build >= 1);
assert!(name_calls_after_build >= 1);
block_on(pipeline.run(Input(0))).unwrap();
block_on(pipeline.run(Input(0))).unwrap();
assert_eq!(
access_calls.load(Ordering::SeqCst),
access_calls_after_build
);
assert_eq!(name_calls.load(Ordering::SeqCst), name_calls_after_build);
}
#[test]
fn run_returns_exhausted_when_every_step_returns_continue() {
let pipeline = Pipeline::<Input, i32>::builder()
.step(scripted("a", AccessSpec::new(), Action::Continue))
.step(scripted("b", AccessSpec::new(), Action::Continue))
.build()
.unwrap();
let result = block_on(pipeline.run(Input(0)));
assert!(matches!(result, Err(PipelineError::Exhausted)));
}
fn compiled(steps: Vec<ScriptedStep>) -> Vec<CompiledStep<i32>> {
steps
.into_iter()
.map(|s| {
let name = s.name().to_string();
let access = s.access();
CompiledStep {
name,
access,
step: Box::new(s),
}
})
.collect()
}
#[test]
fn run_steps_returns_continue_when_every_step_continues() {
let steps = compiled(vec![
scripted("a", AccessSpec::new(), Action::Continue),
scripted("b", AccessSpec::new(), Action::Continue),
]);
let mut ctx = Context::new();
let result = block_on(run_steps(&steps, &mut ctx));
assert!(matches!(result, Ok(Flow::Continue)));
}
#[test]
fn run_steps_propagates_done_and_stops_running_further_steps() {
let steps = compiled(vec![
scripted("a", AccessSpec::new(), Action::Continue),
scripted("b", AccessSpec::new(), Action::Done(9)),
scripted("c", AccessSpec::new(), Action::Done(-1)),
]);
let mut ctx = Context::new();
let result = block_on(run_steps(&steps, &mut ctx));
assert!(matches!(result, Ok(Flow::Done(9))));
}
#[test]
fn run_steps_propagates_err() {
let steps = compiled(vec![scripted("a", AccessSpec::new(), Action::Fail("boom"))]);
let mut ctx = Context::new();
match block_on(run_steps(&steps, &mut ctx)) {
Err(PipelineError::Step { step, source }) => {
assert_eq!(step, "a");
assert_eq!(source.to_string(), "boom");
}
Ok(_) => panic!("expected Step error, got Ok"),
Err(other) => panic!("expected Step error, got {other}"),
}
}
}