//! Error semantics: the first error stops the pipeline and is yielded as the last item of the `PipeIter` //! (or returned by `WorkerPool::run`); no failure may hang. Every test runs under a timeout guard. use obipipeline::{ Pipeline, PipelineError, Throttle, WorkerPool, make_pipe, make_pipeline, throttle, }; use std::io::{Error, ErrorKind}; use std::sync::mpsc; use std::thread; use std::time::Duration; // The `Text` payload is only built, never read back: it exists to trigger a runtime mismatch. #[allow(dead_code)] enum D { Num(u64), Text(String), } /// Runs `f` on a thread and fails the test if it does not finish in time (a hang is the bug to catch). fn within(f: impl FnOnce() -> T + Send + 'static) -> T { let (tx, rx) = mpsc::channel(); thread::spawn(move || { let _ = tx.send(f()); }); rx.recv_timeout(Duration::from_secs(10)) .expect("the pipeline hung") } /// Drains an iterator of results: the Ok values, and the error if there is one. Checks the contract that /// an error is yielded at most once and is the last item. fn drain(it: impl Iterator>) -> (Vec, Option) { let mut oks = Vec::new(); let mut err = None; for r in it { assert!(err.is_none(), "an item came after the error"); match r { Ok(v) => oks.push(v), Err(e) => err = Some(e), } } (oks, err) } fn fails_on_5(x: u64) -> Result { if x == 5 { Err(Error::new(ErrorKind::InvalidData, "boom on 5")) } else { Ok(x) } } fn flat_fails_on_5(x: u64) -> Result, Error> { fails_on_5(x).map(|v| vec![v, v]) } fn panics_on_3(x: u64) -> u64 { assert!(x != 3, "boom on 3"); x } fn to_text(x: u64) -> String { x.to_string() } fn plus_one(x: u64) -> u64 { x + 1 } fn identity(x: u64) -> u64 { x } fn triple(x: u64) -> Vec { vec![x, x, x] } fn ignore(_x: u64) {} fn message(e: &PipelineError) -> String { e.to_string() } // ── Pipe / PipeIter ───────────────────────────────────────────────────────────── #[test] fn fallible_stage_error_is_the_last_item() { let (items, err) = within(|| { let pipe = make_pipe! { D : u64 => u64, |? fails_on_5 : Num => Num, }; drain(pipe.apply(1..=10u64, 2, 4)) }); assert!(items.len() < 10, "the pipeline must stop early"); assert!(message(&err.expect("the error must be yielded")).contains("boom on 5")); } #[test] fn fallible_flat_stage_error_is_the_last_item() { let (_, err) = within(|| { let pipe = make_pipe! { D : u64 => u64, ||? flat_fails_on_5 : Num => Num, }; drain(pipe.apply(1..=10u64, 2, 4)) }); assert!(message(&err.unwrap()).contains("boom on 5")); } #[test] fn runtime_type_mismatch_is_the_last_item() { let (_, err) = within(|| { // The first stage produces a Text, the second one reads a Num. let pipe = make_pipe! { D : u64 => u64, | to_text : Num => Text, | panics_on_3 : Num => Num, }; drain(pipe.apply(1..=10u64, 2, 4)) }); assert!(matches!(err, Some(PipelineError::TypeMismatch))); } #[test] fn type_mismatch_in_every_kind_of_stage() { // Each pipe feeds a Text to a stage that reads a Num. type Case = ( &'static str, Box Option + Send>, ); let kinds: Vec = vec![ ( "transform", Box::new(|| { let p = make_pipe! { D : u64 => u64, | to_text : Num => Text, | plus_one : Num => Num, }; drain(p.apply(1..=3u64, 2, 4)).1 }), ), ( "transform?", Box::new(|| { let p = make_pipe! { D : u64 => u64, | to_text : Num => Text, |? fails_on_5 : Num => Num, }; drain(p.apply(1..=3u64, 2, 4)).1 }), ), ( "flat", Box::new(|| { let p = make_pipe! { D : u64 => u64, | to_text : Num => Text, || triple : Num => Num, }; drain(p.apply(1..=3u64, 2, 4)).1 }), ), ( "flat?", Box::new(|| { let p = make_pipe! { D : u64 => u64, | to_text : Num => Text, ||? flat_fails_on_5 : Num => Num, }; drain(p.apply(1..=3u64, 2, 4)).1 }), ), ]; for (name, run) in kinds { let err = within(run); assert!( matches!(err, Some(PipelineError::TypeMismatch)), "{name}: {err:?}" ); } } #[test] fn worker_panic_is_the_last_item() { let (_, err) = within(|| { let pipe = make_pipe! { D : u64 => u64, | panics_on_3 : Num => Num, }; drain(pipe.apply(1..=10u64, 2, 4)) }); assert!(message(&err.unwrap()).contains("boom on 3")); } #[test] fn no_error_item_when_everything_went_through() { let (items, err) = within(|| { let pipe = make_pipe! { D : u64 => u64, |? fails_on_5 : Num => Num, }; drain(pipe.apply(6..=20u64, 3, 4)) }); assert_eq!(items.len(), 15); assert!(err.is_none()); } #[test] fn capacity_one_works() { let (items, err) = within(|| { let pipe = make_pipe! { D : u64 => u64, |? fails_on_5 : Num => Num, }; drain(pipe.apply(6..=205u64, 2, 1)) }); assert_eq!(items.len(), 200); assert!(err.is_none()); } #[test] #[should_panic(expected = "at least one worker")] fn zero_workers_is_rejected() { let pipe = make_pipe! { D : u64 => u64, |? fails_on_5 : Num => Num, }; let _ = pipe.apply(0..3u64, 0, 4); } #[test] #[should_panic(expected = "capacity of at least 1")] fn zero_capacity_is_rejected() { let pipe = make_pipe! { D : u64 => u64, |? fails_on_5 : Num => Num, }; let _ = pipe.apply(0..3u64, 2, 0); } #[test] #[should_panic(expected = "at least one slot")] fn throttle_new_zero_is_rejected() { let _ = Throttle::new(0); } #[test] #[should_panic(expected = "at least one slot")] fn throttle_zero_is_rejected() { let _ = throttle(0..3u32, 0).count(); } // ── Pipeline / WorkerPool (the lower-level runtime) ───────────────────────────── fn pool_run(pipeline: Pipeline) -> Result<(), PipelineError> { WorkerPool::new(pipeline, 3, 4).run() } #[test] fn pipeline_runs_and_reaches_the_sink() { let (tx, rx) = mpsc::channel::(); let result = within(move || { let collect = move |x: u64| tx.send(x).unwrap(); let pipeline = make_pipeline! { D, source 1..=50u64 => Num, | plus_one : Num => Num, sink collect @ Num, }; pool_run(pipeline) }); assert!(result.is_ok()); let mut got: Vec = rx.try_iter().collect(); got.sort_unstable(); assert_eq!(got, (2..=51).collect::>()); } #[test] fn pipeline_returns_a_stage_error() { let result = within(|| { pool_run(make_pipeline! { D, source 1..=20u64 => Num, |? fails_on_5 : Num => Num, sink ignore @ Num, }) }); assert!(message(&result.unwrap_err()).contains("boom on 5")); } fn fallible_source_failing() -> Vec> { vec![ Ok(1), Ok(2), Err(Error::new(ErrorKind::UnexpectedEof, "source broke")), Ok(4), ] } fn fallible_source_ok() -> Vec> { (1..=10).map(Ok).collect() } #[test] fn pipeline_returns_a_source_error() { let result = within(|| { pool_run(make_pipeline! { D, source? fallible_source_failing() => Num, | identity : Num => Num, sink ignore @ Num, }) }); assert!(message(&result.unwrap_err()).contains("source broke")); } #[test] fn fallible_source_that_runs_dry_ends_normally() { let result = within(|| { pool_run(make_pipeline! { D, source? fallible_source_ok() => Num, | identity : Num => Num, sink ignore @ Num, }) }); assert!(result.is_ok()); } fn failing_sink(x: u64) -> Result<(), Error> { if x == 7 { Err(Error::new(ErrorKind::BrokenPipe, "sink broke")) } else { Ok(()) } } #[test] fn pipeline_returns_a_sink_error() { let result = within(|| { pool_run(make_pipeline! { D, source 1..=20u64 => Num, | identity : Num => Num, sink? failing_sink @ Num, }) }); assert!(message(&result.unwrap_err()).contains("sink broke")); } #[test] fn pipeline_with_a_flat_stage_counts_every_item() { let (tx, rx) = mpsc::channel::(); let result = within(move || { let collect = move |x: u64| tx.send(x).unwrap(); pool_run(make_pipeline! { D, source 1..=10u64 => Num, || triple : Num => Num, sink collect @ Num, }) }); assert!(result.is_ok()); assert_eq!(rx.try_iter().count(), 30); } fn failing_sink_text(_x: String) -> Result<(), Error> { Ok(()) } fn ignore_text(_x: String) {} #[test] fn type_mismatch_at_the_sink() { // The last stage produces a Num, the sink reads a Text. for infallible in [true, false] { let result = within(move || { if infallible { pool_run(make_pipeline! { D, source 1..=3u64 => Num, | identity : Num => Num, sink ignore_text @ Text, }) } else { pool_run(make_pipeline! { D, source 1..=3u64 => Num, | identity : Num => Num, sink? failing_sink_text @ Text, }) } }); assert!( matches!(result, Err(PipelineError::TypeMismatch)), "infallible = {infallible}: {result:?}" ); } } // ── PipelineError ─────────────────────────────────────────────────────────────── #[test] fn pipeline_error_display_and_source() { use std::error::Error as _; assert_eq!( PipelineError::TypeMismatch.to_string(), "data type mismatch in pipeline stage" ); assert_eq!( PipelineError::EndOfStream.to_string(), "end of input stream" ); assert!(PipelineError::TypeMismatch.source().is_none()); let inner = PipelineError::StepError(Box::new(Error::other("inner"))); assert!(inner.to_string().contains("inner")); assert!(inner.source().is_some()); } // ── Panics outside the plain transform ────────────────────────────────────────── fn flat_panics(x: u64) -> Vec { assert!(x != 2, "flat boom"); vec![x] } fn panics_with_a_number(x: u64) -> u64 { if x == 2 { std::panic::panic_any(42_u32); } x } fn sink_panics(_x: u64) { panic!("sink boom"); } struct PanickingSource(u64); impl Iterator for PanickingSource { type Item = u64; fn next(&mut self) -> Option { self.0 += 1; assert!(self.0 != 3, "source boom"); (self.0 < 20).then_some(self.0) } } #[test] fn flat_stage_panic_is_the_last_item() { let (_, err) = within(|| { let pipe = make_pipe! { D : u64 => u64, || flat_panics : Num => Num, }; drain(pipe.apply(1..=10u64, 2, 4)) }); assert!(message(&err.unwrap()).contains("flat boom")); } #[test] fn panic_with_a_non_string_payload_is_reported() { let (_, err) = within(|| { let pipe = make_pipe! { D : u64 => u64, | panics_with_a_number : Num => Num, }; drain(pipe.apply(1..=10u64, 2, 4)) }); assert!(message(&err.unwrap()).contains("non-string panic payload")); } #[test] fn sink_panic_is_returned_by_run() { let result = within(|| { pool_run(make_pipeline! { D, source 1..=20u64 => Num, | identity : Num => Num, sink sink_panics @ Num, }) }); assert!(message(&result.unwrap_err()).contains("panicked")); } #[test] fn source_panic_is_returned_by_run() { let result = within(|| { pool_run(make_pipeline! { D, source PanickingSource(0) => Num, | identity : Num => Num, sink ignore @ Num, }) }); assert!(message(&result.unwrap_err()).contains("panicked")); } #[test] fn pipeline_without_any_stage_connects_source_to_sink() { let (tx, rx) = mpsc::channel::(); let result = within(move || { let collect = move |x: u64| tx.send(x).unwrap(); let pipeline = Pipeline::new( obipipeline::make_source!(D, 1..=5u64, Num), Vec::new(), obipipeline::make_sink!(D, collect, Num), ); pool_run(pipeline) }); assert!(result.is_ok()); assert_eq!(rx.try_iter().count(), 5); }