refactor: remove obipipeline crate and migrate dependencies
Release / create-release (push) Successful in 32s
Release / build-linux-x86_64 (push) Successful in 6m51s
Release / build-macos-arm64 (push) Failing after 40s

Delete the `obipipeline` crate and update all dependent crates to use the
published `obipipeline` version 0.2 from the `obi` registry. Migrate
specific pipeline logic into consuming crates: move error handling to
`obikindexer` and batch iteration logic to `obiskio`. Update build
scripts to support MSRV checking and improved dependency management.

- Delete `src/obipipeline/` entirely, removing the pipeline runtime,
  scheduler, macros, and throttle implementations.
- Move `fmt` (now `pipeline_error`) from `obipipeline` error handling to
  `src/obikindexer/src/graph_pipeline.rs` for graph building errors.
- Move `apply` (now `iter_canonical_kmer_batches_owned`) from
  `obipipeline` pipe logic to `src/obiskio/src/unitig_index/reader.rs`
  to provide lazy batch iteration for canonical kmers.
- Update `src/obikindexer`, `src/obikmerge`, `src/obikphylo`, and
  `src/obiskim` to depend on `obipipeline` version 0.2 from the `obi`
  registry instead of the local path.
- Refactor `src/obikindexer/src/graph_pipeline.rs` to use the new
  `pipeline_error` function and update `build_graph` to accept an
  iterator-returning `open` function.
- Refactor `src/obikmerge` to use `iter_canonical_kmer_batches_owned`
  for streaming batches in `merge_partition` and `run_pass2`, replacing
  previous pipeline stage logic.
- Refactor `src/obikphylo` to handle errors via `OKIError::InvalidData`
  in `build_layer_sibling_annex` and `scan_layer_families`.
- Refactor `src/obiskim` to use `.expect("pipeline error")` for batch
  processing in `query` and `superkmer` commands.
- Add `src/obiskio/src/unitig_index/reader.rs` method
  `iter_canonical_kmer_batches_owned` for lazy batch iteration.
- Add `.crate-kit/scripts/msrv-check.sh` to verify the declared
  `rust-version` builds successfully with the specified toolchain.
- Update `.crate-kit/scripts/deps-check.sh` and `deps-lib.sh` to
  support `cargo update` with specific arguments and improved lockfile
  handling.
- Update `.crate-kit/scripts/bump-version.sh` to use `sed -E` for
  robust version string replacement in `README.md`.
- Update `.crate-kit/scripts/publish-guard.sh` and `publish.sh` to
  enforce registry settings and exclude internal files from packages.
- Update `.gitea/workflows/release.yml` to pass the private cargo
  registry index environment variable during macOS binary builds.
- Remove `Cargo.lock` from the repository root and update
  `src/Cargo.lock` to reflect the new `obipipeline` dependency version.
- Update `src/Cargo.toml` workspace members to remove `obikseq` and
  add `obifastwrite`.
This commit is contained in:
Eric Coissac committed 2026-12-02 16:16:40 +01:00
1 parent e4528725d4
commit b2222afbe3
39 files changed
+304 -1304

No files matched your search

