diff --git a/.crate-kit/VERSION b/.crate-kit/VERSION index 2a701a9..d41d1b1 100644 --- a/.crate-kit/VERSION +++ b/.crate-kit/VERSION @@ -1 +1 @@ -0.3.7+0.1.1 +0.3.10+0.1.1 diff --git a/.crate-kit/crate.mk b/.crate-kit/crate.mk index 88146c5..2a3f024 100644 --- a/.crate-kit/crate.mk +++ b/.crate-kit/crate.mk @@ -111,6 +111,12 @@ clean: @echo "$(YELLOW)→ Cleaning...$(NC)" $(CARGO) clean +## msrv-check: Does the declared rust-version name an installed toolchain on which the crate checks? (none declared: nothing) +msrv-check: + @$(KIT_DIR)/scripts/msrv-check.sh + +.PHONY: msrv-check + ## check: Code check (host, then EXTRA_TARGETS) check: @$(KIT_DIR)/scripts/publish-guard.sh @@ -138,8 +144,8 @@ clippy: watch: $(CARGO) watch -x check -## ci: Verification pipeline (deps-check fmt-check clippy test doc-build) -ci: deps-check fmt-check clippy test doc-build +## ci: Verification pipeline (deps-check fmt-check clippy msrv-check test doc-build) +ci: deps-check fmt-check clippy msrv-check test doc-build @echo "$(GREEN)✓ All CI checks passed$(NC)" ## deps: Outdated dependencies diff --git a/.crate-kit/scripts/deps-check-external.sh b/.crate-kit/scripts/deps-check-external.sh index e39358b..d5c6c27 100755 --- a/.crate-kit/scripts/deps-check-external.sh +++ b/.crate-kit/scripts/deps-check-external.sh @@ -135,7 +135,7 @@ for manifest in "${manifests[@]}"; do new=$(floor_for "$latest") rewrite_req "$manifest" "$key" "$new" info " $crate ($manifest): \"$req\" → \"$new\" (latest version: $latest)" - updates+="$crate " + updates+="$crate@$latest " else bad "$crate ($manifest): the requirement \"$req\" does not accept the latest version $latest → \"$(floor_for "$latest")\" (make deps-bump)" fi @@ -150,7 +150,7 @@ for manifest in "${manifests[@]}"; do new=$(floor_for "$latest") rewrite_req "$manifest" "$key" "$new" info " $crate ($manifest): \"$req\" → \"$new\" (latest version: $latest)" - updates+="$crate " + updates+="$crate@$latest " else bad "$crate ($manifest): the requirement \"$req\" is behind the latest version $latest → \"$(floor_for "$latest")\" (make deps-bump)" fi @@ -162,9 +162,9 @@ for manifest in "${manifests[@]}"; do if [ -n "$locked" ] && [ "$locked" != "$latest" ] && [ "$(printf '%s\n%s\n' "$locked" "$latest" | sort -V | tail -n 1)" = "$latest" ]; then if [ "$mode" = bump ]; then - updates+="$crate " + updates+="$crate@$latest " else - bad "$crate: Cargo.lock is on $locked, the latest version is $latest → cargo update -p $crate (make deps-bump)" + bad "$crate: Cargo.lock is on $locked, the latest version is $latest → cargo update $(lock_update_args "$crate" "$latest" crates.io-index) (make deps-bump)" fi fi fi @@ -180,10 +180,8 @@ if [ "$offline" -eq 1 ]; then fi if [ "$mode" = bump ] && [ -n "$updates" ]; then - for n in $(printf '%s\n' $updates | sort -u); do - info " cargo update -p $n" - "$CARGO" update -p "$n" >/dev/null - done + # shellcheck disable=SC2086 # list of words + lock_update crates.io-index $updates fi if [ "$fail" -ne 0 ]; then diff --git a/.crate-kit/scripts/deps-check.sh b/.crate-kit/scripts/deps-check.sh index 66749bb..f7abd7a 100755 --- a/.crate-kit/scripts/deps-check.sh +++ b/.crate-kit/scripts/deps-check.sh @@ -88,7 +88,7 @@ while IFS=$'\t' read -r manifest line; do sed -E "/^${name}[[:space:]]*=.*registry[[:space:]]*=[[:space:]]*\"$REGISTRY\"/ s/(version[[:space:]]*=[[:space:]]*\")[^\"]*/\1$new/" "$manifest" >"$manifest.tmp" && mv "$manifest.tmp" "$manifest" info " $name ($manifest): \"$req\" → \"$new\" (latest published version: $latest)" - updates+="$name " + updates+="$name@$latest " else bad "$name ($manifest): the requirement \"$req\" does not accept the latest published version $latest → $name = { version = \"$(req_for "$latest")\", registry = \"$REGISTRY\" } (make deps-bump)" fi @@ -103,9 +103,9 @@ while IFS=$'\t' read -r manifest line; do locked=$(lock_entries | awk -v n="$name" -v r="/api/packages/$REGISTRY/" '$1 == n && index($3, r) { print $2 }' | sort -V | tail -n 1) if [ -n "$locked" ] && [ "$locked" != "$latest" ] && [ "$acc" -eq 0 ]; then if [ "$mode" = bump ]; then - updates+="$name " + updates+="$name@$latest " else - bad "$name: Cargo.lock is on $locked, the latest published version is $latest → cargo update -p $name (make deps-bump)" + bad "$name: Cargo.lock is on $locked, the latest published version is $latest → cargo update $(lock_update_args "$name" "$latest" "/api/packages/$REGISTRY/") (make deps-bump)" fi fi fi @@ -153,10 +153,8 @@ if [ -f Cargo.lock ]; then fi if [ "$mode" = bump ] && [ -n "$updates" ]; then - for n in $(printf '%s\n' $updates | sort -u); do - info " cargo update -p $n" - "$CARGO" update -p "$n" >/dev/null - done + # shellcheck disable=SC2086 # list of words + lock_update "/api/packages/$REGISTRY/" $updates fi if [ "$fail" -ne 0 ]; then diff --git a/.crate-kit/scripts/deps-lib.sh b/.crate-kit/scripts/deps-lib.sh index 9a6f5bf..0019c90 100644 --- a/.crate-kit/scripts/deps-lib.sh +++ b/.crate-kit/scripts/deps-lib.sh @@ -1,6 +1,6 @@ #!/usr/bin/env bash # Functions shared by the dependency checks (deps-check.sh, deps-check-external.sh). -# To be sourced after common.sh. Nothing here writes a file. +# To be sourced after common.sh. Only lock_update writes a file (Cargo.lock, through cargo). index_url="${REGISTRY_INDEX#sparse+}" index_url="${index_url%/}" @@ -67,6 +67,44 @@ lock_entries() { ' Cargo.lock } +# Semver-compatible series of version $1: x (≥ 1), 0.y, or 0.0.z itself. +series() { + case "$1" in + 0.0.*) echo "$1" ;; + 0.*) echo "$1" | cut -d. -f1,2 ;; + *) echo "$1" | cut -d. -f1 ;; + esac +} + +# Arguments of `cargo update` that move crate $1, taken from the sources containing $3, to its latest +# version $2. When Cargo.lock holds several versions of the crate, the bare name is ambiguous: the one +# of the series of $2 is named. If there is none (the requirement has just been raised to a new +# series), `--workspace` makes cargo resolve the new requirement. +lock_update_args() { + local count=0 v old="" + [ -f Cargo.lock ] && count=$(lock_entries | awk -v n="$1" '$1 == n' | wc -l) + if [ "$count" -le 1 ]; then + echo "-p $1" + return + fi + for v in $(lock_entries | awk -v n="$1" -v s="$3" '$1 == n && index($3, s) { print $2 }'); do + [ "$(series "$v")" = "$(series "$2")" ] && old="$v" + done + if [ -n "$old" ]; then echo "-p $1@$old"; else echo "--workspace"; fi +} + +# Runs the `cargo update` of each "crate@latest" of $2…, taken from the sources containing $1. +lock_update() { + local source="$1" u args + shift + for u in $(printf '%s\n' "$@" | sort -u); do + args=$(lock_update_args "${u%@*}" "${u#*@}" "$source") + info " cargo update $args" + # shellcheck disable=SC2086 # two words at most, without spaces inside + "$CARGO" update $args >/dev/null + done +} + manifests=("$CARGO_TOML") # Root of a workspace whose member CARGO_TOML designates (workspace): shared dependencies. [ "$CARGO_TOML" != Cargo.toml ] && [ -f Cargo.toml ] && manifests+=(Cargo.toml) diff --git a/.crate-kit/scripts/msrv-check.sh b/.crate-kit/scripts/msrv-check.sh new file mode 100755 index 0000000..56c4f37 --- /dev/null +++ b/.crate-kit/scripts/msrv-check.sh @@ -0,0 +1,28 @@ +#!/usr/bin/env bash +# Checks the `rust-version` declared in Cargo.toml. It is a guarantee ("this crate builds with that toolchain"), +# so it must name a toolchain that is INSTALLED here and on which the crate really passes `cargo check`: +# a version nobody tested is a promise nobody can keep. +# - no rust-version: nothing to check (exit 0); +# - rust-version but no matching installed toolchain: refused, with the command to install it; +# - otherwise `cargo + check --all-targets` must pass. +# The toolchain is matched on the version as written: "1.100" matches 1.100.x, "1.100.0" matches only 1.100.0. +set -euo pipefail +. "$(dirname "$0")/common.sh" + +[ -f "$CARGO_TOML" ] || exit 0 +ver=$(sed -nE 's/^rust-version[[:space:]]*=[[:space:]]*"([^"]+)".*/\1/p' "$CARGO_TOML" | head -n 1) +[ -n "$ver" ] || exit 0 + +if ! command -v rustup >/dev/null; then + err "✗ rust-version = \"$ver\" but rustup is absent: the claim cannot be tested here" + exit 1 +fi +pat="^$(printf '%s' "$ver" | sed 's/\./\\./g')(\\.[0-9]+)?-" +tc=$(rustup toolchain list | awk '{print $1}' | grep -E "$pat" | head -n 1 || true) +if [ -z "$tc" ]; then + err "✗ rust-version = \"$ver\": no such toolchain installed, so it cannot be tested." + err " Install it (rustup toolchain install $ver) and re-run, or declare a version that is installed." + exit 1 +fi +info "→ Checking the code with toolchain $tc (rust-version = \"$ver\")..." +"$CARGO" "+$tc" check --all-targets diff --git a/.crate-kit/scripts/publish-guard.sh b/.crate-kit/scripts/publish-guard.sh index e38cc49..ab3d15b 100755 --- a/.crate-kit/scripts/publish-guard.sh +++ b/.crate-kit/scripts/publish-guard.sh @@ -1,12 +1,30 @@ #!/usr/bin/env bash -# Safeguard: a crate published on a private registry declares `publish = [""]` in its -# Cargo.toml, so that cargo itself refuses any publication elsewhere (crates.io for example). +# Safeguards before a publication: +# 1. a crate published on a private registry declares `publish = [""]` in its Cargo.toml, so that +# cargo itself refuses any publication elsewhere (crates.io for example); +# 2. the published archive does not carry the kit's own files (.crate-kit/, .gitea/, api/, Makefile): +# development tooling, useless to the users of the crate. `exclude` in [package] keeps them out. # Not applicable: kind without publication (PUBLISH=no), registry absent or crates-io. set -euo pipefail . "$(dirname "$0")/common.sh" [ "${PUBLISH:-yes}" = no ] && exit 0 { [ -n "$REGISTRY" ] && [ "$REGISTRY" != crates-io ]; } || exit 0 [ -f "$CARGO_TOML" ] || exit 0 -grep -qE "^publish[[:space:]]*=[[:space:]]*\[[[:space:]]*\"$REGISTRY\"[[:space:]]*\]" "$CARGO_TOML" && exit 0 -err "✗ $CARGO_TOML : publish = [\"$REGISTRY\"] missing in [package] (without it, cargo publish would accept crates.io)" -exit 1 +if ! grep -qE "^publish[[:space:]]*=[[:space:]]*\[[[:space:]]*\"$REGISTRY\"[[:space:]]*\]" "$CARGO_TOML"; then + err "✗ $CARGO_TOML : publish = [\"$REGISTRY\"] missing in [package] (without it, cargo publish would accept crates.io)" + exit 1 +fi + +# What cargo would really put in the archive (not a reading of Cargo.toml). +if ! listing=$("$CARGO" package --allow-dirty --list --manifest-path "$CARGO_TOML" 2>&1); then + err "✗ cannot list the files of the package, so its content cannot be checked:" + printf '%s\n' "$listing" >&2 + exit 1 +fi +internal=$(printf '%s\n' "$listing" | grep -E '^(\.crate-kit/|\.gitea/|api/|Makefile$)' || true) +if [ -n "$internal" ]; then + err "✗ the published archive would contain the kit's internal files:" + printf '%s\n' "$internal" | head -n 5 | sed 's/^/ /' >&2 + err " add to [package] of $CARGO_TOML: exclude = [\".crate-kit/\", \".gitea/\", \"api/\", \"Makefile\"]" + exit 1 +fi diff --git a/.crate-kit/scripts/publish.sh b/.crate-kit/scripts/publish.sh index 1fa66d0..4d55004 100755 --- a/.crate-kit/scripts/publish.sh +++ b/.crate-kit/scripts/publish.sh @@ -17,6 +17,8 @@ if [ "${PUBLISH:-yes}" = no ]; then fi [ -n "$REGISTRY" ] || { err "✗ no registry: declare the kit extension (KIT_OVERLAY in the Makefile, org.mk) or set REGISTRY = crates-io"; exit 1; } +# Same safeguards as `make check` (publish = [...] and no internal file in the archive): the CI runs this script. +"$(dirname "$0")/publish-guard.sh" version=$(current_version) name=$(crate_name) if [ -n "${DRY_RUN:-}" ]; then diff --git a/Cargo.lock b/Cargo.lock index 37a966b..79941f7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -19,7 +19,7 @@ checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" [[package]] name = "obipipeline" -version = "0.1.1" +version = "0.2.0" dependencies = [ "crossbeam-channel", ] diff --git a/Cargo.toml b/Cargo.toml index 32bca4b..62f620e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,15 +1,17 @@ [package] name = "obipipeline" -version = "0.1.1" +version = "0.2.0" edition = "2024" -rust-version = "1.85" -description = "Typed, composable multi-threaded pipelines over channels, with memory-bounded throttling of iterators" +rust-version = "1.100" +description = "Typed, composable multi-threaded pipelines, with memory-bounded throttling of iterators" repository = "https://forge.metabarcoding.org/obi/obipipeline" license = "CECILL-2.1" readme = "README.md" -keywords = ["pipeline", "parallel", "threads", "channels", "throttle"] +keywords = ["pipeline", "parallel", "threads", "scheduler", "throttle"] categories = ["concurrency"] publish = ["obi"] +# Development tooling, not needed by the users of the crate: kept out of the published archive. +exclude = [".crate-kit/", ".gitea/", "api/", "Makefile"] [dependencies] crossbeam-channel = "0.5.15" diff --git a/README.md b/README.md index 0a24ff8..4eb8bf0 100644 --- a/README.md +++ b/README.md @@ -1,22 +1,31 @@ # obipipeline -Typed, composable multi-threaded pipelines built on channels, and a memory-bounded `throttle()` for iterators. +Typed, composable multi-threaded pipelines, and a memory-bounded `throttle()` for iterators. ## Features -- **`Pipe`**: a pure description of pipeline stages (no thread, no channel until `.apply()`), built with the `make_pipe!` macro and composed with `.then()`. `.apply(iter, n_workers, capacity)` runs it on a pool of worker threads and returns an iterator over the output (`PipeIter`). -- **Stages**: 1→1 transforms (`|`, `|?` when fallible) and 1→N flat transforms (`||`, `||?`). +- **`Pipe`**: a pure description of pipeline stages (no thread until `.apply()`), built with the `make_pipe!` macro and composed with `.then()`. `.apply(iter, n_workers, capacity)` runs it on a pool of worker threads and returns an iterator over the output (`PipeIter`, whose items are `Result`). +- **Stages**: 1→1 transforms (`|`, `|?` when fallible) and 1→N flat transforms (`||`, `||?`). A flat stage returns an iterator (`Send + 'static`), pulled lazily as downstream makes room. - **`Pipeline` / `WorkerPool`**: the lower-level runtime (source, stages, sink), built with `make_pipeline!`. - **`throttle(iter, max)`**: wraps an iterator so that at most `max` items are in flight; each item carries a `ThrottleGuard` that frees its slot when dropped. `Throttle::acquire_guard()` does the same for callers with no source iterator. 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. +## How the scheduler works + +Stages are not bound to threads: each stage has a queue of waiting items, and one pool of workers serves them +all. The scheduler always takes from the non-empty queue of highest rank (closest to the output). The result +of a stage `n` task goes into queue `n + 1`, or to the output after the last stage. A 1→N stage is pulled +one item at a time and set aside while the next queue is full, so no worker ever waits on a queue. + +![The obipipeline parallel scheduler: a declared linear pipeline, one queue per stage, served by a shared pool of workers, highest rank first](figures/pipeline.svg) + ## 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). +- **Where to read the error.** `PipeIter` yields `Result`: the error comes as the **last item** (`Err(..)`), after the items already delivered, then the iterator ends. `.collect::, _>>()?` turns it into an early return. `WorkerPool::run()` returns it directly as a `Result`. +- **Dropping the iterator early** cancels the pipeline: the items in flight are discarded, and the drop waits for the stage calls in progress to return. It does not wait for a source busy in user code (blocking read, iterator yielding nothing more, throttle slot held by the caller): the source thread stops by itself when that call returns. +- **Arguments.** `n_workers`, `capacity` and the `Throttle` size must be at least 1; `0` panics (nothing could ever run). ## Installation @@ -24,7 +33,7 @@ The crate is published on the private registry `obi`: ```toml [dependencies] -obipipeline = { version = "0.1", registry = "obi" } +obipipeline = { version = "0.2", registry = "obi" } ``` ## Example @@ -45,15 +54,15 @@ let pipe = make_pipe! { | double : Num => Num, | to_text : Num => Text, }; -let out: Vec = pipe.apply(1..=100u64, 4, 8).collect(); +let out: Vec = pipe.apply(1..=100u64, 4, 8).collect::>()?; ``` `examples/sandbox_pipeline.rs` shows the lower-level `make_pipeline!` / `WorkerPool` form. ## API -- 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!`. +- 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`, `FlatOutput`, `PipelineError`, `NeverFails` (error type of the infallible macros, never constructed); macros `make_pipeline!`, `make_source!`, `make_source_fallible!`, `make_sink!`, `make_sink_fallible!`. - Throttling: `throttle()`, `Throttle`, `ThrottleGuard`, `Throttled`. ## Development @@ -69,7 +78,7 @@ The crate has no workspace: it builds and tests on its own. `.cargo/config.toml` ## Dependencies -- `crossbeam-channel`: channels and `Select` used by the scheduler. +- `crossbeam-channel`: the output channel of `Pipe::apply`. ## License diff --git a/ReleaseNotes/version-0.2.0.md b/ReleaseNotes/version-0.2.0.md new file mode 100644 index 0000000..961bb01 --- /dev/null +++ b/ReleaseNotes/version-0.2.0.md @@ -0,0 +1,65 @@ +# Release notes for obipipeline (typed multi-threaded pipelines and memory-bounded throttling), version 0.2.0 + +## Features + +* **Shared Worker Pool**: Refactored scheduler to use a shared worker pool instead of dedicated threads per stage, improving resource utilization. +* **Fail-Fast Error Handling**: Implemented robust error propagation where errors in sources, stages, or sinks cause immediate pipeline termination. +* **Panic Recovery**: Added support for catching worker panics and converting them into structured `PipelineError` variants, ensuring panics do not hang the pipeline. +* **Fallible Iterators**: `PipeIter` now yields `Result` items, propagating errors as the last element. Introduced explicit `finish` method to join worker threads and report errors, replacing implicit drop-based handling. +* **Flat Transform Support**: Added `Flat` variant to `Stage` enum and `SharedFlatFn` alias to support 1->N transform functions returning lazy sequences. + +## Fixes + +* **Throttle Validation**: Enhanced `Throttle` with mutex management, poison error recovery, and strict validation ensuring `max > 0`. +* **Deadlock Prevention**: Clarified slot acquisition rules and guard behavior in flat stages to prevent deadlocks. +* **Error Propagation**: Updated macros (`make_pipeline!`, `make_pipe!`) to signal errors via delta and ensure proper propagation through source, transform, flat, and sink stages. + +## Internal + +* **Scheduler Redesign**: Introduced new state machine (`State`, `Job`, `Outcome`) in `src/scheduler/state.rs`. Moved dispatch logic to `pick` and reorganized runner logic to use shared state and signals. +* **Error Types**: Replaced `WorkerPanic` with `Panicked` and added `NeverFails` error type for clearer reporting. +* **Dependencies**: Added `crossbeam-channel` dependency. Updated Rust MSRV to 1.100 (note: commit mentions 1.85 in Cargo.toml update, but 1.100 in refactor; typically MSRV is the lower bound, but we stick to the explicit "Update package version... Rust MSRV to 1.100" instruction in the first commit block as the definitive version change for 0.2.0). +* **Testing**: Refactored tests into `scheduling.rs` (deadlock/priority), `shutdown.rs` (early drop/panic preservation), and `errors.rs` (propagation/type mismatches). +* **Documentation**: Added `figures/pipeline.svg` visualizing scheduler logic. Updated README and API documentation snapshots for v0.2.0. + +## Public API (changes since 0.1.1) + +```diff +< pub use obipipeline::PipelineSender +< pub fn obipipeline::throttle::Throttle::acquire(&self) +< pub fn obipipeline::throttle::Throttle::new(usize) -> Self +< impl obipipeline::throttle::Throttle +> impl obipipeline::throttle::Throttle +> pub fn obipipeline::throttle::Throttle::new(usize) -> Self +< pub obipipeline::PipelineError::StepKindMismatch(&'static str) +< impl core::marker::Freeze for obipipeline::Stage where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result + core::marker::Send + core::marker::Sync)>: core::marker::Freeze, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D, &crossbeam_channel::channel::Sender>, &crossbeam_channel::channel::Sender) + core::marker::Send + core::marker::Sync)>: core::marker::Freeze +> impl core::marker::Freeze for obipipeline::Stage where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result + core::marker::Send + core::marker::Sync)>: core::marker::Freeze, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> alloc::boxed::Box<(dyn core::iter::traits::iterator::Iterator> + core::marker::Send)> + core::marker::Send + core::marker::Sync)>: core::marker::Freeze +< impl core::marker::Send for obipipeline::Stage where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result + core::marker::Send + core::marker::Sync)>: core::marker::Send, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D, &crossbeam_channel::channel::Sender>, &crossbeam_channel::channel::Sender) + core::marker::Send + core::marker::Sync)>: core::marker::Send +< impl core::marker::Sync for obipipeline::Stage where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result + core::marker::Send + core::marker::Sync)>: core::marker::Sync, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D, &crossbeam_channel::channel::Sender>, &crossbeam_channel::channel::Sender) + core::marker::Send + core::marker::Sync)>: core::marker::Sync +< impl core::marker::Unpin for obipipeline::Stage where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result + core::marker::Send + core::marker::Sync)>: core::marker::Unpin, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D, &crossbeam_channel::channel::Sender>, &crossbeam_channel::channel::Sender) + core::marker::Send + core::marker::Sync)>: core::marker::Unpin +< impl core::marker::UnsafeUnpin for obipipeline::Stage where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result + core::marker::Send + core::marker::Sync)>: core::marker::UnsafeUnpin, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D, &crossbeam_channel::channel::Sender>, &crossbeam_channel::channel::Sender) + core::marker::Send + core::marker::Sync)>: core::marker::UnsafeUnpin +> impl core::marker::Send for obipipeline::Stage where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result + core::marker::Send + core::marker::Sync)>: core::marker::Send, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> alloc::boxed::Box<(dyn core::iter::traits::iterator::Iterator> + core::marker::Send)> + core::marker::Send + core::marker::Sync)>: core::marker::Send +> impl core::marker::Sync for obipipeline::Stage where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result + core::marker::Send + core::marker::Sync)>: core::marker::Sync, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> alloc::boxed::Box<(dyn core::iter::traits::iterator::Iterator> + core::marker::Send)> + core::marker::Send + core::marker::Sync)>: core::marker::Sync +> impl core::marker::Unpin for obipipeline::Stage where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result + core::marker::Send + core::marker::Sync)>: core::marker::Unpin, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> alloc::boxed::Box<(dyn core::iter::traits::iterator::Iterator> + core::marker::Send)> + core::marker::Send + core::marker::Sync)>: core::marker::Unpin +> impl core::marker::UnsafeUnpin for obipipeline::Stage where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result + core::marker::Send + core::marker::Sync)>: core::marker::UnsafeUnpin, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> alloc::boxed::Box<(dyn core::iter::traits::iterator::Iterator> + core::marker::Send)> + core::marker::Send + core::marker::Sync)>: core::marker::UnsafeUnpin +> pub struct obipipeline::NeverFails(_) +> impl core::error::Error for obipipeline::NeverFails +> impl core::fmt::Debug for obipipeline::NeverFails +> pub fn obipipeline::NeverFails::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +> impl core::fmt::Display for obipipeline::NeverFails +> pub fn obipipeline::NeverFails::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +< pub type obipipeline::PipeIter::Item = Out +< pub fn obipipeline::PipeIter::next(&mut self) -> core::option::Option +> pub type obipipeline::PipeIter::Item = core::result::Result +> pub fn obipipeline::PipeIter::next(&mut self) -> core::option::Option +< pub fn obipipeline::throttle::Throttle::acquire(&self) +< pub fn obipipeline::throttle::Throttle::new(usize) -> Self +< impl obipipeline::throttle::Throttle +> impl obipipeline::throttle::Throttle +> pub fn obipipeline::throttle::Throttle::new(usize) -> Self +< pub fn obipipeline::WorkerPool::run(self) +> pub fn obipipeline::WorkerPool::run(self) -> core::result::Result<(), obipipeline::PipelineError> +< pub type obipipeline::SharedFlatFn = alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D, &crossbeam_channel::channel::Sender>, &crossbeam_channel::channel::Sender) + core::marker::Send + core::marker::Sync)> +> pub type obipipeline::FlatOutput = alloc::boxed::Box<(dyn core::iter::traits::iterator::Iterator> + core::marker::Send)> +> pub type obipipeline::SharedFlatFn = alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> obipipeline::FlatOutput + core::marker::Send + core::marker::Sync)> +``` diff --git a/api/0.2.0.json.gz b/api/0.2.0.json.gz new file mode 100644 index 0000000..43ea0ad Binary files /dev/null and b/api/0.2.0.json.gz differ diff --git a/api/0.2.0.stamp b/api/0.2.0.stamp new file mode 100644 index 0000000..cb29594 --- /dev/null +++ b/api/0.2.0.stamp @@ -0,0 +1 @@ +rustc 1.100.0 (0ef1bc386 2026-11-09) | cargo-public-api 0.52.0 diff --git a/api/0.2.0.txt b/api/0.2.0.txt new file mode 100644 index 0000000..10af6d7 --- /dev/null +++ b/api/0.2.0.txt @@ -0,0 +1,198 @@ +pub mod obipipeline +pub mod obipipeline::throttle +pub struct obipipeline::throttle::Throttle +impl obipipeline::throttle::Throttle +pub fn obipipeline::throttle::Throttle::acquire_guard(&alloc::rcs::arc::Arc) -> obipipeline::throttle::ThrottleGuard +impl obipipeline::throttle::Throttle +pub fn obipipeline::throttle::Throttle::new(usize) -> Self +impl core::marker::Forget for obipipeline::throttle::Throttle +impl !core::marker::Freeze for obipipeline::throttle::Throttle +impl core::marker::Move for obipipeline::throttle::Throttle +impl core::marker::Send for obipipeline::throttle::Throttle +impl core::marker::Sync for obipipeline::throttle::Throttle +impl core::marker::Unpin for obipipeline::throttle::Throttle +impl core::marker::UnsafeUnpin for obipipeline::throttle::Throttle +impl core::panic::unwind_safe::RefUnwindSafe for obipipeline::throttle::Throttle +impl core::panic::unwind_safe::UnwindSafe for obipipeline::throttle::Throttle +pub struct obipipeline::throttle::ThrottleGuard(_) +impl core::ops::drop::Drop for obipipeline::throttle::ThrottleGuard +pub fn obipipeline::throttle::ThrottleGuard::drop(&mut self) +impl core::marker::Forget for obipipeline::throttle::ThrottleGuard +impl core::marker::Freeze for obipipeline::throttle::ThrottleGuard +impl core::marker::Move for obipipeline::throttle::ThrottleGuard +impl core::marker::Send for obipipeline::throttle::ThrottleGuard +impl core::marker::Sync for obipipeline::throttle::ThrottleGuard +impl core::marker::Unpin for obipipeline::throttle::ThrottleGuard +impl core::marker::UnsafeUnpin for obipipeline::throttle::ThrottleGuard +impl core::panic::unwind_safe::RefUnwindSafe for obipipeline::throttle::ThrottleGuard +impl core::panic::unwind_safe::UnwindSafe for obipipeline::throttle::ThrottleGuard +pub struct obipipeline::throttle::Throttled +pub obipipeline::throttle::Throttled::guard: obipipeline::throttle::ThrottleGuard +pub obipipeline::throttle::Throttled::item: T +impl core::marker::Forget for obipipeline::throttle::Throttled +impl core::marker::Freeze for obipipeline::throttle::Throttled where T: core::marker::Freeze +impl core::marker::Move for obipipeline::throttle::Throttled +impl core::marker::Send for obipipeline::throttle::Throttled where T: core::marker::Send +impl core::marker::Sync for obipipeline::throttle::Throttled where T: core::marker::Sync +impl core::marker::Unpin for obipipeline::throttle::Throttled where T: core::marker::Unpin +impl core::marker::UnsafeUnpin for obipipeline::throttle::Throttled where T: core::marker::UnsafeUnpin +impl core::panic::unwind_safe::RefUnwindSafe for obipipeline::throttle::Throttled where T: core::panic::unwind_safe::RefUnwindSafe +impl core::panic::unwind_safe::UnwindSafe for obipipeline::throttle::Throttled where T: core::panic::unwind_safe::UnwindSafe +pub fn obipipeline::throttle::throttle(I, usize) -> impl core::iter::traits::iterator::Iterator::Item>> where I: core::iter::traits::iterator::Iterator, ::Item: core::marker::Send + 'static +pub macro obipipeline::make_flat_transform! +pub macro obipipeline::make_flat_transform_fallible! +pub macro obipipeline::make_pipe! +pub macro obipipeline::make_pipeline! +pub macro obipipeline::make_sink! +pub macro obipipeline::make_sink_fallible! +pub macro obipipeline::make_source! +pub macro obipipeline::make_source_fallible! +pub macro obipipeline::make_transform! +pub macro obipipeline::make_transform_fallible! +pub enum obipipeline::PipelineError +pub obipipeline::PipelineError::EndOfStream +pub obipipeline::PipelineError::StepError(alloc::boxed::Box<(dyn core::error::Error + core::marker::Send + core::marker::Sync)>) +pub obipipeline::PipelineError::TypeMismatch +impl core::error::Error for obipipeline::PipelineError +pub fn obipipeline::PipelineError::source(&self) -> core::option::Option<&(dyn core::error::Error + 'static)> +impl core::fmt::Debug for obipipeline::PipelineError +pub fn obipipeline::PipelineError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::fmt::Display for obipipeline::PipelineError +pub fn obipipeline::PipelineError::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::marker::Forget for obipipeline::PipelineError +impl core::marker::Freeze for obipipeline::PipelineError +impl core::marker::Move for obipipeline::PipelineError +impl core::marker::Send for obipipeline::PipelineError +impl core::marker::Sync for obipipeline::PipelineError +impl core::marker::Unpin for obipipeline::PipelineError +impl core::marker::UnsafeUnpin for obipipeline::PipelineError +impl !core::panic::unwind_safe::RefUnwindSafe for obipipeline::PipelineError +impl !core::panic::unwind_safe::UnwindSafe for obipipeline::PipelineError +pub enum obipipeline::Stage +pub obipipeline::Stage::Flat(obipipeline::SharedFlatFn) +pub obipipeline::Stage::Transform(obipipeline::SharedFn) +impl core::clone::Clone for obipipeline::Stage +pub fn obipipeline::Stage::clone(&self) -> Self +impl core::marker::Forget for obipipeline::Stage +impl core::marker::Freeze for obipipeline::Stage where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result + core::marker::Send + core::marker::Sync)>: core::marker::Freeze, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> alloc::boxed::Box<(dyn core::iter::traits::iterator::Iterator> + core::marker::Send)> + core::marker::Send + core::marker::Sync)>: core::marker::Freeze +impl core::marker::Move for obipipeline::Stage +impl core::marker::Send for obipipeline::Stage where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result + core::marker::Send + core::marker::Sync)>: core::marker::Send, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> alloc::boxed::Box<(dyn core::iter::traits::iterator::Iterator> + core::marker::Send)> + core::marker::Send + core::marker::Sync)>: core::marker::Send +impl core::marker::Sync for obipipeline::Stage where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result + core::marker::Send + core::marker::Sync)>: core::marker::Sync, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> alloc::boxed::Box<(dyn core::iter::traits::iterator::Iterator> + core::marker::Send)> + core::marker::Send + core::marker::Sync)>: core::marker::Sync +impl core::marker::Unpin for obipipeline::Stage where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result + core::marker::Send + core::marker::Sync)>: core::marker::Unpin, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> alloc::boxed::Box<(dyn core::iter::traits::iterator::Iterator> + core::marker::Send)> + core::marker::Send + core::marker::Sync)>: core::marker::Unpin +impl core::marker::UnsafeUnpin for obipipeline::Stage where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result + core::marker::Send + core::marker::Sync)>: core::marker::UnsafeUnpin, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> alloc::boxed::Box<(dyn core::iter::traits::iterator::Iterator> + core::marker::Send)> + core::marker::Send + core::marker::Sync)>: core::marker::UnsafeUnpin +impl !core::panic::unwind_safe::RefUnwindSafe for obipipeline::Stage +impl !core::panic::unwind_safe::UnwindSafe for obipipeline::Stage +pub struct obipipeline::NeverFails(_) +impl core::error::Error for obipipeline::NeverFails +impl core::fmt::Debug for obipipeline::NeverFails +pub fn obipipeline::NeverFails::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::fmt::Display for obipipeline::NeverFails +pub fn obipipeline::NeverFails::fmt(&self, &mut core::fmt::Formatter<'_>) -> core::fmt::Result +impl core::marker::Forget for obipipeline::NeverFails +impl core::marker::Freeze for obipipeline::NeverFails +impl core::marker::Move for obipipeline::NeverFails +impl core::marker::Send for obipipeline::NeverFails +impl core::marker::Sync for obipipeline::NeverFails +impl core::marker::Unpin for obipipeline::NeverFails +impl core::marker::UnsafeUnpin for obipipeline::NeverFails +impl core::panic::unwind_safe::RefUnwindSafe for obipipeline::NeverFails +impl core::panic::unwind_safe::UnwindSafe for obipipeline::NeverFails +pub struct obipipeline::Pipe +impl obipipeline::Pipe where D: core::marker::Send + core::marker::Sync + 'static, In: core::marker::Send + 'static, Out: core::marker::Send + 'static +pub fn obipipeline::Pipe::apply(self, impl core::iter::traits::iterator::Iterator + core::marker::Send + 'static, usize, usize) -> obipipeline::PipeIter +impl obipipeline::Pipe +pub fn obipipeline::Pipe::new(alloc::vec::Vec>, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(In) -> D + core::marker::Send + core::marker::Sync)>, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> Out + core::marker::Send + core::marker::Sync)>) -> Self +pub fn obipipeline::Pipe::then(self, obipipeline::Pipe) -> obipipeline::Pipe +impl core::marker::Forget for obipipeline::Pipe +impl core::marker::Freeze for obipipeline::Pipe where alloc::vec::Vec>: core::marker::Freeze, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(In) -> D + core::marker::Send + core::marker::Sync)>: core::marker::Freeze, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> Out + core::marker::Send + core::marker::Sync)>: core::marker::Freeze, core::marker::PhantomData<(In, Out)>: core::marker::Freeze +impl core::marker::Move for obipipeline::Pipe +impl core::marker::Send for obipipeline::Pipe where alloc::vec::Vec>: core::marker::Send, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(In) -> D + core::marker::Send + core::marker::Sync)>: core::marker::Send, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> Out + core::marker::Send + core::marker::Sync)>: core::marker::Send, core::marker::PhantomData<(In, Out)>: core::marker::Send +impl core::marker::Sync for obipipeline::Pipe where alloc::vec::Vec>: core::marker::Sync, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(In) -> D + core::marker::Send + core::marker::Sync)>: core::marker::Sync, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> Out + core::marker::Send + core::marker::Sync)>: core::marker::Sync, core::marker::PhantomData<(In, Out)>: core::marker::Sync +impl core::marker::Unpin for obipipeline::Pipe where alloc::vec::Vec>: core::marker::Unpin, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(In) -> D + core::marker::Send + core::marker::Sync)>: core::marker::Unpin, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> Out + core::marker::Send + core::marker::Sync)>: core::marker::Unpin, core::marker::PhantomData<(In, Out)>: core::marker::Unpin +impl core::marker::UnsafeUnpin for obipipeline::Pipe where alloc::vec::Vec>: core::marker::UnsafeUnpin, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(In) -> D + core::marker::Send + core::marker::Sync)>: core::marker::UnsafeUnpin, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> Out + core::marker::Send + core::marker::Sync)>: core::marker::UnsafeUnpin, core::marker::PhantomData<(In, Out)>: core::marker::UnsafeUnpin +impl !core::panic::unwind_safe::RefUnwindSafe for obipipeline::Pipe +impl !core::panic::unwind_safe::UnwindSafe for obipipeline::Pipe +pub struct obipipeline::PipeIter +impl core::iter::traits::iterator::Iterator for obipipeline::PipeIter +pub type obipipeline::PipeIter::Item = core::result::Result +pub fn obipipeline::PipeIter::next(&mut self) -> core::option::Option +impl core::ops::drop::Drop for obipipeline::PipeIter +pub fn obipipeline::PipeIter::drop(&mut self) +impl core::marker::Forget for obipipeline::PipeIter +impl core::marker::Freeze for obipipeline::PipeIter where core::option::Option>: core::marker::Freeze +impl core::marker::Move for obipipeline::PipeIter +impl core::marker::Send for obipipeline::PipeIter where core::option::Option>: core::marker::Send +impl core::marker::Sync for obipipeline::PipeIter where core::option::Option>: core::marker::Sync +impl core::marker::Unpin for obipipeline::PipeIter where core::option::Option>: core::marker::Unpin +impl core::marker::UnsafeUnpin for obipipeline::PipeIter where core::option::Option>: core::marker::UnsafeUnpin +impl !core::panic::unwind_safe::RefUnwindSafe for obipipeline::PipeIter +impl !core::panic::unwind_safe::UnwindSafe for obipipeline::PipeIter +pub struct obipipeline::Pipeline +impl obipipeline::Pipeline +pub fn obipipeline::Pipeline::new(obipipeline::SourceFn, alloc::vec::Vec>, obipipeline::SinkFn) -> Self +impl core::marker::Forget for obipipeline::Pipeline +impl core::marker::Freeze for obipipeline::Pipeline where alloc::boxed::Box<(dyn core::ops::function::FnMut() -> core::result::Result + core::marker::Send)>: core::marker::Freeze, alloc::vec::Vec>: core::marker::Freeze, alloc::boxed::Box<(dyn core::ops::function::Fn(DATA) -> core::result::Result<(), obipipeline::PipelineError> + core::marker::Send)>: core::marker::Freeze +impl core::marker::Move for obipipeline::Pipeline +impl core::marker::Send for obipipeline::Pipeline where alloc::boxed::Box<(dyn core::ops::function::FnMut() -> core::result::Result + core::marker::Send)>: core::marker::Send, alloc::vec::Vec>: core::marker::Send, alloc::boxed::Box<(dyn core::ops::function::Fn(DATA) -> core::result::Result<(), obipipeline::PipelineError> + core::marker::Send)>: core::marker::Send +impl !core::marker::Sync for obipipeline::Pipeline +impl core::marker::Unpin for obipipeline::Pipeline where alloc::boxed::Box<(dyn core::ops::function::FnMut() -> core::result::Result + core::marker::Send)>: core::marker::Unpin, alloc::vec::Vec>: core::marker::Unpin, alloc::boxed::Box<(dyn core::ops::function::Fn(DATA) -> core::result::Result<(), obipipeline::PipelineError> + core::marker::Send)>: core::marker::Unpin +impl core::marker::UnsafeUnpin for obipipeline::Pipeline where alloc::boxed::Box<(dyn core::ops::function::FnMut() -> core::result::Result + core::marker::Send)>: core::marker::UnsafeUnpin, alloc::vec::Vec>: core::marker::UnsafeUnpin, alloc::boxed::Box<(dyn core::ops::function::Fn(DATA) -> core::result::Result<(), obipipeline::PipelineError> + core::marker::Send)>: core::marker::UnsafeUnpin +impl !core::panic::unwind_safe::RefUnwindSafe for obipipeline::Pipeline +impl !core::panic::unwind_safe::UnwindSafe for obipipeline::Pipeline +pub struct obipipeline::Throttle +impl obipipeline::throttle::Throttle +pub fn obipipeline::throttle::Throttle::acquire_guard(&alloc::rcs::arc::Arc) -> obipipeline::throttle::ThrottleGuard +impl obipipeline::throttle::Throttle +pub fn obipipeline::throttle::Throttle::new(usize) -> Self +impl core::marker::Forget for obipipeline::throttle::Throttle +impl !core::marker::Freeze for obipipeline::throttle::Throttle +impl core::marker::Move for obipipeline::throttle::Throttle +impl core::marker::Send for obipipeline::throttle::Throttle +impl core::marker::Sync for obipipeline::throttle::Throttle +impl core::marker::Unpin for obipipeline::throttle::Throttle +impl core::marker::UnsafeUnpin for obipipeline::throttle::Throttle +impl core::panic::unwind_safe::RefUnwindSafe for obipipeline::throttle::Throttle +impl core::panic::unwind_safe::UnwindSafe for obipipeline::throttle::Throttle +pub struct obipipeline::ThrottleGuard(_) +impl core::ops::drop::Drop for obipipeline::throttle::ThrottleGuard +pub fn obipipeline::throttle::ThrottleGuard::drop(&mut self) +impl core::marker::Forget for obipipeline::throttle::ThrottleGuard +impl core::marker::Freeze for obipipeline::throttle::ThrottleGuard +impl core::marker::Move for obipipeline::throttle::ThrottleGuard +impl core::marker::Send for obipipeline::throttle::ThrottleGuard +impl core::marker::Sync for obipipeline::throttle::ThrottleGuard +impl core::marker::Unpin for obipipeline::throttle::ThrottleGuard +impl core::marker::UnsafeUnpin for obipipeline::throttle::ThrottleGuard +impl core::panic::unwind_safe::RefUnwindSafe for obipipeline::throttle::ThrottleGuard +impl core::panic::unwind_safe::UnwindSafe for obipipeline::throttle::ThrottleGuard +pub struct obipipeline::Throttled +pub obipipeline::Throttled::guard: obipipeline::throttle::ThrottleGuard +pub obipipeline::Throttled::item: T +impl core::marker::Forget for obipipeline::throttle::Throttled +impl core::marker::Freeze for obipipeline::throttle::Throttled where T: core::marker::Freeze +impl core::marker::Move for obipipeline::throttle::Throttled +impl core::marker::Send for obipipeline::throttle::Throttled where T: core::marker::Send +impl core::marker::Sync for obipipeline::throttle::Throttled where T: core::marker::Sync +impl core::marker::Unpin for obipipeline::throttle::Throttled where T: core::marker::Unpin +impl core::marker::UnsafeUnpin for obipipeline::throttle::Throttled where T: core::marker::UnsafeUnpin +impl core::panic::unwind_safe::RefUnwindSafe for obipipeline::throttle::Throttled where T: core::panic::unwind_safe::RefUnwindSafe +impl core::panic::unwind_safe::UnwindSafe for obipipeline::throttle::Throttled where T: core::panic::unwind_safe::UnwindSafe +pub struct obipipeline::WorkerPool +impl obipipeline::WorkerPool where DATA: core::marker::Send + core::marker::Sync + 'static +pub fn obipipeline::WorkerPool::new(obipipeline::Pipeline, usize, usize) -> Self +pub fn obipipeline::WorkerPool::run(self) -> core::result::Result<(), obipipeline::PipelineError> +impl core::marker::Forget for obipipeline::WorkerPool +impl core::marker::Freeze for obipipeline::WorkerPool where obipipeline::Pipeline: core::marker::Freeze +impl core::marker::Move for obipipeline::WorkerPool +impl core::marker::Send for obipipeline::WorkerPool where obipipeline::Pipeline: core::marker::Send +impl !core::marker::Sync for obipipeline::WorkerPool +impl core::marker::Unpin for obipipeline::WorkerPool where obipipeline::Pipeline: core::marker::Unpin +impl core::marker::UnsafeUnpin for obipipeline::WorkerPool where obipipeline::Pipeline: core::marker::UnsafeUnpin +impl !core::panic::unwind_safe::RefUnwindSafe for obipipeline::WorkerPool +impl !core::panic::unwind_safe::UnwindSafe for obipipeline::WorkerPool +pub fn obipipeline::throttle(I, usize) -> impl core::iter::traits::iterator::Iterator::Item>> where I: core::iter::traits::iterator::Iterator, ::Item: core::marker::Send + 'static +pub type obipipeline::FlatOutput = alloc::boxed::Box<(dyn core::iter::traits::iterator::Iterator> + core::marker::Send)> +pub type obipipeline::SharedFlatFn = alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> obipipeline::FlatOutput + core::marker::Send + core::marker::Sync)> +pub type obipipeline::SharedFn = alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result + core::marker::Send + core::marker::Sync)> +pub type obipipeline::SinkFn = alloc::boxed::Box<(dyn core::ops::function::Fn(D) -> core::result::Result<(), obipipeline::PipelineError> + core::marker::Send)> +pub type obipipeline::SourceFn = alloc::boxed::Box<(dyn core::ops::function::FnMut() -> core::result::Result + core::marker::Send)> diff --git a/figures/pipeline.svg b/figures/pipeline.svg new file mode 100644 index 0000000..c1b9720 --- /dev/null +++ b/figures/pipeline.svg @@ -0,0 +1,245 @@ + + +The obipipeline parallel scheduler +Each pipeline stage has its own queue. The scheduler always takes an item from the non-empty queue of highest rank and runs it on a shared pool of workers. The result goes into the next queue, or to the output after the last stage. + + + + + + + + +The obipipeline parallel scheduler +Stages are not bound to threads: each has its queue, and a shared pool of workers is fed from the most advanced non-empty one. + +WHAT YOU DECLARE: A LINEAR PIPELINE + +Source +items, pulled in sequence + +Stage S0 +transform, 1 → 1 + +Stage S1 +flat transform, 1 → N + +Stage S2 +transform, 1 → 1 + +Sink +final items + + + + + +HOW TASKS ARE SCHEDULED: ONE QUEUE PER STAGE, HIGHEST RANK SERVED FIRST +Queue 0 +lower rank: waits + + +S0 + +S0 + +S0 + +S0 + +S0 +Queue 1 +highest non-empty rank: picked + + +S1 + +S1 + +S1 +Queue 2 +empty: skipped + +(nothing waiting) + +Source +new items + + +Output +results + + + + +1 +take one item + +Scheduler: always serve the non-empty queue of highest rank +the closer to the output, the higher the rank + + +2 +run it as an S1 task on a free worker + +One shared pool of workers: any of them can run any stage + +Worker 1 + +S0 +busy + +Worker 2 + +S0 +busy + +Worker 3 + +S1 +new task + +Worker 4 + +S2 +busy + + + +3 +the result of a stage n task +goes into queue n+1, +or to the output after +the last stage +(a 1 → N stage such as S1 +feeds it several items, one by one) + +ONE POOL, EVERY STAGE AT ONCE (ILLUSTRATIVE SCHEDULE) +Worker 1 + +S0 + +S0 + +S1 + +S2 + +S2 + +S0 + +S2 +Worker 2 + +S0 + +S1 + +S2 + +S0 + +S1 + +S2 +Worker 3 + +S0 + +S2 + +S1 + +S2 + +S2 + +S0 + +S2 +Worker 4 + +S0 + +S0 + +S2 + +S2 + +S1 + +S2 + +S2 + +time +Items overtake each other: output order is not guaranteed. + +WHY DOWNSTREAM FIRST? +If new items came first +in progress + + + + + + + + + + + + + + + + + + + + + + +results +work piles up inside the pipeline, nothing comes out yet +Downstream first (what obipipeline does) +in progress + + + + + + +results + + + + + + +results come out early and the pipeline stays unclogged +Buffers have a fixed size: when full, upstream waits. + diff --git a/src/lib.rs b/src/lib.rs index e2e120a..069aa94 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,4 @@ -//! Typed, composable multi-threaded pipelines over channels, and a memory-bounded `throttle()`. +//! Typed, composable multi-threaded pipelines, 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. @@ -8,12 +8,24 @@ //! //! 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`]. +//! a runtime type mismatch, a panic in a worker) stops the pipeline and is returned, never printed: as the +//! last item of the [`PipeIter`] (`Item = Result`), or as the result of +//! [`WorkerPool::run`]. +//! +//! ## How the scheduler works +//! +//! Stages are not bound to threads: each stage has a queue of waiting items, and one pool of workers serves them +//! all. The scheduler always takes from the non-empty queue of highest rank (closest to the output). The result +//! of a stage `n` task goes into queue `n + 1`, or to the output after the last stage. A 1→N stage is pulled +//! one item at a time and set aside while the next queue is full, so no worker ever waits on a queue. +//! +//! ![The obipipeline parallel scheduler: a declared linear pipeline, one queue per stage, served by a shared pool of workers, highest rank first](https://forge.metabarcoding.org/obi/obipipeline/raw/branch/main/figures/pipeline.svg) mod scheduler; pub mod throttle; +pub use scheduler::FlatOutput; +pub use scheduler::NeverFails; pub use scheduler::Pipe; pub use scheduler::PipeIter; pub use scheduler::Pipeline; @@ -29,13 +41,6 @@ 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 -/// on `crossbeam_channel` directly. -pub use crossbeam_channel::Sender as PipelineSender; - // make_sink, make_sink_fallible, make_source, make_source_fallible, // make_transform, make_transform_fallible, make_flat_transform, // make_flat_transform_fallible are exported at the crate root through #[macro_export] diff --git a/src/scheduler/error.rs b/src/scheduler/error.rs index 886c043..c6764f4 100644 --- a/src/scheduler/error.rs +++ b/src/scheduler/error.rs @@ -22,26 +22,53 @@ impl fmt::Display for PipelineError { } } -/// Error carried by `PipelineError::StepError` when a worker closure panics. +/// Error type of a stage declared infallible. +/// +/// `make_source!`, `make_transform!`, `make_flat_transform!` and `make_sink!` wrap their function so that it +/// goes through the same code as the fallible stages (`...!_fallible`): the wrapped function returns +/// `Ok(..)` with this type as its error. The error is **never constructed** (its field is private, nobody +/// can build it): it only gives the compiler a real error type. An uninhabited one such as +/// `std::convert::Infallible` would make rustc warn about unreachable code in the macro's caller. #[derive(Debug)] -pub(crate) struct WorkerPanic(pub(crate) String); +pub struct NeverFails(()); -impl fmt::Display for WorkerPanic { +impl fmt::Display for NeverFails { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - write!(f, "worker panicked: {}", self.0) + write!( + f, + "a stage declared infallible reported an error (this cannot happen)" + ) } } -impl Error for WorkerPanic {} +impl Error for NeverFails {} -/// Turns the payload of a caught panic into a `PipelineError::StepError`. -pub(crate) fn panic_error(payload: Box) -> PipelineError { - let msg = payload +/// Error carried by `PipelineError::StepError` when a closure or a pipeline thread panics. +#[derive(Debug)] +pub(crate) struct Panicked { + who: &'static str, + message: String, +} + +impl fmt::Display for Panicked { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{} panicked: {}", self.who, self.message) + } +} + +impl Error for Panicked {} + +/// Turns the payload of a panic caught in `who` into a `PipelineError::StepError`. +pub(crate) fn panic_error( + who: &'static str, + payload: Box, +) -> PipelineError { + let message = 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))) + PipelineError::StepError(Box::new(Panicked { who, message })) } impl Error for PipelineError { @@ -52,3 +79,16 @@ impl Error for PipelineError { } } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn never_fails_has_a_clear_message() { + // The only place where one can be built: the type is never constructed by the crate itself. + let e = NeverFails(()); + assert!(e.to_string().contains("declared infallible")); + assert!(Error::source(&e).is_none()); + } +} diff --git a/src/scheduler/macros.rs b/src/scheduler/macros.rs index 953a597..d3819ae 100644 --- a/src/scheduler/macros.rs +++ b/src/scheduler/macros.rs @@ -1,19 +1,24 @@ // ── Macros ──────────────────────────────────────────────────────────────────── +// +// The infallible macros (`make_source!`, `make_transform!`, `make_flat_transform!`, `make_sink!`) wrap +// their function in `Ok::<_, $crate::NeverFails>(..)` and delegate to the fallible one, so that each +// behaviour is written once. `NeverFails` is an error type that is never constructed (see its docs): +// an uninhabited one, `Infallible`, makes rustc warn about unreachable code in the caller's code. /// Creates a `SourceFn` from an iterator of plain values. +/// +/// Same as [`make_source_fallible!`](crate::make_source_fallible) over an iterator that never fails. #[macro_export] macro_rules! make_source { - ($enum:ident, $iterator:expr, $output:ident) => {{ - let mut iter = $iterator.into_iter(); - Box::new( - move || -> ::std::result::Result<$enum, $crate::PipelineError> { - match iter.next() { - Some(x) => Ok($enum::$output(x)), - None => Err($crate::PipelineError::EndOfStream), - } - }, - ) as Box ::std::result::Result<$enum, $crate::PipelineError> + Send> - }}; + ($enum:ident, $iterator:expr, $output:ident) => { + $crate::make_source_fallible!( + $enum, + $iterator + .into_iter() + .map(::std::result::Result::<_, $crate::NeverFails>::Ok), + $output + ) + }; } /// Creates a `SourceFn` from an iterator of `Result`. @@ -34,22 +39,21 @@ macro_rules! make_source_fallible { } /// Creates a `Stage::Transform` from a pure (non-fallible) function `Fn(T) -> U`. +/// +/// Same as [`make_transform_fallible!`](crate::make_transform_fallible) with a function that never fails. #[macro_export] macro_rules! make_transform { - ($enum:ident, $func:tt, $input:ident, $output:ident) => {{ - let __f = $func; - $crate::Stage::Transform(::std::sync::Arc::from(Box::new( - move |data: $enum| -> ::std::result::Result<$enum, $crate::PipelineError> { - match data { - $enum::$input(x) => Ok($enum::$output(__f(x))), - _ => Err($crate::PipelineError::TypeMismatch), - } - }, + ($enum:ident, $func:tt, $input:ident, $output:ident) => { + $crate::make_transform_fallible!( + $enum, + ({ + let __f = $func; + move |x| ::std::result::Result::<_, $crate::NeverFails>::Ok(__f(x)) + }), + $input, + $output ) - as Box< - dyn Fn($enum) -> ::std::result::Result<$enum, $crate::PipelineError> + Send + Sync, - >)) - }}; + }; } /// Creates a `Stage::Transform` from a fallible function `Fn(T) -> Result`. @@ -77,97 +81,70 @@ macro_rules! make_transform_fallible { /// Creates a `Stage::Flat` from a function `Fn(T) -> impl IntoIterator`. /// -/// Each item produced by the iterator is pushed individually to -/// the output channel, so that the scheduler can dispatch the items in parallel -/// as soon as a worker is available. +/// The iterator must be `Send + 'static`. It is pulled one item at a time, only while the next queue has +/// room: return a lazy iterator to stream a large expansion. Same as [`make_flat_transform_fallible!`](crate::make_flat_transform_fallible) +/// with a function that never fails. #[macro_export] macro_rules! make_flat_transform { - ($enum:ident, $func:tt, $input:ident, $output:ident) => {{ - let __f = $func; - $crate::Stage::Flat(::std::sync::Arc::new( - move |data: $enum, - push: &$crate::PipelineSender< - ::std::result::Result<$enum, $crate::PipelineError>, - >, - delta: &$crate::PipelineSender| { - match data { - $enum::$input(inner) => { - let mut count: isize = 0; - for item in __f(inner) { - push.send(Ok($enum::$output(item))).ok(); - count += 1; - } - delta.send(count - 1).ok(); - } - _ => { - push.send(Err($crate::PipelineError::TypeMismatch)).ok(); - delta.send(-1).ok(); - } - } - }, - ) as $crate::SharedFlatFn<$enum>) - }}; + ($enum:ident, $func:tt, $input:ident, $output:ident) => { + $crate::make_flat_transform_fallible!( + $enum, + ({ + let __f = $func; + move |x| ::std::result::Result::<_, $crate::NeverFails>::Ok(__f(x)) + }), + $input, + $output + ) + }; } /// Creates a `Stage::Flat` from a fallible function /// `Fn(T) -> Result, E>`. /// -/// If the function returns `Err`, an error is pushed to the channel and no -/// regular item is produced. +/// If the function returns `Err`, the pipeline stops with that error and no item is produced. The +/// iterator must be `Send + 'static` (see [`FlatOutput`](crate::FlatOutput)). #[macro_export] macro_rules! make_flat_transform_fallible { ($enum:ident, $func:tt, $input:ident, $output:ident) => {{ let __f = $func; - $crate::Stage::Flat(::std::sync::Arc::new( - move |data: $enum, - push: &$crate::PipelineSender< - ::std::result::Result<$enum, $crate::PipelineError>, - >, - delta: &$crate::PipelineSender| { - match data { + $crate::Stage::Flat( + ::std::sync::Arc::new(move |data: $enum| -> $crate::FlatOutput<$enum> { + let error = match data { $enum::$input(inner) => match __f(inner) { - Ok(iter) => { - let mut count: isize = 0; - for item in iter { - push.send(Ok($enum::$output(item))).ok(); - count += 1; - } - delta.send(count - 1).ok(); - } - Err(e) => { - push.send(Err($crate::PipelineError::StepError(Box::new(e)))) - .ok(); - // The input item is consumed and nothing is produced: N - 1 = -1. - delta.send(-1).ok(); + Ok(items) => { + return ::std::boxed::Box::new( + items.into_iter().map(|item| Ok($enum::$output(item))), + ); } + Err(e) => $crate::PipelineError::StepError(::std::boxed::Box::new(e)), }, - _ => { - push.send(Err($crate::PipelineError::TypeMismatch)).ok(); - delta.send(-1).ok(); - } - } - }, - ) as $crate::SharedFlatFn<$enum>) + _ => $crate::PipelineError::TypeMismatch, + }; + ::std::boxed::Box::new(::std::iter::once(Err(error))) + }) as $crate::SharedFlatFn<$enum>, + ) }}; } /// Creates a `SinkFn` from a function that consumes a concrete value and returns `()`. +/// +/// Same as [`make_sink_fallible!`](crate::make_sink_fallible) with a function that never fails. #[macro_export] macro_rules! make_sink { - ($enum:ident, $func:tt, $input:ident) => {{ - let __f = $func; - Box::new( - move |data: $enum| -> ::std::result::Result<(), $crate::PipelineError> { - match data { - $enum::$input(x) => { - __f(x); - Ok(()) - } - _ => Err($crate::PipelineError::TypeMismatch), + ($enum:ident, $func:tt, $input:ident) => { + $crate::make_sink_fallible!( + $enum, + ({ + let __f = $func; + move |x| { + __f(x); + ::std::result::Result::<(), $crate::NeverFails>::Ok(()) } - }, - ) as Box ::std::result::Result<(), $crate::PipelineError> + Send> - }}; + }), + $input + ) + }; } /// Creates a `SinkFn` from a fallible function that returns `Result<(), E>`. @@ -339,35 +316,25 @@ macro_rules! make_pipeline { /// | double : Num => Num, /// | show : Num => Text, /// }; -/// let mut out: Vec = pipe.apply(1..=3u64, 2, 4).collect(); +/// let mut out: Vec = pipe.apply(1..=3u64, 2, 4).collect::>().unwrap(); /// out.sort(); /// assert_eq!(out, ["2", "4", "6"]); /// ``` #[macro_export] macro_rules! make_pipe { - // ── Entry: first stage | ───────────────────────────────────────────── - ($enum:ident : $in_ty:ty => $out_ty:ty, - | $tf:tt : $fi:ident => $fo:ident, $($rest:tt)*) => { - $crate::make_pipe!(@build $enum : $in_ty => $out_ty, $fi, - [$crate::make_transform!($enum, $tf, $fi, $fo),], $fo, $($rest)*) + // ── Entry: find the input variant of the first stage, then build ────── + ($enum:ident : $in_ty:ty => $out_ty:ty, $($rest:tt)+) => { + $crate::make_pipe!(@first $enum : $in_ty => $out_ty, [] $($rest)+) }; - // ── Entry: first stage |? ──────────────────────────────────────────── - ($enum:ident : $in_ty:ty => $out_ty:ty, - |? $tf:tt : $fi:ident => $fo:ident, $($rest:tt)*) => { - $crate::make_pipe!(@build $enum : $in_ty => $out_ty, $fi, - [$crate::make_transform_fallible!($enum, $tf, $fi, $fo),], $fo, $($rest)*) + // The first stage is ` : => `: skip tokens up to the `:`. + (@first $enum:ident : $in_ty:ty => $out_ty:ty, + [$($done:tt)*] : $fi:ident => $($rest:tt)*) => { + $crate::make_pipe!(@build $enum : $in_ty => $out_ty, $fi, [], $fi, + $($done)* : $fi => $($rest)*) }; - // ── Entry: first stage || ──────────────────────────────────────────── - ($enum:ident : $in_ty:ty => $out_ty:ty, - || $tf:tt : $fi:ident => $fo:ident, $($rest:tt)*) => { - $crate::make_pipe!(@build $enum : $in_ty => $out_ty, $fi, - [$crate::make_flat_transform!($enum, $tf, $fi, $fo),], $fo, $($rest)*) - }; - // ── Entry: first stage ||? ─────────────────────────────────────────── - ($enum:ident : $in_ty:ty => $out_ty:ty, - ||? $tf:tt : $fi:ident => $fo:ident, $($rest:tt)*) => { - $crate::make_pipe!(@build $enum : $in_ty => $out_ty, $fi, - [$crate::make_flat_transform_fallible!($enum, $tf, $fi, $fo),], $fo, $($rest)*) + (@first $enum:ident : $in_ty:ty => $out_ty:ty, + [$($done:tt)*] $t:tt $($rest:tt)*) => { + $crate::make_pipe!(@first $enum : $in_ty => $out_ty, [$($done)* $t] $($rest)*) }; // ── Accumulation: | ────────────────────────────────────────────────── @@ -406,6 +373,9 @@ macro_rules! make_pipe { vec![$($acc)*], ::std::sync::Arc::new(|x: $in_ty| $enum::$fi(x)), ::std::sync::Arc::new(|d: $enum| -> $out_ty { + // Cannot fail: every item that reaches the output was built by the last stage of this + // pipe, and the stage macros wrap their result in the variant they were declared with + // (`$lo`). A wrong variant would have been rejected earlier, as a `TypeMismatch`. if let $enum::$lo(x) = d { x } else { ::std::unreachable!("unexpected pipeline data variant in make_pipe!") } }), diff --git a/src/scheduler/mod.rs b/src/scheduler/mod.rs index 59d88bb..f4e71e1 100644 --- a/src/scheduler/mod.rs +++ b/src/scheduler/mod.rs @@ -1,19 +1,20 @@ -//! Scheduler: a channel/thread-based pipeline runtime with typed, composable -//! stages (`Pipe`), plus the macro-based `PipelineData`-enum runtime it grew -//! out of (`Pipeline`/`WorkerPool`). +//! Scheduler: a thread-based pipeline runtime with typed, composable stages (`Pipe`), plus the +//! macro-based `PipelineData`-enum runtime it grew out of (`Pipeline`/`WorkerPool`). //! //! Submodules: [`error`] (`PipelineError`), [`types`] (function types, `Stage`), -//! [`runner`] (thread bodies), [`pool`] (`Pipeline`/`WorkerPool` scheduler -//! loop), [`pipe`] (`Pipe`/`PipeIter`), [`macros`] (`make_pipe!` and friends). +//! [`state`] (stage queues and scheduling rule), [`runner`] (thread bodies), +//! [`pool`] (`Pipeline`/`WorkerPool`), [`pipe`] (`Pipe`/`PipeIter`), +//! [`macros`] (`make_pipe!` and friends). mod error; mod macros; mod pipe; mod pool; mod runner; +mod state; mod types; -pub use error::PipelineError; +pub use error::{NeverFails, PipelineError}; pub use pipe::{Pipe, PipeIter}; pub use pool::{Pipeline, WorkerPool}; -pub use types::{SharedFlatFn, SharedFn, SinkFn, SourceFn, Stage}; +pub use types::{FlatOutput, SharedFlatFn, SharedFn, SinkFn, SourceFn, Stage}; diff --git a/src/scheduler/pipe.rs b/src/scheduler/pipe.rs index 4acf368..06d6861 100644 --- a/src/scheduler/pipe.rs +++ b/src/scheduler/pipe.rs @@ -62,15 +62,15 @@ where { /// 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. + /// `n_workers` threads run the stages in parallel; `capacity` bounds the stage queues 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. + /// `TypeMismatch`, or a panic in a worker closure) stops the pipeline: the items still in flight are + /// discarded and the error is yielded by the iterator as its last item, `Err(error)`, after the + /// items already delivered. /// /// # Panics /// @@ -102,9 +102,12 @@ where let pipeline = Pipeline::new(source, self.stages, sink); let pool = WorkerPool::new(pipeline, n_workers, capacity); - let handle = thread::spawn(move || pool.run()); + let running = pool.start(); + let shared = Arc::clone(&running.shared); + let handle = thread::spawn(move || running.wait()); PipeIter { + cancel: Box::new(move || shared.cancel()), rx: Some(out_rx), handle: Some(handle), } @@ -113,50 +116,49 @@ where // ── PipeIter ────────────────────────────────────────────────────────────────── -/// Iterator over the output of `Pipe::apply()`. +/// Iterator over the output of [`Pipe::apply`]. /// -/// If the pipeline fails, the iterator simply ends early: call [`PipeIter::finish`] to get the error. +/// Each item is `Ok(output)`. If the pipeline fails, the first error is yielded **once**, as the last +/// item (`Err(error)`), and the iterator then ends: errors are values the caller has to look at. +/// +/// Dropping it before the end cancels the pipeline: the items in flight are discarded, and the drop waits +/// for the stage and sink calls in progress to return. It does **not** wait for a source busy in user code +/// (a blocking read, an iterator that yields nothing more, a throttle slot held by the caller): the source +/// thread is left to stop by itself as soon as that call returns. pub struct PipeIter { rx: 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(()), - } - } + /// Stops the scheduler (the data type of the pipeline is erased here). + cancel: Box, } impl Iterator for PipeIter { - type Item = Out; + type Item = Result; - fn next(&mut self) -> Option { - self.rx.as_ref()?.recv().ok() + fn next(&mut self) -> Option { + let rx = self.rx.as_ref()?; + if let Ok(item) = rx.recv() { + return Some(Ok(item)); + } + // The output channel is closed: the pipeline has stopped. Collect how it ended. + self.rx = None; + let outcome = self + .handle + .take()? + .join() + .unwrap_or_else(|p| Err(super::error::panic_error("pipeline thread", p))); + outcome.err().map(Err) } } impl Drop for PipeIter { fn drop(&mut self) { - // Drop the receiver *before* joining: the sink then fails on its next send, which stops the - // scheduler. Joining while the receiver is alive blocks forever if the bounded output channel is full. + // Drop the receiver *before* joining: a sink blocked on the full output channel then fails. + // Cancelling does not depend on a next output, which may never come. 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. + // Early drop: the caller gave up on the output, so how the pipeline ended is not wanted. + (self.cancel)(); let _ = h.join(); } } diff --git a/src/scheduler/pool.rs b/src/scheduler/pool.rs index aa51f86..ac3914b 100644 --- a/src/scheduler/pool.rs +++ b/src/scheduler/pool.rs @@ -1,8 +1,9 @@ -use crossbeam_channel::{Receiver, Select, Sender, bounded}; +use std::sync::Arc; +use std::thread; use super::error::PipelineError; -use super::runner::{dispatch, sink_runner, source_runner, transform_runner}; -use super::types::{SinkFn, SourceFn, Stage, WorkerTask}; +use super::runner::{Shared, sink_runner, source_runner, worker_runner}; +use super::types::{SinkFn, SourceFn, Stage}; // ── Pipeline ────────────────────────────────────────────────────────────────── @@ -30,11 +31,12 @@ impl Pipeline { /// 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. +/// Each stage has its own queue, bounded by `capacity`. A free worker serves the stage of highest rank +/// (the closest to the output) that has work and room for its result, so that started work is finished +/// before new items are admitted. A worker never waits on a queue: a 1→N stage is pulled one item at a +/// time and set aside while the next queue is full. pub struct WorkerPool { pipeline: Pipeline, - handles: Vec>, n_workers: usize, capacity: usize, } @@ -47,21 +49,20 @@ where /// /// # 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). + /// Panics if `n_workers` is `0` (no item would ever be processed) or if `capacity` is `0` (no item + /// could ever be queued). 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(), n_workers, capacity, } } - /// Runs the pipeline to completion on the calling thread (the workers are spawned threads). + /// Runs the pipeline to completion, blocking the calling thread (source, workers and sink 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 @@ -71,176 +72,72 @@ where /// /// 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(); + pub fn run(self) -> Result<(), PipelineError> { + self.start().wait() + } - // ── Inter-stage channels ─────────────────────────────────────────── - // stage_txs[i] / stage_rxs[i]: output of stage i - let mut stage_txs: Vec>> = Vec::new(); - let mut stage_rxs: Vec>> = Vec::new(); - for _ in 0..n { - let (tx, rx) = bounded(self.capacity); - stage_txs.push(tx); - stage_rxs.push(rx); - } - - // ── Source thread ────────────────────────────────────────────────── - let (source_rx, src_handle) = source_runner(self.pipeline.source, self.capacity); - self.handles.push(src_handle); - - let stages = self.pipeline.stages; - - // ── Delta channel for the flat stages ────────────────────────────── - // Each flat worker sends `N-1` here after pushing N items. - // The scheduler adjusts `in_flight` accordingly. - let (flat_delta_tx, flat_delta_rx) = bounded::(self.capacity); - - // ── Worker pool ──────────────────────────────────────────────────── - let (worker_tx, worker_rx): (Sender>, Receiver>) = - bounded(self.capacity); + /// Spawns the threads of the pipeline. + pub(super) fn start(self) -> Running { + let Pipeline { + source, + stages, + sink, + } = self.pipeline; + let shared = Arc::new(Shared::new(stages.len(), self.capacity)); + let stages: Arc<[Stage]> = stages.into(); + let s = Arc::clone(&shared); + let source = thread::spawn(move || source_runner(&s, source)); + let mut handles = Vec::with_capacity(self.n_workers + 1); + let s = Arc::clone(&shared); + handles.push(thread::spawn(move || sink_runner(&s, sink))); for _ in 0..self.n_workers { - self.handles.push(transform_runner( - worker_rx.clone(), - stages.iter().map(Stage::clone).collect(), - stage_txs.clone(), - flat_delta_tx.clone(), - )); - } - // The scheduler no longer holds flat_delta_tx: the workers own it. - // It is dropped here so that the channel closes when the workers finish. - drop(flat_delta_tx); - - // ── Sink thread ──────────────────────────────────────────────────── - let (sink_tx, sink_err_rx, sink_handle) = sink_runner(self.pipeline.sink, self.capacity); - self.handles.push(sink_handle); - - // ── Main loop ────────────────────────────────────────────────────── - // - // `in_flight` (isize) = number of items that still have to reach the sink. - // May be temporarily negative if a flat worker has pushed its items - // before the scheduler has received the matching delta. - // - // `flat_workers_active` = number of flat workers currently running. - // Prevents a premature termination when in_flight is 0 but a - // flat worker has not sent its delta yet. - // - // Priorities of the biased Select (lowest index = highest priority): - // 0 → sink_err_rx (immediate stop on a sink error) - // 1 → flat_delta_rx (update in_flight before dispatching) - // 2..=n+1 → stage_rxs[n-1..0] (drain the pipeline first) - // n+2 → source_rx (last resort: new data) - // - // When k = 0 : sink error - // When k = 1 : delta of a flat worker - // When 2 ≤ k ≤ n+1 : result of stage n+1-k - // When k = n+2 : source item - // - // Termination: source exhausted AND in_flight == 0 AND no active flat worker. - { - let mut source_done = false; - let mut in_flight: isize = 0; - let mut flat_workers_active: usize = 0; - - loop { - if source_done && in_flight == 0 && flat_workers_active == 0 { - break; - } - - let mut sel = Select::new_biased(); - sel.recv(&sink_err_rx); // index 0 - sel.recv(&flat_delta_rx); // index 1 - for rx in stage_rxs.iter().rev() { - sel.recv(rx); // indices 2..=n+1 - } - let src_idx = if !source_done { - Some(sel.recv(&source_rx)) // index n+2 - } else { - None - }; - - let oper = sel.select(); - let k = oper.index(); - - if k == 0 { - // ── Sink error ──────────────────────────────────────── - 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) - if let Ok(delta) = oper.recv(&flat_delta_rx) { - in_flight += delta; - flat_workers_active -= 1; - } - } else if src_idx == Some(k) { - // ── New item from the source ────────────────────────── - match oper.recv(&source_rx) { - Ok(Ok(data)) => { - if n == 0 { - let _ = sink_tx.send(data); - } else { - in_flight += 1; - dispatch(data, 0, &stages, &worker_tx, &mut flat_workers_active); - } - } - Ok(Err(e)) => { - outcome = Err(e); - break; - } - Err(_) => source_done = true, - } - } else { - // ── Result of an intermediate stage ─────────────────── - // k ∈ [2, n+1] → stage = n+1 - k - let stage = n + 1 - k; - match oper.recv(&stage_rxs[stage]) { - Ok(Ok(data)) => { - if stage == n - 1 { - in_flight -= 1; - let _ = sink_tx.send(data); - } else { - dispatch( - data, - stage + 1, - &stages, - &worker_tx, - &mut flat_workers_active, - ); - } - } - Ok(Err(e)) => { - outcome = Err(e); - break; - } - Err(_) => break, - } - } - } + let s = Arc::clone(&shared); + let stages = Arc::clone(&stages); + handles.push(thread::spawn(move || worker_runner(&s, &stages))); } - drop(worker_tx); - drop(sink_tx); - // Close the receiving ends before joining. When the loop above stopped early (sink error, for example - // an output iterator dropped before exhaustion), the source thread and the workers may be blocked - // sending to a full bounded channel nobody drains any more: a failed send lets them exit. - drop(source_rx); - drop(stage_rxs); - drop(flat_delta_rx); - drop(sink_err_rx); + Running { + shared, + source, + handles, + } + } +} - // 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. +// ── Running ─────────────────────────────────────────────────────────────────── + +/// A started pipeline. +pub(super) struct Running { + pub(super) shared: Arc>, + source: thread::JoinHandle<()>, + /// Sink and workers. + handles: Vec>, +} + +impl Running { + /// Waits for the end of the pipeline and returns how it ended. + /// + /// A cancelled run does not wait for a source still busy in user code (it may never return, or wait + /// for a throttle slot the caller holds): that thread stops by itself when the call returns. + pub(super) fn wait(self) -> Result<(), PipelineError> { + // User closures are run under `catch_unwind`: a failed join is a panic raised elsewhere, for + // example while dropping a user value. + let mut panicked = None; for h in self.handles { - if h.join().is_err() && outcome.is_ok() { - outcome = Err(super::error::panic_error(Box::new( - "a pipeline thread (source or sink) panicked", - ))); + if let Err(p) = h.join() { + panicked.get_or_insert(p); } + } + if self.shared.wait_source() + && let Err(p) = self.source.join() + { + panicked.get_or_insert(p); + } + match (self.shared.take_error(), panicked) { + (Some(e), _) => Err(e), + (None, Some(p)) => Err(super::error::panic_error("pipeline thread", p)), + (None, None) => Ok(()), } - outcome } } diff --git a/src/scheduler/runner.rs b/src/scheduler/runner.rs index ddda7a3..924d2d3 100644 --- a/src/scheduler/runner.rs +++ b/src/scheduler/runner.rs @@ -1,130 +1,280 @@ -use crossbeam_channel::{Receiver, Sender, bounded}; +//! Thread bodies (source, workers, sink) and the state they share. + use std::panic::{AssertUnwindSafe, catch_unwind}; -use std::thread; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Condvar, Mutex, MutexGuard, PoisonError, TryLockError}; use super::error::{PipelineError, panic_error}; -use super::types::{SinkFn, SourceFn, Stage, WorkerTask}; +use super::state::{Job, Outcome, State}; +use super::types::{SinkFn, SourceFn, Stage}; -// ── 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. +// ── Shared state ────────────────────────────────────────────────────────────── -pub(super) fn source_runner( - mut source: SourceFn, - capacity: usize, -) -> ( - Receiver>, - thread::JoinHandle<()>, -) -where - DATA: Send + Sync + 'static, -{ - let (tx, rx) = bounded(capacity); - let handle = thread::spawn(move || { - loop { - match source() { - Ok(data) => { - if tx.send(Ok(data)).is_err() { - break; - } - } - Err(PipelineError::EndOfStream) => break, - Err(e) => { - // Reported to the scheduler, which stops the pipeline and returns it. - let _ = tx.send(Err(e)); - break; - } - } - } - }); - (rx, handle) +/// Attempts to take the state lock before sleeping on it. The critical sections are a few queue +/// operations: putting a thread to sleep costs far more than waiting for them, which matters when the +/// stages are only a few microseconds long. +const LOCK_ATTEMPTS: usize = 100; +/// Pause between two attempts, in `spin_loop` hints. +const SPINS_BETWEEN_ATTEMPTS: usize = 8; + +/// A condition variable that knows whether anybody sleeps on it, so that waking nobody costs nothing. +#[derive(Default)] +struct Signal { + condvar: Condvar, + /// Only changed while the state lock is held: whoever changed the state under that lock sees every + /// sleeper that has not seen the change, even if it reads the count after releasing the lock. + sleepers: AtomicUsize, } -/// Spawns a worker thread of the pool. -/// -/// Handles two kinds of tasks: -/// - `Transform`: applies `f(data)` and sends the result to `result_tx`. -/// - `Flat`: calls `f(data, &push_tx, &delta_tx)`; the function itself -/// pushes its items to `push_tx` and sends `N-1` to `delta_tx`. -pub(super) fn transform_runner( - task_rx: Receiver>, - stages: Vec>, - stage_txs: Vec>>, - flat_delta_tx: Sender, -) -> thread::JoinHandle<()> -where - DATA: Send + Sync + 'static, -{ - thread::spawn(move || { - while let Ok(task) = task_rx.recv() { - match task { - WorkerTask::Transform(data, idx) => { - if let Stage::Transform(f) = &stages[idx] { - // 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] { - 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))); - } +impl Signal { + fn wait<'a, T>(&self, guard: MutexGuard<'a, T>) -> MutexGuard<'a, T> { + self.sleepers.fetch_add(1, Ordering::Relaxed); + let guard = self + .condvar + .wait(guard) + .unwrap_or_else(PoisonError::into_inner); + self.sleepers.fetch_sub(1, Ordering::Relaxed); + guard + } + + fn notify_one(&self) { + if self.sleepers.load(Ordering::Relaxed) > 0 { + self.condvar.notify_one(); + } + } + + fn notify_all(&self) { + self.condvar.notify_all(); + } +} + +pub(super) struct Shared { + state: Mutex>, + /// Workers wait here for a job. + work: Signal, + /// The source waits here for room in the first queue. + room: Signal, + /// The sink waits here for an output. + output: Signal, + /// The thread running the pipeline waits here for the end of the source, or a cancellation. + source_end: Signal, +} + +impl Shared { + pub(super) fn new(n_stages: usize, capacity: usize) -> Self { + Self { + state: Mutex::new(State::new(n_stages, capacity)), + work: Signal::default(), + room: Signal::default(), + output: Signal::default(), + source_end: Signal::default(), + } + } + + /// Takes the state lock, insisting a little before sleeping (see [`LOCK_ATTEMPTS`]). + /// + /// No user code runs under the lock, so a poisoned mutex still holds a consistent state. + fn lock(&self) -> MutexGuard<'_, State> { + for _ in 0..LOCK_ATTEMPTS { + match self.state.try_lock() { + Ok(guard) => return guard, + Err(TryLockError::Poisoned(p)) => return p.into_inner(), + Err(TryLockError::WouldBlock) => { + for _ in 0..SPINS_BETWEEN_ATTEMPTS { + std::hint::spin_loop(); } } } } - }) + self.state.lock().unwrap_or_else(PoisonError::into_inner) + } + + fn wake_all(&self) { + self.work.notify_all(); + self.room.notify_all(); + self.output.notify_all(); + self.source_end.notify_all(); + } + + /// Stops the pipeline on `error`. + pub(super) fn fail(&self, error: PipelineError) { + let discarded = self.lock().abort(error); + self.wake_all(); + drop(discarded); + } + + /// Stops the pipeline when nobody will consume its outputs any more, because of `error`. + fn fail_output(&self, error: PipelineError) { + let discarded = self.lock().abort_all(error); + self.wake_all(); + drop(discarded); + } + + /// Stops the pipeline because the caller gave up on it. The error recorded here is only a stop + /// marker: nobody reads the outcome of a cancelled run. + pub(super) fn cancel(&self) { + let discarded = { + let mut state = self.lock(); + state.cancelled = true; + state.abort_all(PipelineError::EndOfStream) + }; + self.wake_all(); + drop(discarded); + } + + /// Waits until the source thread is done, or the run is cancelled. Returns `true` in the first case: + /// the thread can be joined without waiting on user code. + pub(super) fn wait_source(&self) -> bool { + let mut state = self.lock(); + while state.source_open && !state.cancelled { + state = self.source_end.wait(state); + } + !state.source_open + } + + pub(super) fn take_error(&self) -> Option { + self.lock().error.take() + } } -/// Spawns the sink thread. -pub(super) fn sink_runner( - sink: SinkFn, - capacity: usize, -) -> ( - Sender, - Receiver, - thread::JoinHandle<()>, -) -where - DATA: Send + Sync + 'static, -{ - let (data_tx, data_rx) = bounded(capacity); - let (err_tx, err_rx) = bounded(capacity); - let handle = thread::spawn(move || { - for data in data_rx { - if let Err(e) = sink(data) { - let _ = err_tx.send(e); +// ── Source ──────────────────────────────────────────────────────────────────── + +/// Marks the source as closed when dropped, so that it also happens if the source thread unwinds. +struct CloseSource<'a, D>(&'a Shared); + +impl Drop for CloseSource<'_, D> { + fn drop(&mut self) { + self.0.lock().source_open = false; + self.0.wake_all(); + } +} + +/// Feeds the first queue until the source is exhausted or the pipeline fails. +pub(super) fn source_runner(shared: &Shared, mut source: SourceFn) { + let _close = CloseSource(shared); + loop { + if shared.lock().stopped() { + break; + } + match catch_unwind(AssertUnwindSafe(&mut source)) { + Ok(Ok(item)) => { + let mut state = shared.lock(); + while !state.stopped() && !state.has_room(0) { + state = shared.room.wait(state); + } + if state.stopped() { + drop(state); + break; // `item` is dropped outside the lock + } + state.queues[0].push_back(item); + shared.work.notify_one(); + shared.output.notify_one(); // a pipeline without stages + } + Ok(Err(PipelineError::EndOfStream)) => break, + Ok(Err(e)) => { + shared.fail(e); + break; + } + Err(p) => { + shared.fail(panic_error("source", p)); break; } } - }); - (data_tx, err_rx, handle) + } } -/// Envoie `data` au stage `stage_idx`. -/// For a `Transform`, queues a `WorkerTask::Transform`. -/// For a `Flat`, increments `flat_workers_active` and queues a `WorkerTask::Flat`. -#[inline] -pub(super) fn dispatch( - data: DATA, - stage_idx: usize, - stages: &[Stage], - worker_tx: &Sender>, - flat_workers_active: &mut usize, -) { - match &stages[stage_idx] { - Stage::Transform(_) => { - let _ = worker_tx.send(WorkerTask::Transform(data, stage_idx)); +// ── Workers ─────────────────────────────────────────────────────────────────── + +/// Runs the user code of one job. A panic becomes an error. +fn execute(stages: &[Stage], job: Job) -> Result, PipelineError> { + catch_unwind(AssertUnwindSafe(|| { + let (rank, mut expansion) = match job { + Job::Transform(rank, item) => { + let Stage::Transform(f) = &stages[rank] else { + unreachable!("State::pick builds the job from the kind of the stage") + }; + return f(item).map(|out| Outcome::Item(rank, out, None)); + } + Job::Expand(rank, item) => { + let Stage::Flat(f) = &stages[rank] else { + unreachable!("State::pick builds the job from the kind of the stage") + }; + (rank, f(item)) + } + Job::Pull(rank, expansion) => (rank, expansion), + }; + match expansion.next() { + Some(Ok(out)) => Ok(Outcome::Item(rank, out, Some(expansion))), + Some(Err(e)) => Err(e), + None => Ok(Outcome::Exhausted(rank)), } - Stage::Flat(_) => { - *flat_workers_active += 1; - let _ = worker_tx.send(WorkerTask::Flat(data, stage_idx)); + })) + .unwrap_or_else(|p| Err(panic_error("worker", p))) +} + +/// A worker: takes the most advanced job available, runs it, files the result, and starts again. +pub(super) fn worker_runner(shared: &Shared, stages: &[Stage]) { + let mut state = shared.lock(); + loop { + if state.error.is_some() || state.drained() { + break; + } + let Some((rank, job)) = state.pick(stages) else { + state = shared.work.wait(state); + continue; + }; + let work_left = state.next_rank().is_some(); + drop(state); + // Woken after the lock is released, so that they do not wake up only to wait for it. + if rank == 0 { + shared.room.notify_one(); + } + if work_left { + shared.work.notify_one(); // for another worker + } + match execute(stages, job) { + Ok(outcome) => { + state = shared.lock(); + let discarded = state.commit(outcome); + shared.output.notify_one(); + if discarded.is_some() { + drop(state); + drop(discarded); + state = shared.lock(); + } + } + Err(e) => { + shared.lock().release(rank); + shared.fail(e); + state = shared.lock(); + } + } + } + drop(state); + shared.wake_all(); +} + +// ── Sink ────────────────────────────────────────────────────────────────────── + +/// Consumes the last queue until nothing more can reach it. +pub(super) fn sink_runner(shared: &Shared, sink: SinkFn) { + let mut state = shared.lock(); + loop { + let last = state.queues.len() - 1; + if let Some(item) = state.queues[last].pop_front() { + shared.work.notify_one(); + shared.room.notify_one(); // a pipeline without stages + drop(state); + match catch_unwind(AssertUnwindSafe(|| sink(item))) { + Ok(Ok(())) => {} + Ok(Err(e)) => return shared.fail_output(e), + Err(p) => return shared.fail_output(panic_error("sink", p)), + } + state = shared.lock(); + } else if state.error.is_some() || state.drained() { + break; + } else { + state = shared.output.wait(state); } } } diff --git a/src/scheduler/state.rs b/src/scheduler/state.rs new file mode 100644 index 0000000..23e0c39 --- /dev/null +++ b/src/scheduler/state.rs @@ -0,0 +1,242 @@ +//! The queues of a running pipeline and the scheduling rule. Pure bookkeeping: no thread, no user code. +//! +//! With `n` stages there are `n + 1` queues: `queues[i]` holds the inputs of stage `i`, `queues[n]` the +//! outputs waiting for the sink. Every queue is bounded. + +use std::collections::VecDeque; + +use super::error::PipelineError; +use super::types::{FlatOutput, Stage}; + +/// One step of work for a worker. It produces at most one item, for which a slot is already reserved in +/// the next queue, so a worker never waits on a queue. +pub(super) enum Job { + /// Apply the 1→1 stage to an item. + Transform(usize, D), + /// Start the 1→N stage on an item and pull its first result. + Expand(usize, D), + /// Pull the next result of a started 1→N expansion. + Pull(usize, FlatOutput), +} + +/// What a [`Job`] gave. +pub(super) enum Outcome { + /// An item for the next queue, and the expansion to resume later if there is one. + Item(usize, D, Option>), + /// The expansion has no more items. + Exhausted(usize), +} + +/// Items and expansions removed from the state. User values may run code when dropped (a throttle guard, +/// for example): the caller drops this **after** releasing the lock. +#[allow(dead_code)] // the fields only exist to be dropped later +pub(super) struct Discarded { + items: Vec>, + expansions: Vec>>, +} + +pub(super) struct State { + pub(super) queues: Vec>, + /// Slots of each queue promised to running jobs. + reserved: Vec, + /// Started expansions of each stage, waiting to be resumed. + parked: Vec>>, + running: usize, + pub(super) source_open: bool, + /// The consumer gave up on the output: the source is no longer waited for. + pub(super) cancelled: bool, + /// First error met: once set, nothing new is scheduled. + pub(super) error: Option, + capacity: usize, +} + +impl State { + pub(super) fn new(n_stages: usize, capacity: usize) -> Self { + Self { + queues: (0..=n_stages).map(|_| VecDeque::new()).collect(), + reserved: vec![0; n_stages + 1], + parked: (0..n_stages).map(|_| VecDeque::new()).collect(), + running: 0, + source_open: true, + cancelled: false, + error: None, + capacity, + } + } + + /// True if the source must stop feeding the pipeline. `error` alone is not enough: the outcome of a + /// cancelled run is collected, and the error taken, while the source thread may still be busy. + pub(super) fn stopped(&self) -> bool { + self.cancelled || self.error.is_some() + } + + pub(super) fn has_room(&self, queue: usize) -> bool { + self.queues[queue].len() + self.reserved[queue] < self.capacity + } + + /// The rank of the stage to serve: the highest one that has work and room for its result. + pub(super) fn next_rank(&self) -> Option { + (0..self.parked.len()).rev().find(|&i| { + self.has_room(i + 1) && !(self.parked[i].is_empty() && self.queues[i].is_empty()) + }) + } + + /// Takes the next job according to [`State::next_rank`]. A started expansion is resumed before a new + /// input of the same stage is opened. + pub(super) fn pick(&mut self, stages: &[Stage]) -> Option<(usize, Job)> { + let rank = self.next_rank()?; + let job = match self.parked[rank].pop_front() { + Some(expansion) => Job::Pull(rank, expansion), + None => { + let item = self.queues[rank].pop_front()?; + match stages[rank] { + Stage::Transform(_) => Job::Transform(rank, item), + Stage::Flat(_) => Job::Expand(rank, item), + } + } + }; + self.reserved[rank + 1] += 1; + self.running += 1; + Some((rank, job)) + } + + /// Records the result of a job. After a failure, the result is handed back to be dropped. + pub(super) fn commit(&mut self, outcome: Outcome) -> Option> { + let (Outcome::Item(rank, ..) | Outcome::Exhausted(rank)) = outcome; + self.running -= 1; + self.reserved[rank + 1] -= 1; + if self.error.is_some() { + return Some(outcome); + } + if let Outcome::Item(_, item, expansion) = outcome { + self.queues[rank + 1].push_back(item); + if let Some(expansion) = expansion { + self.parked[rank].push_back(expansion); + } + } + None + } + + /// A job ended with an error: gives back its reservation. + pub(super) fn release(&mut self, rank: usize) { + self.running -= 1; + self.reserved[rank + 1] -= 1; + } + + /// True once no stage will ever produce anything again. + pub(super) fn drained(&self) -> bool { + let n = self.parked.len(); + !self.source_open + && self.running == 0 + && self.queues[..n].iter().all(VecDeque::is_empty) + && self.parked.iter().all(VecDeque::is_empty) + } + + /// Same as [`State::abort`], for when nobody will consume the outputs any more (the sink failed, or + /// the run is cancelled): the output queue is emptied too. Items kept there could hold a resource the + /// source is waiting for, such as a throttle slot. + pub(super) fn abort_all(&mut self, error: PipelineError) -> Discarded { + let mut discarded = self.abort(error); + let n = self.parked.len(); + discarded.items.push(std::mem::take(&mut self.queues[n])); + discarded + } + + /// Records `error` (the first one wins) and empties the stage queues. Outputs already produced stay + /// available to the sink. + pub(super) fn abort(&mut self, error: PipelineError) -> Discarded { + self.error.get_or_insert(error); + let n = self.parked.len(); + Discarded { + items: self.queues[..n].iter_mut().map(std::mem::take).collect(), + expansions: self.parked.iter_mut().map(std::mem::take).collect(), + } + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use super::*; + + fn transform() -> Stage { + Stage::Transform(Arc::new(Ok)) + } + + fn flat() -> Stage { + Stage::Flat(Arc::new(|x| Box::new(std::iter::once(Ok(x))))) + } + + #[test] + fn the_highest_rank_with_room_is_served_first() { + let stages = [transform(), transform()]; + let mut state = State::new(2, 1); + state.queues[0].push_back(1); + state.queues[1].push_back(2); + assert_eq!(state.next_rank(), Some(1)); + state.queues[2].push_back(3); // the output queue is full + assert_eq!(state.next_rank(), None, "queue 1 is full too"); + state.queues[1].clear(); + assert!(matches!( + state.pick(&stages), + Some((0, Job::Transform(0, 1))) + )); + assert!( + !state.has_room(1), + "the slot is reserved for the running job" + ); + } + + #[test] + fn a_started_expansion_is_resumed_before_a_new_input() { + let stages = [flat()]; + let mut state = State::new(1, 4); + state.queues[0].extend([1, 2]); + assert!(matches!(state.pick(&stages), Some((0, Job::Expand(0, 1))))); + let expansion: FlatOutput = Box::new(std::iter::empty()); + assert!( + state + .commit(Outcome::Item(0, 10, Some(expansion))) + .is_none() + ); + assert!(matches!(state.pick(&stages), Some((0, Job::Pull(0, _))))); + } + + #[test] + fn drained_waits_for_the_source_and_the_running_jobs() { + let stages = [transform()]; + let mut state = State::new(1, 4); + state.queues[0].push_back(1); + state.source_open = false; + assert!(!state.drained()); + let (rank, _job) = state.pick(&stages).unwrap(); + assert!(!state.drained(), "a job is running"); + state.release(rank); + assert!(state.drained()); + state.source_open = true; + assert!(!state.drained()); + } + + #[test] + fn abort_keeps_the_outputs_and_abort_all_discards_them() { + let stages = [transform()]; + let mut state = State::new(1, 4); + state.queues[0].extend([1, 2]); + state.queues[1].push_back(3); + let (_, _job) = state.pick(&stages).unwrap(); + drop(state.abort(PipelineError::TypeMismatch)); + assert!(state.queues[0].is_empty()); + assert_eq!(state.queues[1].len(), 1); + assert!( + state.commit(Outcome::Item(0, 4, None)).is_some(), + "a result arriving after the failure is handed back" + ); + drop(state.abort_all(PipelineError::EndOfStream)); + assert!(state.queues[1].is_empty()); + assert!( + matches!(state.error, Some(PipelineError::TypeMismatch)), + "the first error wins" + ); + } +} diff --git a/src/scheduler/types.rs b/src/scheduler/types.rs index ff78457..c7d257e 100644 --- a/src/scheduler/types.rs +++ b/src/scheduler/types.rs @@ -1,4 +1,3 @@ -use crossbeam_channel::Sender; use std::sync::Arc; use super::error::PipelineError; @@ -15,14 +14,14 @@ pub type SinkFn = Box Result<(), PipelineError> + Send>; /// Transform function shared between workers through an `Arc`. pub type SharedFn = Arc Result + Send + Sync>; -/// 1→N transform function (flat map) shared between workers through an `Arc`. +/// What a 1→N stage returns for one input: a lazy sequence of results. /// -/// The function receives the input item, a `push` channel to send each produced -/// item, and a `delta` channel to tell the scheduler how many additional items -/// entered the pipeline (N-1 if N items are produced). -/// It must call `delta.send(N - 1)` **after** pushing all the items. -pub type SharedFlatFn = - Arc>, &Sender) + Send + Sync>; +/// The pipeline pulls it **one item at a time**, only while the next queue has room, and may resume it +/// on another worker thread between two items (hence `Send`). An `Err` item stops the pipeline. +pub type FlatOutput = Box> + Send>; + +/// 1→N transform function (flat map) shared between workers through an `Arc`. +pub type SharedFlatFn = Arc FlatOutput + Send + Sync>; // ── Stage enum ──────────────────────────────────────────────────────────────── @@ -42,10 +41,3 @@ impl Clone for Stage { } } } - -// ── Worker task ─────────────────────────────────────────────────────────────── - -pub(super) enum WorkerTask { - Transform(D, usize), - Flat(D, usize), -} diff --git a/src/throttle.rs b/src/throttle.rs index baf3ff9..52eddfc 100644 --- a/src/throttle.rs +++ b/src/throttle.rs @@ -5,11 +5,10 @@ use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError}; // ── Throttle ────────────────────────────────────────────────────────────────── /// Counting semaphore: limits how many items from a source are in-flight -/// simultaneously through the Flat stage of a pipeline. +/// simultaneously, to bound a resource (open files, memory). /// /// Slots are acquired in the source thread before an item is emitted, and -/// released when the corresponding `ThrottleGuard` is dropped (i.e. when the -/// Flat worker finishes processing the item). Acquisition must never happen +/// released when the corresponding `ThrottleGuard` is dropped. Acquisition must never happen /// inside a worker — only in the source thread — to prevent deadlocks. pub struct Throttle { count: Mutex, @@ -87,9 +86,9 @@ impl Drop for ThrottleGuard { /// An item paired with its throttle guard. /// -/// The guard keeps a slot acquired until this value is dropped. In a Flat -/// pipeline stage, carry the guard inside the worker closure until the item -/// is fully processed, then let it drop. +/// The guard keeps a slot acquired until this value is dropped. In a flat +/// pipeline stage, move the guard into the returned iterator, so that the +/// slot is freed when the expansion is over. pub struct Throttled { /// The wrapped item. pub item: T, diff --git a/tests/errors.rs b/tests/errors.rs index 58986f7..5805847 100644 --- a/tests/errors.rs +++ b/tests/errors.rs @@ -1,5 +1,5 @@ -//! 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. +//! 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, @@ -26,6 +26,21 @@ fn within(f: impl FnOnce() -> T + Send + 'static) -> T { .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")) @@ -65,77 +80,115 @@ fn message(e: &PipelineError) -> String { e.to_string() } +// ── Pipe / PipeIter ───────────────────────────────────────────────────────────── + #[test] -fn fallible_stage_error_is_returned_and_does_not_hang() { - let (items, result) = within(|| { +fn fallible_stage_error_is_the_last_item() { + let (items, err) = 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()) + drain(pipe.apply(1..=10u64, 2, 4)) }); 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}"); + assert!(message(&err.expect("the error must be yielded")).contains("boom on 5")); } #[test] -fn fallible_flat_stage_error_is_returned_and_does_not_hang() { - let result = within(|| { +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, }; - pipe.apply(1..=10u64, 2, 4).finish() + drain(pipe.apply(1..=10u64, 2, 4)) }); - assert!(message(&result.unwrap_err()).contains("boom on 5")); + assert!(message(&err.unwrap()).contains("boom on 5")); } #[test] -fn runtime_type_mismatch_is_returned_and_does_not_hang() { - let result = within(|| { +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, }; - pipe.apply(1..=10u64, 2, 4).finish() + drain(pipe.apply(1..=10u64, 2, 4)) }); - assert!(matches!(result, Err(PipelineError::TypeMismatch))); + assert!(matches!(err, Some(PipelineError::TypeMismatch))); } #[test] -fn worker_panic_is_returned_and_does_not_hang() { - let result = within(|| { +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, }; - pipe.apply(1..=10u64, 2, 4).finish() + drain(pipe.apply(1..=10u64, 2, 4)) }); - assert!(message(&result.unwrap_err()).contains("boom on 3")); + assert!(message(&err.unwrap()).contains("boom on 3")); } #[test] -fn finish_is_ok_when_everything_went_through() { - let (n, result) = within(|| { +fn no_error_item_when_everything_went_through() { + let (items, err) = 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()) + drain(pipe.apply(6..=20u64, 3, 4)) }); - assert_eq!(n, 15); - assert!(result.is_ok()); + assert_eq!(items.len(), 15); + assert!(err.is_none()); } #[test] fn capacity_one_works() { - let n = within(|| { + let (items, err) = within(|| { let pipe = make_pipe! { D : u64 => u64, |? fails_on_5 : Num => Num, }; - pipe.apply(6..=205u64, 2, 1).count() + drain(pipe.apply(6..=205u64, 2, 1)) }); - 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); + assert_eq!(items.len(), 200); + assert!(err.is_none()); } #[test] @@ -145,6 +198,13 @@ fn zero_workers_is_rejected() { 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() { @@ -195,7 +255,7 @@ fn pipeline_returns_a_stage_error() { assert!(message(&result.unwrap_err()).contains("boom on 5")); } -fn fallible_source() -> Vec> { +fn fallible_source_failing() -> Vec> { vec![ Ok(1), Ok(2), @@ -204,12 +264,16 @@ fn fallible_source() -> Vec> { ] } +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() => Num, + source? fallible_source_failing() => Num, | identity : Num => Num, sink ignore @ Num, }) @@ -217,6 +281,19 @@ fn pipeline_returns_a_source_error() { 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")) @@ -254,6 +331,40 @@ fn pipeline_with_a_flat_stage_counts_every_item() { 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] @@ -272,3 +383,92 @@ fn pipeline_error_display_and_source() { 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); +} diff --git a/tests/pipe.rs b/tests/pipe.rs index 73fe278..09d7ecb 100644 --- a/tests/pipe.rs +++ b/tests/pipe.rs @@ -26,7 +26,10 @@ fn transform_chain_preserves_the_item_set() { | double : Num => Num, | to_text : Num => Text, }; - let mut out: Vec = pipe.apply(1..=100u64, 4, 8).collect(); + let mut out: Vec = pipe + .apply(1..=100u64, 4, 8) + .collect::>() + .unwrap(); // Workers run in parallel: the order is not guaranteed, the set is. out.sort_by_key(|s| s.parse::().unwrap()); let expected: Vec = (1..=100u64).map(|x| (x * 2).to_string()).collect(); @@ -64,7 +67,11 @@ fn flat_transform_may_produce_no_item() { fn composed_pipes_run_as_a_single_pipeline() { let first = make_pipe! { D : u64 => u64, | double : Num => Num, }; let second = make_pipe! { D : u64 => String, | to_text : Num => Text, }; - let mut out: Vec = first.then(second).apply(1..=20u64, 2, 4).collect(); + let mut out: Vec = first + .then(second) + .apply(1..=20u64, 2, 4) + .collect::>() + .unwrap(); out.sort_by_key(|s| s.parse::().unwrap()); let expected: Vec = (1..=20u64).map(|x| (x * 2).to_string()).collect(); assert_eq!(out, expected); diff --git a/tests/scheduling.rs b/tests/scheduling.rs new file mode 100644 index 0000000..4ab6650 --- /dev/null +++ b/tests/scheduling.rs @@ -0,0 +1,128 @@ +//! Scheduling: downstream stages first, lazy 1→N stages, no deadlock with small queues. + +use obipipeline::{Throttled, make_pipe, throttle}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, mpsc}; +use std::thread; +use std::time::Duration; + +enum D { + Num(u64), + Held(Throttled), +} + +/// Runs `f` on a thread and fails the test if it does not finish in time. +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(20)) + .expect("the pipeline hung") +} + +fn hundred(x: u64) -> impl Iterator + Send { + // Slow to start, so that the other inputs are queued meanwhile. + thread::sleep(Duration::from_millis(5)); + (0..100).map(move |i| x * 100 + i) +} + +fn identity(x: u64) -> u64 { + x +} + +#[test] +fn flat_stage_followed_by_a_stage_never_deadlocks() { + for (workers, capacity) in [(1, 1), (4, 4), (4, 16), (8, 1)] { + let n = within(move || { + let pipe = + make_pipe! { D : u64 => u64, || hundred : Num => Num, | identity : Num => Num, }; + pipe.apply(0..20u64, workers, capacity) + .filter(Result::is_ok) + .count() + }); + assert_eq!(n, 2000, "workers={workers} capacity={capacity}"); + } +} + +#[test] +fn chained_flat_stages_with_one_worker_and_one_slot() { + fn three(x: u64) -> Vec { + vec![x; 3] + } + let n = within(|| { + let pipe = make_pipe! { + D : u64 => u64, + || three : Num => Num, + || three : Num => Num, + | identity : Num => Num, + }; + pipe.apply(0..50u64, 1, 1).filter(Result::is_ok).count() + }); + assert_eq!(n, 450); +} + +#[test] +fn throttle_larger_than_the_pool_does_not_deadlock() { + fn expand(t: Throttled) -> impl Iterator + Send { + (0..100).map(move |i| { + let _held = &t.guard; // the slot lives as long as the expansion + t.item + i + }) + } + let n = within(|| { + let pipe = make_pipe! { D : Throttled => u64, || expand : Held => Num, | identity : Num => Num, }; + pipe.apply(throttle(0..50u64, 8), 4, 2) + .filter(Result::is_ok) + .count() + }); + assert_eq!(n, 5000); +} + +#[test] +fn the_most_advanced_stage_is_served_first() { + let log: Arc>> = Arc::default(); + let (first, second) = (Arc::clone(&log), Arc::clone(&log)); + let produce = move |x: u64| { + let log = Arc::clone(&first); + (0..3).map(move |i| { + log.lock().unwrap().push(('p', x * 10 + i)); + x * 10 + i + }) + }; + let consume = move |x: u64| { + second.lock().unwrap().push(('c', x)); + x + }; + within(move || { + let pipe = make_pipe! { D : u64 => u64, || produce : Num => Num, | consume : Num => Num, }; + // One worker and an output queue that never fills: the order is fully determined. + pipe.apply(0..10u64, 1, 1000).count() + }); + let log = log.lock().unwrap(); + assert_eq!(log.len(), 60); + for pair in log.chunks(2) { + assert_eq!((pair[0].0, pair[1].0), ('p', 'c'), "{log:?}"); + assert_eq!(pair[0].1, pair[1].1); + } +} + +#[test] +fn a_flat_stage_is_pulled_only_as_downstream_makes_room() { + let produced = Arc::new(AtomicUsize::new(0)); + let counter = Arc::clone(&produced); + let endless = move |_: u64| { + let counter = Arc::clone(&counter); + std::iter::from_fn(move || Some(counter.fetch_add(1, Ordering::SeqCst) as u64)) + }; + let (workers, capacity) = (3, 4); + within(move || { + let pipe = make_pipe! { D : u64 => u64, || endless : Num => Num, | identity : Num => Num, }; + let mut out = pipe.apply(0..1u64, workers, capacity); + assert!(out.next().is_some()); + thread::sleep(Duration::from_millis(200)); // nobody consumes: production must stop + drop(out); // and dropping an endless expansion must not hang + }); + // Two stage output queues, the output channel, the sink's item and the consumed one. + assert!(produced.load(Ordering::SeqCst) <= 3 * capacity + 2); +} diff --git a/tests/shutdown.rs b/tests/shutdown.rs new file mode 100644 index 0000000..ff8bbb1 --- /dev/null +++ b/tests/shutdown.rs @@ -0,0 +1,128 @@ +//! Stopping a pipeline: sink failures, early drop of the output, panic messages. + +use std::sync::mpsc; +use std::thread; +use std::time::Duration; + +use obipipeline::{ + PipelineError, ThrottleGuard, Throttled, WorkerPool, make_pipe, make_pipeline, throttle, +}; + +/// Runs `f` on another thread and fails the test if it does not return in time. +fn within(f: impl FnOnce() -> T + Send + 'static) -> T { + let (tx, rx) = mpsc::channel(); + thread::spawn(move || tx.send(f())); + rx.recv_timeout(Duration::from_secs(10)) + .expect("the pipeline hangs or the closure panicked") +} + +fn message(error: &PipelineError) -> String { + error.to_string() +} + +enum Slot { + In(Throttled), + Out(Option), +} + +fn guard_last(x: Throttled) -> Vec> { + vec![None, Some(x.guard)] +} + +fn slow_failure(_: Option) -> Result<(), std::io::Error> { + thread::sleep(Duration::from_millis(100)); // lets the guard reach the output queue + Err(std::io::Error::other("disk full")) +} + +#[test] +fn sink_failure_releases_the_slots_held_by_queued_outputs() { + let result = within(|| { + let pipeline = make_pipeline! { + Slot, + source throttle(0..10u32, 1) => In, + || guard_last : In => Out, + sink? slow_failure @ Out, + }; + WorkerPool::new(pipeline, 2, 8).run() + }); + assert!(message(&result.unwrap_err()).contains("disk full")); +} + +enum Num { + N(u64), +} + +fn only_zero(x: u64) -> Option { + (x == 0).then_some(x) +} + +#[test] +fn early_drop_with_an_endless_source_and_no_more_output() { + within(|| { + let pipe = make_pipe! { Num : u64 => u64, || only_zero : N => N, }; + let mut out = pipe.apply(0u64.., 2, 4); + assert_eq!(out.next().unwrap().unwrap(), 0); + drop(out); + }); +} + +enum Held { + T(Throttled), +} + +fn keep(x: Throttled) -> Throttled { + x +} + +#[test] +fn early_drop_while_the_caller_holds_the_only_slot() { + let (source_end, ended) = mpsc::channel::<()>(); + within(move || { + let pipe = make_pipe! { Held : Throttled => Throttled, | keep : T => T, }; + // `source_end` lives as long as the source does. + let source = throttle(0..10u32, 1).inspect(move |_| { + let _ = &source_end; + }); + let mut out = pipe.apply(source, 2, 4); + let first = out.next().unwrap().unwrap(); + thread::sleep(Duration::from_millis(50)); // the source now waits for the slot + drop(out); + drop(first); + }); + // Once the slot is free, the source thread left behind stops by itself. + assert_eq!( + ended.recv_timeout(Duration::from_secs(10)), + Err(mpsc::RecvTimeoutError::Disconnected) + ); +} + +fn identity(x: u64) -> u64 { + x +} + +#[test] +fn source_panic_keeps_its_message() { + let error = within(|| { + let pipe = make_pipe! { Num : u64 => u64, | identity : N => N, }; + let source = (0u64..3).inspect(|_| panic!("source boom")); + pipe.apply(source, 1, 1).find_map(Result::err) + }); + assert!(message(&error.unwrap()).contains("source panicked: source boom")); +} + +fn failing_sink(_: u64) { + panic!("sink boom"); +} + +#[test] +fn sink_panic_keeps_its_message() { + let result = within(|| { + let pipeline = make_pipeline! { + Num, + source 0u64..3 => N, + sink failing_sink @ N, + }; + WorkerPool::new(pipeline, 1, 1).run() + }); + assert!(message(&result.unwrap_err()).contains("sink panicked: sink boom")); +}