use serde::{Deserialize, Serialize};
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::LazyLock;
pub const HOST_PARALLELISM_VERSION: u16 = 1;
pub const FALLBACK_LOGICAL_CPUS: u32 = 1;
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum ParallelismProvenance {
Platform,
Configured,
Quota,
FallbackDefault,
}
impl ParallelismProvenance {
pub const ALL: [Self; 4] = [
Self::Platform,
Self::Configured,
Self::Quota,
Self::FallbackDefault,
];
}
impl ParallelismProvenance {
pub const fn as_str(self) -> &'static str {
match self {
Self::Platform => "platform",
Self::Configured => "configured",
Self::Quota => "quota",
Self::FallbackDefault => "fallback-default",
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct HostParallelism {
pub version: u16,
pub logical_cpus: u32,
pub provenance: ParallelismProvenance,
}
static OVERRIDE_PARALLELISM: AtomicU32 = AtomicU32::new(0);
static FORCED_FAILURE: AtomicU32 = AtomicU32::new(0);
static RESOLVED_PARALLELISM: LazyLock<HostParallelism> =
LazyLock::new(resolve_host_parallelism_internal);
fn resolve_host_parallelism_internal() -> HostParallelism {
if FORCED_FAILURE.load(Ordering::Relaxed) != 0 {
return HostParallelism {
version: HOST_PARALLELISM_VERSION,
logical_cpus: FALLBACK_LOGICAL_CPUS,
provenance: ParallelismProvenance::FallbackDefault,
};
}
match std::thread::available_parallelism() {
Ok(n) => HostParallelism {
version: HOST_PARALLELISM_VERSION,
logical_cpus: u32::try_from(n.get()).unwrap_or(u32::MAX),
provenance: ParallelismProvenance::Platform,
},
Err(_) => HostParallelism {
version: HOST_PARALLELISM_VERSION,
logical_cpus: FALLBACK_LOGICAL_CPUS,
provenance: ParallelismProvenance::FallbackDefault,
},
}
}
pub fn host_parallelism() -> HostParallelism {
let override_val = OVERRIDE_PARALLELISM.load(Ordering::Relaxed);
if override_val > 0 {
return HostParallelism {
version: HOST_PARALLELISM_VERSION,
logical_cpus: override_val,
provenance: ParallelismProvenance::Configured,
};
}
if FORCED_FAILURE.load(Ordering::Relaxed) != 0 {
return HostParallelism {
version: HOST_PARALLELISM_VERSION,
logical_cpus: FALLBACK_LOGICAL_CPUS,
provenance: ParallelismProvenance::FallbackDefault,
};
}
*RESOLVED_PARALLELISM
}
#[inline]
pub fn logical_cpus() -> u32 {
host_parallelism().logical_cpus
}
#[inline]
pub fn logical_cpu_count() -> usize {
host_parallelism().logical_cpus as usize
}
pub fn set_host_parallelism_override(width: u32) {
OVERRIDE_PARALLELISM.store(width, Ordering::SeqCst);
}
pub fn clear_host_parallelism_override() {
OVERRIDE_PARALLELISM.store(0, Ordering::SeqCst);
}
pub fn set_forced_probe_failure(forced: bool) {
FORCED_FAILURE.store(if forced { 1 } else { 0 }, Ordering::SeqCst);
}