diff --git a/Cargo.toml b/Cargo.toml index a5fb285..32bca4b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,6 +2,7 @@ name = "obipipeline" version = "0.1.1" edition = "2024" +rust-version = "1.85" description = "Typed, composable multi-threaded pipelines over channels, with memory-bounded throttling of iterators" repository = "https://forge.metabarcoding.org/obi/obipipeline" license = "CECILL-2.1" diff --git a/README.md b/README.md index 17ade0b..0a24ff8 100644 --- a/README.md +++ b/README.md @@ -11,6 +11,13 @@ Typed, composable multi-threaded pipelines built on channels, and a memory-bound Items go through a single user-defined enum `D`; each stage names the variant it reads and the one it writes. The order of the output is **not** guaranteed when several workers run. +## Errors and limits + +- **Fail-fast.** The first error (a fallible stage returning `Err`, a source or sink error, a runtime type mismatch, or a panic in a worker, source or sink closure) stops the pipeline: the items still in flight are discarded and nothing is printed. +- **Where to read the error.** `PipeIter` ends early and the error is **not** an item: call `PipeIter::finish()` once the iterator is consumed (`Ok(())` if every input item went through). `WorkerPool::run()` returns it directly as a `Result`. +- **Dropping the iterator early is safe**: the pipeline stops and its threads are joined. +- **Arguments.** `n_workers`, `capacity` and the `Throttle` size must be at least 1; `0` panics (it would block forever or deadlock the scheduler). + ## Installation The crate is published on the private registry `obi`: @@ -45,8 +52,8 @@ let out: Vec = pipe.apply(1..=100u64, 4, 8).collect(); ## API -- Pipes: `Pipe`, `PipeIter`, macros `make_pipe!`, `make_transform!`, `make_transform_fallible!`, `make_flat_transform!`, `make_flat_transform_fallible!`. -- Runtime: `Pipeline`, `WorkerPool`, `Stage`, `SourceFn`, `SinkFn`, `SharedFn`, `SharedFlatFn`, `PipelineError`, `PipelineSender`; macros `make_pipeline!`, `make_source!`, `make_source_fallible!`, `make_sink!`, `make_sink_fallible!`. +- Pipes: `Pipe`, `PipeIter` (with `finish()`), macros `make_pipe!`, `make_transform!`, `make_transform_fallible!`, `make_flat_transform!`, `make_flat_transform_fallible!`. +- Runtime: `Pipeline`, `WorkerPool`, `Stage`, `SourceFn`, `SinkFn`, `SharedFn`, `SharedFlatFn`, `PipelineError`; macros `make_pipeline!`, `make_source!`, `make_source_fallible!`, `make_sink!`, `make_sink_fallible!`. - Throttling: `throttle()`, `Throttle`, `ThrottleGuard`, `Throttled`. ## Development diff --git a/examples/sandbox_pipeline.rs b/examples/sandbox_pipeline.rs index e95efda..44d968d 100644 --- a/examples/sandbox_pipeline.rs +++ b/examples/sandbox_pipeline.rs @@ -75,5 +75,7 @@ fn main() { sink? step_4 @ Unsigned, }; - WorkerPool::new(pipeline, 4, 64).run(); + WorkerPool::new(pipeline, 4, 64) + .run() + .expect("pipeline failed"); } diff --git a/src/lib.rs b/src/lib.rs index 8a69839..e2e120a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,16 @@ +//! Typed, composable multi-threaded pipelines over channels, and a memory-bounded `throttle()`. +//! +//! - [`Pipe`] describes stages (built with `make_pipe!`, composed with [`Pipe::then`]) and runs them on a +//! worker pool with [`Pipe::apply`], which returns an iterator ([`PipeIter`]) over the output. +//! - [`Pipeline`] / [`WorkerPool`] is the lower-level runtime (source, stages, sink), built with +//! `make_pipeline!`. +//! - [`throttle()`] / [`Throttle`] bound the number of items in flight. +//! +//! Items travel through one user-defined enum; each stage names the variant it reads and the one it +//! writes. The output order is **not** guaranteed. Errors are fail-fast: the first one (a fallible stage, +//! a runtime type mismatch, a panic in a worker) stops the pipeline and is returned, never printed; see +//! [`PipeIter::finish`] and [`WorkerPool::run`]. + mod scheduler; pub mod throttle; @@ -16,6 +29,7 @@ pub use throttle::ThrottleGuard; pub use throttle::Throttled; pub use throttle::throttle; +#[doc(hidden)] /// Re-export of `crossbeam_channel::Sender`, used by the flat transform macros. /// It lets the `make_flat_transform!` / `make_flat_transform_fallible!` macros use /// `$crate::PipelineSender` without the calling crate having to depend diff --git a/src/scheduler/error.rs b/src/scheduler/error.rs index fc4a012..886c043 100644 --- a/src/scheduler/error.rs +++ b/src/scheduler/error.rs @@ -6,8 +6,6 @@ use std::fmt; pub enum PipelineError { /// A stage received a `PipelineData` variant it did not expect. TypeMismatch, - /// The step kind is not compatible with the data type. - StepKindMismatch(&'static str), /// The source has no more data to produce. EndOfStream, /// An error occurred inside a stage (e.g., I/O, parsing, custom logic). @@ -18,13 +16,34 @@ impl fmt::Display for PipelineError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { PipelineError::TypeMismatch => write!(f, "data type mismatch in pipeline stage"), - PipelineError::StepKindMismatch(s) => write!(f, "step kind mismatch: {}", s), PipelineError::EndOfStream => write!(f, "end of input stream"), PipelineError::StepError(e) => write!(f, "stage error: {}", e), } } } +/// Error carried by `PipelineError::StepError` when a worker closure panics. +#[derive(Debug)] +pub(crate) struct WorkerPanic(pub(crate) String); + +impl fmt::Display for WorkerPanic { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "worker panicked: {}", self.0) + } +} + +impl Error for WorkerPanic {} + +/// Turns the payload of a caught panic into a `PipelineError::StepError`. +pub(crate) fn panic_error(payload: Box) -> PipelineError { + let msg = payload + .downcast_ref::<&str>() + .map(|s| (*s).to_string()) + .or_else(|| payload.downcast_ref::().cloned()) + .unwrap_or_else(|| "non-string panic payload".to_string()); + PipelineError::StepError(Box::new(WorkerPanic(msg))) +} + impl Error for PipelineError { fn source(&self) -> Option<&(dyn Error + 'static)> { match self { diff --git a/src/scheduler/macros.rs b/src/scheduler/macros.rs index 680ecab..953a597 100644 --- a/src/scheduler/macros.rs +++ b/src/scheduler/macros.rs @@ -101,7 +101,7 @@ macro_rules! make_flat_transform { } _ => { push.send(Err($crate::PipelineError::TypeMismatch)).ok(); - delta.send(0).ok(); + delta.send(-1).ok(); } } }, @@ -137,12 +137,13 @@ macro_rules! make_flat_transform_fallible { Err(e) => { push.send(Err($crate::PipelineError::StepError(Box::new(e)))) .ok(); - delta.send(0).ok(); + // The input item is consumed and nothing is produced: N - 1 = -1. + delta.send(-1).ok(); } }, _ => { push.send(Err($crate::PipelineError::TypeMismatch)).ok(); - delta.send(0).ok(); + delta.send(-1).ok(); } } }, @@ -190,7 +191,7 @@ macro_rules! make_sink_fallible { /// Builds a `Pipeline` from a source, a list of stages and a sink. /// /// Syntax: -/// ```ignore +/// ```text /// make_pipeline! { /// MyData, /// source my_iter => Variant, // infallible source @@ -203,6 +204,35 @@ macro_rules! make_sink_fallible { /// sink? my_func @ Variant, // fallible sink /// } /// ``` +/// +/// Each function is a name or a parenthesised closure. Run the result with `WorkerPool::run`. +/// +/// # Example +/// +/// ``` +/// use obipipeline::{WorkerPool, make_pipeline}; +/// use std::sync::mpsc; +/// +/// enum D { +/// Num(u64), +/// } +/// fn double(x: u64) -> u64 { +/// x * 2 +/// } +/// +/// let (tx, rx) = mpsc::channel(); +/// let collect = move |x: u64| tx.send(x).unwrap(); +/// let pipeline = make_pipeline! { +/// D, +/// source 1..=3u64 => Num, +/// | double : Num => Num, +/// sink collect @ Num, +/// }; +/// WorkerPool::new(pipeline, 2, 4).run().unwrap(); +/// let mut got: Vec = rx.try_iter().collect(); +/// got.sort(); +/// assert_eq!(got, [2, 4, 6]); +/// ``` #[macro_export] macro_rules! make_pipeline { // ── Entry points ───────────────────────────────────────────────────── @@ -277,7 +307,7 @@ macro_rules! make_pipeline { /// Builds a typed `Pipe` — sourceless and sinkless. /// /// Syntax: -/// ```ignore +/// ```text /// make_pipe! { /// MyData : InType => OutType, /// | func : InVariant => OutVariant, // transform 1→1 @@ -286,6 +316,33 @@ macro_rules! make_pipeline { /// ||? func : InVariant => OutVariant, // flat transform 1→N fallible /// } /// ``` +/// +/// # Example +/// +/// ``` +/// use obipipeline::make_pipe; +/// +/// #[allow(dead_code)] +/// enum D { +/// Num(u64), +/// Text(String), +/// } +/// fn double(x: u64) -> u64 { +/// x * 2 +/// } +/// fn show(x: u64) -> String { +/// x.to_string() +/// } +/// +/// let pipe = make_pipe! { +/// D : u64 => String, +/// | double : Num => Num, +/// | show : Num => Text, +/// }; +/// let mut out: Vec = pipe.apply(1..=3u64, 2, 4).collect(); +/// out.sort(); +/// assert_eq!(out, ["2", "4", "6"]); +/// ``` #[macro_export] macro_rules! make_pipe { // ── Entry: first stage | ───────────────────────────────────────────── diff --git a/src/scheduler/pipe.rs b/src/scheduler/pipe.rs index 1aef94d..4acf368 100644 --- a/src/scheduler/pipe.rs +++ b/src/scheduler/pipe.rs @@ -60,7 +60,21 @@ where In: Send + 'static, Out: Send + 'static, { - /// Run the pipeline in a background thread; returns an iterator over the output. + /// Runs the pipeline in a background thread; returns an iterator over the output. + /// + /// `n_workers` threads run the stages in parallel; `capacity` bounds the internal channels and the + /// output channel. The order of the output is **not** guaranteed. + /// + /// # Errors + /// + /// The run is fail-fast. The first error (a fallible stage returning `Err`, a runtime + /// `TypeMismatch`, or a panic in a worker closure) stops the pipeline: the iterator ends early and + /// the error is **not** an item. Call [`PipeIter::finish`] once the iterator is consumed to learn + /// whether it ended normally or because of an error. + /// + /// # Panics + /// + /// Panics if `n_workers` or `capacity` is `0` (see [`WorkerPool::new`]). pub fn apply( self, input: impl Iterator + Send + 'static, @@ -87,9 +101,8 @@ where }); let pipeline = Pipeline::new(source, self.stages, sink); - let handle = thread::spawn(move || { - WorkerPool::new(pipeline, n_workers, capacity).run(); - }); + let pool = WorkerPool::new(pipeline, n_workers, capacity); + let handle = thread::spawn(move || pool.run()); PipeIter { rx: Some(out_rx), @@ -101,9 +114,32 @@ where // ── PipeIter ────────────────────────────────────────────────────────────────── /// Iterator over the output of `Pipe::apply()`. +/// +/// If the pipeline fails, the iterator simply ends early: call [`PipeIter::finish`] to get the error. pub struct PipeIter { rx: Option>, - handle: Option>, + handle: Option>>, +} + +impl PipeIter { + /// Consumes the items not read yet, waits for the pipeline to stop and returns how it ended. + /// + /// # Errors + /// + /// Returns the first error met by the pipeline (see [`Pipe::apply`]); `Ok(())` if every input item went + /// through. Call it after iterating: items left in the iterator are discarded. + pub fn finish(mut self) -> Result<(), PipelineError> { + if let Some(rx) = self.rx.as_ref() { + for _ in rx.iter() {} + } + drop(self.rx.take()); + match self.handle.take() { + Some(h) => h + .join() + .unwrap_or_else(|p| Err(super::error::panic_error(p))), + None => Ok(()), + } + } } impl Iterator for PipeIter { @@ -120,6 +156,7 @@ impl Drop for PipeIter { // scheduler. Joining while the receiver is alive blocks forever if the bounded output channel is full. drop(self.rx.take()); if let Some(h) = self.handle.take() { + // The outcome is not wanted here (early drop): `finish` is the way to get it. let _ = h.join(); } } diff --git a/src/scheduler/pool.rs b/src/scheduler/pool.rs index 78feda2..aa51f86 100644 --- a/src/scheduler/pool.rs +++ b/src/scheduler/pool.rs @@ -6,6 +6,9 @@ use super::types::{SinkFn, SourceFn, Stage, WorkerTask}; // ── Pipeline ────────────────────────────────────────────────────────────────── +/// A complete pipeline description: a source, the ordered stages and a sink, all over one data type. +/// +/// Build it with the `make_pipeline!` macro and run it with [`WorkerPool`]. pub struct Pipeline { source: SourceFn, stages: Vec>, @@ -13,6 +16,7 @@ pub struct Pipeline { } impl Pipeline { + /// Assembles a pipeline from its parts. Prefer the `make_pipeline!` macro. pub fn new(source: SourceFn, stages: Vec>, sink: SinkFn) -> Self { Self { source, @@ -24,6 +28,10 @@ impl Pipeline { // ── WorkerPool ──────────────────────────────────────────────────────────────── +/// Runs a [`Pipeline`] on a pool of worker threads. +/// +/// Stages run in parallel on `n_workers` threads; `capacity` bounds every internal channel, which +/// bounds the number of items in flight. pub struct WorkerPool { pipeline: Pipeline, handles: Vec>, @@ -35,7 +43,16 @@ impl WorkerPool where DATA: Send + Sync + 'static, { + /// Creates a pool for `pipeline`. + /// + /// # Panics + /// + /// Panics if `n_workers` is `0` (no item would ever be processed) or if `capacity` is `0` + /// (rendezvous channels: the scheduler can then block sending a task while every worker blocks + /// sending its result, which is a deadlock). pub fn new(pipeline: Pipeline, n_workers: usize, capacity: usize) -> Self { + assert!(n_workers > 0, "WorkerPool needs at least one worker"); + assert!(capacity > 0, "WorkerPool needs a capacity of at least 1"); Self { pipeline, handles: Vec::new(), @@ -44,7 +61,18 @@ where } } - pub fn run(mut self) { + /// Runs the pipeline to completion on the calling thread (the workers are spawned threads). + /// + /// The run is fail-fast: the first error (a fallible stage or sink returning `Err`, a source + /// error, a runtime `TypeMismatch`, or a panic in a worker, source or sink closure) stops the + /// pipeline, discards the items still in flight and is returned. Nothing is printed. + /// + /// # Errors + /// + /// Returns the first [`PipelineError`] met, `Ok(())` if the source was exhausted and every item + /// reached the sink. + pub fn run(mut self) -> Result<(), PipelineError> { + let mut outcome: Result<(), PipelineError> = Ok(()); let n = self.pipeline.stages.len(); // ── Inter-stage channels ─────────────────────────────────────────── @@ -137,13 +165,10 @@ where if k == 0 { // ── Sink error ──────────────────────────────────────── - match oper.recv(&sink_err_rx) { - Ok(e) => { - eprintln!("Sink error: {:?}", e); - break; - } - Err(_) => break, + if let Ok(e) = oper.recv(&sink_err_rx) { + outcome = Err(e); } + break; } else if k == 1 { // ── Delta of a flat worker ──────────────────────────── // delta = N - 1 (N items pushed, 1 item consumed) @@ -162,7 +187,10 @@ where dispatch(data, 0, &stages, &worker_tx, &mut flat_workers_active); } } - Ok(Err(e)) => eprintln!("Source error: {:?}", e), + Ok(Err(e)) => { + outcome = Err(e); + break; + } Err(_) => source_done = true, } } else { @@ -184,7 +212,10 @@ where ); } } - Ok(Err(e)) => eprintln!("Stage {} error: {:?}", stage, e), + Ok(Err(e)) => { + outcome = Err(e); + break; + } Err(_) => break, } } @@ -201,8 +232,15 @@ where drop(flat_delta_rx); drop(sink_err_rx); + // A thread that panicked outside the caught worker closures (source or sink closure) is an error + // too: its channel just closes, which the loop above cannot tell from a normal end. for h in self.handles { - let _ = h.join(); + if h.join().is_err() && outcome.is_ok() { + outcome = Err(super::error::panic_error(Box::new( + "a pipeline thread (source or sink) panicked", + ))); + } } + outcome } } diff --git a/src/scheduler/runner.rs b/src/scheduler/runner.rs index 3e54556..ddda7a3 100644 --- a/src/scheduler/runner.rs +++ b/src/scheduler/runner.rs @@ -1,10 +1,14 @@ use crossbeam_channel::{Receiver, Sender, bounded}; +use std::panic::{AssertUnwindSafe, catch_unwind}; use std::thread; -use super::error::PipelineError; +use super::error::{PipelineError, panic_error}; use super::types::{SinkFn, SourceFn, Stage, WorkerTask}; // ── Thread runners ──────────────────────────────────────────────────────────── +// +// A failed `send` in these runners means the receiving end is gone: the pipeline is stopping (an error +// was recorded by the scheduler, or the output iterator was dropped). The item is dropped on purpose. pub(super) fn source_runner( mut source: SourceFn, @@ -27,7 +31,7 @@ where } Err(PipelineError::EndOfStream) => break, Err(e) => { - eprintln!("Source error: {:?}", e); + // Reported to the scheduler, which stops the pipeline and returns it. let _ = tx.send(Err(e)); break; } @@ -57,12 +61,20 @@ where match task { WorkerTask::Transform(data, idx) => { if let Stage::Transform(f) = &stages[idx] { - let _ = stage_txs[idx].send(f(data)); + // A panicking closure becomes a stage error instead of losing the item. + let r = catch_unwind(AssertUnwindSafe(|| f(data))) + .unwrap_or_else(|p| Err(panic_error(p))); + let _ = stage_txs[idx].send(r); } } WorkerTask::Flat(data, idx) => { if let Stage::Flat(f) = &stages[idx] { - f(data, &stage_txs[idx], &flat_delta_tx); + let outcome = catch_unwind(AssertUnwindSafe(|| { + f(data, &stage_txs[idx], &flat_delta_tx) + })); + if let Err(p) = outcome { + let _ = stage_txs[idx].send(Err(panic_error(p))); + } } } } diff --git a/src/scheduler/types.rs b/src/scheduler/types.rs index 7e1b03c..ff78457 100644 --- a/src/scheduler/types.rs +++ b/src/scheduler/types.rs @@ -28,7 +28,9 @@ pub type SharedFlatFn = /// A pipeline stage: plain transform (1→1) or flat transform (1→N). pub enum Stage { + /// 1→1 transform. Transform(SharedFn), + /// 1→N flat transform. Flat(SharedFlatFn), } diff --git a/src/throttle.rs b/src/throttle.rs index 1dca89f..baf3ff9 100644 --- a/src/throttle.rs +++ b/src/throttle.rs @@ -1,4 +1,6 @@ -use std::sync::{Arc, Condvar, Mutex}; +//! Counting semaphore and an iterator adaptor that bounds the number of items in flight. + +use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError}; // ── Throttle ────────────────────────────────────────────────────────────────── @@ -16,7 +18,13 @@ pub struct Throttle { } impl Throttle { + /// Creates a semaphore with `max` slots. + /// + /// # Panics + /// + /// Panics if `max` is `0`: no slot could ever be acquired. pub fn new(max: usize) -> Self { + assert!(max > 0, "Throttle needs at least one slot"); Self { count: Mutex::new(0), condvar: Condvar::new(), @@ -24,16 +32,28 @@ impl Throttle { } } - pub fn acquire(&self) { - let mut count = self.count.lock().unwrap(); + /// Locks the counter. The counter stays consistent even if another thread panicked while holding the + /// lock (the critical sections only add or subtract one), so a poisoned mutex is recovered, not + /// propagated: this runs in `Drop`, where a second panic would abort the process. + fn lock(&self) -> MutexGuard<'_, usize> { + self.count.lock().unwrap_or_else(PoisonError::into_inner) + } + + /// Takes one slot, waiting until one is free. Pair it with `release`: use + /// [`Throttle::acquire_guard`], which does it on drop. + pub(crate) fn acquire(&self) { + let mut count = self.lock(); while *count >= self.max { - count = self.condvar.wait(count).unwrap(); + count = self + .condvar + .wait(count) + .unwrap_or_else(PoisonError::into_inner); } *count += 1; } fn release(&self) { - let mut count = self.count.lock().unwrap(); + let mut count = self.lock(); *count -= 1; self.condvar.notify_one(); } @@ -71,24 +91,38 @@ impl Drop for ThrottleGuard { /// pipeline stage, carry the guard inside the worker closure until the item /// is fully processed, then let it drop. pub struct Throttled { + /// The wrapped item. pub item: T, + /// Holds one throttle slot until dropped. pub guard: ThrottleGuard, } // ── throttle() ──────────────────────────────────────────────────────────────── -/// Wrap `source` so that at most `max_concurrent` items are emitted before +/// Wraps `source` so that at most `max_concurrent` items are emitted before /// earlier ones have been fully processed (i.e. their `ThrottleGuard` dropped). /// /// Acquisition blocks the source thread until a slot is available. This must /// be called in the source thread, never inside a pipeline worker. /// +/// # Panics +/// +/// Panics if `max_concurrent` is `0`. +/// /// # Example /// -/// ```ignore -/// let throttled = obipipeline::throttle(file_paths, n_workers - 1); -/// // Use `throttled` as the pipeline source; carry `item.guard` through the -/// // Flat stage and let it drop when the file is fully read. +/// ``` +/// let paths = vec!["a.fa", "b.fa", "c.fa"]; +/// // At most 2 items are in flight: the third one is emitted once a guard is dropped. +/// let mut throttled = obipipeline::throttle(paths.into_iter(), 2); +/// let first = throttled.next().unwrap(); +/// let second = throttled.next().unwrap(); +/// drop(first.guard); // releases a slot +/// let third = throttled.next().unwrap(); +/// assert_eq!( +/// (first.item, second.item, third.item), +/// ("a.fa", "b.fa", "c.fa") +/// ); /// ``` pub fn throttle(source: I, max_concurrent: usize) -> impl Iterator> where diff --git a/tests/errors.rs b/tests/errors.rs new file mode 100644 index 0000000..58986f7 --- /dev/null +++ b/tests/errors.rs @@ -0,0 +1,274 @@ +//! Error semantics: the first error stops the pipeline and is returned by `finish()` / `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") +} + +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() +} + +#[test] +fn fallible_stage_error_is_returned_and_does_not_hang() { + let (items, result) = within(|| { + let pipe = make_pipe! { D : u64 => u64, |? fails_on_5 : Num => Num, }; + let mut it = pipe.apply(1..=10u64, 2, 4); + let items: Vec = it.by_ref().collect(); + (items, it.finish()) + }); + assert!(items.len() < 10, "the pipeline must stop early"); + let err = result.expect_err("the stage error must be returned"); + assert!(message(&err).contains("boom on 5"), "{err}"); +} + +#[test] +fn fallible_flat_stage_error_is_returned_and_does_not_hang() { + let result = within(|| { + let pipe = make_pipe! { D : u64 => u64, ||? flat_fails_on_5 : Num => Num, }; + pipe.apply(1..=10u64, 2, 4).finish() + }); + assert!(message(&result.unwrap_err()).contains("boom on 5")); +} + +#[test] +fn runtime_type_mismatch_is_returned_and_does_not_hang() { + let result = 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, + }; + pipe.apply(1..=10u64, 2, 4).finish() + }); + assert!(matches!(result, Err(PipelineError::TypeMismatch))); +} + +#[test] +fn worker_panic_is_returned_and_does_not_hang() { + let result = within(|| { + let pipe = make_pipe! { D : u64 => u64, | panics_on_3 : Num => Num, }; + pipe.apply(1..=10u64, 2, 4).finish() + }); + assert!(message(&result.unwrap_err()).contains("boom on 3")); +} + +#[test] +fn finish_is_ok_when_everything_went_through() { + let (n, result) = within(|| { + let pipe = make_pipe! { D : u64 => u64, |? fails_on_5 : Num => Num, }; + let mut it = pipe.apply(6..=20u64, 3, 4); + let n = it.by_ref().count(); + (n, it.finish()) + }); + assert_eq!(n, 15); + assert!(result.is_ok()); +} + +#[test] +fn capacity_one_works() { + let n = within(|| { + let pipe = make_pipe! { D : u64 => u64, |? fails_on_5 : Num => Num, }; + pipe.apply(6..=205u64, 2, 1).count() + }); + assert_eq!(n, 200); +} + +#[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 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 = "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() -> Vec> { + vec![ + Ok(1), + Ok(2), + Err(Error::new(ErrorKind::UnexpectedEof, "source broke")), + Ok(4), + ] +} + +#[test] +fn pipeline_returns_a_source_error() { + let result = within(|| { + pool_run(make_pipeline! { + D, + source? fallible_source() => Num, + | identity : Num => Num, + sink ignore @ Num, + }) + }); + assert!(message(&result.unwrap_err()).contains("source broke")); +} + +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); +} + +// ── 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()); +}