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(
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 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 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 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
327pub struct LocalCustomDistribution<'a> {
332 histogram: Histogram<LinearOrExponential>,
333 metric: &'a CustomDistributionMetric,
334}
335
336impl<'a> LocalCustomDistribution<'a> {
337 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 pub fn accumulate(&mut self, sample: u64) {
362 self.histogram.accumulate(sample)
363 }
364
365 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 let empty = Histogram::_linear(0, 0, 0);
380 let buffer = mem::replace(&mut self.histogram, empty);
381 self.metric.commit_histogram(buffer);
382 }
383}