use std::collections::BTreeMap;
use redup_config::{Config, Report};
use crate::telemetry::buckets_by_unit::BucketsByUnit;
use crate::telemetry::metrics::Unit;
const MANY_BOUNDARIES: usize = 20;
type Grid = Vec<f64>;
#[derive(Debug, Clone, Default, Config)]
#[config(validate)]
pub struct HistogramConfig {
buckets_by_unit: BucketsByUnit,
buckets_by_substring: BTreeMap<String, Vec<f64>>,
}
impl HistogramConfig {
pub(crate) const DEFAULT: [f64; 15] = [
0.0, 5.0, 10.0, 25.0, 50.0, 75.0, 100.0, 250.0, 500.0, 750.0, 1000.0, 2500.0, 5000.0,
7500.0, 10000.0,
];
pub fn seconds(&self) -> &[f64] {
self.buckets_by_unit.seconds()
}
pub fn bytes(&self) -> &[u64] {
self.buckets_by_unit.bytes()
}
pub fn buckets_by_substring(&self) -> &BTreeMap<String, Vec<f64>> {
&self.buckets_by_substring
}
pub(crate) fn buckets_for(&self, name: &str, unit: Unit) -> Grid {
let normalized = normalize(name);
if let Some((_, buckets)) = self
.buckets_by_substring
.iter()
.filter(|(pattern, _)| !pattern.is_empty() && normalized.contains(&normalize(pattern)))
.max_by_key(|(pattern, _)| pattern.len())
{
return buckets.clone();
}
let by_unit = match unit {
Unit::Seconds => non_empty(self.seconds()),
Unit::Bytes => {
let bytes: Vec<f64> = self.bytes().iter().map(|bucket| *bucket as f64).collect();
non_empty(&bytes)
}
Unit::Count | Unit::Ratio => None,
};
by_unit.unwrap_or_else(|| Self::DEFAULT.to_vec())
}
fn validate(&self, report: &mut Report) {
checked("bucketsByUnit.seconds", self.seconds(), report);
let bytes: Vec<f64> = self.bytes().iter().map(|bucket| *bucket as f64).collect();
checked("bucketsByUnit.bytes", &bytes, report);
for (pattern, buckets) in &self.buckets_by_substring {
checked(&format!("bucketsBySubstring[{pattern}]"), buckets, report);
}
}
}
fn checked(field: &str, buckets: &[f64], report: &mut Report) {
if buckets.len() > MANY_BOUNDARIES {
report.warning(
field,
format!(
"{} boundaries, more than {MANY_BOUNDARIES}: many buckets multiply the number of \
series",
buckets.len()
),
);
}
for (index, bucket) in buckets.iter().enumerate() {
if *bucket <= 0.0 {
report.error(
field,
format!("[{index}] = {bucket}: bucket boundaries must be positive"),
);
}
if index > 0 && *bucket <= buckets[index - 1] {
report.error(
field,
format!(
"[{index}] = {bucket}: bucket boundaries must be strictly increasing, but the \
previous one is {}",
buckets[index - 1]
),
);
}
}
}
fn non_empty(buckets: &[f64]) -> Option<Grid> {
(!buckets.is_empty()).then(|| buckets.to_vec())
}
fn normalize(name: &str) -> String {
name.to_lowercase().replace('.', "_")
}
#[cfg(test)]
mod tests {
use redup_config::{Source, load};
use super::HistogramConfig;
use crate::telemetry::metrics::Unit;
fn read(yaml: &str) -> HistogramConfig {
let directory = tempfile::tempdir().expect("a temporary directory");
std::fs::write(directory.path().join("config.yaml"), yaml).expect("the configuration file");
load::<HistogramConfig>(&Source::directory(directory.path()))
.expect("the configuration is accepted")
.value
}
#[test]
fn seconds_grid_is_taken_for_time() {
let buckets =
HistogramConfig::default().buckets_for("blobpacker_operation_duration", Unit::Seconds);
assert_eq!(buckets.first(), Some(&0.001));
assert_eq!(buckets.last(), Some(&1000.0));
assert_eq!(buckets.len(), 13);
}
#[test]
fn bytes_grid_is_taken_for_volume() {
let buckets = HistogramConfig::default().buckets_for("blobpacker_blob_size", Unit::Bytes);
assert_eq!(buckets.first(), Some(&1.0));
assert_eq!(buckets.last().copied(), Some((1u64 << 30) as f64));
assert_eq!(buckets.len(), 7);
}
#[test]
fn count_and_ratio_take_the_default_grid() {
let config = HistogramConfig::default();
assert_eq!(
config.buckets_for("blobpacker_batch_items", Unit::Count),
HistogramConfig::DEFAULT
);
assert_eq!(
config.buckets_for("blobpacker_pack_ratio", Unit::Ratio),
HistogramConfig::DEFAULT
);
}
#[test]
fn substring_wins_over_unit_and_longest_substring_wins() {
let config = read(
"histogram:\n\
\x20 bucketsBySubstring:\n\
\x20 ratio: [1, 2]\n\
\x20 pack.ratio: [1, 5, 25]\n\
\x20 duration: [0.5, 1]\n",
);
assert_eq!(
config.buckets_for("blobpacker_PACK_RATIO", Unit::Ratio),
vec![1.0, 5.0, 25.0]
);
assert_eq!(
config.buckets_for("service_cache_ratio", Unit::Ratio),
vec![1.0, 2.0]
);
assert_eq!(
config.buckets_for("service_stage_duration", Unit::Seconds),
vec![0.5, 1.0]
);
}
#[test]
fn empty_grid_falls_back_to_the_default_grid() {
let config = read("histogram:\n bucketsByUnit:\n seconds: []\n");
assert_eq!(
config.buckets_for("service_stage_duration", Unit::Seconds),
HistogramConfig::DEFAULT
);
}
#[test]
fn non_increasing_or_non_positive_boundaries_are_rejected() {
let directory = tempfile::tempdir().expect("a temporary directory");
std::fs::write(
directory.path().join("config.yaml"),
"histogram:\n bucketsByUnit:\n seconds: [0.1, 0.1, -1]\n",
)
.expect("the configuration file");
let source = Source::directory(directory.path());
let problems = load::<HistogramConfig>(&source).expect_err("the configuration is rejected");
let text = problems.to_string();
assert!(
text.contains("[1] = 0.1: bucket boundaries must be strictly increasing"),
"{text}"
);
assert!(
text.contains("[2] = -1: bucket boundaries must be positive"),
"{text}"
);
assert!(text.contains("seconds"), "{text}");
}
#[test]
fn many_boundaries_are_reported_as_a_warning() {
let boundaries: Vec<String> = (1..=21).map(|value| value.to_string()).collect();
let yaml = format!(
"histogram:\n bucketsBySubstring:\n wide: [{}]\n",
boundaries.join(", ")
);
let directory = tempfile::tempdir().expect("a temporary directory");
std::fs::write(directory.path().join("config.yaml"), yaml).expect("the configuration file");
let loaded = load::<HistogramConfig>(&Source::directory(directory.path()))
.expect("the configuration is accepted");
assert_eq!(loaded.warnings.len(), 1);
let warning = loaded.warnings[0].to_string();
assert!(warning.contains("21 boundaries"), "{warning}");
assert!(warning.contains("wide"), "{warning}");
}
}