Debian Codegraph @

third_party/rust/glean-core/src/metrics/labeled.rs

raw
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
5 use std::borrow::Cow;
6 use std::collections::{hash_map::Entry, HashMap};
7 use std::mem;
8 use std::sync::{Arc, Mutex};
9
10 use malloc_size_of::MallocSizeOf;
11
12 use crate::common_metric_data::{CommonMetricData, CommonMetricDataInternal};
13 use crate::error_recording::{record_error, test_get_num_recorded_errors, ErrorType};
14 use crate::histogram::HistogramType;
15 use crate::metrics::{
16 BooleanMetric, CounterMetric, CustomDistributionMetric, MemoryDistributionMetric, MemoryUnit,
17 Metric, MetricType, QuantityMetric, StringMetric, TimeUnit, TimingDistributionMetric,
18 };
19 use crate::Glean;
20
21 const MAX_LABELS: usize = 16;
22 const OTHER_LABEL: &str = "__other__";
23 const MAX_LABEL_LENGTH: usize = 111;
24
25 /// A labeled counter.
26 pub type LabeledCounter = LabeledMetric<CounterMetric>;
27
28 /// A labeled boolean.
29 pub type LabeledBoolean = LabeledMetric<BooleanMetric>;
30
31 /// A labeled string.
32 pub type LabeledString = LabeledMetric<StringMetric>;
33
34 /// A labeled custom_distribution.
35 pub type LabeledCustomDistribution = LabeledMetric<CustomDistributionMetric>;
36
37 /// A labeled memory_distribution.
38 pub type LabeledMemoryDistribution = LabeledMetric<MemoryDistributionMetric>;
39
40 /// A labeled timing_distribution.
41 pub type LabeledTimingDistribution = LabeledMetric<TimingDistributionMetric>;
42
43 /// A labeled quantity
44 pub type LabeledQuantity = LabeledMetric<QuantityMetric>;
45
46 /// The metric data needed to construct inner submetrics.
47 ///
48 /// Different Labeled metrics require different amounts and kinds of information to
49 /// be constructed.
50 pub enum LabeledMetricData {
51 /// The common case: just a CMD.
52 #[allow(missing_docs)]
53 Common { cmd: CommonMetricData },
54 /// The custom_distribution-specific case.
55 #[allow(missing_docs)]
56 CustomDistribution {
57 cmd: CommonMetricData,
58 range_min: i64,
59 range_max: i64,
60 bucket_count: i64,
61 histogram_type: HistogramType,
62 },
63 /// The memory_distribution-specific case.
64 #[allow(missing_docs)]
65 MemoryDistribution {
66 cmd: CommonMetricData,
67 unit: MemoryUnit,
68 },
69 /// The timing_distribution-specific case.
70 #[allow(missing_docs)]
71 TimingDistribution {
72 cmd: CommonMetricData,
73 unit: TimeUnit,
74 },
75 }
76
77 /// A labeled metric.
78 ///
79 /// Labeled metrics allow to record multiple sub-metrics of the same type under different string labels.
80 #[derive(Debug)]
81 pub struct LabeledMetric<T> {
82 labels: Option<Vec<Cow<'static, str>>>,
83 /// Type of the underlying metric
84 /// We hold on to an instance of it, which is cloned to create new modified instances.
85 submetric: T,
86
87 /// A map from a unique ID for the labeled submetric to a handle of an instantiated
88 /// metric type.
89 label_map: Mutex<HashMap<String, Arc<T>>>,
90 }
91
92 impl<T: MallocSizeOf> ::malloc_size_of::MallocSizeOf for LabeledMetric<T> {
93 fn size_of(&self, ops: &mut malloc_size_of::MallocSizeOfOps) -> usize {
94 let map = self.label_map.lock().unwrap();
95
96 // Copy of `MallocShallowSizeOf` implementation for `HashMap<K, V>` in `wr_malloc_size_of`.
97 // Note: An instantiated submetric is behind an `Arc`.
98 // `size_of` should only be called from a single thread to avoid double-counting.
99 let shallow_size = if ops.has_malloc_enclosing_size_of() {
100 map.values()
101 .next()
102 .map_or(0, |v| unsafe { ops.malloc_enclosing_size_of(v) })
103 } else {
104 map.capacity()
105 * (mem::size_of::<String>() + mem::size_of::<T>() + mem::size_of::<usize>())
106 };
107
108 let mut map_size = shallow_size;
109 for (k, v) in map.iter() {
110 map_size += k.size_of(ops);
111 map_size += v.size_of(ops);
112 }
113
114 self.labels.size_of(ops) + self.submetric.size_of(ops) + map_size
115 }
116 }
117
118 /// Sealed traits protect against downstream implementations.
119 ///
120 /// We wrap it in a private module that is inaccessible outside of this module.
121 mod private {
122 use super::LabeledMetricData;
123 use crate::metrics::{
124 BooleanMetric, CounterMetric, CustomDistributionMetric, MemoryDistributionMetric,
125 QuantityMetric, StringMetric, TimingDistributionMetric,
126 };
127
128 /// The sealed labeled trait.
129 ///
130 /// This also allows us to hide methods, that are only used internally
131 /// and should not be visible to users of the object implementing the
132 /// `Labeled<T>` trait.
133 pub trait Sealed {
134 /// Create a new `glean_core` metric from the metadata.
135 fn new_inner(meta: LabeledMetricData) -> Self;
136 }
137
138 impl Sealed for CounterMetric {
139 fn new_inner(meta: LabeledMetricData) -> Self {
140 match meta {
141 LabeledMetricData::Common { cmd } => Self::new(cmd),
142 _ => panic!("Incorrect construction of Labeled<CounterMetric>"),
143 }
144 }
145 }
146
147 impl Sealed for BooleanMetric {
148 fn new_inner(meta: LabeledMetricData) -> Self {
149 match meta {
150 LabeledMetricData::Common { cmd } => Self::new(cmd),
151 _ => panic!("Incorrect construction of Labeled<BooleanMetric>"),
152 }
153 }
154 }
155
156 impl Sealed for StringMetric {
157 fn new_inner(meta: LabeledMetricData) -> Self {
158 match meta {
159 LabeledMetricData::Common { cmd } => Self::new(cmd),
160 _ => panic!("Incorrect construction of Labeled<StringMetric>"),
161 }
162 }
163 }
164
165 impl Sealed for CustomDistributionMetric {
166 fn new_inner(meta: LabeledMetricData) -> Self {
167 match meta {
168 LabeledMetricData::CustomDistribution {
169 cmd,
170 range_min,
171 range_max,
172 bucket_count,
173 histogram_type,
174 } => Self::new(cmd, range_min, range_max, bucket_count, histogram_type),
175 _ => panic!("Incorrect construction of Labeled<CustomDistributionMetric>"),
176 }
177 }
178 }
179
180 impl Sealed for MemoryDistributionMetric {
181 fn new_inner(meta: LabeledMetricData) -> Self {
182 match meta {
183 LabeledMetricData::MemoryDistribution { cmd, unit } => Self::new(cmd, unit),
184 _ => panic!("Incorrect construction of Labeled<MemoryDistributionMetric>"),
185 }
186 }
187 }
188
189 impl Sealed for TimingDistributionMetric {
190 fn new_inner(meta: LabeledMetricData) -> Self {
191 match meta {
192 LabeledMetricData::TimingDistribution { cmd, unit } => Self::new(cmd, unit),
193 _ => panic!("Incorrect construction of Labeled<TimingDistributionMetric>"),
194 }
195 }
196 }
197
198 impl Sealed for QuantityMetric {
199 fn new_inner(meta: LabeledMetricData) -> Self {
200 match meta {
201 LabeledMetricData::Common { cmd } => Self::new(cmd),
202 _ => panic!("Incorrect construction of Labeled<QuantityMetric>"),
203 }
204 }
205 }
206 }
207
208 /// Trait for metrics that can be nested inside a labeled metric.
209 pub trait AllowLabeled: MetricType {
210 /// Create a new labeled metric.
211 fn new_labeled(meta: LabeledMetricData) -> Self;
212 }
213
214 // Implement the trait for everything we marked as allowed.
215 impl<T> AllowLabeled for T
216 where
217 T: MetricType,
218 T: private::Sealed,
219 {
220 fn new_labeled(meta: LabeledMetricData) -> Self {
221 T::new_inner(meta)
222 }
223 }
224
225 impl<T> LabeledMetric<T>
226 where
227 T: AllowLabeled + Clone,
228 {
229 /// Creates a new labeled metric from the given metric instance and optional list of labels.
230 ///
231 /// See [`get`](LabeledMetric::get) for information on how static or dynamic labels are handled.
232 pub fn new(
233 meta: LabeledMetricData,
234 labels: Option<Vec<Cow<'static, str>>>,
235 ) -> LabeledMetric<T> {
236 let submetric = T::new_labeled(meta);
237 LabeledMetric::new_inner(submetric, labels)
238 }
239
240 fn new_inner(submetric: T, labels: Option<Vec<Cow<'static, str>>>) -> LabeledMetric<T> {
241 let label_map = Default::default();
242 LabeledMetric {
243 labels,
244 submetric,
245 label_map,
246 }
247 }
248
249 /// Creates a new metric with a specific label.
250 ///
251 /// This is used for static labels where we can just set the name to be `name/label`.
252 fn new_metric_with_name(&self, name: String) -> T {
253 self.submetric.with_name(name)
254 }
255
256 /// Creates a new metric with a specific label.
257 ///
258 /// This is used for dynamic labels where we have to actually validate and correct the
259 /// label later when we have a Glean object.
260 fn new_metric_with_dynamic_label(&self, label: String) -> T {
261 self.submetric.with_dynamic_label(label)
262 }
263
264 /// Creates a static label.
265 ///
266 /// # Safety
267 ///
268 /// Should only be called when static labels are available on this metric.
269 ///
270 /// # Arguments
271 ///
272 /// * `label` - The requested label
273 ///
274 /// # Returns
275 ///
276 /// The requested label if it is in the list of allowed labels.
277 /// Otherwise `OTHER_LABEL` is returned.
278 fn static_label<'a>(&self, label: &'a str) -> &'a str {
279 debug_assert!(self.labels.is_some());
280 let labels = self.labels.as_ref().unwrap();
281 if labels.iter().any(|l| l == label) {
282 label
283 } else {
284 OTHER_LABEL
285 }
286 }
287
288 /// Gets a specific metric for a given label.
289 ///
290 /// If a set of acceptable labels were specified in the `metrics.yaml` file,
291 /// and the given label is not in the set, it will be recorded under the special `OTHER_LABEL` label.
292 ///
293 /// If a set of acceptable labels was not specified in the `metrics.yaml` file,
294 /// only the first 16 unique labels will be used.
295 /// After that, any additional labels will be recorded under the special `OTHER_LABEL` label.
296 ///
297 /// Labels must have a maximum of 111 characters, and may comprise any printable ASCII characters.
298 /// If an invalid label is used, the metric will be recorded in the special `OTHER_LABEL` label.
299 pub fn get<S: AsRef<str>>(&self, label: S) -> Arc<T> {
300 let label = label.as_ref();
301
302 // The handle is a unique number per metric.
303 // The label identifies the submetric.
304 let id = format!("{}/{}", self.submetric.meta().base_identifier(), label);
305
306 let mut map = self.label_map.lock().unwrap();
307 match map.entry(id) {
308 Entry::Occupied(entry) => Arc::clone(entry.get()),
309 Entry::Vacant(entry) => {
310 // We have 2 scenarios to consider:
311 // * Static labels. No database access needed. We just look at what is in memory.
312 // * Dynamic labels. We look up in the database all previously stored
313 // labels in order to keep a maximum of allowed labels. This is done later
314 // when the specific metric is actually recorded, when we are guaranteed to have
315 // an initialized Glean object.
316 let metric = match self.labels {
317 Some(_) => {
318 let label = self.static_label(label);
319 self.new_metric_with_name(combine_base_identifier_and_label(
320 &self.submetric.meta().inner.name,
321 label,
322 ))
323 }
324 None => self.new_metric_with_dynamic_label(label.to_string()),
325 };
326 let metric = Arc::new(metric);
327 entry.insert(Arc::clone(&metric));
328 metric
329 }
330 }
331 }
332
333 /// **Exported for test purposes.**
334 ///
335 /// Gets the number of recorded errors for the given metric and error type.
336 ///
337 /// # Arguments
338 ///
339 /// * `error` - The type of error
340 ///
341 /// # Returns
342 ///
343 /// The number of errors reported.
344 pub fn test_get_num_recorded_errors(&self, error: ErrorType) -> i32 {
345 crate::block_on_dispatcher();
346 crate::core::with_glean(|glean| {
347 test_get_num_recorded_errors(glean, self.submetric.meta(), error).unwrap_or(0)
348 })
349 }
350 }
351
352 /// Combines a metric's base identifier and label
353 pub fn combine_base_identifier_and_label(base_identifer: &str, label: &str) -> String {
354 format!("{}/{}", base_identifer, label)
355 }
356
357 /// Strips the label off of a complete identifier
358 pub fn strip_label(identifier: &str) -> &str {
359 identifier.split_once('/').map_or(identifier, |s| s.0)
360 }
361
362 /// Validates a dynamic label, changing it to `OTHER_LABEL` if it's invalid.
363 ///
364 /// Checks the requested label against limitations, such as the label length and allowed
365 /// characters.
366 ///
367 /// # Arguments
368 ///
369 /// * `label` - The requested label
370 ///
371 /// # Returns
372 ///
373 /// The entire identifier for the metric, including the base identifier and the corrected label.
374 /// The errors are logged.
375 pub fn validate_dynamic_label(
376 glean: &Glean,
377 meta: &CommonMetricDataInternal,
378 base_identifier: &str,
379 label: &str,
380 ) -> String {
381 let key = combine_base_identifier_and_label(base_identifier, label);
382 for store in &meta.inner.send_in_pings {
383 if glean.storage().has_metric(meta.inner.lifetime, store, &key) {
384 return key;
385 }
386 }
387
388 let mut label_count = 0;
389 let prefix = &key[..=base_identifier.len()];
390 let mut snapshotter = |_: &[u8], _: &Metric| {
391 label_count += 1;
392 };
393
394 let lifetime = meta.inner.lifetime;
395 for store in &meta.inner.send_in_pings {
396 glean
397 .storage()
398 .iter_store_from(lifetime, store, Some(prefix), &mut snapshotter);
399 }
400
401 let error = if label_count >= MAX_LABELS {
402 true
403 } else if label.len() > MAX_LABEL_LENGTH {
404 let msg = format!(
405 "label length {} exceeds maximum of {}",
406 label.len(),
407 MAX_LABEL_LENGTH
408 );
409 record_error(glean, meta, ErrorType::InvalidLabel, msg, None);
410 true
411 } else if label.chars().any(|c| !c.is_ascii() || c.is_ascii_control()) {
412 let msg = format!("label must be printable ascii, got '{}'", label);
413 record_error(glean, meta, ErrorType::InvalidLabel, msg, None);
414 true
415 } else {
416 false
417 };
418
419 if error {
420 combine_base_identifier_and_label(base_identifier, OTHER_LABEL)
421 } else {
422 key
423 }
424 }