Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8fbd73a657 | ||
|
|
f68243cde0 |
No files matched your search
+1
-1
@@ -1 +1 @@
|
||||
0.3.7+0.1.1
|
||||
0.3.10+0.1.1
|
||||
+8
-2
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
|
||||
Executable
+28
@@ -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 +<toolchain> 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
|
||||
@@ -1,12 +1,30 @@
|
||||
#!/usr/bin/env bash
|
||||
# Safeguard: a crate published on a private registry declares `publish = ["<registry>"]` 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 = ["<registry>"]` 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
|
||||
@@ -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
|
||||
|
||||
Generated
+1
-1
@@ -19,7 +19,7 @@ checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
|
||||
|
||||
[[package]]
|
||||
name = "obipipeline"
|
||||
version = "0.1.1"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"crossbeam-channel",
|
||||
]
|
||||
+6
-3
@@ -1,14 +1,17 @@
|
||||
[package]
|
||||
name = "obipipeline"
|
||||
version = "0.1.1"
|
||||
version = "0.2.0"
|
||||
edition = "2024"
|
||||
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"
|
||||
@@ -1,23 +1,39 @@
|
||||
# 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<D, In, Out>`**: 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<D, In, Out>`**: 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<Out, PipelineError>`).
|
||||
- **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.
|
||||
|
||||

