use nmbrs_metrics::controls::{BranchScope, Control, ControlBuilder};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ControlValueType {
Count,
Rate,
Fraction,
Frequency,
}
impl ControlValueType {
pub fn label(self) -> &'static str {
match self {
ControlValueType::Count => "count(u32)",
ControlValueType::Rate => "rate(ops/s)",
ControlValueType::Fraction => "fraction",
ControlValueType::Frequency => "freq(hz)",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DeclaredWhen {
Always,
PhaseField(&'static str),
AdapterActive(&'static str),
Driver(&'static str),
}
impl std::fmt::Display for DeclaredWhen {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
DeclaredWhen::Always => write!(f, "always"),
DeclaredWhen::PhaseField(field) => write!(f, "when a phase sets `{field}:`"),
DeclaredWhen::AdapterActive(name) => write!(f, "when the `{name}` adapter is active"),
DeclaredWhen::Driver(driver) => write!(f, "when the `{driver}` driver is active"),
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct ControlDesc {
pub name: &'static str,
pub value_type: ControlValueType,
pub default: f64,
pub min: f64,
pub max: f64,
pub unit: &'static str,
pub doc: &'static str,
pub declared_when: DeclaredWhen,
}
impl ControlDesc {
pub fn build_u32(&self, initial: u32) -> Control<u32> {
debug_assert_eq!(
self.value_type,
ControlValueType::Count,
"{} is not a Count control",
self.name
);
let (name, min, max) = (self.name, self.min, self.max);
ControlBuilder::new(name, initial)
.reify_as_gauge(|v: &u32| Some(*v as f64))
.from_f64(move |v| {
if !v.is_finite() || !(min..=max).contains(&v) {
Err(format!("{name} out of range [{min}, {max}]: got {v}"))
} else {
Ok(v as u32)
}
})
.branch_scope(BranchScope::Local)
.build()
}
pub fn build_f64(&self, initial: f64) -> Control<f64> {
debug_assert!(
matches!(
self.value_type,
ControlValueType::Fraction | ControlValueType::Frequency
),
"{} is not an f64-shaped control",
self.name
);
let (name, min, max) = (self.name, self.min, self.max);
ControlBuilder::new(name, initial)
.reify_as_gauge(|v: &f64| Some(*v))
.from_f64(move |v| {
if !v.is_finite() || !(min..=max).contains(&v) {
Err(format!("{name} must be in [{min}, {max}]: got {v}"))
} else {
Ok(v)
}
})
.branch_scope(BranchScope::Local)
.build()
}
pub fn build_rate(&self, initial_ops_per_sec: f64) -> Control<nmbrs_rate::RateSpec> {
debug_assert_eq!(
self.value_type,
ControlValueType::Rate,
"{} is not a Rate control",
self.name
);
let name = self.name;
ControlBuilder::new(name, nmbrs_rate::RateSpec::new(initial_ops_per_sec))
.reify_as_gauge(|spec: &nmbrs_rate::RateSpec| Some(spec.ops_per_sec))
.from_f64(move |v| {
if v <= 0.0 {
Err(format!("{name} must be > 0, got {v}"))
} else {
Ok(nmbrs_rate::RateSpec::new(v))
}
})
.branch_scope(BranchScope::Local)
.build()
}
}
pub const CONCURRENCY: ControlDesc = ControlDesc {
name: "concurrency",
value_type: ControlValueType::Count,
default: 1.0,
min: 1.0,
max: 100_000.0,
unit: "fibers",
doc: "Concurrent fibers the executor maintains; re-balanced live on every change.",
declared_when: DeclaredWhen::Always,
};
pub const RATE: ControlDesc = ControlDesc {
name: "rate",
value_type: ControlValueType::Rate,
default: 0.0,
min: 0.0,
max: f64::INFINITY,
unit: "ops/sec",
doc: "Target cycle rate (ops/sec) enforced by the rate limiter.",
declared_when: DeclaredWhen::PhaseField("rate"),
};
pub const RETRY_EXEMPLAR_RATE: ControlDesc = ControlDesc {
name: "retry_exemplar_rate",
value_type: ControlValueType::Fraction,
default: 0.0,
min: 0.0,
max: 1.0,
unit: "probability",
doc: "Fraction of retried op errors sampled to the session log as counter-exemplars (0 = off, 1 = all); moves every op without a pinned retry_exemplar_* param.",
declared_when: DeclaredWhen::Always,
};
pub const RETRY_EXEMPLAR_MAX_HZ: ControlDesc = ControlDesc {
name: "retry_exemplar_max_hz",
value_type: ControlValueType::Frequency,
default: 5.0,
min: 0.0,
max: 1_000_000.0,
unit: "events/sec",
doc: "Ceiling on retry-exemplar emissions per second; excess is squelched and counted, never silent. 0 = uncapped.",
declared_when: DeclaredWhen::Always,
};
pub fn core_controls() -> &'static [ControlDesc] {
const CORE: &[ControlDesc] = &[
CONCURRENCY,
RATE,
RETRY_EXEMPLAR_RATE,
RETRY_EXEMPLAR_MAX_HZ,
];
CORE
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ControlOwner {
Core,
Adapter(String),
}
impl std::fmt::Display for ControlOwner {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ControlOwner::Core => write!(f, "core"),
ControlOwner::Adapter(name) => write!(f, "adapter:{name}"),
}
}
}
pub struct ControlEntry {
pub desc: &'static ControlDesc,
pub owner: ControlOwner,
}
pub fn all_controls() -> Vec<ControlEntry> {
let mut out: Vec<ControlEntry> = core_controls()
.iter()
.map(|d| ControlEntry {
desc: d,
owner: ControlOwner::Core,
})
.collect();
for reg in inventory::iter::<crate::adapter::AdapterRegistration> {
let owner_name = (reg.names)().first().copied().unwrap_or("?");
for d in (reg.supported_controls)() {
out.push(ControlEntry {
desc: d,
owner: ControlOwner::Adapter(owner_name.to_string()),
});
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use nmbrs_metrics::controls::ControlOrigin;
#[test]
fn core_controls_cover_concurrency_and_rate_with_conditions() {
let core = core_controls();
let conc = core
.iter()
.find(|d| d.name == "concurrency")
.expect("concurrency present");
let rate = core
.iter()
.find(|d| d.name == "rate")
.expect("rate present");
assert_eq!(conc.declared_when, DeclaredWhen::Always);
assert_eq!(rate.declared_when, DeclaredWhen::PhaseField("rate"));
assert_eq!(conc.value_type, ControlValueType::Count);
assert_eq!(rate.value_type, ControlValueType::Rate);
}
#[tokio::test]
async fn build_u32_derives_name_and_range_from_descriptor() {
use nmbrs_metrics::controls::ErasedControl;
let ctl = CONCURRENCY.build_u32(8);
assert_eq!(ctl.name(), "concurrency");
assert_eq!(ctl.value(), 8);
assert!(ctl.set_f64(16.0, ControlOrigin::Launch).await.is_ok());
assert_eq!(ctl.value(), 16);
assert!(ctl.set_f64(0.0, ControlOrigin::Launch).await.is_err());
}
#[tokio::test]
async fn build_rate_rejects_non_positive() {
use nmbrs_metrics::controls::ErasedControl;
let ctl = RATE.build_rate(1000.0);
assert_eq!(ctl.name(), "rate");
assert!(ctl.set_f64(500.0, ControlOrigin::Launch).await.is_ok());
assert!(ctl.set_f64(0.0, ControlOrigin::Launch).await.is_err());
}
#[test]
fn all_controls_includes_core_and_is_owner_tagged() {
let all = all_controls();
let conc = all
.iter()
.find(|e| e.desc.name == "concurrency")
.expect("concurrency enumerated");
assert_eq!(conc.owner, ControlOwner::Core);
}
}