glean_core/metrics/numerator.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::sync::Arc;
6
7use crate::common_metric_data::CommonMetricDataInternal;
8use crate::error_recording::ErrorType;
9use crate::metrics::MetricType;
10use crate::metrics::Rate;
11use crate::metrics::RateMetric;
12use crate::CommonMetricData;
13use crate::Glean;
14
15/// Developer-facing API for recording rate metrics with external denominators.
16///
17/// Instances of this class type are automatically generated by the parsers
18/// at build time, allowing developers to record values that were previously
19/// registered in the metrics.yaml file.
20#[derive(Clone)]
21pub struct NumeratorMetric(pub(crate) Arc<RateMetric>);
22
23impl MetricType for NumeratorMetric {
24 fn meta(&self) -> &CommonMetricDataInternal {
25 self.0.meta()
26 }
27}
28
29impl NumeratorMetric {
30 /// The public constructor used by automatically generated metrics.
31 pub fn new(meta: CommonMetricData) -> Self {
32 Self(Arc::new(RateMetric::new(meta)))
33 }
34
35 /// Increases the numerator by `amount`.
36 ///
37 /// # Arguments
38 ///
39 /// * `amount` - The amount to increase by. Should be non-negative.
40 ///
41 /// ## Notes
42 ///
43 /// Logs an error if the `amount` is negative.
44 pub fn add_to_numerator(&self, amount: i32) {
45 let metric = self.clone();
46 crate::launch_with_glean(move |glean| metric.add_to_numerator_sync(glean, amount));
47 }
48
49 #[doc(hidden)]
50 pub fn add_to_numerator_sync(&self, glean: &Glean, amount: i32) {
51 self.0.add_to_numerator_sync(glean, amount)
52 }
53
54 /// **Exported for test purposes.**
55 ///
56 /// Gets the currently stored value as a pair of integers.
57 ///
58 /// This doesn't clear the stored value.
59 ///
60 /// # Arguments
61 ///
62 /// * `ping_name` - the optional name of the ping to retrieve the metric
63 /// for. Defaults to the first value in `send_in_pings`.
64 ///
65 /// # Returns
66 ///
67 /// The stored value or `None` if nothing stored.
68 pub fn test_get_value(&self, ping_name: Option<String>) -> Option<Rate> {
69 crate::block_on_dispatcher();
70 crate::core::with_glean(|glean| self.get_value(glean, ping_name.as_deref()))
71 }
72
73 #[doc(hidden)]
74 pub fn get_value<'a, S: Into<Option<&'a str>>>(
75 &self,
76 glean: &Glean,
77 ping_name: S,
78 ) -> Option<Rate> {
79 self.0.get_value(glean, ping_name)
80 }
81
82 /// **Exported for test purposes.**
83 ///
84 /// Gets the number of recorded errors for the given metric and error type.
85 ///
86 /// # Arguments
87 ///
88 /// * `error` - The type of error
89 ///
90 /// # Returns
91 ///
92 /// The number of errors reported.
93 pub fn test_get_num_recorded_errors(&self, error: ErrorType) -> i32 {
94 self.0.test_get_num_recorded_errors(error)
95 }
96}