|
||||
|
||||
## 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` yields `Result<Out, PipelineError>`: the error comes as the **last item** (`Err(..)`), after the items already delivered, then the iterator ends. `.collect::<Result<Vec<_>, _>>()?` 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
|
||||
|
||||
The crate is published on the private registry `obi`:
|
||||
|
||||
```toml
|
||||
[dependencies]
|
||||
obipipeline = { version = "0.1", registry = "obi" }
|
||||
obipipeline = { version = "0.2", registry = "obi" }
|
||||
```
|
||||
|
||||
## Example
|
||||
@@ -38,7 +54,7 @@ let pipe = make_pipe! {
|
||||
| double : Num => Num,
|
||||
| to_text : Num => Text,
|
||||
};
|
||||
let out: Vec<String> = pipe.apply(1..=100u64, 4, 8).collect();
|
||||
let out: Vec<String> = pipe.apply(1..=100u64, 4, 8).collect::<Result<_, _>>()?;
|
||||
```
|
||||
|
||||
`examples/sandbox_pipeline.rs` shows the lower-level `make_pipeline!` / `WorkerPool` form.
|
||||
@@ -46,7 +62,7 @@ let out: Vec<String> = pipe.apply(1..=100u64, 4, 8).collect();
|
||||
## API
|
||||
|
||||
- Pipes: `Pipe`, `PipeIter`, macros `make_pipe!`, `make_transform!`, `make_transform_fallible!`, `make_flat_transform!`, `make_flat_transform_fallible!`.
|
||||
- Runtime: `Pipeline`, `WorkerPool`, `Stage`, `SourceFn`, `SinkFn`, `SharedFn`, `SharedFlatFn`, `PipelineError`, `PipelineSender`; macros `make_pipeline!`, `make_source!`, `make_source_fallible!`, `make_sink!`, `make_sink_fallible!`.
|
||||
- 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
|
||||
@@ -62,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
|
||||
|
||||
|
||||
@@ -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<D> core::marker::Freeze for obipipeline::Stage<D> where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result<D, obipipeline::PipelineError> + core::marker::Send + core::marker::Sync)>: core::marker::Freeze, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D, &crossbeam_channel::channel::Sender<core::result::Result<D, obipipeline::PipelineError>>, &crossbeam_channel::channel::Sender<isize>) + core::marker::Send + core::marker::Sync)>: core::marker::Freeze
|
||||
> impl<D> core::marker::Freeze for obipipeline::Stage<D> where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result<D, obipipeline::PipelineError> + 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<Item = core::result::Result<D, obipipeline::PipelineError>> + core::marker::Send)> + core::marker::Send + core::marker::Sync)>: core::marker::Freeze
|
||||
< impl<D> core::marker::Send for obipipeline::Stage<D> where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result<D, obipipeline::PipelineError> + core::marker::Send + core::marker::Sync)>: core::marker::Send, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D, &crossbeam_channel::channel::Sender<core::result::Result<D, obipipeline::PipelineError>>, &crossbeam_channel::channel::Sender<isize>) + core::marker::Send + core::marker::Sync)>: core::marker::Send
|
||||
< impl<D> core::marker::Sync for obipipeline::Stage<D> where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result<D, obipipeline::PipelineError> + core::marker::Send + core::marker::Sync)>: core::marker::Sync, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D, &crossbeam_channel::channel::Sender<core::result::Result<D, obipipeline::PipelineError>>, &crossbeam_channel::channel::Sender<isize>) + core::marker::Send + core::marker::Sync)>: core::marker::Sync
|
||||
< impl<D> core::marker::Unpin for obipipeline::Stage<D> where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result<D, obipipeline::PipelineError> + core::marker::Send + core::marker::Sync)>: core::marker::Unpin, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D, &crossbeam_channel::channel::Sender<core::result::Result<D, obipipeline::PipelineError>>, &crossbeam_channel::channel::Sender<isize>) + core::marker::Send + core::marker::Sync)>: core::marker::Unpin
|
||||
< impl<D> core::marker::UnsafeUnpin for obipipeline::Stage<D> where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result<D, obipipeline::PipelineError> + core::marker::Send + core::marker::Sync)>: core::marker::UnsafeUnpin, alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D, &crossbeam_channel::channel::Sender<core::result::Result<D, obipipeline::PipelineError>>, &crossbeam_channel::channel::Sender<isize>) + core::marker::Send + core::marker::Sync)>: core::marker::UnsafeUnpin
|
||||
> impl<D> core::marker::Send for obipipeline::Stage<D> where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result<D, obipipeline::PipelineError> + 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<Item = core::result::Result<D, obipipeline::PipelineError>> + core::marker::Send)> + core::marker::Send + core::marker::Sync)>: core::marker::Send
|
||||
> impl<D> core::marker::Sync for obipipeline::Stage<D> where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result<D, obipipeline::PipelineError> + 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<Item = core::result::Result<D, obipipeline::PipelineError>> + core::marker::Send)> + core::marker::Send + core::marker::Sync)>: core::marker::Sync
|
||||
> impl<D> core::marker::Unpin for obipipeline::Stage<D> where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result<D, obipipeline::PipelineError> + 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<Item = core::result::Result<D, obipipeline::PipelineError>> + core::marker::Send)> + core::marker::Send + core::marker::Sync)>: core::marker::Unpin
|
||||
> impl<D> core::marker::UnsafeUnpin for obipipeline::Stage<D> where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result<D, obipipeline::PipelineError> + 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<Item = core::result::Result<D, obipipeline::PipelineError>> + 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<Out>::Item = Out
|
||||
< pub fn obipipeline::PipeIter<Out>::next(&mut self) -> core::option::Option<Out>
|
||||
> pub type obipipeline::PipeIter<Out>::Item = core::result::Result<Out, obipipeline::PipelineError>
|
||||
> pub fn obipipeline::PipeIter<Out>::next(&mut self) -> core::option::Option<Self::Item>
|
||||
< 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<DATA>::run(self)
|
||||
> pub fn obipipeline::WorkerPool<DATA>::run(self) -> core::result::Result<(), obipipeline::PipelineError>
|
||||
< pub type obipipeline::SharedFlatFn<D> = alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D, &crossbeam_channel::channel::Sender<core::result::Result<D, obipipeline::PipelineError>>, &crossbeam_channel::channel::Sender<isize>) + core::marker::Send + core::marker::Sync)>
|
||||
> pub type obipipeline::FlatOutput<D> = alloc::boxed::Box<(dyn core::iter::traits::iterator::Iterator<Item = core::result::Result<D, obipipeline::PipelineError>> + core::marker::Send)>
|
||||
> pub type obipipeline::SharedFlatFn<D> = alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> obipipeline::FlatOutput<D> + core::marker::Send + core::marker::Sync)>
|
||||
```
|
||||
Binary file not shown.
@@ -0,0 +1 @@
|
||||
rustc 1.100.0 (0ef1bc386 2026-11-09) | cargo-public-api 0.52.0
|
||||
+198
@@ -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<Self>) -> 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<T>
|
||||
pub obipipeline::throttle::Throttled::guard: obipipeline::throttle::ThrottleGuard
|
||||
pub obipipeline::throttle::Throttled::item: T
|
||||
impl<T> core::marker::Forget for obipipeline::throttle::Throttled<T>
|
||||
impl<T> core::marker::Freeze for obipipeline::throttle::Throttled<T> where T: core::marker::Freeze
|
||||
impl<T> core::marker::Move for obipipeline::throttle::Throttled<T>
|
||||
impl<T> core::marker::Send for obipipeline::throttle::Throttled<T> where T: core::marker::Send
|
||||
impl<T> core::marker::Sync for obipipeline::throttle::Throttled<T> where T: core::marker::Sync
|
||||
impl<T> core::marker::Unpin for obipipeline::throttle::Throttled<T> where T: core::marker::Unpin
|
||||
impl<T> core::marker::UnsafeUnpin for obipipeline::throttle::Throttled<T> where T: core::marker::UnsafeUnpin
|
||||
impl<T> core::panic::unwind_safe::RefUnwindSafe for obipipeline::throttle::Throttled<T> where T: core::panic::unwind_safe::RefUnwindSafe
|
||||
impl<T> core::panic::unwind_safe::UnwindSafe for obipipeline::throttle::Throttled<T> where T: core::panic::unwind_safe::UnwindSafe
|
||||
pub fn obipipeline::throttle::throttle<I>(I, usize) -> impl core::iter::traits::iterator::Iterator<Item = obipipeline::throttle::Throttled<<I as core::iter::traits::iterator::Iterator>::Item>> where I: core::iter::traits::iterator::Iterator, <I as 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<D>
|
||||
pub obipipeline::Stage::Flat(obipipeline::SharedFlatFn<D>)
|
||||
pub obipipeline::Stage::Transform(obipipeline::SharedFn<D>)
|
||||
impl<D> core::clone::Clone for obipipeline::Stage<D>
|
||||
pub fn obipipeline::Stage<D>::clone(&self) -> Self
|
||||
impl<D> core::marker::Forget for obipipeline::Stage<D>
|
||||
impl<D> core::marker::Freeze for obipipeline::Stage<D> where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result<D, obipipeline::PipelineError> + 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<Item = core::result::Result<D, obipipeline::PipelineError>> + core::marker::Send)> + core::marker::Send + core::marker::Sync)>: core::marker::Freeze
|
||||
impl<D> core::marker::Move for obipipeline::Stage<D>
|
||||
impl<D> core::marker::Send for obipipeline::Stage<D> where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result<D, obipipeline::PipelineError> + 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<Item = core::result::Result<D, obipipeline::PipelineError>> + core::marker::Send)> + core::marker::Send + core::marker::Sync)>: core::marker::Send
|
||||
impl<D> core::marker::Sync for obipipeline::Stage<D> where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result<D, obipipeline::PipelineError> + 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<Item = core::result::Result<D, obipipeline::PipelineError>> + core::marker::Send)> + core::marker::Send + core::marker::Sync)>: core::marker::Sync
|
||||
impl<D> core::marker::Unpin for obipipeline::Stage<D> where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result<D, obipipeline::PipelineError> + 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<Item = core::result::Result<D, obipipeline::PipelineError>> + core::marker::Send)> + core::marker::Send + core::marker::Sync)>: core::marker::Unpin
|
||||
impl<D> core::marker::UnsafeUnpin for obipipeline::Stage<D> where alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result<D, obipipeline::PipelineError> + 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<Item = core::result::Result<D, obipipeline::PipelineError>> + core::marker::Send)> + core::marker::Send + core::marker::Sync)>: core::marker::UnsafeUnpin
|
||||
impl<D> !core::panic::unwind_safe::RefUnwindSafe for obipipeline::Stage<D>
|
||||
impl<D> !core::panic::unwind_safe::UnwindSafe for obipipeline::Stage<D>
|
||||
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<D, In, Out>
|
||||
impl<D, In, Out> obipipeline::Pipe<D, In, Out> where D: core::marker::Send + core::marker::Sync + 'static, In: core::marker::Send + 'static, Out: core::marker::Send + 'static
|
||||
pub fn obipipeline::Pipe<D, In, Out>::apply(self, impl core::iter::traits::iterator::Iterator<Item = In> + core::marker::Send + 'static, usize, usize) -> obipipeline::PipeIter<Out>
|
||||
impl<D, In, Out> obipipeline::Pipe<D, In, Out>
|
||||
pub fn obipipeline::Pipe<D, In, Out>::new(alloc::vec::Vec<obipipeline::Stage<D>>, 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<D, In, Out>::then<Next>(self, obipipeline::Pipe<D, Out, Next>) -> obipipeline::Pipe<D, In, Next>
|
||||
impl<D, In, Out> core::marker::Forget for obipipeline::Pipe<D, In, Out>
|
||||
impl<D, In, Out> core::marker::Freeze for obipipeline::Pipe<D, In, Out> where alloc::vec::Vec<obipipeline::Stage<D>>: 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<D, In, Out> core::marker::Move for obipipeline::Pipe<D, In, Out>
|
||||
impl<D, In, Out> core::marker::Send for obipipeline::Pipe<D, In, Out> where alloc::vec::Vec<obipipeline::Stage<D>>: 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<D, In, Out> core::marker::Sync for obipipeline::Pipe<D, In, Out> where alloc::vec::Vec<obipipeline::Stage<D>>: 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<D, In, Out> core::marker::Unpin for obipipeline::Pipe<D, In, Out> where alloc::vec::Vec<obipipeline::Stage<D>>: 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<D, In, Out> core::marker::UnsafeUnpin for obipipeline::Pipe<D, In, Out> where alloc::vec::Vec<obipipeline::Stage<D>>: 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<D, In, Out> !core::panic::unwind_safe::RefUnwindSafe for obipipeline::Pipe<D, In, Out>
|
||||
impl<D, In, Out> !core::panic::unwind_safe::UnwindSafe for obipipeline::Pipe<D, In, Out>
|
||||
pub struct obipipeline::PipeIter<Out>
|
||||
impl<Out> core::iter::traits::iterator::Iterator for obipipeline::PipeIter<Out>
|
||||
pub type obipipeline::PipeIter<Out>::Item = core::result::Result<Out, obipipeline::PipelineError>
|
||||
pub fn obipipeline::PipeIter<Out>::next(&mut self) -> core::option::Option<Self::Item>
|
||||
impl<Out> core::ops::drop::Drop for obipipeline::PipeIter<Out>
|
||||
pub fn obipipeline::PipeIter<Out>::drop(&mut self)
|
||||
impl<Out> core::marker::Forget for obipipeline::PipeIter<Out>
|
||||
impl<Out> core::marker::Freeze for obipipeline::PipeIter<Out> where core::option::Option<crossbeam_channel::channel::Receiver<Out>>: core::marker::Freeze
|
||||
impl<Out> core::marker::Move for obipipeline::PipeIter<Out>
|
||||
impl<Out> core::marker::Send for obipipeline::PipeIter<Out> where core::option::Option<crossbeam_channel::channel::Receiver<Out>>: core::marker::Send
|
||||
impl<Out> core::marker::Sync for obipipeline::PipeIter<Out> where core::option::Option<crossbeam_channel::channel::Receiver<Out>>: core::marker::Sync
|
||||
impl<Out> core::marker::Unpin for obipipeline::PipeIter<Out> where core::option::Option<crossbeam_channel::channel::Receiver<Out>>: core::marker::Unpin
|
||||
impl<Out> core::marker::UnsafeUnpin for obipipeline::PipeIter<Out> where core::option::Option<crossbeam_channel::channel::Receiver<Out>>: core::marker::UnsafeUnpin
|
||||
impl<Out> !core::panic::unwind_safe::RefUnwindSafe for obipipeline::PipeIter<Out>
|
||||
impl<Out> !core::panic::unwind_safe::UnwindSafe for obipipeline::PipeIter<Out>
|
||||
pub struct obipipeline::Pipeline<DATA>
|
||||
impl<DATA> obipipeline::Pipeline<DATA>
|
||||
pub fn obipipeline::Pipeline<DATA>::new(obipipeline::SourceFn<DATA>, alloc::vec::Vec<obipipeline::Stage<DATA>>, obipipeline::SinkFn<DATA>) -> Self
|
||||
impl<DATA> core::marker::Forget for obipipeline::Pipeline<DATA>
|
||||
impl<DATA> core::marker::Freeze for obipipeline::Pipeline<DATA> where alloc::boxed::Box<(dyn core::ops::function::FnMut() -> core::result::Result<DATA, obipipeline::PipelineError> + core::marker::Send)>: core::marker::Freeze, alloc::vec::Vec<obipipeline::Stage<DATA>>: core::marker::Freeze, alloc::boxed::Box<(dyn core::ops::function::Fn(DATA) -> core::result::Result<(), obipipeline::PipelineError> + core::marker::Send)>: core::marker::Freeze
|
||||
impl<DATA> core::marker::Move for obipipeline::Pipeline<DATA>
|
||||
impl<DATA> core::marker::Send for obipipeline::Pipeline<DATA> where alloc::boxed::Box<(dyn core::ops::function::FnMut() -> core::result::Result<DATA, obipipeline::PipelineError> + core::marker::Send)>: core::marker::Send, alloc::vec::Vec<obipipeline::Stage<DATA>>: core::marker::Send, alloc::boxed::Box<(dyn core::ops::function::Fn(DATA) -> core::result::Result<(), obipipeline::PipelineError> + core::marker::Send)>: core::marker::Send
|
||||
impl<DATA> !core::marker::Sync for obipipeline::Pipeline<DATA>
|
||||
impl<DATA> core::marker::Unpin for obipipeline::Pipeline<DATA> where alloc::boxed::Box<(dyn core::ops::function::FnMut() -> core::result::Result<DATA, obipipeline::PipelineError> + core::marker::Send)>: core::marker::Unpin, alloc::vec::Vec<obipipeline::Stage<DATA>>: core::marker::Unpin, alloc::boxed::Box<(dyn core::ops::function::Fn(DATA) -> core::result::Result<(), obipipeline::PipelineError> + core::marker::Send)>: core::marker::Unpin
|
||||
impl<DATA> core::marker::UnsafeUnpin for obipipeline::Pipeline<DATA> where alloc::boxed::Box<(dyn core::ops::function::FnMut() -> core::result::Result<DATA, obipipeline::PipelineError> + core::marker::Send)>: core::marker::UnsafeUnpin, alloc::vec::Vec<obipipeline::Stage<DATA>>: core::marker::UnsafeUnpin, alloc::boxed::Box<(dyn core::ops::function::Fn(DATA) -> core::result::Result<(), obipipeline::PipelineError> + core::marker::Send)>: core::marker::UnsafeUnpin
|
||||
impl<DATA> !core::panic::unwind_safe::RefUnwindSafe for obipipeline::Pipeline<DATA>
|
||||
impl<DATA> !core::panic::unwind_safe::UnwindSafe for obipipeline::Pipeline<DATA>
|
||||
pub struct obipipeline::Throttle
|
||||
impl obipipeline::throttle::Throttle
|
||||
pub fn obipipeline::throttle::Throttle::acquire_guard(&alloc::rcs::arc::Arc<Self>) -> 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<T>
|
||||
pub obipipeline::Throttled::guard: obipipeline::throttle::ThrottleGuard
|
||||
pub obipipeline::Throttled::item: T
|
||||
impl<T> core::marker::Forget for obipipeline::throttle::Throttled<T>
|
||||
impl<T> core::marker::Freeze for obipipeline::throttle::Throttled<T> where T: core::marker::Freeze
|
||||
impl<T> core::marker::Move for obipipeline::throttle::Throttled<T>
|
||||
impl<T> core::marker::Send for obipipeline::throttle::Throttled<T> where T: core::marker::Send
|
||||
impl<T> core::marker::Sync for obipipeline::throttle::Throttled<T> where T: core::marker::Sync
|
||||
impl<T> core::marker::Unpin for obipipeline::throttle::Throttled<T> where T: core::marker::Unpin
|
||||
impl<T> core::marker::UnsafeUnpin for obipipeline::throttle::Throttled<T> where T: core::marker::UnsafeUnpin
|
||||
impl<T> core::panic::unwind_safe::RefUnwindSafe for obipipeline::throttle::Throttled<T> where T: core::panic::unwind_safe::RefUnwindSafe
|
||||
impl<T> core::panic::unwind_safe::UnwindSafe for obipipeline::throttle::Throttled<T> where T: core::panic::unwind_safe::UnwindSafe
|
||||
pub struct obipipeline::WorkerPool<DATA>
|
||||
impl<DATA> obipipeline::WorkerPool<DATA> where DATA: core::marker::Send + core::marker::Sync + 'static
|
||||
pub fn obipipeline::WorkerPool<DATA>::new(obipipeline::Pipeline<DATA>, usize, usize) -> Self
|
||||
pub fn obipipeline::WorkerPool<DATA>::run(self) -> core::result::Result<(), obipipeline::PipelineError>
|
||||
impl<DATA> core::marker::Forget for obipipeline::WorkerPool<DATA>
|
||||
impl<DATA> core::marker::Freeze for obipipeline::WorkerPool<DATA> where obipipeline::Pipeline<DATA>: core::marker::Freeze
|
||||
impl<DATA> core::marker::Move for obipipeline::WorkerPool<DATA>
|
||||
impl<DATA> core::marker::Send for obipipeline::WorkerPool<DATA> where obipipeline::Pipeline<DATA>: core::marker::Send
|
||||
impl<DATA> !core::marker::Sync for obipipeline::WorkerPool<DATA>
|
||||
impl<DATA> core::marker::Unpin for obipipeline::WorkerPool<DATA> where obipipeline::Pipeline<DATA>: core::marker::Unpin
|
||||
impl<DATA> core::marker::UnsafeUnpin for obipipeline::WorkerPool<DATA> where obipipeline::Pipeline<DATA>: core::marker::UnsafeUnpin
|
||||
impl<DATA> !core::panic::unwind_safe::RefUnwindSafe for obipipeline::WorkerPool<DATA>
|
||||
impl<DATA> !core::panic::unwind_safe::UnwindSafe for obipipeline::WorkerPool<DATA>
|
||||
pub fn obipipeline::throttle<I>(I, usize) -> impl core::iter::traits::iterator::Iterator<Item = obipipeline::throttle::Throttled<<I as core::iter::traits::iterator::Iterator>::Item>> where I: core::iter::traits::iterator::Iterator, <I as core::iter::traits::iterator::Iterator>::Item: core::marker::Send + 'static
|
||||
pub type obipipeline::FlatOutput<D> = alloc::boxed::Box<(dyn core::iter::traits::iterator::Iterator<Item = core::result::Result<D, obipipeline::PipelineError>> + core::marker::Send)>
|
||||
pub type obipipeline::SharedFlatFn<D> = alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> obipipeline::FlatOutput<D> + core::marker::Send + core::marker::Sync)>
|
||||
pub type obipipeline::SharedFn<D> = alloc::rcs::arc::Arc<(dyn core::ops::function::Fn(D) -> core::result::Result<D, obipipeline::PipelineError> + core::marker::Send + core::marker::Sync)>
|
||||
pub type obipipeline::SinkFn<D> = alloc::boxed::Box<(dyn core::ops::function::Fn(D) -> core::result::Result<(), obipipeline::PipelineError> + core::marker::Send)>
|
||||
pub type obipipeline::SourceFn<D> = alloc::boxed::Box<(dyn core::ops::function::FnMut() -> core::result::Result<D, obipipeline::PipelineError> + core::marker::Send)>
|
||||
@@ -75,5 +75,7 @@ fn main() {
|
||||
sink? step_4 @ Unsigned,
|
||||
};
|
||||
|
||||
WorkerPool::new(pipeline, 4, 64).run();
|
||||
WorkerPool::new(pipeline, 4, 64)
|
||||
.run()
|
||||
.expect("pipeline failed");
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="1600" height="1220" viewBox="0 0 1600 1220" role="img" aria-labelledby="title desc">
|
||||
<title id="title">The obipipeline parallel scheduler</title>
|
||||
<desc id="desc">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.</desc>
|
||||
<style>
|
||||
text{font-family:Helvetica,Arial,sans-serif;fill:#182338}
|
||||
.title{font-size:34px;font-weight:700}
|
||||
.sub{font-size:17px;fill:#55637a}
|
||||
.section{font-size:15px;font-weight:700;letter-spacing:1.4px;fill:#526078}
|
||||
.head{font-size:19px;font-weight:700}
|
||||
.body{font-size:15px;fill:#35445a}
|
||||
.small{font-size:13px;fill:#55637a}
|
||||
.mono{font-family:Menlo,Consolas,monospace;font-size:13px;fill:#26364f}
|
||||
.chip{font-size:13px;font-weight:700}
|
||||
.badge{font-size:14px;font-weight:700;fill:#fff}
|
||||
.panel{fill:#fff;stroke:#d7deea;stroke-width:1.5}
|
||||
.sched{fill:#eeeaff;stroke:#8d7bdc;stroke-width:2.2}
|
||||
.row{fill:#fff;stroke:#c3b9ee;stroke-width:1.2}
|
||||
.pool{fill:#f4f7fc;stroke:#a8b8d4;stroke-width:1.6}
|
||||
.worker{fill:#fff;stroke:#b9c6dc;stroke-width:1.3}
|
||||
.chan{fill:#fff6e4;stroke:#dcb361;stroke-width:1.5}
|
||||
.io{fill:#eef1f6;stroke:#9aa8bd;stroke-width:1.6}
|
||||
.off{fill:none;stroke:#aab4c4;stroke-width:2;stroke-dasharray:5 5}
|
||||
.line{fill:none;stroke:#52647e;stroke-width:2.4}
|
||||
.err{fill:none;stroke:#c0473a;stroke-width:2;stroke-dasharray:6 5}
|
||||
</style>
|
||||
<defs>
|
||||
<marker id="p" markerWidth="15" markerHeight="14" refX="12" refY="7" orient="auto" markerUnits="userSpaceOnUse"><path d="M0 0L15 7L0 14z" fill="#b9501c"/></marker>
|
||||
<linearGradient id="ramp" x1="400" x2="1310" y1="0" y2="0" gradientUnits="userSpaceOnUse"><stop offset="0" stop-color="#e6e2fb"/><stop offset="1" stop-color="#4b3f9e"/></linearGradient>
|
||||
<marker id="a" markerWidth="9" markerHeight="8" refX="8" refY="4" orient="auto" markerUnits="userSpaceOnUse"><path d="M0 0L9 4L0 8z" fill="#52647e"/></marker>
|
||||
<marker id="e" markerWidth="9" markerHeight="8" refX="8" refY="4" orient="auto" markerUnits="userSpaceOnUse"><path d="M0 0L9 4L0 8z" fill="#c0473a"/></marker>
|
||||
</defs>
|
||||
<rect width="1600" height="1220" fill="#f7f9fc"/>
|
||||
<text x="50" y="58" class="title" text-anchor="start" >The obipipeline parallel scheduler</text>
|
||||
<text x="50" y="88" class="sub" text-anchor="start" >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.</text>
|
||||
<rect x="40" y="112" width="1520" height="165" rx="16" class="panel" />
|
||||
<text x="66" y="144" class="section" text-anchor="start" >WHAT YOU DECLARE: A LINEAR PIPELINE</text>
|
||||
<rect x="110" y="170" width="190" height="78" rx="12" class="io" />
|
||||
<text x="205.0" y="203" class="head" text-anchor="middle" >Source</text>
|
||||
<text x="205.0" y="228" class="small" text-anchor="middle" >items, pulled in sequence</text>
|
||||
<rect x="400" y="170" width="230" height="78" rx="12" fill="#dbe9fb" stroke="#2a64b8" stroke-width="1.8"/>
|
||||
<text x="515.0" y="203" class="head" text-anchor="middle" >Stage S0</text>
|
||||
<text x="515.0" y="228" class="small" text-anchor="middle" >transform, 1 → 1</text>
|
||||
<rect x="730" y="170" width="230" height="78" rx="12" fill="#fde4d6" stroke="#b9501c" stroke-width="1.8"/>
|
||||
<text x="845.0" y="203" class="head" text-anchor="middle" >Stage S1</text>
|
||||
<text x="845.0" y="228" class="small" text-anchor="middle" >flat transform, 1 → N</text>
|
||||
<rect x="1060" y="170" width="230" height="78" rx="12" fill="#d6f1e6" stroke="#137a58" stroke-width="1.8"/>
|
||||
<text x="1175.0" y="203" class="head" text-anchor="middle" >Stage S2</text>
|
||||
<text x="1175.0" y="228" class="small" text-anchor="middle" >transform, 1 → 1</text>
|
||||
<rect x="1390" y="170" width="120" height="78" rx="12" class="io" />
|
||||
<text x="1450.0" y="203" class="head" text-anchor="middle" >Sink</text>
|
||||
<text x="1450.0" y="228" class="small" text-anchor="middle" >final items</text>
|
||||
<path d="M300 209H398" class="line" marker-end="url(#a)"/>
|
||||
<path d="M630 209H728" class="line" marker-end="url(#a)"/>
|
||||
<path d="M960 209H1058" class="line" marker-end="url(#a)"/>
|
||||
<path d="M1290 209H1388" class="line" marker-end="url(#a)"/>
|
||||
<rect x="40" y="297" width="1520" height="600" rx="16" class="panel" />
|
||||
<text x="66" y="329" class="section" text-anchor="start" >HOW TASKS ARE SCHEDULED: ONE QUEUE PER STAGE, HIGHEST RANK SERVED FIRST</text>
|
||||
<text x="420" y="366" class="head" text-anchor="middle" >Queue 0</text>
|
||||
<text x="420" y="387" class="small" text-anchor="middle" style="fill:#55637a;font-weight:700">lower rank: waits</text>
|
||||
<rect x="295" y="398" width="250" height="60" rx="10" fill="#fff" stroke="#2a64b8" stroke-width="1.6"/>
|
||||
<rect x="493" y="413" width="42" height="30" rx="6" fill="#dbe9fb" stroke="#2a64b8" stroke-width="1.6"/>
|
||||
<text x="514.0" y="433.0" class="chip" text-anchor="middle" style="fill:#2a64b8">S0</text>
|
||||
<rect x="445" y="413" width="42" height="30" rx="6" fill="#dbe9fb" stroke="#2a64b8" stroke-width="1.6"/>
|
||||
<text x="466.0" y="433.0" class="chip" text-anchor="middle" style="fill:#2a64b8">S0</text>
|
||||
<rect x="397" y="413" width="42" height="30" rx="6" fill="#dbe9fb" stroke="#2a64b8" stroke-width="1.6"/>
|
||||
<text x="418.0" y="433.0" class="chip" text-anchor="middle" style="fill:#2a64b8">S0</text>
|
||||
<rect x="349" y="413" width="42" height="30" rx="6" fill="#dbe9fb" stroke="#2a64b8" stroke-width="1.6"/>
|
||||
<text x="370.0" y="433.0" class="chip" text-anchor="middle" style="fill:#2a64b8">S0</text>
|
||||
<rect x="301" y="413" width="42" height="30" rx="6" fill="#dbe9fb" stroke="#2a64b8" stroke-width="1.6"/>
|
||||
<text x="322.0" y="433.0" class="chip" text-anchor="middle" style="fill:#2a64b8">S0</text>
|
||||
<text x="740" y="366" class="head" text-anchor="middle" >Queue 1</text>
|
||||
<text x="740" y="387" class="small" text-anchor="middle" style="fill:#b9501c;font-weight:700">highest non-empty rank: picked</text>
|
||||
<rect x="615" y="398" width="250" height="60" rx="10" fill="#fff" stroke="#b9501c" stroke-width="3.4"/>
|
||||
<rect x="813" y="413" width="42" height="30" rx="6" fill="#fde4d6" stroke="#b9501c" stroke-width="1.6"/>
|
||||
<text x="834.0" y="433.0" class="chip" text-anchor="middle" style="fill:#b9501c">S1</text>
|
||||
<rect x="765" y="413" width="42" height="30" rx="6" fill="#fde4d6" stroke="#b9501c" stroke-width="1.6"/>
|
||||
<text x="786.0" y="433.0" class="chip" text-anchor="middle" style="fill:#b9501c">S1</text>
|
||||
<rect x="717" y="413" width="42" height="30" rx="6" fill="#fde4d6" stroke="#b9501c" stroke-width="1.6"/>
|
||||
<text x="738.0" y="433.0" class="chip" text-anchor="middle" style="fill:#b9501c">S1</text>
|
||||
<text x="1060" y="366" class="head" text-anchor="middle" >Queue 2</text>
|
||||
<text x="1060" y="387" class="small" text-anchor="middle" style="fill:#55637a;font-weight:700">empty: skipped</text>
|
||||
<rect x="935" y="398" width="250" height="60" rx="10" fill="#fff" stroke="#137a58" stroke-width="1.6"/>
|
||||
<text x="1060" y="433" class="small" text-anchor="middle" >(nothing waiting)</text>
|
||||
<rect x="70" y="392" width="170" height="72" rx="12" class="io" />
|
||||
<text x="155" y="422" class="head" text-anchor="middle" >Source</text>
|
||||
<text x="155" y="447" class="small" text-anchor="middle" >new items</text>
|
||||
<path d="M240 428H293" class="line" marker-end="url(#a)"/>
|
||||
<rect x="1340" y="392" width="170" height="72" rx="12" class="io" />
|
||||
<text x="1425" y="422" class="head" text-anchor="middle" >Output</text>
|
||||
<text x="1425" y="447" class="small" text-anchor="middle" >results</text>
|
||||
<path d="M370 458V566" class="off"/>
|
||||
<path d="M1010 458V566" class="off"/>
|
||||
<path d="M740 458V564" fill="none" stroke="#b9501c" stroke-width="4.5" marker-end="url(#p)"/>
|
||||
<circle cx="740" cy="513" r="13" fill="#4b3f9e"/>
|
||||
<text x="740" y="518" class="badge" text-anchor="middle" >1</text>
|
||||
<text x="762" y="505" class="body" text-anchor="start" >take one item</text>
|
||||
<rect x="295" y="568" width="895" height="70" rx="14" class="sched" />
|
||||
<text x="742" y="597" class="head" text-anchor="middle" >Scheduler: always serve the non-empty queue of highest rank</text>
|
||||
<text x="742" y="622" class="body" text-anchor="middle" >the closer to the output, the higher the rank</text>
|
||||
<path d="M740 638V698" class="line" marker-end="url(#a)"/>
|
||||
<circle cx="740" cy="668" r="13" fill="#4b3f9e"/>
|
||||
<text x="740" y="673" class="badge" text-anchor="middle" >2</text>
|
||||
<text x="762" y="673" class="body" text-anchor="start" >run it as an S1 task on a free worker</text>
|
||||
<rect x="295" y="700" width="895" height="160" rx="14" class="pool" />
|
||||
<text x="742" y="730" class="small" text-anchor="middle" >One shared pool of workers: any of them can run any stage</text>
|
||||
<rect x="315" y="752" width="204" height="80" rx="9" class="worker" />
|
||||
<text x="417" y="780" class="body" text-anchor="middle" style="font-weight:700">Worker 1</text>
|
||||
<rect x="357" y="791" width="44" height="28" rx="6" fill="#dbe9fb" stroke="#2a64b8" stroke-width="1.6"/>
|
||||
<text x="379.0" y="810.0" class="chip" text-anchor="middle" style="fill:#2a64b8">S0</text>
|
||||
<text x="411" y="810" class="small" text-anchor="start" >busy</text>
|
||||
<rect x="532" y="752" width="204" height="80" rx="9" class="worker" />
|
||||
<text x="634" y="780" class="body" text-anchor="middle" style="font-weight:700">Worker 2</text>
|
||||
<rect x="574" y="791" width="44" height="28" rx="6" fill="#dbe9fb" stroke="#2a64b8" stroke-width="1.6"/>
|
||||
<text x="596.0" y="810.0" class="chip" text-anchor="middle" style="fill:#2a64b8">S0</text>
|
||||
<text x="628" y="810" class="small" text-anchor="start" >busy</text>
|
||||
<rect x="749" y="752" width="204" height="80" rx="9" fill="#fff" stroke="#b9501c" stroke-width="3"/>
|
||||
<text x="851" y="780" class="body" text-anchor="middle" style="font-weight:700">Worker 3</text>
|
||||
<rect x="791" y="791" width="44" height="28" rx="6" fill="#fde4d6" stroke="#b9501c" stroke-width="1.6"/>
|
||||
<text x="813.0" y="810.0" class="chip" text-anchor="middle" style="fill:#b9501c">S1</text>
|
||||
<text x="845" y="810" class="small" text-anchor="start" >new task</text>
|
||||
<rect x="966" y="752" width="204" height="80" rx="9" class="worker" />
|
||||
<text x="1068" y="780" class="body" text-anchor="middle" style="font-weight:700">Worker 4</text>
|
||||
<rect x="1008" y="791" width="44" height="28" rx="6" fill="#d6f1e6" stroke="#137a58" stroke-width="1.6"/>
|
||||
<text x="1030.0" y="810.0" class="chip" text-anchor="middle" style="fill:#137a58">S2</text>
|
||||
<text x="1062" y="810" class="small" text-anchor="start" >busy</text>
|
||||
<path d="M1190 780H1245V522H1120V460" class="line" marker-end="url(#a)"/>
|
||||
<path d="M1245 522H1425V466" class="line" marker-end="url(#a)"/>
|
||||
<circle cx="1245" cy="660" r="13" fill="#4b3f9e"/>
|
||||
<text x="1245" y="665" class="badge" text-anchor="middle" >3</text>
|
||||
<text x="1270" y="655" class="body" text-anchor="start" >the result of a stage n task</text>
|
||||
<text x="1270" y="677" class="body" text-anchor="start" >goes into queue n+1,</text>
|
||||
<text x="1270" y="699" class="body" text-anchor="start" >or to the output after</text>
|
||||
<text x="1270" y="721" class="body" text-anchor="start" >the last stage</text>
|
||||
<text x="1270" y="757" class="small" text-anchor="start" >(a 1 → N stage such as S1</text>
|
||||
<text x="1270" y="776" class="small" text-anchor="start" >feeds it several items, one by one)</text>
|
||||
<rect x="40" y="917" width="960" height="268" rx="16" class="panel" />
|
||||
<text x="66" y="949" class="section" text-anchor="start" >ONE POOL, EVERY STAGE AT ONCE (ILLUSTRATIVE SCHEDULE)</text>
|
||||
<text x="130" y="989" class="body" text-anchor="end" >Worker 1</text>
|
||||
<rect x="150" y="968" width="122" height="30" rx="6" fill="#dbe9fb" stroke="#2a64b8" stroke-width="1.6"/>
|
||||
<text x="211.0" y="988.0" class="chip" text-anchor="middle" style="fill:#2a64b8">S0</text>
|
||||
<rect x="278" y="968" width="122" height="30" rx="6" fill="#dbe9fb" stroke="#2a64b8" stroke-width="1.6"/>
|
||||
<text x="339.0" y="988.0" class="chip" text-anchor="middle" style="fill:#2a64b8">S0</text>
|
||||
<rect x="406" y="968" width="186" height="30" rx="6" fill="#fde4d6" stroke="#b9501c" stroke-width="1.6"/>
|
||||
<text x="499.0" y="988.0" class="chip" text-anchor="middle" style="fill:#b9501c">S1</text>
|
||||
<rect x="598" y="968" width="58" height="30" rx="6" fill="#d6f1e6" stroke="#137a58" stroke-width="1.6"/>
|
||||
<text x="627.0" y="988.0" class="chip" text-anchor="middle" style="fill:#137a58">S2</text>
|
||||
<rect x="662" y="968" width="58" height="30" rx="6" fill="#d6f1e6" stroke="#137a58" stroke-width="1.6"/>
|
||||
<text x="691.0" y="988.0" class="chip" text-anchor="middle" style="fill:#137a58">S2</text>
|
||||
<rect x="726" y="968" width="122" height="30" rx="6" fill="#dbe9fb" stroke="#2a64b8" stroke-width="1.6"/>
|
||||
<text x="787.0" y="988.0" class="chip" text-anchor="middle" style="fill:#2a64b8">S0</text>
|
||||
<rect x="854" y="968" width="58" height="30" rx="6" fill="#d6f1e6" stroke="#137a58" stroke-width="1.6"/>
|
||||
<text x="883.0" y="988.0" class="chip" text-anchor="middle" style="fill:#137a58">S2</text>
|
||||
<text x="130" y="1029" class="body" text-anchor="end" >Worker 2</text>
|
||||
<rect x="150" y="1008" width="122" height="30" rx="6" fill="#dbe9fb" stroke="#2a64b8" stroke-width="1.6"/>
|
||||
<text x="211.0" y="1028.0" class="chip" text-anchor="middle" style="fill:#2a64b8">S0</text>
|
||||
<rect x="278" y="1008" width="186" height="30" rx="6" fill="#fde4d6" stroke="#b9501c" stroke-width="1.6"/>
|
||||
<text x="371.0" y="1028.0" class="chip" text-anchor="middle" style="fill:#b9501c">S1</text>
|
||||
<rect x="470" y="1008" width="58" height="30" rx="6" fill="#d6f1e6" stroke="#137a58" stroke-width="1.6"/>
|
||||
<text x="499.0" y="1028.0" class="chip" text-anchor="middle" style="fill:#137a58">S2</text>
|
||||
<rect x="534" y="1008" width="122" height="30" rx="6" fill="#dbe9fb" stroke="#2a64b8" stroke-width="1.6"/>
|
||||
<text x="595.0" y="1028.0" class="chip" text-anchor="middle" style="fill:#2a64b8">S0</text>
|
||||
<rect x="662" y="1008" width="186" height="30" rx="6" fill="#fde4d6" stroke="#b9501c" stroke-width="1.6"/>
|
||||
<text x="755.0" y="1028.0" class="chip" text-anchor="middle" style="fill:#b9501c">S1</text>
|
||||
<rect x="854" y="1008" width="58" height="30" rx="6" fill="#d6f1e6" stroke="#137a58" stroke-width="1.6"/>
|
||||
<text x="883.0" y="1028.0" class="chip" text-anchor="middle" style="fill:#137a58">S2</text>
|
||||
<text x="130" y="1069" class="body" text-anchor="end" >Worker 3</text>
|
||||
<rect x="150" y="1048" width="122" height="30" rx="6" fill="#dbe9fb" stroke="#2a64b8" stroke-width="1.6"/>
|
||||
<text x="211.0" y="1068.0" class="chip" text-anchor="middle" style="fill:#2a64b8">S0</text>
|
||||
<rect x="278" y="1048" width="58" height="30" rx="6" fill="#d6f1e6" stroke="#137a58" stroke-width="1.6"/>
|
||||
<text x="307.0" y="1068.0" class="chip" text-anchor="middle" style="fill:#137a58">S2</text>
|
||||
<rect x="342" y="1048" width="186" height="30" rx="6" fill="#fde4d6" stroke="#b9501c" stroke-width="1.6"/>
|
||||
<text x="435.0" y="1068.0" class="chip" text-anchor="middle" style="fill:#b9501c">S1</text>
|
||||
<rect x="534" y="1048" width="58" height="30" rx="6" fill="#d6f1e6" stroke="#137a58" stroke-width="1.6"/>
|
||||
<text x="563.0" y="1068.0" class="chip" text-anchor="middle" style="fill:#137a58">S2</text>
|
||||
<rect x="598" y="1048" width="58" height="30" rx="6" fill="#d6f1e6" stroke="#137a58" stroke-width="1.6"/>
|
||||
<text x="627.0" y="1068.0" class="chip" text-anchor="middle" style="fill:#137a58">S2</text>
|
||||
<rect x="662" y="1048" width="122" height="30" rx="6" fill="#dbe9fb" stroke="#2a64b8" stroke-width="1.6"/>
|
||||
<text x="723.0" y="1068.0" class="chip" text-anchor="middle" style="fill:#2a64b8">S0</text>
|
||||
<rect x="790" y="1048" width="58" height="30" rx="6" fill="#d6f1e6" stroke="#137a58" stroke-width="1.6"/>
|
||||
<text x="819.0" y="1068.0" class="chip" text-anchor="middle" style="fill:#137a58">S2</text>
|
||||
<text x="130" y="1109" class="body" text-anchor="end" >Worker 4</text>
|
||||
<rect x="150" y="1088" width="122" height="30" rx="6" fill="#dbe9fb" stroke="#2a64b8" stroke-width="1.6"/>
|
||||
<text x="211.0" y="1108.0" class="chip" text-anchor="middle" style="fill:#2a64b8">S0</text>
|
||||
<rect x="278" y="1088" width="122" height="30" rx="6" fill="#dbe9fb" stroke="#2a64b8" stroke-width="1.6"/>
|
||||
<text x="339.0" y="1108.0" class="chip" text-anchor="middle" style="fill:#2a64b8">S0</text>
|
||||
<rect x="406" y="1088" width="58" height="30" rx="6" fill="#d6f1e6" stroke="#137a58" stroke-width="1.6"/>
|
||||
<text x="435.0" y="1108.0" class="chip" text-anchor="middle" style="fill:#137a58">S2</text>
|
||||
<rect x="470" y="1088" width="58" height="30" rx="6" fill="#d6f1e6" stroke="#137a58" stroke-width="1.6"/>
|
||||
<text x="499.0" y="1108.0" class="chip" text-anchor="middle" style="fill:#137a58">S2</text>
|
||||
<rect x="534" y="1088" width="186" height="30" rx="6" fill="#fde4d6" stroke="#b9501c" stroke-width="1.6"/>
|
||||
<text x="627.0" y="1108.0" class="chip" text-anchor="middle" style="fill:#b9501c">S1</text>
|
||||
<rect x="726" y="1088" width="58" height="30" rx="6" fill="#d6f1e6" stroke="#137a58" stroke-width="1.6"/>
|
||||
<text x="755.0" y="1108.0" class="chip" text-anchor="middle" style="fill:#137a58">S2</text>
|
||||
<rect x="790" y="1088" width="58" height="30" rx="6" fill="#d6f1e6" stroke="#137a58" stroke-width="1.6"/>
|
||||
<text x="819.0" y="1108.0" class="chip" text-anchor="middle" style="fill:#137a58">S2</text>
|
||||
<path d="M150 1138H960" class="line" marker-end="url(#a)"/>
|
||||
<text x="960" y="1158" class="small" text-anchor="end" >time</text>
|
||||
<text x="150" y="1168" class="small" text-anchor="start" >Items overtake each other: output order is not guaranteed.</text>
|
||||
<rect x="1020" y="917" width="540" height="268" rx="16" class="panel" />
|
||||
<text x="1046" y="949" class="section" text-anchor="start" >WHY DOWNSTREAM FIRST?</text>
|
||||
<text x="1046" y="982" class="body" text-anchor="start" style="font-weight:700;fill:#8a5a12">If new items came first</text>
|
||||
<text x="1046" y="1013" class="small" text-anchor="start" >in progress</text>
|
||||
<rect x="1130" y="995" width="18" height="26" rx="6" fill="#dbe9fb" stroke="#2a64b8" stroke-width="1.6"/>
|
||||
<text x="1139.0" y="1013.0" class="chip" text-anchor="middle" style="fill:#2a64b8"> </text>
|
||||
<rect x="1152" y="995" width="18" height="26" rx="6" fill="#dbe9fb" stroke="#2a64b8" stroke-width="1.6"/>
|
||||
<text x="1161.0" y="1013.0" class="chip" text-anchor="middle" style="fill:#2a64b8"> </text>
|
||||
<rect x="1174" y="995" width="18" height="26" rx="6" fill="#fde4d6" stroke="#b9501c" stroke-width="1.6"/>
|
||||
<text x="1183.0" y="1013.0" class="chip" text-anchor="middle" style="fill:#b9501c"> </text>
|
||||
<rect x="1196" y="995" width="18" height="26" rx="6" fill="#fde4d6" stroke="#b9501c" stroke-width="1.6"/>
|
||||
<text x="1205.0" y="1013.0" class="chip" text-anchor="middle" style="fill:#b9501c"> </text>
|
||||
<rect x="1218" y="995" width="18" height="26" rx="6" fill="#fde4d6" stroke="#b9501c" stroke-width="1.6"/>
|
||||
<text x="1227.0" y="1013.0" class="chip" text-anchor="middle" style="fill:#b9501c"> </text>
|
||||
<rect x="1240" y="995" width="18" height="26" rx="6" fill="#fde4d6" stroke="#b9501c" stroke-width="1.6"/>
|
||||
<text x="1249.0" y="1013.0" class="chip" text-anchor="middle" style="fill:#b9501c"> </text>
|
||||
<rect x="1262" y="995" width="18" height="26" rx="6" fill="#fde4d6" stroke="#b9501c" stroke-width="1.6"/>
|
||||
<text x="1271.0" y="1013.0" class="chip" text-anchor="middle" style="fill:#b9501c"> </text>
|
||||
<rect x="1284" y="995" width="18" height="26" rx="6" fill="#fde4d6" stroke="#b9501c" stroke-width="1.6"/>
|
||||
<text x="1293.0" y="1013.0" class="chip" text-anchor="middle" style="fill:#b9501c"> </text>
|
||||
<rect x="1306" y="995" width="18" height="26" rx="6" fill="#fde4d6" stroke="#b9501c" stroke-width="1.6"/>
|
||||
<text x="1315.0" y="1013.0" class="chip" text-anchor="middle" style="fill:#b9501c"> </text>
|
||||
<rect x="1328" y="995" width="18" height="26" rx="6" fill="#fde4d6" stroke="#b9501c" stroke-width="1.6"/>
|
||||
<text x="1337.0" y="1013.0" class="chip" text-anchor="middle" style="fill:#b9501c"> </text>
|
||||
<rect x="1350" y="995" width="18" height="26" rx="6" fill="#fde4d6" stroke="#b9501c" stroke-width="1.6"/>
|
||||
<text x="1359.0" y="1013.0" class="chip" text-anchor="middle" style="fill:#b9501c"> </text>
|
||||
<text x="1420" y="1013" class="small" text-anchor="end" >results</text>
|
||||
<text x="1046" y="1042" class="small" text-anchor="start" >work piles up inside the pipeline, nothing comes out yet</text>
|
||||
<text x="1046" y="1070" class="body" text-anchor="start" style="font-weight:700;fill:#137a58">Downstream first (what obipipeline does)</text>
|
||||
<text x="1046" y="1101" class="small" text-anchor="start" >in progress</text>
|
||||
<rect x="1130" y="1083" width="18" height="26" rx="6" fill="#dbe9fb" stroke="#2a64b8" stroke-width="1.6"/>
|
||||
<text x="1139.0" y="1101.0" class="chip" text-anchor="middle" style="fill:#2a64b8"> </text>
|
||||
<rect x="1152" y="1083" width="18" height="26" rx="6" fill="#fde4d6" stroke="#b9501c" stroke-width="1.6"/>
|
||||
<text x="1161.0" y="1101.0" class="chip" text-anchor="middle" style="fill:#b9501c"> </text>
|
||||
<rect x="1174" y="1083" width="18" height="26" rx="6" fill="#d6f1e6" stroke="#137a58" stroke-width="1.6"/>
|
||||
<text x="1183.0" y="1101.0" class="chip" text-anchor="middle" style="fill:#137a58"> </text>
|
||||
<text x="1420" y="1101" class="small" text-anchor="end" >results</text>
|
||||
<rect x="1430" y="1087" width="14" height="18" rx="3" fill="#52647e"/>
|
||||
<rect x="1448" y="1087" width="14" height="18" rx="3" fill="#52647e"/>
|
||||
<rect x="1466" y="1087" width="14" height="18" rx="3" fill="#52647e"/>
|
||||
<rect x="1484" y="1087" width="14" height="18" rx="3" fill="#52647e"/>
|
||||
<rect x="1502" y="1087" width="14" height="18" rx="3" fill="#52647e"/>
|
||||
<rect x="1520" y="1087" width="14" height="18" rx="3" fill="#52647e"/>
|
||||
<text x="1046" y="1130" class="small" text-anchor="start" >results come out early and the pipeline stays unclogged</text>
|
||||
<text x="1046" y="1166" class="body" text-anchor="start" >Buffers have a fixed size: when full, upstream waits.</text>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 21 KiB |
+25
-6
@@ -1,6 +1,31 @@
|
||||
//! 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.
|
||||
//! - [`Pipeline`] / [`WorkerPool`] is the lower-level runtime (source, stages, sink), built with
|
||||
//! `make_pipeline!`.
|
||||
//! - [`throttle()`] / [`Throttle`] bound the number of items in flight.
|
||||
//!
|
||||
//! Items travel through one user-defined enum; each stage names the variant it reads and the one it
|
||||
//! writes. The output order is **not** guaranteed. Errors are fail-fast: the first one (a fallible stage,
|
||||
//! a runtime type mismatch, a panic in a worker) stops the pipeline and is returned, never printed: as the
|
||||
//! last item of the [`PipeIter`] (`Item = Result<Out, PipelineError>`), 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.
|
||||
//!
|
||||
//! 
|
||||
|
||||
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;
|
||||
@@ -16,12 +41,6 @@ pub use throttle::ThrottleGuard;
|
||||
pub use throttle::Throttled;
|
||||
pub use throttle::throttle;
|
||||
|
||||
/// 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]
|
||||
+62
-3
@@ -6,8 +6,6 @@ use std::fmt;
|
||||
pub enum PipelineError {
|
||||
/// A stage received a `PipelineData` variant it did not expect.
|
||||
TypeMismatch,
|
||||
/// The step kind is not compatible with the data type.
|
||||
StepKindMismatch(&'static str),
|
||||
/// The source has no more data to produce.
|
||||
EndOfStream,
|
||||
/// An error occurred inside a stage (e.g., I/O, parsing, custom logic).
|
||||
@@ -18,13 +16,61 @@ impl fmt::Display for PipelineError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
PipelineError::TypeMismatch => write!(f, "data type mismatch in pipeline stage"),
|
||||
PipelineError::StepKindMismatch(s) => write!(f, "step kind mismatch: {}", s),
|
||||
PipelineError::EndOfStream => write!(f, "end of input stream"),
|
||||
PipelineError::StepError(e) => write!(f, "stage error: {}", e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Error 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 struct NeverFails(());
|
||||
|
||||
impl fmt::Display for NeverFails {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"a stage declared infallible reported an error (this cannot happen)"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl Error for NeverFails {}
|
||||
|
||||
/// 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<dyn std::any::Any + Send>,
|
||||
) -> PipelineError {
|
||||
let message = payload
|
||||
.downcast_ref::<&str>()
|
||||
.map(|s| (*s).to_string())
|
||||
.or_else(|| payload.downcast_ref::<String>().cloned())
|
||||
.unwrap_or_else(|| "non-string panic payload".to_string());
|
||||
PipelineError::StepError(Box::new(Panicked { who, message }))
|
||||
}
|
||||
|
||||
impl Error for PipelineError {
|
||||
fn source(&self) -> Option<&(dyn Error + 'static)> {
|
||||
match self {
|
||||
@@ -33,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());
|
||||
}
|
||||
}
|
||||
+143
-116
@@ -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<dyn FnMut() -> ::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<T, E>`.
|
||||
@@ -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<U, E>`.
|
||||
@@ -77,96 +81,70 @@ macro_rules! make_transform_fallible {
|
||||
|
||||
/// Creates a `Stage::Flat` from a function `Fn(T) -> impl IntoIterator<Item = U>`.
|
||||
///
|
||||
/// 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<isize>| {
|
||||
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(0).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<impl IntoIterator<Item = U>, 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<isize>| {
|
||||
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();
|
||||
delta.send(0).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(0).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<dyn Fn($enum) -> ::std::result::Result<(), $crate::PipelineError> + Send>
|
||||
}};
|
||||
}),
|
||||
$input
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
/// Creates a `SinkFn` from a fallible function that returns `Result<(), E>`.
|
||||
@@ -190,7 +168,7 @@ macro_rules! make_sink_fallible {
|
||||
/// Builds a `Pipeline` from a source, a list of stages and a sink.
|
||||
///
|
||||
/// Syntax:
|
||||
/// ```ignore
|
||||
/// ```text
|
||||
/// make_pipeline! {
|
||||
/// MyData,
|
||||
/// source my_iter => Variant, // infallible source
|
||||
@@ -203,6 +181,35 @@ macro_rules! make_sink_fallible {
|
||||
/// sink? my_func @ Variant, // fallible sink
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// Each function is a name or a parenthesised closure. Run the result with `WorkerPool::run`.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use obipipeline::{WorkerPool, make_pipeline};
|
||||
/// use std::sync::mpsc;
|
||||
///
|
||||
/// enum D {
|
||||
/// Num(u64),
|
||||
/// }
|
||||
/// fn double(x: u64) -> u64 {
|
||||
/// x * 2
|
||||
/// }
|
||||
///
|
||||
/// let (tx, rx) = mpsc::channel();
|
||||
/// let collect = move |x: u64| tx.send(x).unwrap();
|
||||
/// let pipeline = make_pipeline! {
|
||||
/// D,
|
||||
/// source 1..=3u64 => Num,
|
||||
/// | double : Num => Num,
|
||||
/// sink collect @ Num,
|
||||
/// };
|
||||
/// WorkerPool::new(pipeline, 2, 4).run().unwrap();
|
||||
/// let mut got: Vec<u64> = rx.try_iter().collect();
|
||||
/// got.sort();
|
||||
/// assert_eq!(got, [2, 4, 6]);
|
||||
/// ```
|
||||
#[macro_export]
|
||||
macro_rules! make_pipeline {
|
||||
// ── Entry points ─────────────────────────────────────────────────────
|
||||
@@ -277,7 +284,7 @@ macro_rules! make_pipeline {
|
||||
/// Builds a typed `Pipe<D, In, Out>` — sourceless and sinkless.
|
||||
///
|
||||
/// Syntax:
|
||||
/// ```ignore
|
||||
/// ```text
|
||||
/// make_pipe! {
|
||||
/// MyData : InType => OutType,
|
||||
/// | func : InVariant => OutVariant, // transform 1→1
|
||||
@@ -286,31 +293,48 @@ macro_rules! make_pipeline {
|
||||
/// ||? func : InVariant => OutVariant, // flat transform 1→N fallible
|
||||
/// }
|
||||
/// ```
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use obipipeline::make_pipe;
|
||||
///
|
||||
/// #[allow(dead_code)]
|
||||
/// enum D {
|
||||
/// Num(u64),
|
||||
/// Text(String),
|
||||
/// }
|
||||
/// fn double(x: u64) -> u64 {
|
||||
/// x * 2
|
||||
/// }
|
||||
/// fn show(x: u64) -> String {
|
||||
/// x.to_string()
|
||||
/// }
|
||||
///
|
||||
/// let pipe = make_pipe! {
|
||||
/// D : u64 => String,
|
||||
/// | double : Num => Num,
|
||||
/// | show : Num => Text,
|
||||
/// };
|
||||
/// let mut out: Vec<String> = pipe.apply(1..=3u64, 2, 4).collect::<Result<_, _>>().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 `<op> <function> : <InVariant> => <OutVariant>`: 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: | ──────────────────────────────────────────────────
|
||||
@@ -349,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!") }
|
||||
}),
|
||||
|
||||
@@ -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};
|
||||
+50
-11
@@ -60,7 +60,21 @@ where
|
||||
In: Send + 'static,
|
||||
Out: Send + 'static,
|
||||
{
|
||||
/// Run the pipeline in a background thread; returns an iterator over the output.
|
||||
/// Runs the pipeline in a background thread; returns an iterator over the output.
|
||||
///
|
||||
/// `n_workers` threads run the stages in parallel; `capacity` bounds the 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 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
|
||||
///
|
||||
/// Panics if `n_workers` or `capacity` is `0` (see [`WorkerPool::new`]).
|
||||
pub fn apply(
|
||||
self,
|
||||
input: impl Iterator<Item = In> + Send + 'static,
|
||||
@@ -87,11 +101,13 @@ where
|
||||
});
|
||||
|
||||
let pipeline = Pipeline::new(source, self.stages, sink);
|
||||
let handle = thread::spawn(move || {
|
||||
WorkerPool::new(pipeline, n_workers, capacity).run();
|
||||
});
|
||||
let pool = WorkerPool::new(pipeline, n_workers, capacity);
|
||||
let 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),
|
||||
}
|
||||
@@ -100,26 +116,49 @@ where
|
||||
|
||||
// ── PipeIter ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/// Iterator over the output of `Pipe::apply()`.
|
||||
/// Iterator over the output of [`Pipe::apply`].
|
||||
///
|
||||
/// 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<Out> {
|
||||
rx: Option<Receiver<Out>>,
|
||||
handle: Option<thread::JoinHandle<()>>,
|
||||
handle: Option<thread::JoinHandle<Result<(), PipelineError>>>,
|
||||
/// Stops the scheduler (the data type of the pipeline is erased here).
|
||||
cancel: Box<dyn Fn() + Send + Sync>,
|
||||
}
|
||||
|
||||
impl<Out> Iterator for PipeIter<Out> {
|
||||
type Item = Out;
|
||||
type Item = Result<Out, PipelineError>;
|
||||
|
||||
fn next(&mut self) -> Option<Out> {
|
||||
self.rx.as_ref()?.recv().ok()
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
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<Out> Drop for PipeIter<Out> {
|
||||
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() {
|
||||
// Early drop: the caller gave up on the output, so how the pipeline ended is not wanted.
|
||||
(self.cancel)();
|
||||
let _ = h.join();
|
||||
}
|
||||
}
|
||||
|
||||
+92
-157
@@ -1,11 +1,15 @@
|
||||
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 ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/// A complete pipeline description: a source, the ordered stages and a sink, all over one data type.
|
||||
///
|
||||
/// Build it with the `make_pipeline!` macro and run it with [`WorkerPool`].
|
||||
pub struct Pipeline<DATA> {
|
||||
source: SourceFn<DATA>,
|
||||
stages: Vec<Stage<DATA>>,
|
||||
@@ -13,6 +17,7 @@ pub struct Pipeline<DATA> {
|
||||
}
|
||||
|
||||
impl<DATA> Pipeline<DATA> {
|
||||
/// Assembles a pipeline from its parts. Prefer the `make_pipeline!` macro.
|
||||
pub fn new(source: SourceFn<DATA>, stages: Vec<Stage<DATA>>, sink: SinkFn<DATA>) -> Self {
|
||||
Self {
|
||||
source,
|
||||
@@ -24,9 +29,14 @@ impl<DATA> Pipeline<DATA> {
|
||||
|
||||
// ── WorkerPool ────────────────────────────────────────────────────────────────
|
||||
|
||||
/// Runs a [`Pipeline`] on a pool of worker threads.
|
||||
///
|
||||
/// 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<DATA> {
|
||||
pipeline: Pipeline<DATA>,
|
||||
handles: Vec<std::thread::JoinHandle<()>>,
|
||||
n_workers: usize,
|
||||
capacity: usize,
|
||||
}
|
||||
@@ -35,174 +45,99 @@ impl<DATA> WorkerPool<DATA>
|
||||
where
|
||||
DATA: Send + Sync + 'static,
|
||||
{
|
||||
/// Creates a pool for `pipeline`.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if `n_workers` is `0` (no item would ever be processed) or if `capacity` is `0` (no item
|
||||
/// could ever be queued).
|
||||
pub fn new(pipeline: Pipeline<DATA>, 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,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run(mut self) {
|
||||
let n = self.pipeline.stages.len();
|
||||
/// 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
|
||||
/// pipeline, discards the items still in flight and is returned. Nothing is printed.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns the first [`PipelineError`] met, `Ok(())` if the source was exhausted and every item
|
||||
/// reached the sink.
|
||||
pub fn run(self) -> Result<(), PipelineError> {
|
||||
self.start().wait()
|
||||
}
|
||||
|
||||
// ── Inter-stage channels ───────────────────────────────────────────
|
||||
// stage_txs[i] / stage_rxs[i]: output of stage i
|
||||
let mut stage_txs: Vec<Sender<Result<DATA, PipelineError>>> = Vec::new();
|
||||
let mut stage_rxs: Vec<Receiver<Result<DATA, PipelineError>>> = 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::<isize>(self.capacity);
|
||||
|
||||
// ── Worker pool ────────────────────────────────────────────────────
|
||||
let (worker_tx, worker_rx): (Sender<WorkerTask<DATA>>, Receiver<WorkerTask<DATA>>) =
|
||||
bounded(self.capacity);
|
||||
/// Spawns the threads of the pipeline.
|
||||
pub(super) fn start(self) -> Running<DATA> {
|
||||
let Pipeline {
|
||||
source,
|
||||
stages,
|
||||
sink,
|
||||
} = self.pipeline;
|
||||
let shared = Arc::new(Shared::new(stages.len(), self.capacity));
|
||||
let stages: Arc<[Stage<DATA>]> = 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 ────────────────────────────────────────
|
||||
match oper.recv(&sink_err_rx) {
|
||||
Ok(e) => {
|
||||
eprintln!("Sink error: {:?}", e);
|
||||
break;
|
||||
}
|
||||
Err(_) => 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)) => eprintln!("Source error: {:?}", e),
|
||||
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)) => eprintln!("Stage {} error: {:?}", stage, e),
|
||||
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,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Running ───────────────────────────────────────────────────────────────────
|
||||
|
||||
/// A started pipeline.
|
||||
pub(super) struct Running<DATA> {
|
||||
pub(super) shared: Arc<Shared<DATA>>,
|
||||
source: thread::JoinHandle<()>,
|
||||
/// Sink and workers.
|
||||
handles: Vec<thread::JoinHandle<()>>,
|
||||
}
|
||||
|
||||
impl<DATA> Running<DATA> {
|
||||
/// 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 {
|
||||
let _ = h.join();
|
||||
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(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
+260
-98
@@ -1,118 +1,280 @@
|
||||
use crossbeam_channel::{Receiver, Sender, bounded};
|
||||
use std::thread;
|
||||
//! Thread bodies (source, workers, sink) and the state they share.
|
||||
|
||||
use super::error::PipelineError;
|
||||
use super::types::{SinkFn, SourceFn, Stage, WorkerTask};
|
||||
use std::panic::{AssertUnwindSafe, catch_unwind};
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::{Condvar, Mutex, MutexGuard, PoisonError, TryLockError};
|
||||
|
||||
// ── Thread runners ────────────────────────────────────────────────────────────
|
||||
use super::error::{PipelineError, panic_error};
|
||||
use super::state::{Job, Outcome, State};
|
||||
use super::types::{SinkFn, SourceFn, Stage};
|
||||
|
||||
pub(super) fn source_runner<DATA>(
|
||||
mut source: SourceFn<DATA>,
|
||||
capacity: usize,
|
||||
) -> (
|
||||
Receiver<Result<DATA, PipelineError>>,
|
||||
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) => {
|
||||
eprintln!("Source error: {:?}", e);
|
||||
let _ = tx.send(Err(e));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
(rx, handle)
|
||||
// ── Shared state ──────────────────────────────────────────────────────────────
|
||||
|
||||
/// 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<DATA>(
|
||||
task_rx: Receiver<WorkerTask<DATA>>,
|
||||
stages: Vec<Stage<DATA>>,
|
||||
stage_txs: Vec<Sender<Result<DATA, PipelineError>>>,
|
||||
flat_delta_tx: Sender<isize>,
|
||||
) -> 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] {
|
||||
let _ = stage_txs[idx].send(f(data));
|
||||
}
|
||||
}
|
||||
WorkerTask::Flat(data, idx) => {
|
||||
if let Stage::Flat(f) = &stages[idx] {
|
||||
f(data, &stage_txs[idx], &flat_delta_tx);
|
||||
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<D> {
|
||||
state: Mutex<State<D>>,
|
||||
/// 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<D> Shared<D> {
|
||||
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<D>> {
|
||||
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<PipelineError> {
|
||||
self.lock().error.take()
|
||||
}
|
||||
}
|
||||
|
||||
/// Spawns the sink thread.
|
||||
pub(super) fn sink_runner<DATA>(
|
||||
sink: SinkFn<DATA>,
|
||||
capacity: usize,
|
||||
) -> (
|
||||
Sender<DATA>,
|
||||
Receiver<PipelineError>,
|
||||
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<D>);
|
||||
|
||||
impl<D> 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<D>(shared: &Shared<D>, mut source: SourceFn<D>) {
|
||||
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: DATA,
|
||||
stage_idx: usize,
|
||||
stages: &[Stage<DATA>],
|
||||
worker_tx: &Sender<WorkerTask<DATA>>,
|
||||
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<D>(stages: &[Stage<D>], job: Job<D>) -> Result<Outcome<D>, 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<D>(shared: &Shared<D>, stages: &[Stage<D>]) {
|
||||
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<D>(shared: &Shared<D>, sink: SinkFn<D>) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<D> {
|
||||
/// 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<D>),
|
||||
}
|
||||
|
||||
/// What a [`Job`] gave.
|
||||
pub(super) enum Outcome<D> {
|
||||
/// An item for the next queue, and the expansion to resume later if there is one.
|
||||
Item(usize, D, Option<FlatOutput<D>>),
|
||||
/// 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<D> {
|
||||
items: Vec<VecDeque<D>>,
|
||||
expansions: Vec<VecDeque<FlatOutput<D>>>,
|
||||
}
|
||||
|
||||
pub(super) struct State<D> {
|
||||
pub(super) queues: Vec<VecDeque<D>>,
|
||||
/// Slots of each queue promised to running jobs.
|
||||
reserved: Vec<usize>,
|
||||
/// Started expansions of each stage, waiting to be resumed.
|
||||
parked: Vec<VecDeque<FlatOutput<D>>>,
|
||||
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<PipelineError>,
|
||||
capacity: usize,
|
||||
}
|
||||
|
||||
impl<D> State<D> {
|
||||
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<usize> {
|
||||
(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<D>]) -> Option<(usize, Job<D>)> {
|
||||
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<D>) -> Option<Outcome<D>> {
|
||||
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<D> {
|
||||
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<D> {
|
||||
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<u32> {
|
||||
Stage::Transform(Arc::new(Ok))
|
||||
}
|
||||
|
||||
fn flat() -> Stage<u32> {
|
||||
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<u32> = 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"
|
||||
);
|
||||
}
|
||||
}
|
||||
+9
-15
@@ -1,4 +1,3 @@
|
||||
use crossbeam_channel::Sender;
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::error::PipelineError;
|
||||
@@ -15,20 +14,22 @@ pub type SinkFn<D> = Box<dyn Fn(D) -> Result<(), PipelineError> + Send>;
|
||||
/// Transform function shared between workers through an `Arc`.
|
||||
pub type SharedFn<D> = Arc<dyn Fn(D) -> Result<D, PipelineError> + 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<D> =
|
||||
Arc<dyn Fn(D, &Sender<Result<D, PipelineError>>, &Sender<isize>) + 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<D> = Box<dyn Iterator<Item = Result<D, PipelineError>> + Send>;
|
||||
|
||||
/// 1→N transform function (flat map) shared between workers through an `Arc`.
|
||||
pub type SharedFlatFn<D> = Arc<dyn Fn(D) -> FlatOutput<D> + Send + Sync>;
|
||||
|
||||
// ── Stage enum ────────────────────────────────────────────────────────────────
|
||||
|
||||
/// A pipeline stage: plain transform (1→1) or flat transform (1→N).
|
||||
pub enum Stage<D> {
|
||||
/// 1→1 transform.
|
||||
Transform(SharedFn<D>),
|
||||
/// 1→N flat transform.
|
||||
Flat(SharedFlatFn<D>),
|
||||
}
|
||||
|
||||
@@ -40,10 +41,3 @@ impl<D> Clone for Stage<D> {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Worker task ───────────────────────────────────────────────────────────────
|
||||
|
||||
pub(super) enum WorkerTask<D> {
|
||||
Transform(D, usize),
|
||||
Flat(D, usize),
|
||||
}
|
||||
+49
-16
@@ -1,13 +1,14 @@
|
||||
use std::sync::{Arc, Condvar, Mutex};
|
||||
//! Counting semaphore and an iterator adaptor that bounds the number of items in flight.
|
||||
|
||||
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
|
||||
|
||||
// ── Throttle ──────────────────────────────────────────────────────────────────
|
||||
|
||||
/// 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<usize>,
|
||||
@@ -16,7 +17,13 @@ pub struct Throttle {
|
||||
}
|
||||
|
||||
impl Throttle {
|
||||
/// Creates a semaphore with `max` slots.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if `max` is `0`: no slot could ever be acquired.
|
||||
pub fn new(max: usize) -> Self {
|
||||
assert!(max > 0, "Throttle needs at least one slot");
|
||||
Self {
|
||||
count: Mutex::new(0),
|
||||
condvar: Condvar::new(),
|
||||
@@ -24,16 +31,28 @@ impl Throttle {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn acquire(&self) {
|
||||
let mut count = self.count.lock().unwrap();
|
||||
/// Locks the counter. The counter stays consistent even if another thread panicked while holding the
|
||||
/// lock (the critical sections only add or subtract one), so a poisoned mutex is recovered, not
|
||||
/// propagated: this runs in `Drop`, where a second panic would abort the process.
|
||||
fn lock(&self) -> MutexGuard<'_, usize> {
|
||||
self.count.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// Takes one slot, waiting until one is free. Pair it with `release`: use
|
||||
/// [`Throttle::acquire_guard`], which does it on drop.
|
||||
pub(crate) fn acquire(&self) {
|
||||
let mut count = self.lock();
|
||||
while *count >= self.max {
|
||||
count = self.condvar.wait(count).unwrap();
|
||||
count = self
|
||||
.condvar
|
||||
.wait(count)
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
}
|
||||
*count += 1;
|
||||
}
|
||||
|
||||
fn release(&self) {
|
||||
let mut count = self.count.lock().unwrap();
|
||||
let mut count = self.lock();
|
||||
*count -= 1;
|
||||
self.condvar.notify_one();
|
||||
}
|
||||
@@ -67,28 +86,42 @@ 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<T> {
|
||||
/// The wrapped item.
|
||||
pub item: T,
|
||||
/// Holds one throttle slot until dropped.
|
||||
pub guard: ThrottleGuard,
|
||||
}
|
||||
|
||||
// ── throttle() ────────────────────────────────────────────────────────────────
|
||||
|
||||
/// Wrap `source` so that at most `max_concurrent` items are emitted before
|
||||
/// Wraps `source` so that at most `max_concurrent` items are emitted before
|
||||
/// earlier ones have been fully processed (i.e. their `ThrottleGuard` dropped).
|
||||
///
|
||||
/// Acquisition blocks the source thread until a slot is available. This must
|
||||
/// be called in the source thread, never inside a pipeline worker.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if `max_concurrent` is `0`.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```ignore
|
||||
/// let throttled = obipipeline::throttle(file_paths, n_workers - 1);
|
||||
/// // Use `throttled` as the pipeline source; carry `item.guard` through the
|
||||
/// // Flat stage and let it drop when the file is fully read.
|
||||
/// ```
|
||||
/// let paths = vec!["a.fa", "b.fa", "c.fa"];
|
||||
/// // At most 2 items are in flight: the third one is emitted once a guard is dropped.
|
||||
/// let mut throttled = obipipeline::throttle(paths.into_iter(), 2);
|
||||
/// let first = throttled.next().unwrap();
|
||||
/// let second = throttled.next().unwrap();
|
||||
/// drop(first.guard); // releases a slot
|
||||
/// let third = throttled.next().unwrap();
|
||||
/// assert_eq!(
|
||||
/// (first.item, second.item, third.item),
|
||||
/// ("a.fa", "b.fa", "c.fa")
|
||||
/// );
|
||||
/// ```
|
||||
pub fn throttle<I>(source: I, max_concurrent: usize) -> impl Iterator<Item = Throttled<I::Item>>
|
||||
where
|
||||
|
||||
+474
@@ -0,0 +1,474 @@
|
||||
//! Error semantics: the first error stops the pipeline and is yielded as the last item of the `PipeIter`
|
||||
//! (or returned by `WorkerPool::run`); no failure may hang. Every test runs under a timeout guard.
|
||||
|
||||
use obipipeline::{
|
||||
Pipeline, PipelineError, Throttle, WorkerPool, make_pipe, make_pipeline, throttle,
|
||||
};
|
||||
use std::io::{Error, ErrorKind};
|
||||
use std::sync::mpsc;
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
// The `Text` payload is only built, never read back: it exists to trigger a runtime mismatch.
|
||||
#[allow(dead_code)]
|
||||
enum D {
|
||||
Num(u64),
|
||||
Text(String),
|
||||
}
|
||||
|
||||
/// Runs `f` on a thread and fails the test if it does not finish in time (a hang is the bug to catch).
|
||||
fn within<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> T {
|
||||
let (tx, rx) = mpsc::channel();
|
||||
thread::spawn(move || {
|
||||
let _ = tx.send(f());
|
||||
});
|
||||
rx.recv_timeout(Duration::from_secs(10))
|
||||
.expect("the pipeline hung")
|
||||
}
|
||||
|
||||
/// Drains an iterator of results: the Ok values, and the error if there is one. Checks the contract that
|
||||
/// an error is yielded at most once and is the last item.
|
||||
fn drain<T>(it: impl Iterator<Item = Result<T, PipelineError>>) -> (Vec<T>, Option<PipelineError>) {
|
||||
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<u64, Error> {
|
||||
if x == 5 {
|
||||
Err(Error::new(ErrorKind::InvalidData, "boom on 5"))
|
||||
} else {
|
||||
Ok(x)
|
||||
}
|
||||
}
|
||||
|
||||
fn flat_fails_on_5(x: u64) -> Result<Vec<u64>, Error> {
|
||||
fails_on_5(x).map(|v| vec![v, v])
|
||||
}
|
||||
|
||||
fn panics_on_3(x: u64) -> u64 {
|
||||
assert!(x != 3, "boom on 3");
|
||||
x
|
||||
}
|
||||
|
||||
fn to_text(x: u64) -> String {
|
||||
x.to_string()
|
||||
}
|
||||
|
||||
fn plus_one(x: u64) -> u64 {
|
||||
x + 1
|
||||
}
|
||||
|
||||
fn identity(x: u64) -> u64 {
|
||||
x
|
||||
}
|
||||
|
||||
fn triple(x: u64) -> Vec<u64> {
|
||||
vec![x, x, x]
|
||||
}
|
||||
|
||||
fn ignore(_x: u64) {}
|
||||
|
||||
fn message(e: &PipelineError) -> String {
|
||||
e.to_string()
|
||||
}
|
||||
|
||||
// ── Pipe / PipeIter ─────────────────────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn fallible_stage_error_is_the_last_item() {
|
||||
let (items, err) = within(|| {
|
||||
let pipe = make_pipe! { D : u64 => u64, |? fails_on_5 : Num => Num, };
|
||||
drain(pipe.apply(1..=10u64, 2, 4))
|
||||
});
|
||||
assert!(items.len() < 10, "the pipeline must stop early");
|
||||
assert!(message(&err.expect("the error must be yielded")).contains("boom on 5"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fallible_flat_stage_error_is_the_last_item() {
|
||||
let (_, err) = within(|| {
|
||||
let pipe = make_pipe! { D : u64 => u64, ||? flat_fails_on_5 : Num => Num, };
|
||||
drain(pipe.apply(1..=10u64, 2, 4))
|
||||
});
|
||||
assert!(message(&err.unwrap()).contains("boom on 5"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runtime_type_mismatch_is_the_last_item() {
|
||||
let (_, err) = within(|| {
|
||||
// The first stage produces a Text, the second one reads a Num.
|
||||
let pipe = make_pipe! {
|
||||
D : u64 => u64,
|
||||
| to_text : Num => Text,
|
||||
| panics_on_3 : Num => Num,
|
||||
};
|
||||
drain(pipe.apply(1..=10u64, 2, 4))
|
||||
});
|
||||
assert!(matches!(err, Some(PipelineError::TypeMismatch)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn type_mismatch_in_every_kind_of_stage() {
|
||||
// Each pipe feeds a Text to a stage that reads a Num.
|
||||
type Case = (
|
||||
&'static str,
|
||||
Box<dyn FnOnce() -> Option<PipelineError> + Send>,
|
||||
);
|
||||
let kinds: Vec<Case> = vec![
|
||||
(
|
||||
"transform",
|
||||
Box::new(|| {
|
||||
let p = make_pipe! { D : u64 => u64, | to_text : Num => Text, | plus_one : Num => Num, };
|
||||
drain(p.apply(1..=3u64, 2, 4)).1
|
||||
}),
|
||||
),
|
||||
(
|
||||
"transform?",
|
||||
Box::new(|| {
|
||||
let p = make_pipe! { D : u64 => u64, | to_text : Num => Text, |? fails_on_5 : Num => Num, };
|
||||
drain(p.apply(1..=3u64, 2, 4)).1
|
||||
}),
|
||||
),
|
||||
(
|
||||
"flat",
|
||||
Box::new(|| {
|
||||
let p =
|
||||
make_pipe! { D : u64 => u64, | to_text : Num => Text, || triple : Num => Num, };
|
||||
drain(p.apply(1..=3u64, 2, 4)).1
|
||||
}),
|
||||
),
|
||||
(
|
||||
"flat?",
|
||||
Box::new(|| {
|
||||
let p = make_pipe! { D : u64 => u64, | to_text : Num => Text, ||? flat_fails_on_5 : Num => Num, };
|
||||
drain(p.apply(1..=3u64, 2, 4)).1
|
||||
}),
|
||||
),
|
||||
];
|
||||
for (name, run) in kinds {
|
||||
let err = within(run);
|
||||
assert!(
|
||||
matches!(err, Some(PipelineError::TypeMismatch)),
|
||||
"{name}: {err:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn worker_panic_is_the_last_item() {
|
||||
let (_, err) = within(|| {
|
||||
let pipe = make_pipe! { D : u64 => u64, | panics_on_3 : Num => Num, };
|
||||
drain(pipe.apply(1..=10u64, 2, 4))
|
||||
});
|
||||
assert!(message(&err.unwrap()).contains("boom on 3"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_error_item_when_everything_went_through() {
|
||||
let (items, err) = within(|| {
|
||||
let pipe = make_pipe! { D : u64 => u64, |? fails_on_5 : Num => Num, };
|
||||
drain(pipe.apply(6..=20u64, 3, 4))
|
||||
});
|
||||
assert_eq!(items.len(), 15);
|
||||
assert!(err.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn capacity_one_works() {
|
||||
let (items, err) = within(|| {
|
||||
let pipe = make_pipe! { D : u64 => u64, |? fails_on_5 : Num => Num, };
|
||||
drain(pipe.apply(6..=205u64, 2, 1))
|
||||
});
|
||||
assert_eq!(items.len(), 200);
|
||||
assert!(err.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "at least one worker")]
|
||||
fn zero_workers_is_rejected() {
|
||||
let pipe = make_pipe! { D : u64 => u64, |? fails_on_5 : Num => Num, };
|
||||
let _ = pipe.apply(0..3u64, 0, 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "capacity of at least 1")]
|
||||
fn zero_capacity_is_rejected() {
|
||||
let pipe = make_pipe! { D : u64 => u64, |? fails_on_5 : Num => Num, };
|
||||
let _ = pipe.apply(0..3u64, 2, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "at least one slot")]
|
||||
fn throttle_new_zero_is_rejected() {
|
||||
let _ = Throttle::new(0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "at least one slot")]
|
||||
fn throttle_zero_is_rejected() {
|
||||
let _ = throttle(0..3u32, 0).count();
|
||||
}
|
||||
|
||||
// ── Pipeline / WorkerPool (the lower-level runtime) ─────────────────────────────
|
||||
|
||||
fn pool_run(pipeline: Pipeline<D>) -> Result<(), PipelineError> {
|
||||
WorkerPool::new(pipeline, 3, 4).run()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pipeline_runs_and_reaches_the_sink() {
|
||||
let (tx, rx) = mpsc::channel::<u64>();
|
||||
let result = within(move || {
|
||||
let collect = move |x: u64| tx.send(x).unwrap();
|
||||
let pipeline = make_pipeline! {
|
||||
D,
|
||||
source 1..=50u64 => Num,
|
||||
| plus_one : Num => Num,
|
||||
sink collect @ Num,
|
||||
};
|
||||
pool_run(pipeline)
|
||||
});
|
||||
assert!(result.is_ok());
|
||||
let mut got: Vec<u64> = rx.try_iter().collect();
|
||||
got.sort_unstable();
|
||||
assert_eq!(got, (2..=51).collect::<Vec<_>>());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pipeline_returns_a_stage_error() {
|
||||
let result = within(|| {
|
||||
pool_run(make_pipeline! {
|
||||
D,
|
||||
source 1..=20u64 => Num,
|
||||
|? fails_on_5 : Num => Num,
|
||||
sink ignore @ Num,
|
||||
})
|
||||
});
|
||||
assert!(message(&result.unwrap_err()).contains("boom on 5"));
|
||||
}
|
||||
|
||||
fn fallible_source_failing() -> Vec<Result<u64, Error>> {
|
||||
vec![
|
||||
Ok(1),
|
||||
Ok(2),
|
||||
Err(Error::new(ErrorKind::UnexpectedEof, "source broke")),
|
||||
Ok(4),
|
||||
]
|
||||
}
|
||||
|
||||
fn fallible_source_ok() -> Vec<Result<u64, Error>> {
|
||||
(1..=10).map(Ok).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pipeline_returns_a_source_error() {
|
||||
let result = within(|| {
|
||||
pool_run(make_pipeline! {
|
||||
D,
|
||||
source? fallible_source_failing() => Num,
|
||||
| identity : Num => Num,
|
||||
sink ignore @ Num,
|
||||
})
|
||||
});
|
||||
assert!(message(&result.unwrap_err()).contains("source broke"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fallible_source_that_runs_dry_ends_normally() {
|
||||
let result = within(|| {
|
||||
pool_run(make_pipeline! {
|
||||
D,
|
||||
source? fallible_source_ok() => Num,
|
||||
| identity : Num => Num,
|
||||
sink ignore @ Num,
|
||||
})
|
||||
});
|
||||
assert!(result.is_ok());
|
||||
}
|
||||
|
||||
fn failing_sink(x: u64) -> Result<(), Error> {
|
||||
if x == 7 {
|
||||
Err(Error::new(ErrorKind::BrokenPipe, "sink broke"))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pipeline_returns_a_sink_error() {
|
||||
let result = within(|| {
|
||||
pool_run(make_pipeline! {
|
||||
D,
|
||||
source 1..=20u64 => Num,
|
||||
| identity : Num => Num,
|
||||
sink? failing_sink @ Num,
|
||||
})
|
||||
});
|
||||
assert!(message(&result.unwrap_err()).contains("sink broke"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pipeline_with_a_flat_stage_counts_every_item() {
|
||||
let (tx, rx) = mpsc::channel::<u64>();
|
||||
let result = within(move || {
|
||||
let collect = move |x: u64| tx.send(x).unwrap();
|
||||
pool_run(make_pipeline! {
|
||||
D,
|
||||
source 1..=10u64 => Num,
|
||||
|| triple : Num => Num,
|
||||
sink collect @ Num,
|
||||
})
|
||||
});
|
||||
assert!(result.is_ok());
|
||||
assert_eq!(rx.try_iter().count(), 30);
|
||||
}
|
||||
|
||||
fn failing_sink_text(_x: String) -> Result<(), Error> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn ignore_text(_x: String) {}
|
||||
|
||||
#[test]
|
||||
fn type_mismatch_at_the_sink() {
|
||||
// The last stage produces a Num, the sink reads a Text.
|
||||
for infallible in [true, false] {
|
||||
let result = within(move || {
|
||||
if infallible {
|
||||
pool_run(make_pipeline! {
|
||||
D,
|
||||
source 1..=3u64 => Num,
|
||||
| identity : Num => Num,
|
||||
sink ignore_text @ Text,
|
||||
})
|
||||
} else {
|
||||
pool_run(make_pipeline! {
|
||||
D,
|
||||
source 1..=3u64 => Num,
|
||||
| identity : Num => Num,
|
||||
sink? failing_sink_text @ Text,
|
||||
})
|
||||
}
|
||||
});
|
||||
assert!(
|
||||
matches!(result, Err(PipelineError::TypeMismatch)),
|
||||
"infallible = {infallible}: {result:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ── PipelineError ───────────────────────────────────────────────────────────────
|
||||
|
||||
#[test]
|
||||
fn pipeline_error_display_and_source() {
|
||||
use std::error::Error as _;
|
||||
assert_eq!(
|
||||
PipelineError::TypeMismatch.to_string(),
|
||||
"data type mismatch in pipeline stage"
|
||||
);
|
||||
assert_eq!(
|
||||
PipelineError::EndOfStream.to_string(),
|
||||
"end of input stream"
|
||||
);
|
||||
assert!(PipelineError::TypeMismatch.source().is_none());
|
||||
let inner = PipelineError::StepError(Box::new(Error::other("inner")));
|
||||
assert!(inner.to_string().contains("inner"));
|
||||
assert!(inner.source().is_some());
|
||||
}
|
||||
|
||||
// ── Panics outside the plain transform ──────────────────────────────────────────
|
||||
|
||||
fn flat_panics(x: u64) -> Vec<u64> {
|
||||
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<u64> {
|
||||
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::<u64>();
|
||||
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);
|
||||
}
|
||||
+9
-2
@@ -26,7 +26,10 @@ fn transform_chain_preserves_the_item_set() {
|
||||
| double : Num => Num,
|
||||
| to_text : Num => Text,
|
||||
};
|
||||
let mut out: Vec<String> = pipe.apply(1..=100u64, 4, 8).collect();
|
||||
let mut out: Vec<String> = pipe
|
||||
.apply(1..=100u64, 4, 8)
|
||||
.collect::<Result<_, _>>()
|
||||
.unwrap();
|
||||
// Workers run in parallel: the order is not guaranteed, the set is.
|
||||
out.sort_by_key(|s| s.parse::<u64>().unwrap());
|
||||
let expected: Vec<String> = (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<String> = first.then(second).apply(1..=20u64, 2, 4).collect();
|
||||
let mut out: Vec<String> = first
|
||||
.then(second)
|
||||
.apply(1..=20u64, 2, 4)
|
||||
.collect::<Result<_, _>>()
|
||||
.unwrap();
|
||||
out.sort_by_key(|s| s.parse::<u64>().unwrap());
|
||||
let expected: Vec<String> = (1..=20u64).map(|x| (x * 2).to_string()).collect();
|
||||
assert_eq!(out, expected);
|
||||
|
||||
@@ -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<u64>),
|
||||
}
|
||||
|
||||
/// Runs `f` on a thread and fails the test if it does not finish in time.
|
||||
fn within<T: Send + 'static>(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<Item = u64> + 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<u64> {
|
||||
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<u64>) -> impl Iterator<Item = u64> + 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> => 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<Mutex<Vec<(char, u64)>>> = 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);
|
||||
}
|
||||
@@ -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<T: Send + 'static>(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<u32>),
|
||||
Out(Option<ThrottleGuard>),
|
||||
}
|
||||
|
||||
fn guard_last(x: Throttled<u32>) -> Vec<Option<ThrottleGuard>> {
|
||||
vec![None, Some(x.guard)]
|
||||
}
|
||||
|
||||
fn slow_failure(_: Option<ThrottleGuard>) -> 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<u64> {
|
||||
(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<u32>),
|
||||
}
|
||||
|
||||
fn keep(x: Throttled<u32>) -> Throttled<u32> {
|
||||
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<u32> => Throttled<u32>, | 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"));
|
||||
}
|
||||
Reference in new issue
Block a user