Skip to main content

glean_core/metrics/
custom_distribution.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5use 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/// A custom distribution metric.
16#[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
25/// Create a snapshot of the histogram.
26///
27/// The snapshot can be serialized into the payload format.
28pub(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
70// IMPORTANT:
71//
72// When changing this implementation, make sure all the operations are
73// also declared in the related trait in `../traits/`.
74impl CustomDistributionMetric {
75    /// Creates a new memory distribution metric.
76    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    /// Accumulates the provided signed samples in the metric.
93    ///
94    /// This is required so that the platform-specific code can provide us with
95    /// 64 bit signed integers if no `u64` comparable type is available. This
96    /// will take care of filtering and reporting errors for any provided negative
97    /// sample.
98    ///
99    /// # Arguments
100    ///
101    /// - `samples` - The vector holding the samples to be recorded by the metric.
102    ///
103    /// ## Notes
104    ///
105    /// Discards any negative value in `samples` and report an [`ErrorType::InvalidValue`]
106    /// for each of them.
107    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    /// Accumulates precisely one signed sample and appends it to the metric.
113    ///
114    /// Signed is required so that the platform-specific code can provide us with a
115    /// 64 bit signed integer if no `u64` comparable type is available. This
116    /// will take care of filtering and reporting errors.
117    ///
118    /// # Arguments
119    ///
120    /// - `sample` - The singular sample to be recorded by the metric.
121    ///
122    /// ## Notes
123    ///
124    /// Discards any negative value of `sample` and reports an
125    /// [`ErrorType::InvalidValue`].
126    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    /// Accumulates the provided sample in the metric synchronously.
132    ///
133    /// See [`accumulate_samples`](Self::accumulate_samples) for details.
134    #[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        // Generic accumulation function to handle the different histogram types and count negative
143        // samples.
144        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    /// Gets the currently stored histogram.
210    #[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(
221            #[cfg(not(feature = "sqlite"))]
222            glean,
223            self.meta(),
224            queried_ping_name,
225        ) {
226            Some(Metric::CustomDistributionExponential(hist)) => Some(snapshot(&hist)),
227            Some(Metric::CustomDistributionLinear(hist)) => Some(snapshot(&hist)),
228            _ => None,
229        }
230    }
231
232    /// **Exported for test purposes.**
233    ///
234    /// Gets the number of recorded errors for the given metric and error type.
235    ///
236    /// # Arguments
237    ///
238    /// * `error` - The type of error
239    ///
240    /// # Returns
241    ///
242    /// The number of errors reported.
243    pub fn test_get_num_recorded_errors(&self, error: ErrorType) -> i32 {
244        crate::block_on_dispatcher();
245
246        crate::core::with_glean(|glean| {
247            test_get_num_recorded_errors(glean, self.meta(), error).unwrap_or(0)
248        })
249    }
250
251    /// **Experimental:** Start a new histogram buffer associated with this custom distribution metric.
252    ///
253    /// A histogram buffer accumulates in-memory.
254    /// Data is recorded into the metric on drop.
255    pub fn start_buffer(&self) -> LocalCustomDistribution<'_> {
256        LocalCustomDistribution::new(self)
257    }
258
259    fn commit_histogram(&self, histogram: Histogram<LinearOrExponential>) {
260        let metric = self.clone();
261        crate::launch_with_glean(move |glean| {
262            glean
263                .storage()
264                .record_with(glean, &metric.meta, move |old_value| {
265                    match metric.histogram_type {
266                        HistogramType::Linear => {
267                            let mut hist =
268                                if let Some(Metric::CustomDistributionLinear(hist)) = old_value {
269                                    hist
270                                } else {
271                                    Histogram::linear(
272                                        metric.range_min,
273                                        metric.range_max,
274                                        metric.bucket_count as usize,
275                                    )
276                                };
277
278                            hist._merge(&histogram);
279                            Metric::CustomDistributionLinear(hist)
280                        }
281                        HistogramType::Exponential => {
282                            let mut hist = if let Some(Metric::CustomDistributionExponential(
283                                hist,
284                            )) = old_value
285                            {
286                                hist
287                            } else {
288                                Histogram::exponential(
289                                    metric.range_min,
290                                    metric.range_max,
291                                    metric.bucket_count as usize,
292                                )
293                            };
294
295                            hist._merge(&histogram);
296                            Metric::CustomDistributionExponential(hist)
297                        }
298                    }
299                });
300        });
301    }
302}
303
304impl TestGetValue for CustomDistributionMetric {
305    type Output = DistributionData;
306
307    /// **Test-only API (exported for FFI purposes).**
308    ///
309    /// Gets the currently stored value as an integer.
310    ///
311    /// This doesn't clear the stored value.
312    ///
313    /// # Arguments
314    ///
315    /// * `ping_name` - the optional name of the ping to retrieve the metric
316    ///                 for. Defaults to the first value in `send_in_pings`.
317    ///
318    /// # Returns
319    ///
320    /// The stored value or `None` if nothing stored.
321    fn test_get_value(&self, ping_name: Option<String>) -> Option<DistributionData> {
322        crate::block_on_dispatcher();
323        crate::core::with_glean(|glean| self.get_value(glean, ping_name.as_deref()))
324    }
325}
326
327/// **Experimental:** A histogram buffer associated with a specific instance of a [`CustomDistributionMetric`].
328///
329/// Accumulation happens in-memory.
330/// Data is merged into the metric on [`Drop::drop`].
331pub struct LocalCustomDistribution<'a> {
332    histogram: Histogram<LinearOrExponential>,
333    metric: &'a CustomDistributionMetric,
334}
335
336impl<'a> LocalCustomDistribution<'a> {
337    /// Create a new histogram buffer referencing the custom distribution it will record into.
338    fn new(metric: &'a CustomDistributionMetric) -> Self {
339        let histogram = match metric.histogram_type {
340            HistogramType::Linear => Histogram::<LinearOrExponential>::_linear(
341                metric.range_min,
342                metric.range_max,
343                metric.bucket_count as usize,
344            ),
345            HistogramType::Exponential => Histogram::<LinearOrExponential>::_exponential(
346                metric.range_min,
347                metric.range_max,
348                metric.bucket_count as usize,
349            ),
350        };
351        Self { histogram, metric }
352    }
353
354    /// Accumulates one sample into the histogram.
355    ///
356    /// The provided sample must be in the "unit" declared by the instance of the metric type
357    /// (e.g. if the instance this method was called on is using [`crate::TimeUnit::Second`], then
358    /// `sample` is assumed to be in seconds).
359    ///
360    /// Accumulation happens in-memory only.
361    pub fn accumulate(&mut self, sample: u64) {
362        self.histogram.accumulate(sample)
363    }
364
365    /// Abandon this histogram buffer and don't commit accumulated data.
366    pub fn abandon(mut self) {
367        self.histogram.clear();
368    }
369}
370
371impl Drop for LocalCustomDistribution<'_> {
372    fn drop(&mut self) {
373        if self.histogram.is_empty() {
374            return;
375        }
376
377        // We want to move that value.
378        // A `0/0` histogram doesn't allocate.
379        let empty = Histogram::_linear(0, 0, 0);
380        let buffer = mem::replace(&mut self.histogram, empty);
381        self.metric.commit_histogram(buffer);
382    }
383}