+1 -1
View File
@@ -1657,7 +1657,7 @@ dependencies = [
[[package]]
name = "obipipeline"
version = "0.1.0"
version = "0.2.0"
dependencies = [
"crossbeam-channel",
]
+1 -1
View File
@@ -1,5 +1,5 @@
[workspace]
resolver = "3"
members = ["obikseq", "obiread", "obiskbuilder", "obifastwrite", "obiskim","obikrope","obipipeline", "obiskio","obidebruinj", "obicompactvec", "obisys", "obikindex", "obikindexer", "obikquery", "obikdump", "obikfilter", "obikselect", "obikrebuild", "obikmerge", "obikstats", "obikidxcache", "obitaxonomy", "obikentropy", "obikphylo", "obikalgorithm", "obiksession"]
members = ["obikseq", "obiread", "obiskbuilder", "obifastwrite", "obiskim","obikrope", "obiskio","obidebruinj", "obicompactvec", "obisys", "obikindex", "obikindexer", "obikquery", "obikdump", "obikfilter", "obikselect", "obikrebuild", "obikmerge", "obikstats", "obikidxcache", "obitaxonomy", "obikentropy", "obikphylo", "obikalgorithm", "obiksession"]
[profile.release]
debug = 1
+1 -1
View File
@@ -9,7 +9,7 @@ repository = "https://forge.metabarcoding.org/obi/obiskim"
obikindex = { path = "../obikindex"}
obikseq = { path = "../obikseq"}
obicompactvec = { path = "../obicompactvec" }
obipipeline = { path = "../obipipeline" }
obipipeline = { version = "0.2", registry = "obi" }
ndarray = "0.17"
rayon = "1"
+1 -1
View File
@@ -13,7 +13,7 @@ obidebruinj = { path = "../obidebruinj" }
obiskio = { path = "../obiskio" }
obisys = { path = "../obisys", default-features = false }
obicompactvec = { path = "../obicompactvec" }
obipipeline = { path = "../obipipeline" }
obipipeline = { version = "0.2", registry = "obi" }
obiread = { path = "../obiread" }
obiskbuilder = { path = "../obiskbuilder" }
epserde = "0.13"
@@ -308,6 +308,7 @@ impl Algorithm for PartitionRouter<'_> {
const REPORT_INTERVAL: f64 = 0.1;
for batch in pipe.apply(throttled, n_workers, 1) {
let batch = batch?;
total_bases += batch
.iter()
.map(|sk| (sk.seql() as u64).saturating_sub(kmer_overlap))
+37 -40
View File
@@ -2,7 +2,7 @@ use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use obipipeline::{
Pipeline, PipelineError, PipelineSender, SharedFlatFn, Stage, WorkerPool, make_sink,
Pipeline, PipelineError, Throttled, WorkerPool, make_flat_transform_fallible, make_sink,
make_source, make_transform, throttle,
};
use tracing::debug;
@@ -24,59 +24,48 @@ enum KmerGraphData {
/// Phase 1: pipeline that reads files, filters kmers, pushes into a GraphDeBruijn.
///
/// `flat_fn(path, emit)`: opens path, iterates kmers, calls `emit(batch)` for each batch.
/// `open(path)`: opens path and returns its k-mer batches, as a lazy iterator: a batch is only read when
/// the pipeline has room for it. At most `max_open` of these iterators are alive at once.
/// `filter(kmer) -> bool`: secondary filter applied in the Transform stage.
pub fn build_graph<I, F, G>(
pub fn build_graph<I, F, B, G>(
file_source: I,
flat_fn: F,
open: F,
filter: G,
n_workers: usize,
max_open: usize,
) -> OKIResult<GraphDeBruijn>
where
I: Iterator<Item = PathBuf> + Send + 'static,
F: Fn(PathBuf, &mut dyn FnMut(Vec<CanonicalKmer>)) -> OKIResult<()> + Send + Sync + 'static,
F: Fn(PathBuf) -> OKIResult<B> + Send + Sync + 'static,
B: Iterator<Item = Vec<CanonicalKmer>> + Send + 'static,
G: Fn(CanonicalKmer) -> bool + Send + Sync + 'static,
{
let capacity = 2;
let flat_fn = Arc::new(flat_fn);
let filter = Arc::new(filter);
let g_shared = Arc::new(Mutex::new(GraphDeBruijn::new()));
let g_sink = Arc::clone(&g_shared);
let err_cap: Arc<Mutex<Option<OKIError>>> = Arc::new(Mutex::new(None));
let err_flat = Arc::clone(&err_cap);
let throttled = throttle(file_source, max_open);
let pipeline = Pipeline::new(
make_source!(KmerGraphData, throttled, File),
vec![
Stage::Flat(Arc::new(
move |data: KmerGraphData,
push: &PipelineSender<Result<KmerGraphData, PipelineError>>,
delta: &PipelineSender<isize>| {
if let KmerGraphData::File(t) = data {
let path = t.item;
let _guard = t.guard; // released at end of block
let mut count: isize = 0;
let push_clone = push.clone();
let result = flat_fn(path, &mut |batch: Vec<CanonicalKmer>| {
push_clone.send(Ok(KmerGraphData::RawBatch(batch))).ok();
count += 1;
});
match result {
Ok(()) => {
delta.send(count - 1).ok();
}
Err(e) => {
*err_flat.lock().unwrap() = Some(e);
delta.send(-1).ok();
}
}
make_flat_transform_fallible!(
KmerGraphData,
{
move |file: Throttled<PathBuf>| {
let guard = file.guard;
open(file.item).map(|batches| {
batches.inspect(move |_| {
let _open_file = &guard; // slot held as long as the file is read
})
})
}
},
) as SharedFlatFn<KmerGraphData>),
File,
RawBatch
),
make_transform!(
KmerGraphData,
{
@@ -103,15 +92,16 @@ where
),
);
WorkerPool::new(pipeline, n_workers, capacity).run();
if let Some(e) = Arc::try_unwrap(err_cap)
.unwrap_or_else(|_| panic!("build_graph: err_cap not uniquely owned after pipeline"))
.into_inner()
.unwrap_or_else(|e| e.into_inner())
{
return Err(e);
}
WorkerPool::new(pipeline, n_workers, capacity)
.run()
.map_err(|e| match e {
// An error of `open` is handed back as it was.
PipelineError::StepError(inner) => match inner.downcast::<OKIError>() {
Ok(e) => *e,
Err(other) => pipeline_error(other.to_string()),
},
other => pipeline_error(other.to_string()),
})?;
let g = Arc::try_unwrap(g_shared)
.unwrap_or_else(|_| panic!("build_graph: g_shared not uniquely owned after pipeline"))
@@ -121,6 +111,13 @@ where
Ok(g)
}
fn pipeline_error(detail: String) -> OKIError {
OKIError::InvalidData {
context: "build_graph pipeline",
detail,
}
}
// ── write_graph_as_unitigs ────────────────────────────────────────────────────
/// Phase 2 (write unitigs only): compute degrees, write unitigs to `layer_dir`, drop graph.
+1 -1
View File
@@ -12,7 +12,7 @@ obikalgorithm = { path = "../obikalgorithm" }
obicompactvec = { path = "../obicompactvec" }
obiskio = { path = "../obiskio" }
obikseq = { path = "../obikseq" }
obipipeline = { path = "../obipipeline" }
obipipeline = { version = "0.2", registry = "obi" }
obisys = { path = "../obisys", default-features = false }
rayon = "1"
tracing = "0.1.44"
+5 -18
View File
@@ -21,7 +21,6 @@ use obicompactvec::{ColBuilder, MatrixBuilder};
use obikindex::layer::{IndexMode, KmerLayer, TypedLayer};
use obikindex::{KmerIndex, OKIError, OKIResult};
use obikindexer::{build_graph, materialize_layer};
use obikseq::CanonicalKmer;
use obiskio::UnitigFileReader;
use crate::MergeMode;
@@ -82,7 +81,7 @@ pub(crate) fn merge_partition(
// ── Pass 1: pipeline — parallel file read + dst filter + graph fill ────
//
// Source : list of unitigs.bin paths (one per source × layer)
// Flat : open file, emit Vec<CanonicalKmer> batches (BeeGFS parallel I/O)
// Flat : open file, stream Vec<CanonicalKmer> batches (BeeGFS parallel I/O)
// Transform: filter via dst_layers — Arc<[KmerLayer]>: Sync
// Sink : push new kmers into GraphDeBruijn (single thread, no locks needed)
//
@@ -106,28 +105,16 @@ pub(crate) fn merge_partition(
const BATCH: usize = 4096;
let n_workers = rayon::current_num_threads().clamp(4, 16);
// At most 2 files open simultaneously: keeps n_workers-2 workers free
// for the Transform stage. Each open file monopolises one worker for the
// full duration of its read, so this must stay well below n_workers.
// At most 2 files open simultaneously (I/O bound, not needed for the pipeline to progress).
let max_open = 2;
let dst_filter = Arc::clone(&dst_layers);
let g = build_graph(
unitig_paths.into_iter(),
move |path: PathBuf, emit: &mut dyn FnMut(Vec<CanonicalKmer>)| -> OKIResult<()> {
let reader = UnitigFileReader::open_sequential(&path)?;
let mut batch: Vec<CanonicalKmer> = Vec::with_capacity(BATCH);
for (kmer, _, _) in reader.iter_indexed_canonical_kmers() {
batch.push(kmer);
if batch.len() == BATCH {
emit(std::mem::replace(&mut batch, Vec::with_capacity(BATCH)));
}
}
if !batch.is_empty() {
emit(batch);
}
Ok(())
move |path: PathBuf| -> OKIResult<_> {
let reader = Arc::new(UnitigFileReader::open_sequential(&path)?);
Ok(reader.iter_canonical_kmer_batches_owned(BATCH))
},
move |kmer| dst_filter.iter().all(|l| l.find_slot(kmer).is_none()),
n_workers,
+30 -63
View File
@@ -7,8 +7,8 @@ use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use obipipeline::{
Pipeline, PipelineError, PipelineSender, SharedFlatFn, Stage, ThrottleGuard, WorkerPool,
make_sink, make_source, make_transform, throttle,
Pipeline, ThrottleGuard, WorkerPool, make_flat_transform_fallible, make_sink, make_source,
make_transform, throttle,
};
use obicompactvec::ColBuilder;
@@ -88,8 +88,6 @@ pub(super) fn run_pass2(
let new_sink: Vec<Arc<Mutex<ColBuilder>>> = new_locked.iter().map(Arc::clone).collect();
let dst_layers_t2 = Arc::clone(dst_layers);
let new_mphf_t2 = new_mphf.clone();
let pass2_err: Arc<Mutex<Option<String>>> = Arc::new(Mutex::new(None));
let err_cap2 = Arc::clone(&pass2_err);
let capacity = 2;
let throttled_pass2 = throttle(items.into_iter(), max_open);
@@ -104,58 +102,33 @@ pub(super) fn run_pass2(
SrcLayer
),
vec![
Stage::Flat(Arc::new(
move |data: Pass2Data,
push: &PipelineSender<Result<Pass2Data, PipelineError>>,
delta: &PipelineSender<isize>| {
if let Pass2Data::SrcLayer((
col_offset,
src_n,
unitigs_path,
src_layer,
_guard,
)) = data
{
// _guard dropped at end of block, releasing the slot.
make_flat_transform_fallible!(
Pass2Data,
{
move |(col_offset, src_n, unitigs_path, src_layer, guard): (
usize,
usize,
PathBuf,
Arc<KmerLayer>,
ThrottleGuard,
)| {
// `src_layer` (MPHF + matrix) was already opened by
// the caller — only the unitigs.bin stream itself is
// opened (and throttled) here.
let reader = match UnitigFileReader::open_sequential(&unitigs_path) {
Ok(r) => r,
Err(e) => {
*err_cap2.lock().unwrap() = Some(e.to_string());
delta.send(-1).ok();
return;
}
};
const BATCH: usize = 4096;
let mut batch: Vec<CanonicalKmer> = Vec::with_capacity(BATCH);
let mut count: isize = 0;
for (kmer, _, _) in reader.iter_indexed_canonical_kmers() {
batch.push(kmer);
if batch.len() == BATCH {
let b = std::mem::replace(&mut batch, Vec::with_capacity(BATCH));
push.send(Ok(Pass2Data::RawBatch((
col_offset,
src_n,
Arc::clone(&src_layer),
b,
))))
.ok();
count += 1;
}
}
if !batch.is_empty() {
push.send(Ok(Pass2Data::RawBatch((
col_offset, src_n, src_layer, batch,
))))
.ok();
count += 1;
}
delta.send(count - 1).ok();
UnitigFileReader::open_sequential(&unitigs_path).map(|reader| {
const BATCH: usize = 4096;
Arc::new(reader)
.iter_canonical_kmer_batches_owned(BATCH)
.map(move |kmers| {
let _open_file = &guard; // slot held as long as the file is read
(col_offset, src_n, Arc::clone(&src_layer), kmers)
})
})
}
},
) as SharedFlatFn<Pass2Data>),
SrcLayer,
RawBatch
),
make_transform!(
Pass2Data,
{
@@ -239,18 +212,12 @@ pub(super) fn run_pass2(
),
);
WorkerPool::new(pipeline2, n_workers, capacity).run();
if let Some(msg) = Arc::try_unwrap(pass2_err)
.unwrap_or_else(|_| panic!("pass2: pass2_err not uniquely owned"))
.into_inner()
.unwrap_or_else(|e| e.into_inner())
{
return Err(OKIError::InvalidData {
context: "merge pass2",
detail: msg,
});
}
WorkerPool::new(pipeline2, n_workers, capacity)
.run()
.map_err(|e| OKIError::InvalidData {
context: "merge pass2 pipeline",
detail: e.to_string(),
})?;
let unlock = |b: Arc<Mutex<ColBuilder>>| -> ColBuilder {
Arc::try_unwrap(b)
+1 -1
View File
@@ -12,7 +12,7 @@ obiskio = { path = "../obiskio" }
obisys = { path = "../obisys", default-features = false }
obicompactvec = { path = "../obicompactvec" }
obikidxcache = { path = "../obikidxcache" }
obipipeline = { path = "../obipipeline" }
obipipeline = { version = "0.2", registry = "obi" }
kodama = "0.3.0"
memmap2 = "0.9"
ndarray = "0.17"
@@ -4,8 +4,8 @@ use std::sync::atomic::Ordering;
use rayon::prelude::*;
use obikidxcache::index_cache::IndexCache;
use obikindex::OKIResult;
use obikindex::layer::KmerLayer;
use obikindex::{OKIError, OKIResult};
use obikseq::CanonicalKmer;
use obipipeline::ThrottleGuard;
@@ -181,6 +181,10 @@ pub(crate) fn build_layer_sibling_annex(
let mut outgoing: Vec<Vec<(CanonicalKmer, usize, u8)>> =
(0..n_parts).map(|_| Vec::new()).collect();
for vb in pipe.apply(throttled, n_workers, capacity) {
let vb = vb.map_err(|e| OKIError::InvalidData {
context: "sibling annex pipeline",
detail: e.to_string(),
})?;
for (dest_partition, variant, source_order, base) in vb.items {
outgoing[dest_partition].push((variant, source_order, base));
}
@@ -326,6 +326,10 @@ pub(crate) fn scan_layer_families(
let mut next_expected = 0usize;
let mut scratch = vec![0u8; n_genomes];
for generated in pipe.apply(throttled, n_workers, capacity) {
let generated = generated.map_err(|e| OKIError::InvalidData {
context: "family scan pipeline",
detail: e.to_string(),
})?;
pending.insert(generated.start_family_idx, generated);
while let Some(batch) = pending.remove(&next_expected) {
let n = batch.masks.len();
-9
View File
@@ -1,9 +0,0 @@
[package]
name = "obipipeline"
version = "0.1.0"
edition = "2024"
license = "CECILL-2.1"
repository = "https://forge.metabarcoding.org/obi/obiskim"
[dependencies]
crossbeam-channel = "0.5.15"
@@ -1,79 +0,0 @@
use obipipeline::{WorkerPool, make_pipeline};
use std::io::Error;
// ── Itérateur source ──────────────────────────────────────────────────────────
struct Compteur {
count: u64,
stop: u64,
}
impl Compteur {
fn new(start: u64, stop: u64) -> Self {
Self { count: start, stop }
}
}
impl Iterator for Compteur {
type Item = u64;
fn next(&mut self) -> Option<Self::Item> {
if self.count > self.stop {
return None;
}
let result = self.count;
self.count += 1;
Some(result)
}
}
// ── Fonctions de transformation ───────────────────────────────────────────────
fn to_f64(x: u64) -> f64 {
x as f64
}
fn step_1(number: f64) -> String {
format!("{}", number)
}
fn step_2(text: String) -> String {
text.chars().rev().collect()
}
fn step_3(text: String) -> u64 {
let mut hash: u64 = 5381;
for byte in text.bytes() {
hash = hash.wrapping_mul(33).wrapping_add(byte as u64);
}
hash
}
fn step_4(hash: u64) -> Result<(), Error> {
println!("{}", hash);
Ok(())
}
// ── Type de données du pipeline ───────────────────────────────────────────────
enum PipelineData {
Unsigned(u64),
Number(f64),
Text(String),
}
// ── Main ──────────────────────────────────────────────────────────────────────
fn main() {
let pipeline = make_pipeline! {
PipelineData,
source Compteur::new(1000, 1010) => Unsigned,
| to_f64: Unsigned => Number,
| step_1: Number => Text,
| step_2: Text => Text,
| step_3: Text => Unsigned,
sink? step_4 @ Unsigned,
};
WorkerPool::new(pipeline, 4, 64).run();
}
-27
View File
@@ -1,27 +0,0 @@
mod scheduler;
pub mod throttle;
pub use scheduler::Pipe;
pub use scheduler::PipeIter;
pub use scheduler::Pipeline;
pub use scheduler::PipelineError;
pub use scheduler::SharedFlatFn;
pub use scheduler::SharedFn;
pub use scheduler::SinkFn;
pub use scheduler::SourceFn;
pub use scheduler::Stage;
pub use scheduler::WorkerPool;
pub use throttle::Throttle;
pub use throttle::ThrottleGuard;
pub use throttle::Throttled;
pub use throttle::throttle;
/// Re-export de `crossbeam_channel::Sender` utilisé dans les macros flat transform.
/// Permet aux macros `make_flat_transform!` / `make_flat_transform_fallible!` d'utiliser
/// `$crate::PipelineSender` sans que le crate appelant n'ait besoin de dépendre
/// directement de `crossbeam_channel`.
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 sont exportés à la racine du crate via #[macro_export]
-35
View File
@@ -1,35 +0,0 @@
use std::error::Error;
use std::fmt;
/// Error type for pipeline operations.
#[derive(Debug)]
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).
StepError(Box<dyn Error + Send + Sync>),
}
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),
}
}
}
impl Error for PipelineError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
PipelineError::StepError(e) => Some(e.as_ref()),
_ => None,
}
}
}
-357
View File
@@ -1,357 +0,0 @@
// ── Macros ────────────────────────────────────────────────────────────────────
/// Creates a `SourceFn` from an iterator of plain values.
#[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>
}};
}
/// Creates a `SourceFn` from an iterator of `Result<T, E>`.
#[macro_export]
macro_rules! make_source_fallible {
($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(Ok(x)) => Ok($enum::$output(x)),
Some(Err(e)) => Err($crate::PipelineError::StepError(Box::new(e))),
None => Err($crate::PipelineError::EndOfStream),
}
},
) as Box<dyn FnMut() -> ::std::result::Result<$enum, $crate::PipelineError> + Send>
}};
}
/// Creates a `Stage::Transform` from a pure (non-fallible) function `Fn(T) -> U`.
#[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),
}
},
)
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>`.
#[macro_export]
macro_rules! make_transform_fallible {
($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(inner) => {
let result = __f(inner)
.map_err(|e| $crate::PipelineError::StepError(Box::new(e)))?;
Ok($enum::$output(result))
}
_ => Err($crate::PipelineError::TypeMismatch),
}
},
)
as Box<
dyn Fn($enum) -> ::std::result::Result<$enum, $crate::PipelineError> + Send + Sync,
>))
}};
}
/// Creates a `Stage::Flat` from a function `Fn(T) -> impl IntoIterator<Item = U>`.
///
/// Pour chaque item produit par l'itérateur, il est poussé individuellement dans
/// le canal de sortie, permettant au scheduler de dispatcher les items en parallèle
/// dès qu'un worker est disponible.
#[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>)
}};
}
/// Creates a `Stage::Flat` from a fallible function
/// `Fn(T) -> Result<impl IntoIterator<Item = U>, E>`.
///
/// Si la fonction retourne `Err`, une erreur est poussée dans le canal et aucun
/// item normal n'est produit.
#[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 {
$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();
}
},
_ => {
push.send(Err($crate::PipelineError::TypeMismatch)).ok();
delta.send(0).ok();
}
}
},
) as $crate::SharedFlatFn<$enum>)
}};
}
/// Creates a `SinkFn` from a function that consumes a concrete value and returns `()`.
#[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),
}
},
) as Box<dyn Fn($enum) -> ::std::result::Result<(), $crate::PipelineError> + Send>
}};
}
/// Creates a `SinkFn` from a fallible function that returns `Result<(), E>`.
#[macro_export]
macro_rules! make_sink_fallible {
($enum:ident, $func:tt, $input:ident) => {{
let __f = $func;
Box::new(
move |data: $enum| -> ::std::result::Result<(), $crate::PipelineError> {
match data {
$enum::$input(inner) => {
__f(inner).map_err(|e| $crate::PipelineError::StepError(Box::new(e)))
}
_ => Err($crate::PipelineError::TypeMismatch),
}
},
) as Box<dyn Fn($enum) -> ::std::result::Result<(), $crate::PipelineError> + Send>
}};
}
/// Construit un `Pipeline` à partir d'une source, d'une liste de stages et d'un sink.
///
/// Syntaxe :
/// ```ignore
/// make_pipeline! {
/// MyData,
/// source my_iter => Variant, // source non-fallible
/// source? my_iter => Variant, // source fallible (Result<T, E>)
/// | func: In => Out, // transform 1→1 non-fallible
/// |? func: In => Out, // transform 1→1 fallible
/// || func: In => Out, // flat transform 1→N non-fallible
/// ||? func: In => Out, // flat transform 1→N fallible
/// sink my_func @ Variant, // sink non-fallible
/// sink? my_func @ Variant, // sink fallible
/// }
/// ```
#[macro_export]
macro_rules! make_pipeline {
// ── Points d'entrée ──────────────────────────────────────────────────
($enum:ident, source $src:expr => $src_out:ident, $($rest:tt)*) => {
$crate::make_pipeline!(@build $enum,
{ $crate::make_source!($enum, $src, $src_out) },
[],
$($rest)*)
};
($enum:ident, source? $src:expr => $src_out:ident, $($rest:tt)*) => {
$crate::make_pipeline!(@build $enum,
{ $crate::make_source_fallible!($enum, $src, $src_out) },
[],
$($rest)*)
};
// ── Accumulation des stages ──────────────────────────────────────────
// transform 1→1 non-fallible
(@build $enum:ident, $source:tt, [$($acc:tt)*],
| $tf:tt : $t_in:ident => $t_out:ident, $($rest:tt)*) => {
$crate::make_pipeline!(@build $enum, $source,
[$($acc)* $crate::make_transform!($enum, $tf, $t_in, $t_out),],
$($rest)*)
};
// transform 1→1 fallible
(@build $enum:ident, $source:tt, [$($acc:tt)*],
|? $tf:tt : $t_in:ident => $t_out:ident, $($rest:tt)*) => {
$crate::make_pipeline!(@build $enum, $source,
[$($acc)* $crate::make_transform_fallible!($enum, $tf, $t_in, $t_out),],
$($rest)*)
};
// flat transform 1→N non-fallible
(@build $enum:ident, $source:tt, [$($acc:tt)*],
|| $tf:tt : $t_in:ident => $t_out:ident, $($rest:tt)*) => {
$crate::make_pipeline!(@build $enum, $source,
[$($acc)* $crate::make_flat_transform!($enum, $tf, $t_in, $t_out),],
$($rest)*)
};
// flat transform 1→N fallible
(@build $enum:ident, $source:tt, [$($acc:tt)*],
||? $tf:tt : $t_in:ident => $t_out:ident, $($rest:tt)*) => {
$crate::make_pipeline!(@build $enum, $source,
[$($acc)* $crate::make_flat_transform_fallible!($enum, $tf, $t_in, $t_out),],
$($rest)*)
};
// ── Terminaison : sink ───────────────────────────────────────────────
(@build $enum:ident, $source:tt, [$($acc:tt)*],
sink $sink_fn:tt @ $sink_in:ident $(,)?) => {
$crate::Pipeline::new(
$source,
vec![$($acc)*],
$crate::make_sink!($enum, $sink_fn, $sink_in),
)
};
(@build $enum:ident, $source:tt, [$($acc:tt)*],
sink? $sink_fn:tt @ $sink_in:ident $(,)?) => {
$crate::Pipeline::new(
$source,
vec![$($acc)*],
$crate::make_sink_fallible!($enum, $sink_fn, $sink_in),
)
};
}
/// Builds a typed `Pipe<D, In, Out>` — sourceless and sinkless.
///
/// Syntax:
/// ```ignore
/// make_pipe! {
/// MyData : InType => OutType,
/// | func : InVariant => OutVariant, // transform 1→1
/// |? func : InVariant => OutVariant, // transform 1→1 fallible
/// || func : InVariant => OutVariant, // flat transform 1→N
/// ||? func : InVariant => OutVariant, // flat transform 1→N fallible
/// }
/// ```
#[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: 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)*)
};
// ── 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)*)
};
// ── Accumulation: | ──────────────────────────────────────────────────
(@build $enum:ident : $in_ty:ty => $out_ty:ty, $fi:ident,
[$($acc:tt)*], $lo:ident,
| $tf:tt : $ti:ident => $to:ident, $($rest:tt)*) => {
$crate::make_pipe!(@build $enum : $in_ty => $out_ty, $fi,
[$($acc)* $crate::make_transform!($enum, $tf, $ti, $to),], $to, $($rest)*)
};
// ── Accumulation: |? ─────────────────────────────────────────────────
(@build $enum:ident : $in_ty:ty => $out_ty:ty, $fi:ident,
[$($acc:tt)*], $lo:ident,
|? $tf:tt : $ti:ident => $to:ident, $($rest:tt)*) => {
$crate::make_pipe!(@build $enum : $in_ty => $out_ty, $fi,
[$($acc)* $crate::make_transform_fallible!($enum, $tf, $ti, $to),], $to, $($rest)*)
};
// ── Accumulation: || ─────────────────────────────────────────────────
(@build $enum:ident : $in_ty:ty => $out_ty:ty, $fi:ident,
[$($acc:tt)*], $lo:ident,
|| $tf:tt : $ti:ident => $to:ident, $($rest:tt)*) => {
$crate::make_pipe!(@build $enum : $in_ty => $out_ty, $fi,
[$($acc)* $crate::make_flat_transform!($enum, $tf, $ti, $to),], $to, $($rest)*)
};
// ── Accumulation: ||? ────────────────────────────────────────────────
(@build $enum:ident : $in_ty:ty => $out_ty:ty, $fi:ident,
[$($acc:tt)*], $lo:ident,
||? $tf:tt : $ti:ident => $to:ident, $($rest:tt)*) => {
$crate::make_pipe!(@build $enum : $in_ty => $out_ty, $fi,
[$($acc)* $crate::make_flat_transform_fallible!($enum, $tf, $ti, $to),], $to, $($rest)*)
};
// ── Termination ───────────────────────────────────────────────────────
(@build $enum:ident : $in_ty:ty => $out_ty:ty, $fi:ident,
[$($acc:tt)*], $lo:ident $(,)?) => {
$crate::Pipe::new(
vec![$($acc)*],
::std::sync::Arc::new(|x: $in_ty| $enum::$fi(x)),
::std::sync::Arc::new(|d: $enum| -> $out_ty {
if let $enum::$lo(x) = d { x }
else { ::std::unreachable!("unexpected pipeline data variant in make_pipe!") }
}),
)
};
}
-19
View File
@@ -1,19 +0,0 @@
//! 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`).
//!
//! Submodules: [`error`] (`PipelineError`), [`types`] (function types, `Stage`),
//! [`runner`] (thread bodies), [`pool`] (`Pipeline`/`WorkerPool` scheduler
//! loop), [`pipe`] (`Pipe`/`PipeIter`), [`macros`] (`make_pipe!` and friends).
mod error;
mod macros;
mod pipe;
mod pool;
mod runner;
mod types;
pub use error::PipelineError;
pub use pipe::{Pipe, PipeIter};
pub use pool::{Pipeline, WorkerPool};
pub use types::{SharedFlatFn, SharedFn, SinkFn, SourceFn, Stage};
-125
View File
@@ -1,125 +0,0 @@
use crossbeam_channel::{Receiver, bounded};
use std::marker::PhantomData;
use std::sync::Arc;
use std::thread;
use super::error::PipelineError;
use super::pool::{Pipeline, WorkerPool};
use super::types::{SinkFn, SourceFn, Stage};
// ── Pipe ──────────────────────────────────────────────────────────────────────
/// Typed, composable iterator transformer.
///
/// A `Pipe<D, In, Out>` is a pure description of pipeline stages — no threads,
/// no channels, no scheduler. Call `.apply(iter, n_workers, capacity)` to start
/// execution and get back a `PipeIter<Out>`.
///
/// Compose two pipes with `.then()`: the resulting `Pipe` holds the concatenated
/// stage list, so a single scheduler is created when `.apply()` is eventually called.
pub struct Pipe<D, In, Out> {
stages: Vec<Stage<D>>,
wrap: Arc<dyn Fn(In) -> D + Send + Sync>,
unwrap: Arc<dyn Fn(D) -> Out + Send + Sync>,
_phantom: PhantomData<(In, Out)>,
}
impl<D, In, Out> Pipe<D, In, Out> {
/// Build a `Pipe` from stages and wrap/unwrap converters.
/// Prefer the `make_pipe!` macro.
pub fn new(
stages: Vec<Stage<D>>,
wrap: Arc<dyn Fn(In) -> D + Send + Sync>,
unwrap: Arc<dyn Fn(D) -> Out + Send + Sync>,
) -> Self {
Self {
stages,
wrap,
unwrap,
_phantom: PhantomData,
}
}
/// Concatenate stages from two pipes into one.
///
/// Requires `Out` of `self` == `In` of `other`. The single scheduler
/// created at `.apply()` time sees the full combined stage list.
pub fn then<Next>(self, other: Pipe<D, Out, Next>) -> Pipe<D, In, Next> {
Pipe {
stages: self.stages.into_iter().chain(other.stages).collect(),
wrap: self.wrap,
unwrap: other.unwrap,
_phantom: PhantomData,
}
}
}
impl<D, In, Out> Pipe<D, In, Out>
where
D: Send + Sync + 'static,
In: Send + 'static,
Out: Send + 'static,
{
/// Run the pipeline in a background thread; returns an iterator over the output.
pub fn apply(
self,
input: impl Iterator<Item = In> + Send + 'static,
n_workers: usize,
capacity: usize,
) -> PipeIter<Out> {
let wrap = Arc::clone(&self.wrap);
let unwrap = Arc::clone(&self.unwrap);
let mut iter = input;
let source: SourceFn<D> = Box::new(move || match iter.next() {
Some(x) => Ok(wrap(x)),
None => Err(PipelineError::EndOfStream),
});
let (out_tx, out_rx) = bounded::<Out>(capacity);
let sink: SinkFn<D> = Box::new(move |data: D| {
out_tx.send(unwrap(data)).map_err(|_| {
PipelineError::StepError(Box::new(std::io::Error::new(
std::io::ErrorKind::BrokenPipe,
"output channel closed",
)))
})
});
let pipeline = Pipeline::new(source, self.stages, sink);
let handle = thread::spawn(move || {
WorkerPool::new(pipeline, n_workers, capacity).run();
});
PipeIter {
rx: out_rx,
handle: Some(handle),
}
}
}
// ── PipeIter ──────────────────────────────────────────────────────────────────
/// Iterator over the output of `Pipe::apply()`.
pub struct PipeIter<Out> {
rx: Receiver<Out>,
handle: Option<thread::JoinHandle<()>>,
}
impl<Out> Iterator for PipeIter<Out> {
type Item = Out;
fn next(&mut self) -> Option<Out> {
self.rx.recv().ok()
}
}
impl<Out> Drop for PipeIter<Out> {
fn drop(&mut self) {
// Drain buffered items so the scheduler can unblock if the channel is full.
while self.rx.try_recv().is_ok() {}
if let Some(h) = self.handle.take() {
let _ = h.join();
}
}
}
-201
View File
@@ -1,201 +0,0 @@
use crossbeam_channel::{Receiver, Select, Sender, bounded};
use super::error::PipelineError;
use super::runner::{dispatch, sink_runner, source_runner, transform_runner};
use super::types::{SinkFn, SourceFn, Stage, WorkerTask};
// ── Pipeline ──────────────────────────────────────────────────────────────────
pub struct Pipeline<DATA> {
source: SourceFn<DATA>,
stages: Vec<Stage<DATA>>,
sink: SinkFn<DATA>,
}
impl<DATA> Pipeline<DATA> {
pub fn new(source: SourceFn<DATA>, stages: Vec<Stage<DATA>>, sink: SinkFn<DATA>) -> Self {
Self {
source,
stages,
sink,
}
}
}
// ── WorkerPool ────────────────────────────────────────────────────────────────
pub struct WorkerPool<DATA> {
pipeline: Pipeline<DATA>,
handles: Vec<std::thread::JoinHandle<()>>,
n_workers: usize,
capacity: usize,
}
impl<DATA> WorkerPool<DATA>
where
DATA: Send + Sync + 'static,
{
pub fn new(pipeline: Pipeline<DATA>, n_workers: usize, capacity: usize) -> Self {
Self {
pipeline,
handles: Vec::new(),
n_workers,
capacity,
}
}
pub fn run(mut self) {
let n = self.pipeline.stages.len();
// ── Canaux inter-stages ────────────────────────────────────────────
// stage_txs[i] / stage_rxs[i] : sortie du 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;
// ── Canal delta pour les flat stages ───────────────────────────────
// Chaque flat worker envoie `N-1` ici après avoir poussé N items.
// Le scheduler ajuste `in_flight` en conséquence.
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);
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(),
));
}
// Le scheduler ne tient plus flat_delta_tx : les workers le détiennent.
// On le drop ici pour que le canal se ferme quand les workers terminent.
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);
// ── Boucle principale ──────────────────────────────────────────────
//
// `in_flight` (isize) = nb d'items qui doivent encore atteindre le sink.
// Peut temporairement être négatif si un flat worker a poussé ses items
// avant que le scheduler ait reçu le delta correspondant.
//
// `flat_workers_active` = nb de flat workers en cours d'exécution.
// Empêche la terminaison prématurée quand in_flight vaut 0 mais qu'un
// flat worker n'a pas encore envoyé son delta.
//
// Priorités du Select biaisé (index le plus bas = priorité la plus haute) :
// 0 → sink_err_rx (arrêt immédiat sur erreur sink)
// 1 → flat_delta_rx (mettre à jour in_flight avant de dispatcher)
// 2..=n+1 → stage_rxs[n-1..0] (vider le pipeline en priorité)
// n+2 → source_rx (dernier recours : nouvelles données)
//
// Quand k = 0 : erreur du sink
// Quand k = 1 : delta d'un flat worker
// Quand 2 ≤ k ≤ n+1 : résultat du stage n+1-k
// Quand k = n+2 : item source
//
// Terminaison : source tarie ET in_flight == 0 ET aucun flat worker actif.
{
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 {
// ── Erreur du sink ────────────────────────────────────
match oper.recv(&sink_err_rx) {
Ok(e) => {
eprintln!("Sink error: {:?}", e);
break;
}
Err(_) => break,
}
} else if k == 1 {
// ── Delta d'un flat worker ────────────────────────────
// delta = N - 1 (N items poussés, 1 item consommé)
if let Ok(delta) = oper.recv(&flat_delta_rx) {
in_flight += delta;
flat_workers_active -= 1;
}
} else if src_idx == Some(k) {
// ── Nouvel item depuis la 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 {
// ── Résultat d'un stage intermédiaire ─────────────────
// 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,
}
}
}
}
drop(worker_tx);
drop(sink_tx);
for h in self.handles {
let _ = h.join();
}
}
}
-118
View File
@@ -1,118 +0,0 @@
use crossbeam_channel::{Receiver, Sender, bounded};
use std::thread;
use super::error::PipelineError;
use super::types::{SinkFn, SourceFn, Stage, WorkerTask};
// ── Thread runners ────────────────────────────────────────────────────────────
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)
}
/// Lance un thread worker du pool.
///
/// Gère deux types de tâches :
/// - `Transform` : applique `f(data)` et envoie le résultat dans `result_tx`.
/// - `Flat` : appelle `f(data, &push_tx, &delta_tx)` ; la fonction elle-même
/// pousse ses items dans `push_tx` et envoie `N-1` dans `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);
}
}
}
}
})
}
/// Lance le thread sink.
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);
break;
}
}
});
(data_tx, err_rx, handle)
}
/// Envoie `data` au stage `stage_idx`.
/// Pour un `Transform`, empile une `WorkerTask::Transform`.
/// Pour un `Flat`, incrémente `flat_workers_active` et empile une `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));
}
Stage::Flat(_) => {
*flat_workers_active += 1;
let _ = worker_tx.send(WorkerTask::Flat(data, stage_idx));
}
}
}
-49
View File
@@ -1,49 +0,0 @@
use crossbeam_channel::Sender;
use std::sync::Arc;
use super::error::PipelineError;
// ── Function types ────────────────────────────────────────────────────────────
/// Fonction source : appelée répétitivement, retourne le prochain item ou EndOfStream.
/// `FnMut` car elle maintient un état interne (position dans l'itérateur).
pub type SourceFn<D> = Box<dyn FnMut() -> Result<D, PipelineError> + Send>;
/// Fonction sink : consomme un item final, peut échouer (erreur d'I/O, etc.).
pub type SinkFn<D> = Box<dyn Fn(D) -> Result<(), PipelineError> + Send>;
/// Fonction de transformation partagée entre workers via Arc.
pub type SharedFn<D> = Arc<dyn Fn(D) -> Result<D, PipelineError> + Send + Sync>;
/// Fonction de transformation 1→N (flat map) partagée entre workers via Arc.
///
/// La fonction reçoit l'item d'entrée, un canal `push` pour envoyer chaque item
/// produit, et un canal `delta` pour signaler au scheduler combien d'items
/// supplémentaires sont entrés dans le pipeline (N-1 si N items produits).
/// Elle doit appeler `delta.send(N - 1)` **après** avoir poussé tous les items.
pub type SharedFlatFn<D> =
Arc<dyn Fn(D, &Sender<Result<D, PipelineError>>, &Sender<isize>) + Send + Sync>;
// ── Stage enum ────────────────────────────────────────────────────────────────
/// Une étape du pipeline : transform classique (1→1) ou flat transform (1→N).
pub enum Stage<D> {
Transform(SharedFn<D>),
Flat(SharedFlatFn<D>),
}
impl<D> Clone for Stage<D> {
fn clone(&self) -> Self {
match self {
Stage::Transform(f) => Stage::Transform(Arc::clone(f)),
Stage::Flat(f) => Stage::Flat(Arc::clone(f)),
}
}
}
// ── Worker task ───────────────────────────────────────────────────────────────
pub(super) enum WorkerTask<D> {
Transform(D, usize),
Flat(D, usize),
}
-106
View File
@@ -1,106 +0,0 @@
use std::sync::{Arc, Condvar, Mutex};
// ── Throttle ──────────────────────────────────────────────────────────────────
/// Counting semaphore: limits how many items from a source are in-flight
/// simultaneously through the Flat stage of a pipeline.
///
/// 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
/// inside a worker — only in the source thread — to prevent deadlocks.
pub struct Throttle {
count: Mutex<usize>,
condvar: Condvar,
max: usize,
}
impl Throttle {
pub fn new(max: usize) -> Self {
Self {
count: Mutex::new(0),
condvar: Condvar::new(),
max,
}
}
pub fn acquire(&self) {
let mut count = self.count.lock().unwrap();
while *count >= self.max {
count = self.condvar.wait(count).unwrap();
}
*count += 1;
}
fn release(&self) {
let mut count = self.count.lock().unwrap();
*count -= 1;
self.condvar.notify_one();
}
}
impl Throttle {
/// Acquire one slot and return a guard that releases it on drop —
/// for callers with no natural "source iterator" to wrap via
/// [`throttle`] (e.g. bounding concurrency inside a `rayon` parallel
/// iterator's own closure, one call per item, rather than up front in
/// a single source thread). Blocks the calling thread until a slot is
/// free, same as [`throttle`]'s own per-item acquisition.
pub fn acquire_guard(self: &Arc<Self>) -> ThrottleGuard {
self.acquire();
ThrottleGuard(Arc::clone(self))
}
}
// ── ThrottleGuard ─────────────────────────────────────────────────────────────
/// RAII guard: releases one slot in the `Throttle` when dropped.
pub struct ThrottleGuard(Arc<Throttle>);
impl Drop for ThrottleGuard {
fn drop(&mut self) {
self.0.release();
}
}
// ── Throttled<T> ──────────────────────────────────────────────────────────────
/// 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.
pub struct Throttled<T> {
pub item: T,
pub guard: ThrottleGuard,
}
// ── throttle() ────────────────────────────────────────────────────────────────
/// Wrap `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.
///
/// # 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.
/// ```
pub fn throttle<I>(source: I, max_concurrent: usize) -> impl Iterator<Item = Throttled<I::Item>>
where
I: Iterator,
I::Item: Send + 'static,
{
let t = Arc::new(Throttle::new(max_concurrent));
source.map(move |item| {
t.acquire();
Throttled {
item,
guard: ThrottleGuard(Arc::clone(&t)),
}
})
}
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "obiskim"
version = "1.4.9"
version = "1.4.10"
edition = "2024"
license = "CECILL-2.1"
repository = "https://forge.metabarcoding.org/obi/obiskim"
@@ -12,7 +12,7 @@ path = "src/main.rs"
[dependencies]
obikseq = { path = "../obikseq" }
obiread = { path = "../obiread" }
obipipeline = { path = "../obipipeline" }
obipipeline = { version = "0.2", registry = "obi" }
obisys = { path = "../obisys", default-features = false }
obikindex = { path = "../obikindex", default-features = false }
obikindexer = { path = "../obikindexer" }
+7 -7
View File
@@ -286,13 +286,12 @@ pub fn run(args: QueryArgs) {
let path_str = path.to_str().unwrap_or("").to_owned();
files_open.fetch_add(1, Ordering::Relaxed);
let open_start = Instant::now();
// Hard-exit on file-open failure (mirrors the previous behaviour):
// propagating this as a pipeline Err would hit a known scheduler
// hang on early stage errors (obipipeline::scheduler::WorkerPool::run
// breaks its main loop without unblocking the still-running source
// thread, so the final `h.join()` never returns) — worth fixing in
// obipipeline itself, but out of scope here; sidestepping it like the
// original code already did is the safe choice for this change.
// Hard-exit on file-open failure (mirrors the previous behaviour).
// The scheduler hang on early stage errors that once forbade
// returning a pipeline Err here is fixed in obipipeline (a stage
// error now stops the pipeline and comes out of the iterator as its
// last item); the hard exit is kept to preserve the message and exit
// code.
let iter = read_sequence_chunks_sized(&path_str, chunk_bytes).unwrap_or_else(|e| {
eprintln!("error opening {path_str}: {e}");
std::process::exit(1);
@@ -346,6 +345,7 @@ pub fn run(args: QueryArgs) {
let mut out = BufWriter::new(io::stdout());
for block in pipe.apply(path_source, n_workers, 2) {
let block = block.expect("pipeline error");
if !block.is_empty() {
out.write_all(&block).expect("write error");
}
+1
View File
@@ -65,6 +65,7 @@ pub fn run(args: SuperkmerArgs) {
let mut out = BufWriter::new(io::stdout());
for batch in pipe.apply(path_source, n_workers, 1) {
let batch = batch.expect("pipeline error");
write_batch(batch, &mut out, partition_bits, k, m).expect("write error");
}
out.flush().expect("flush error");
+23 -1
View File
@@ -268,7 +268,7 @@ impl UnitigFileReader {
/// through the `Arc` on every step; no data is duplicated up front.
pub fn iter_indexed_canonical_kmers_owned(
self: &Arc<Self>,
) -> impl Iterator<Item = (CanonicalKmer, usize, usize)> + Send + 'static {
) -> impl Iterator<Item = (CanonicalKmer, usize, usize)> + Send + 'static + use<> {
let this = Arc::clone(self);
let k = this.k;
let n = this.n_unitigs;
@@ -290,6 +290,28 @@ impl UnitigFileReader {
.map(move |(rank, kmer)| (kmer, chunk_id, rank))
})
}
/// The canonical k-mers of [`iter_indexed_canonical_kmers_owned`](Self::iter_indexed_canonical_kmers_owned),
/// without their positions, grouped in batches of `size` (the last one may be shorter). Lazy: a batch is
/// read when it is asked for, so a pipeline stage can return this iterator and stream a whole file.
///
/// # Panics
///
/// Panics if `size` is `0`.
pub fn iter_canonical_kmer_batches_owned(
self: &Arc<Self>,
size: usize,
) -> impl Iterator<Item = Vec<CanonicalKmer>> + Send + 'static + use<> {
assert!(size > 0, "a k-mer batch needs at least one slot");
let mut kmers = self
.iter_indexed_canonical_kmers_owned()
.map(|(kmer, _, _)| kmer);
std::iter::from_fn(move || {
let mut batch = Vec::with_capacity(size);
batch.extend(kmers.by_ref().take(size));
(!batch.is_empty()).then_some(batch)
})
}
}
/// Block offsets of a `.idx` file, read in place from its memory map: nothing