Files
obiskim/src/obikmer/src/cli.rs
T
Eric Coissac 9e60a711bc Enforce minimum input paths and handle stdin sentinel
Update CLI validation to require at least 10 input paths, defaulting to stdin (`-`) when the argument list is empty. Refactor the path iterator to explicitly recognize the stdin sentinel, bypassing extension validation and directory expansion to ensure direct passthrough to the file buffer without triggering `stat()` or recursive traversal.
2026-05-26 15:22:38 +02:00

166 lines
5.2 KiB
Rust

use std::io;
use std::path::PathBuf;
use std::sync::{Arc, Condvar, Mutex};
use clap::Args;
use obikrope::Rope;
use obikseq::RoutableSuperKmer;
// ── Shared arguments ──────────────────────────────────────────────────────────
#[derive(Args)]
pub struct CommonArgs {
/// Input files or directories (FASTA/FASTQ, optionally gzip-compressed).
/// If omitted, reads from stdin.
#[arg(num_args = 0..)]
pub inputs: Vec<String>,
/// k-mer size
#[arg(short, long, default_value_t = 31)]
pub kmer_size: usize,
/// Minimizer size
#[arg(short, long, default_value_t = 11)]
pub minimizer_size: usize,
/// Entropy threshold (k-mers with score ≤ theta are rejected)
#[arg(long, default_value_t = 0.7)]
pub theta: f64,
/// Maximum sub-word size for entropy computation
#[arg(long, default_value_t = 6)]
pub level_max: usize,
/// Number of partitions (rounded up to the next power of 2)
#[arg(short, long, default_value_t = 256)]
pub partitions: usize,
/// Number of worker threads
#[arg(
short = 'T',
long,
default_value_t = std::thread::available_parallelism()
.map(|n| n.get())
.unwrap_or(1)
)]
pub threads: usize,
/// Maximum number of input files open simultaneously
#[arg(long, default_value_t = 20)]
pub max_open_files: usize,
}
/// Smallest `b` such that `2^b >= n` (i.e. `n.next_power_of_two().ilog2()`).
/// Minimum 1 (degenerate n=0 or n=1 → 1 partition).
pub fn partitions_to_bits(n: usize) -> usize {
n.max(1).next_power_of_two().trailing_zeros() as usize
}
/// Convert a block size (number of unitigs per block) to its `block_bits` exponent.
/// `block_size=1` → `block_bits=0` (one entry per unitig, O(1) random access).
pub fn block_size_to_bits(n: usize) -> u8 {
n.max(1).next_power_of_two().trailing_zeros() as u8
}
impl CommonArgs {
pub fn seqfile_paths(&self) -> obiread::PathIter {
let paths: Vec<PathBuf> = if self.inputs.is_empty() {
vec![PathBuf::from("-")]
} else {
self.inputs.iter().map(PathBuf::from).collect()
};
obiread::PathIter::new(paths)
}
}
// ── Open-file throttling ──────────────────────────────────────────────────────
struct FileSlots {
count: Mutex<usize>,
condvar: Condvar,
max: usize,
}
impl FileSlots {
fn new(max: usize) -> Self {
Self { count: Mutex::new(0), condvar: Condvar::new(), max }
}
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();
}
}
struct SlotsGuard(Arc<FileSlots>);
impl Drop for SlotsGuard {
fn drop(&mut self) {
self.0.release();
}
}
// ── Pipeline data carrier ─────────────────────────────────────────────────────
/// A path bundled with an opaque guard token.
/// The guard is acquired in the source thread and dropped by the flat worker
/// once the file is fully read, releasing the open-file slot.
pub struct PathWithSlot {
pub path: PathBuf,
pub _guard: Box<dyn Send + 'static>,
}
pub enum PipelineData {
Path(PathWithSlot),
RawChunk(Rope),
NormChunk(Rope),
Batch(Vec<RoutableSuperKmer>),
}
// SAFETY: Rope contains Cell<u8> which is !Sync, but pipeline ownership transfers
// exclusively through channels — no item is ever shared across threads.
unsafe impl Send for PipelineData {}
unsafe impl Sync for PipelineData {}
/// Wrap a path iterator so that at most `max_open` files are open simultaneously.
/// Acquisition happens in the caller's thread (the pipeline source thread),
/// never inside a worker, preventing deadlocks.
pub fn throttle_paths(
source: impl Iterator<Item = PathBuf> + Send + 'static,
max_open: usize,
) -> impl Iterator<Item = PathWithSlot> + Send + 'static {
let slots = Arc::new(FileSlots::new(max_open));
source.map(move |path| {
slots.acquire();
PathWithSlot {
path,
_guard: Box::new(SlotsGuard(Arc::clone(&slots))),
}
})
}
// ── I/O plumbing ──────────────────────────────────────────────────────────────
pub fn open_chunks(path: PathBuf) -> io::Result<impl Iterator<Item = Rope>> {
let path_str = path
.to_str()
.ok_or_else(|| io::Error::new(io::ErrorKind::InvalidInput, "non-UTF-8 path"))?;
let iter = obiread::read_sequence_chunks(path_str)?;
Ok(iter.filter_map(|r| match r {
Ok(rope) => Some(rope),
Err(e) => {
eprintln!("chunk read error: {e}");
None
}
}))
}