redup_bootstrap/telemetry/
histogram_config.rs1use std::collections::BTreeMap;
4
5use redup_config::{Config, Report};
6
7use crate::telemetry::buckets_by_unit::BucketsByUnit;
8use crate::telemetry::metrics::Unit;
9
10const MANY_BOUNDARIES: usize = 20;
12
13type Grid = Vec<f64>;
15
16#[derive(Debug, Clone, Default, Config)]
22#[config(validate)]
23pub struct HistogramConfig {
24 buckets_by_unit: BucketsByUnit,
26 buckets_by_substring: BTreeMap<String, Vec<f64>>,
29}
30
31impl HistogramConfig {
32 pub(crate) const DEFAULT: [f64; 15] = [
35 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,
36 7500.0, 10000.0,
37 ];
38
39 pub fn seconds(&self) -> &[f64] {
41 self.buckets_by_unit.seconds()
42 }
43
44 pub fn bytes(&self) -> &[u64] {
46 self.buckets_by_unit.bytes()
47 }
48
49 pub fn buckets_by_substring(&self) -> &BTreeMap<String, Vec<f64>> {
51 &self.buckets_by_substring
52 }
53
54 pub(crate) fn buckets_for(&self, name: &str, unit: Unit) -> Grid {
56 let normalized = normalize(name);
57 if let Some((_, buckets)) = self
58 .buckets_by_substring
59 .iter()
60 .filter(|(pattern, _)| !pattern.is_empty() && normalized.contains(&normalize(pattern)))
61 .max_by_key(|(pattern, _)| pattern.len())
62 {
63 return buckets.clone();
64 }
65 let by_unit = match unit {
66 Unit::Seconds => non_empty(self.seconds()),
67 Unit::Bytes => {
68 let bytes: Vec<f64> = self.bytes().iter().map(|bucket| *bucket as f64).collect();
69 non_empty(&bytes)
70 }
71 Unit::Count | Unit::Ratio => None,
72 };
73 by_unit.unwrap_or_else(|| Self::DEFAULT.to_vec())
74 }
75
76 fn validate(&self, report: &mut Report) {
77 checked("bucketsByUnit.seconds", self.seconds(), report);
78 let bytes: Vec<f64> = self.bytes().iter().map(|bucket| *bucket as f64).collect();
79 checked("bucketsByUnit.bytes", &bytes, report);
80 for (pattern, buckets) in &self.buckets_by_substring {
81 checked(&format!("bucketsBySubstring[{pattern}]"), buckets, report);
82 }
83 }
84}
85
86fn checked(field: &str, buckets: &[f64], report: &mut Report) {
89 if buckets.len() > MANY_BOUNDARIES {
90 report.warning(
91 field,
92 format!(
93 "{} boundaries, more than {MANY_BOUNDARIES}: many buckets multiply the number of \
94 series",
95 buckets.len()
96 ),
97 );
98 }
99 for (index, bucket) in buckets.iter().enumerate() {
100 if *bucket <= 0.0 {
101 report.error(
102 field,
103 format!("[{index}] = {bucket}: bucket boundaries must be positive"),
104 );
105 }
106 if index > 0 && *bucket <= buckets[index - 1] {
107 report.error(
108 field,
109 format!(
110 "[{index}] = {bucket}: bucket boundaries must be strictly increasing, but the \
111 previous one is {}",
112 buckets[index - 1]
113 ),
114 );
115 }
116 }
117}
118
119fn non_empty(buckets: &[f64]) -> Option<Grid> {
121 (!buckets.is_empty()).then(|| buckets.to_vec())
122}
123
124fn normalize(name: &str) -> String {
126 name.to_lowercase().replace('.', "_")
127}
128
129#[cfg(test)]
130mod tests {
131 use redup_config::{Source, load};
132
133 use super::HistogramConfig;
134 use crate::telemetry::metrics::Unit;
135
136 fn read(yaml: &str) -> HistogramConfig {
137 let directory = tempfile::tempdir().expect("a temporary directory");
138 std::fs::write(directory.path().join("config.yaml"), yaml).expect("the configuration file");
139 load::<HistogramConfig>(&Source::directory(directory.path()))
140 .expect("the configuration is accepted")
141 .value
142 }
143
144 #[test]
145 fn seconds_grid_is_taken_for_time() {
146 let buckets =
147 HistogramConfig::default().buckets_for("blobpacker_operation_duration", Unit::Seconds);
148 assert_eq!(buckets.first(), Some(&0.001));
149 assert_eq!(buckets.last(), Some(&1000.0));
150 assert_eq!(buckets.len(), 13);
151 }
152
153 #[test]
154 fn bytes_grid_is_taken_for_volume() {
155 let buckets = HistogramConfig::default().buckets_for("blobpacker_blob_size", Unit::Bytes);
156 assert_eq!(buckets.first(), Some(&1.0));
157 assert_eq!(buckets.last().copied(), Some((1u64 << 30) as f64));
158 assert_eq!(buckets.len(), 7);
159 }
160
161 #[test]
162 fn count_and_ratio_take_the_default_grid() {
163 let config = HistogramConfig::default();
164 assert_eq!(
165 config.buckets_for("blobpacker_batch_items", Unit::Count),
166 HistogramConfig::DEFAULT
167 );
168 assert_eq!(
169 config.buckets_for("blobpacker_pack_ratio", Unit::Ratio),
170 HistogramConfig::DEFAULT
171 );
172 }
173
174 #[test]
175 fn substring_wins_over_unit_and_longest_substring_wins() {
176 let config = read(
177 "histogram:\n\
178 \x20 bucketsBySubstring:\n\
179 \x20 ratio: [1, 2]\n\
180 \x20 pack.ratio: [1, 5, 25]\n\
181 \x20 duration: [0.5, 1]\n",
182 );
183 assert_eq!(
184 config.buckets_for("blobpacker_PACK_RATIO", Unit::Ratio),
185 vec![1.0, 5.0, 25.0]
186 );
187 assert_eq!(
188 config.buckets_for("service_cache_ratio", Unit::Ratio),
189 vec![1.0, 2.0]
190 );
191 assert_eq!(
192 config.buckets_for("service_stage_duration", Unit::Seconds),
193 vec![0.5, 1.0]
194 );
195 }
196
197 #[test]
198 fn empty_grid_falls_back_to_the_default_grid() {
199 let config = read("histogram:\n bucketsByUnit:\n seconds: []\n");
200 assert_eq!(
201 config.buckets_for("service_stage_duration", Unit::Seconds),
202 HistogramConfig::DEFAULT
203 );
204 }
205
206 #[test]
207 fn non_increasing_or_non_positive_boundaries_are_rejected() {
208 let directory = tempfile::tempdir().expect("a temporary directory");
209 std::fs::write(
210 directory.path().join("config.yaml"),
211 "histogram:\n bucketsByUnit:\n seconds: [0.1, 0.1, -1]\n",
212 )
213 .expect("the configuration file");
214 let source = Source::directory(directory.path());
215 let problems = load::<HistogramConfig>(&source).expect_err("the configuration is rejected");
216 let text = problems.to_string();
217 assert!(
218 text.contains("[1] = 0.1: bucket boundaries must be strictly increasing"),
219 "{text}"
220 );
221 assert!(
222 text.contains("[2] = -1: bucket boundaries must be positive"),
223 "{text}"
224 );
225 assert!(text.contains("seconds"), "{text}");
226 }
227
228 #[test]
229 fn many_boundaries_are_reported_as_a_warning() {
230 let boundaries: Vec<String> = (1..=21).map(|value| value.to_string()).collect();
231 let yaml = format!(
232 "histogram:\n bucketsBySubstring:\n wide: [{}]\n",
233 boundaries.join(", ")
234 );
235 let directory = tempfile::tempdir().expect("a temporary directory");
236 std::fs::write(directory.path().join("config.yaml"), yaml).expect("the configuration file");
237 let loaded = load::<HistogramConfig>(&Source::directory(directory.path()))
238 .expect("the configuration is accepted");
239 assert_eq!(loaded.warnings.len(), 1);
240 let warning = loaded.warnings[0].to_string();
241 assert!(warning.contains("21 boundaries"), "{warning}");
242 assert!(warning.contains("wide"), "{warning}");
243 }
244}