1use std::mem;
6use std::sync::Arc;
7
8use crate::common_metric_data::{CommonMetricDataInternal, MetricLabel};
9use crate::error_recording::{record_error, test_get_num_recorded_errors, ErrorType};
10use crate::histogram::{Bucketing, Histogram, HistogramType, LinearOrExponential};
11use crate::metrics::{DistributionData, Metric, MetricType};
12use crate::Glean;
13use crate::{CommonMetricData, TestGetValue};
14
15#[derive(Clone, Debug)]
17pub struct CustomDistributionMetric {
18 meta: Arc<CommonMetricDataInternal>,
19 range_min: u64,
20 range_max: u64,
21 bucket_count: u64,
22 histogram_type: HistogramType,
23}
24
25pub(crate) fn snapshot<B: Bucketing>(hist: &Histogram<B>) -> DistributionData {
29 DistributionData {
30 values: hist
31 .snapshot_values()
32 .into_iter()
33 .map(|(k, v)| (k as i64, v as i64))
34 .collect(),
35 sum: hist.sum() as i64,
36 count: hist.count() as i64,
37 }
38}
39
40impl MetricType for CustomDistributionMetric {
41 fn meta(&self) -> &CommonMetricDataInternal {
42 &self.meta
43 }
44
45 fn with_name(&self, name: String) -> Self {
46 let mut meta = (*self.meta).clone();
47 meta.inner.name = name;
48 Self {
49 meta: Arc::new(meta),
50 range_min: self.range_min,
51 range_max: self.range_max,
52 bucket_count: self.bucket_count,
53 histogram_type: self.histogram_type,
54 }
55 }
56
57 fn with_label(&self, label: MetricLabel) -> Self {
58 let mut meta = (*self.meta).clone();
59 meta.inner.label = Some(label);
60 Self {
61 meta: Arc::new(meta),
62 range_min: self.range_min,
63 range_max: self.range_max,
64 bucket_count: self.bucket_count,
65 histogram_type: self.histogram_type,
66 }
67 }
68}
69
70impl CustomDistributionMetric {
75 pub fn new(
77 meta: CommonMetricData,
78 range_min: i64,
79 range_max: i64,
80 bucket_count: i64,
81 histogram_type: HistogramType,
82 ) -> Self {
83 Self {
84 meta: Arc::new(meta.into()),
85 range_min: range_min as u64,
86 range_max: range_max as u64,
87 bucket_count: bucket_count as u64,
88 histogram_type,
89 }
90 }
91
92 pub fn accumulate_samples(&self, samples: Vec<i64>) {
108 let metric = self.clone();
109 crate::launch_with_glean(move |glean| metric.accumulate_samples_sync(glean, &samples))
110 }
111
112 pub fn accumulate_single_sample(&self, sample: i64) {
127 let metric = self.clone();
128 crate::launch_with_glean(move |glean| metric.accumulate_samples_sync(glean, &[sample]))
129 }
130
131 #[doc(hidden)]
135 pub fn accumulate_samples_sync(&self, glean: &Glean, samples: &[i64]) {
136 if !self.should_record(glean) {
137 return;
138 }
139
140 let mut num_negative_samples = 0;
141
142 fn accumulate<B: Bucketing, F>(
145 samples: &[i64],
146 mut hist: Histogram<B>,
147 metric: F,
148 ) -> (i32, Metric)
149 where
150 F: Fn(Histogram<B>) -> Metric,
151 {
152 let mut num_negative_samples = 0;
153 for &sample in samples.iter() {
154 if sample < 0 {
155 num_negative_samples += 1;
156 } else {
157 let sample = sample as u64;
158 hist.accumulate(sample);
159 }
160 }
161 (num_negative_samples, metric(hist))
162 }
163
164 glean.storage().record_with(glean, &self.meta, |old_value| {
165 let (num_negative, hist) = match self.histogram_type {
166 HistogramType::Linear => {
167 let hist = if let Some(Metric::CustomDistributionLinear(hist)) = old_value {
168 hist
169 } else {
170 Histogram::linear(
171 self.range_min,
172 self.range_max,
173 self.bucket_count as usize,
174 )
175 };
176 accumulate(samples, hist, Metric::CustomDistributionLinear)
177 }
178 HistogramType::Exponential => {
179 let hist = if let Some(Metric::CustomDistributionExponential(hist)) = old_value
180 {
181 hist
182 } else {
183 Histogram::exponential(
184 self.range_min,
185 self.range_max,
186 self.bucket_count as usize,
187 )
188 };
189 accumulate(samples, hist, Metric::CustomDistributionExponential)
190 }
191 };
192
193 num_negative_samples = num_negative;
194 hist
195 });
196
197 if num_negative_samples > 0 {
198 let msg = format!("Accumulated {} negative samples", num_negative_samples);
199 record_error(
200 glean,
201 &self.meta,
202 ErrorType::InvalidValue,
203 msg,
204 num_negative_samples,
205 );
206 }
207 }
208
209 #[doc(hidden)]
211 pub fn get_value<'a, S: Into<Option<&'a str>>>(
212 &self,
213 glean: &Glean,
214 ping_name: S,
215 ) -> Option<DistributionData> {
216 let queried_ping_name = ping_name
217 .into()
218 .unwrap_or_else(|| &self.meta().inner.send_in_pings[0]);
219
220 match glean.storage().get_metric(self.meta(), queried_ping_name) {
221 Some(Metric::CustomDistributionExponential(hist)) => Some(snapshot(&hist)),
222 Some(Metric::CustomDistributionLinear(hist)) => Some(snapshot(&hist)),
223 _ => None,
224 }
225 }
226
227 pub fn test_get_num_recorded_errors(&self, error: ErrorType) -> i32 {
239 crate::block_on_dispatcher();
240
241 crate::core::with_glean(|glean| {
242 test_get_num_recorded_errors(glean, self.meta(), error).unwrap_or(0)
243 })
244 }
245
246 pub fn start_buffer(&self) -> LocalCustomDistribution<'_> {
251 LocalCustomDistribution::new(self)
252 }
253
254 fn commit_histogram(&self, histogram: Histogram<LinearOrExponential>) {
255 let metric = self.clone();
256 crate::launch_with_glean(move |glean| {
257 glean
258 .storage()
259 .record_with(glean, &metric.meta, move |old_value| {
260 match metric.histogram_type {
261 HistogramType::Linear => {
262 let mut hist =
263 if let Some(Metric::CustomDistributionLinear(hist)) = old_value {
264 hist
265 } else {
266 Histogram::linear(
267 metric.range_min,
268 metric.range_max,
269 metric.bucket_count as usize,
270 )
271 };
272
273 hist._merge(&histogram);
274 Metric::CustomDistributionLinear(hist)
275 }
276 HistogramType::Exponential => {
277 let mut hist = if let Some(Metric::CustomDistributionExponential(
278 hist,
279 )) = old_value
280 {
281 hist
282 } else {
283 Histogram::exponential(
284 metric.range_min,
285 metric.range_max,
286 metric.bucket_count as usize,
287 )
288 };
289
290 hist._merge(&histogram);
291 Metric::CustomDistributionExponential(hist)
292 }
293 }
294 });
295 });
296 }
297}
298
299impl TestGetValue for CustomDistributionMetric {
300 type Output = DistributionData;
301
302 fn test_get_value(&self, ping_name: Option<String>) -> Option<DistributionData> {
317 crate::block_on_dispatcher();
318 crate::core::with_glean(|glean| self.get_value(glean, ping_name.as_deref()))
319 }
320}
321
322pub struct LocalCustomDistribution<'a> {
327 histogram: Histogram<LinearOrExponential>,
328 metric: &'a CustomDistributionMetric,
329}
330
331impl<'a> LocalCustomDistribution<'a> {
332 fn new(metric: &'a CustomDistributionMetric) -> Self {
334 let histogram = match metric.histogram_type {
335 HistogramType::Linear => Histogram::<LinearOrExponential>::_linear(
336 metric.range_min,
337 metric.range_max,
338 metric.bucket_count as usize,
339 ),
340 HistogramType::Exponential => Histogram::<LinearOrExponential>::_exponential(
341 metric.range_min,
342 metric.range_max,
343 metric.bucket_count as usize,
344 ),
345 };
346 Self { histogram, metric }
347 }
348
349 pub fn accumulate(&mut self, sample: u64) {
357 self.histogram.accumulate(sample)
358 }
359
360 pub fn abandon(mut self) {
362 self.histogram.clear();
363 }
364}
365
366impl Drop for LocalCustomDistribution<'_> {
367 fn drop(&mut self) {
368 if self.histogram.is_empty() {
369 return;
370 }
371
372 let empty = Histogram::_linear(0, 0, 0);
375 let buffer = mem::replace(&mut self.histogram, empty);
376 self.metric.commit_histogram(buffer);
377 }
378}