use std::borrow::Cow;
#[derive(Debug, Clone)]
pub struct ObservabilityConfig {
pub namespace: Cow<'static, str>,
pub histogram: HistogramConfig,
}
#[derive(Debug, Clone)]
pub struct HistogramConfig {
pub boundaries: Vec<f64>,
}
impl Default for HistogramConfig {
fn default() -> Self {
Self {
boundaries: vec![
0.001, 0.0025, 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0,
],
}
}
}
impl Default for ObservabilityConfig {
fn default() -> Self {
Self {
namespace: Cow::Borrowed("phantom"),
histogram: HistogramConfig::default(),
}
}
}
impl ObservabilityConfig {
pub fn from_env() -> Self {
let namespace = std::env::var("PHANTOM_TELEMETRY_NAMESPACE")
.ok()
.filter(|s| !s.is_empty())
.map(Cow::Owned)
.unwrap_or(Cow::Borrowed("phantom"));
Self {
namespace,
histogram: HistogramConfig::default(),
}
}
pub fn builder() -> ObservabilityConfigBuilder {
ObservabilityConfigBuilder::default()
}
}
#[derive(Debug, Default)]
pub struct ObservabilityConfigBuilder {
namespace: Option<Cow<'static, str>>,
histogram: Option<HistogramConfig>,
}
impl ObservabilityConfigBuilder {
pub fn namespace<S: Into<Cow<'static, str>>>(mut self, ns: S) -> Self {
self.namespace = Some(ns.into());
self
}
pub fn histogram(mut self, h: HistogramConfig) -> Self {
self.histogram = Some(h);
self
}
pub fn build(self) -> ObservabilityConfig {
let mut cfg = ObservabilityConfig::default();
if let Some(ns) = self.namespace {
cfg.namespace = ns;
}
if let Some(h) = self.histogram {
cfg.histogram = h;
}
cfg
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn default_namespace_is_phantom() {
let cfg = ObservabilityConfig::default();
assert_eq!(cfg.namespace.as_ref(), "phantom");
let b = &cfg.histogram.boundaries;
assert!(!b.is_empty());
assert!(b.windows(2).all(|w| w[0] < w[1]), "boundaries must ascend");
}
#[test]
fn builder_overrides_namespace() {
let cfg = ObservabilityConfig::builder().namespace("myapp").build();
assert_eq!(cfg.namespace.as_ref(), "myapp");
}
#[test]
fn builder_overrides_histogram() {
let cfg = ObservabilityConfig::builder()
.histogram(HistogramConfig {
boundaries: vec![0.001, 0.01, 0.1, 1.0],
})
.build();
assert_eq!(cfg.histogram.boundaries.len(), 4);
}
}