#![warn(missing_docs)]
use std::process::ExitCode;
use clap::Parser;
use tracing::error;
mod cli;
mod commands;
mod config_merge;
mod control;
mod idle;
mod logging;
mod metrics_reporter;
mod persist;
mod preset;
mod runtime;
mod runtime_metrics;
mod thread_cpu;
fn main() -> ExitCode {
let args = cli::Cli::parse();
if let Err(e) = logging::init(args.verbose) {
eprintln!("failed to initialise logging: {e}");
return ExitCode::from(2);
}
cap_rayon_pool();
match commands::dispatch(args) {
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
use fluxframe_core::Diagnostic;
if !e.is_aggregated() {
eprintln!("Error: {}", e.reason());
if let Some(hint) = e.hint() {
eprintln!("Hint: {hint}");
}
}
error!(error = %e, "command failed");
ExitCode::FAILURE
}
}
}
const RAYON_RESERVE_CORES: usize = 2;
const RAYON_MIN_THREADS: usize = 2;
const RAYON_MAX_THREADS: usize = 4;
fn compute_rayon_target(env_override: Option<&str>, available: usize) -> usize {
env_override
.and_then(|s| s.parse::<usize>().ok())
.filter(|n| *n > 0)
.unwrap_or_else(|| {
available
.saturating_sub(RAYON_RESERVE_CORES)
.clamp(RAYON_MIN_THREADS, RAYON_MAX_THREADS)
})
}
fn cap_rayon_pool() {
let env_value = std::env::var("FLUXFRAME_RAYON_THREADS").ok();
let available = std::thread::available_parallelism()
.map(std::num::NonZeroUsize::get)
.unwrap_or(RAYON_MIN_THREADS);
let target = compute_rayon_target(env_value.as_deref(), available);
match rayon::ThreadPoolBuilder::new()
.num_threads(target)
.thread_name(|i| format!("rayon-{i}"))
.build_global()
{
Ok(()) => {
tracing::debug!(threads = target, "rayon global pool capped");
}
Err(e) => {
tracing::debug!(error = %e, "rayon pool already initialised; cap not applied");
}
}
}
#[cfg(test)]
mod tests {
use super::compute_rayon_target;
#[test]
fn auto_path_caps_at_max_on_large_box() {
assert_eq!(compute_rayon_target(None, 22), 4);
}
#[test]
fn auto_path_clamps_to_floor_on_small_box() {
assert_eq!(compute_rayon_target(None, 3), 2);
}
#[test]
fn auto_path_handles_tiny_box_via_saturating_sub() {
assert_eq!(compute_rayon_target(None, 1), 2);
}
#[test]
fn env_override_positive_wins_over_cap() {
assert_eq!(compute_rayon_target(Some("8"), 22), 8);
}
#[test]
fn env_override_zero_is_ignored() {
assert_eq!(compute_rayon_target(Some("0"), 22), 4);
}
#[test]
fn env_override_non_numeric_is_ignored() {
assert_eq!(compute_rayon_target(Some("abc"), 22), 4);
}
#[test]
fn env_override_empty_is_ignored() {
assert_eq!(compute_rayon_target(Some(""), 22), 4);
}
#[test]
fn env_override_negative_is_ignored() {
assert_eq!(compute_rayon_target(Some("-1"), 22), 4);
}
}