| 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 |
//! The different metric types supported by the Glean SDK to handle data. |
| 6 |
|
| 7 |
use std::collections::HashMap; |
| 8 |
use std::sync::atomic::Ordering; |
| 9 |
|
| 10 |
use chrono::{DateTime, FixedOffset}; |
| 11 |
use malloc_size_of::MallocSizeOf; |
| 12 |
use serde::{Deserialize, Serialize}; |
| 13 |
use serde_json::json; |
| 14 |
pub use serde_json::Value as JsonValue; |
| 15 |
|
| 16 |
mod boolean; |
| 17 |
mod counter; |
| 18 |
mod custom_distribution; |
| 19 |
mod datetime; |
| 20 |
mod denominator; |
| 21 |
mod event; |
| 22 |
mod experiment; |
| 23 |
pub(crate) mod labeled; |
| 24 |
mod memory_distribution; |
| 25 |
mod memory_unit; |
| 26 |
mod numerator; |
| 27 |
mod object; |
| 28 |
mod ping; |
| 29 |
mod quantity; |
| 30 |
mod rate; |
| 31 |
mod recorded_experiment; |
| 32 |
mod remote_settings_config; |
| 33 |
mod string; |
| 34 |
mod string_list; |
| 35 |
mod text; |
| 36 |
mod time_unit; |
| 37 |
mod timespan; |
| 38 |
mod timing_distribution; |
| 39 |
mod url; |
| 40 |
mod uuid; |
| 41 |
|
| 42 |
use crate::common_metric_data::CommonMetricDataInternal; |
| 43 |
pub use crate::event_database::RecordedEvent; |
| 44 |
use crate::histogram::{Functional, Histogram, PrecomputedExponential, PrecomputedLinear}; |
| 45 |
pub use crate::metrics::datetime::Datetime; |
| 46 |
use crate::util::get_iso_time_string; |
| 47 |
use crate::Glean; |
| 48 |
|
| 49 |
pub use self::boolean::BooleanMetric; |
| 50 |
pub use self::counter::CounterMetric; |
| 51 |
pub use self::custom_distribution::{CustomDistributionMetric, LocalCustomDistribution}; |
| 52 |
pub use self::datetime::DatetimeMetric; |
| 53 |
pub use self::denominator::DenominatorMetric; |
| 54 |
pub use self::event::EventMetric; |
| 55 |
pub(crate) use self::experiment::ExperimentMetric; |
| 56 |
pub use self::labeled::{ |
| 57 |
LabeledBoolean, LabeledCounter, LabeledCustomDistribution, LabeledMemoryDistribution, |
| 58 |
LabeledMetric, LabeledQuantity, LabeledString, LabeledTimingDistribution, |
| 59 |
}; |
| 60 |
pub use self::memory_distribution::{LocalMemoryDistribution, MemoryDistributionMetric}; |
| 61 |
pub use self::memory_unit::MemoryUnit; |
| 62 |
pub use self::numerator::NumeratorMetric; |
| 63 |
pub use self::object::ObjectMetric; |
| 64 |
pub use self::ping::PingType; |
| 65 |
pub use self::quantity::QuantityMetric; |
| 66 |
pub use self::rate::{Rate, RateMetric}; |
| 67 |
pub use self::string::StringMetric; |
| 68 |
pub use self::string_list::StringListMetric; |
| 69 |
pub use self::text::TextMetric; |
| 70 |
pub use self::time_unit::TimeUnit; |
| 71 |
pub use self::timespan::TimespanMetric; |
| 72 |
pub use self::timing_distribution::LocalTimingDistribution; |
| 73 |
pub use self::timing_distribution::TimerId; |
| 74 |
pub use self::timing_distribution::TimingDistributionMetric; |
| 75 |
pub use self::url::UrlMetric; |
| 76 |
pub use self::uuid::UuidMetric; |
| 77 |
pub use crate::histogram::HistogramType; |
| 78 |
pub use recorded_experiment::RecordedExperiment; |
| 79 |
|
| 80 |
pub use self::remote_settings_config::RemoteSettingsConfig; |
| 81 |
|
| 82 |
/// A snapshot of all buckets and the accumulated sum of a distribution. |
| 83 |
// |
| 84 |
// Note: Be careful when changing this structure. |
| 85 |
// The serialized form ends up in the ping payload. |
| 86 |
// New fields might require to be skipped on serialization. |
| 87 |
#[derive(Debug, Serialize, PartialEq)] |
| 88 |
pub struct DistributionData { |
| 89 |
/// A map containig the bucket index mapped to the accumulated count. |
| 90 |
/// |
| 91 |
/// This can contain buckets with a count of `0`. |
| 92 |
pub values: HashMap<i64, i64>, |
| 93 |
|
| 94 |
/// The accumulated sum of all the samples in the distribution. |
| 95 |
pub sum: i64, |
| 96 |
|
| 97 |
/// The total number of entries in the distribution. |
| 98 |
#[serde(skip)] |
| 99 |
pub count: i64, |
| 100 |
} |
| 101 |
|
| 102 |
/// The available metrics. |
| 103 |
/// |
| 104 |
/// This is the in-memory and persisted layout of a metric. |
| 105 |
/// |
| 106 |
/// ## Note |
| 107 |
/// |
| 108 |
/// The order of metrics in this enum is important, as it is used for serialization. |
| 109 |
/// Do not reorder the variants. |
| 110 |
/// |
| 111 |
/// **Any new metric must be added at the end.** |
| 112 |
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] |
| 113 |
pub enum Metric { |
| 114 |
/// A boolean metric. See [`BooleanMetric`] for more information. |
| 115 |
Boolean(bool), |
| 116 |
/// A counter metric. See [`CounterMetric`] for more information. |
| 117 |
Counter(i32), |
| 118 |
/// A custom distribution with precomputed exponential bucketing. |
| 119 |
/// See [`CustomDistributionMetric`] for more information. |
| 120 |
CustomDistributionExponential(Histogram<PrecomputedExponential>), |
| 121 |
/// A custom distribution with precomputed linear bucketing. |
| 122 |
/// See [`CustomDistributionMetric`] for more information. |
| 123 |
CustomDistributionLinear(Histogram<PrecomputedLinear>), |
| 124 |
/// A datetime metric. See [`DatetimeMetric`] for more information. |
| 125 |
Datetime(DateTime<FixedOffset>, TimeUnit), |
| 126 |
/// An experiment metric. See `ExperimentMetric` for more information. |
| 127 |
Experiment(recorded_experiment::RecordedExperiment), |
| 128 |
/// A quantity metric. See [`QuantityMetric`] for more information. |
| 129 |
Quantity(i64), |
| 130 |
/// A string metric. See [`StringMetric`] for more information. |
| 131 |
String(String), |
| 132 |
/// A string list metric. See [`StringListMetric`] for more information. |
| 133 |
StringList(Vec<String>), |
| 134 |
/// A UUID metric. See [`UuidMetric`] for more information. |
| 135 |
Uuid(String), |
| 136 |
/// A timespan metric. See [`TimespanMetric`] for more information. |
| 137 |
Timespan(std::time::Duration, TimeUnit), |
| 138 |
/// A timing distribution. See [`TimingDistributionMetric`] for more information. |
| 139 |
TimingDistribution(Histogram<Functional>), |
| 140 |
/// A memory distribution. See [`MemoryDistributionMetric`] for more information. |
| 141 |
MemoryDistribution(Histogram<Functional>), |
| 142 |
/// **DEPRECATED**: A JWE metric.. |
| 143 |
/// Note: This variant MUST NOT be removed to avoid backwards-incompatible changes to the |
| 144 |
/// serialization. This type has no underlying implementation anymore. |
| 145 |
Jwe(String), |
| 146 |
/// A rate metric. See [`RateMetric`] for more information. |
| 147 |
Rate(i32, i32), |
| 148 |
/// A URL metric. See [`UrlMetric`] for more information. |
| 149 |
Url(String), |
| 150 |
/// A Text metric. See [`TextMetric`] for more information. |
| 151 |
Text(String), |
| 152 |
/// An Object metric. See [`ObjectMetric`] for more information. |
| 153 |
Object(String), |
| 154 |
} |
| 155 |
|
| 156 |
impl MallocSizeOf for Metric { |
| 157 |
fn size_of(&self, ops: &mut malloc_size_of::MallocSizeOfOps) -> usize { |
| 158 |
match self { |
| 159 |
Metric::Boolean(m) => m.size_of(ops), |
| 160 |
Metric::Counter(m) => m.size_of(ops), |
| 161 |
// Custom distributions are in the same section, no matter what bucketing. |
| 162 |
Metric::CustomDistributionExponential(m) => m.size_of(ops), |
| 163 |
Metric::CustomDistributionLinear(m) => m.size_of(ops), |
| 164 |
Metric::Datetime(_a, b) => b.size_of(ops), |
| 165 |
Metric::Experiment(m) => m.size_of(ops), |
| 166 |
Metric::Quantity(m) => m.size_of(ops), |
| 167 |
Metric::Rate(a, b) => a.size_of(ops) + b.size_of(ops), |
| 168 |
Metric::String(m) => m.size_of(ops), |
| 169 |
Metric::StringList(m) => m.size_of(ops), |
| 170 |
Metric::Timespan(a, b) => a.size_of(ops) + b.size_of(ops), |
| 171 |
Metric::TimingDistribution(m) => m.size_of(ops), |
| 172 |
Metric::Url(m) => m.size_of(ops), |
| 173 |
Metric::Uuid(m) => m.size_of(ops), |
| 174 |
Metric::MemoryDistribution(m) => m.size_of(ops), |
| 175 |
Metric::Jwe(m) => m.size_of(ops), |
| 176 |
Metric::Text(m) => m.size_of(ops), |
| 177 |
Metric::Object(m) => m.size_of(ops), |
| 178 |
} |
| 179 |
} |
| 180 |
} |
| 181 |
|
| 182 |
/// A [`MetricType`] describes common behavior across all metrics. |
| 183 |
pub trait MetricType { |
| 184 |
/// Access the stored metadata |
| 185 |
fn meta(&self) -> &CommonMetricDataInternal; |
| 186 |
|
| 187 |
/// Create a new metric from this with a new name. |
| 188 |
fn with_name(&self, _name: String) -> Self |
| 189 |
where |
| 190 |
Self: Sized, |
| 191 |
{ |
| 192 |
unimplemented!() |
| 193 |
} |
| 194 |
|
| 195 |
/// Create a new metric from this with a specific label. |
| 196 |
fn with_dynamic_label(&self, _label: String) -> Self |
| 197 |
where |
| 198 |
Self: Sized, |
| 199 |
{ |
| 200 |
unimplemented!() |
| 201 |
} |
| 202 |
|
| 203 |
/// Whether this metric should currently be recorded |
| 204 |
/// |
| 205 |
/// This depends on the metrics own state, as determined by its metadata, |
| 206 |
/// and whether upload is enabled on the Glean object. |
| 207 |
fn should_record(&self, glean: &Glean) -> bool { |
| 208 |
// Technically nothing prevents multiple calls to should_record() to run in parallel, |
| 209 |
// meaning both are reading self.meta().disabled and later writing it. In between it can |
| 210 |
// also read remote_settings_config, which also could be modified in between those 2 reads. |
| 211 |
// This means we could write the wrong remote_settings_epoch | current_disabled value. All in all |
| 212 |
// at worst we would see that metric enabled/disabled wrongly once. |
| 213 |
// But since everything is tunneled through the dispatcher, this should never ever happen. |
| 214 |
|
| 215 |
// Get the current disabled field from the metric metadata, including |
| 216 |
// the encoded remote_settings epoch |
| 217 |
let disabled_field = self.meta().disabled.load(Ordering::Relaxed); |
| 218 |
// Grab the epoch from the upper nibble |
| 219 |
let epoch = disabled_field >> 4; |
| 220 |
// Get the disabled flag from the lower nibble |
| 221 |
let disabled = disabled_field & 0xF; |
| 222 |
// Get the current remote_settings epoch to see if we need to bother with the |
| 223 |
// more expensive HashMap lookup |
| 224 |
let remote_settings_epoch = glean.remote_settings_epoch.load(Ordering::Acquire); |
| 225 |
if epoch == remote_settings_epoch { |
| 226 |
return disabled == 0; |
| 227 |
} |
| 228 |
// The epoch's didn't match so we need to look up the disabled flag |
| 229 |
// by the base_identifier from the in-memory HashMap |
| 230 |
let remote_settings_config = &glean.remote_settings_config.lock().unwrap(); |
| 231 |
// Get the value from the remote configuration if it is there, otherwise return the default value. |
| 232 |
let current_disabled = { |
| 233 |
let base_id = self.meta().base_identifier(); |
| 234 |
let identifier = base_id |
| 235 |
.split_once('/') |
| 236 |
.map(|split| split.0) |
| 237 |
.unwrap_or(&base_id); |
| 238 |
// NOTE: The `!` preceding the `*is_enabled` is important for inverting the logic since the |
| 239 |
// underlying property in the metrics.yaml is `disabled` and the outward API is treating it as |
| 240 |
// if it were `enabled` to make it easier to understand. |
| 241 |
|
| 242 |
if !remote_settings_config.metrics_enabled.is_empty() { |
| 243 |
if let Some(is_enabled) = remote_settings_config.metrics_enabled.get(identifier) { |
| 244 |
u8::from(!*is_enabled) |
| 245 |
} else { |
| 246 |
u8::from(self.meta().inner.disabled) |
| 247 |
} |
| 248 |
} else { |
| 249 |
u8::from(self.meta().inner.disabled) |
| 250 |
} |
| 251 |
}; |
| 252 |
|
| 253 |
// Re-encode the epoch and enabled status and update the metadata |
| 254 |
let new_disabled = (remote_settings_epoch << 4) | (current_disabled & 0xF); |
| 255 |
self.meta().disabled.store(new_disabled, Ordering::Relaxed); |
| 256 |
|
| 257 |
// Return a boolean indicating whether or not the metric should be recorded |
| 258 |
current_disabled == 0 |
| 259 |
} |
| 260 |
} |
| 261 |
|
| 262 |
/// A [`MetricIdentifier`] describes an interface for retrieving an |
| 263 |
/// identifier (category, name, label) for a metric |
| 264 |
pub trait MetricIdentifier<'a> { |
| 265 |
/// Retrieve the category, name and (maybe) label of the metric |
| 266 |
fn get_identifiers(&'a self) -> (&'a str, &'a str, Option<&'a str>); |
| 267 |
} |
| 268 |
|
| 269 |
// Provide a blanket implementation for MetricIdentifier for all the types |
| 270 |
// that implement MetricType. |
| 271 |
impl<'a, T> MetricIdentifier<'a> for T |
| 272 |
where |
| 273 |
T: MetricType, |
| 274 |
{ |
| 275 |
fn get_identifiers(&'a self) -> (&'a str, &'a str, Option<&'a str>) { |
| 276 |
let meta = &self.meta().inner; |
| 277 |
(&meta.category, &meta.name, meta.dynamic_label.as_deref()) |
| 278 |
} |
| 279 |
} |
| 280 |
|
| 281 |
impl Metric { |
| 282 |
/// Gets the ping section the metric fits into. |
| 283 |
/// |
| 284 |
/// This determines the section of the ping to place the metric data in when |
| 285 |
/// assembling the ping payload. |
| 286 |
pub fn ping_section(&self) -> &'static str { |
| 287 |
match self { |
| 288 |
Metric::Boolean(_) => "boolean", |
| 289 |
Metric::Counter(_) => "counter", |
| 290 |
// Custom distributions are in the same section, no matter what bucketing. |
| 291 |
Metric::CustomDistributionExponential(_) => "custom_distribution", |
| 292 |
Metric::CustomDistributionLinear(_) => "custom_distribution", |
| 293 |
Metric::Datetime(_, _) => "datetime", |
| 294 |
Metric::Experiment(_) => panic!("Experiments should not be serialized through this"), |
| 295 |
Metric::Quantity(_) => "quantity", |
| 296 |
Metric::Rate(..) => "rate", |
| 297 |
Metric::String(_) => "string", |
| 298 |
Metric::StringList(_) => "string_list", |
| 299 |
Metric::Timespan(..) => "timespan", |
| 300 |
Metric::TimingDistribution(_) => "timing_distribution", |
| 301 |
Metric::Url(_) => "url", |
| 302 |
Metric::Uuid(_) => "uuid", |
| 303 |
Metric::MemoryDistribution(_) => "memory_distribution", |
| 304 |
Metric::Jwe(_) => "jwe", |
| 305 |
Metric::Text(_) => "text", |
| 306 |
Metric::Object(_) => "object", |
| 307 |
} |
| 308 |
} |
| 309 |
|
| 310 |
/// The JSON representation of the metric's data |
| 311 |
pub fn as_json(&self) -> JsonValue { |
| 312 |
match self { |
| 313 |
Metric::Boolean(b) => json!(b), |
| 314 |
Metric::Counter(c) => json!(c), |
| 315 |
Metric::CustomDistributionExponential(hist) => { |
| 316 |
json!(custom_distribution::snapshot(hist)) |
| 317 |
} |
| 318 |
Metric::CustomDistributionLinear(hist) => json!(custom_distribution::snapshot(hist)), |
| 319 |
Metric::Datetime(d, time_unit) => json!(get_iso_time_string(*d, *time_unit)), |
| 320 |
Metric::Experiment(e) => e.as_json(), |
| 321 |
Metric::Quantity(q) => json!(q), |
| 322 |
Metric::Rate(num, den) => { |
| 323 |
json!({"numerator": num, "denominator": den}) |
| 324 |
} |
| 325 |
Metric::String(s) => json!(s), |
| 326 |
Metric::StringList(v) => json!(v), |
| 327 |
Metric::Timespan(time, time_unit) => { |
| 328 |
json!({"value": time_unit.duration_convert(*time), "time_unit": time_unit}) |
| 329 |
} |
| 330 |
Metric::TimingDistribution(hist) => json!(timing_distribution::snapshot(hist)), |
| 331 |
Metric::Url(s) => json!(s), |
| 332 |
Metric::Uuid(s) => json!(s), |
| 333 |
Metric::MemoryDistribution(hist) => json!(memory_distribution::snapshot(hist)), |
| 334 |
Metric::Jwe(s) => json!(s), |
| 335 |
Metric::Text(s) => json!(s), |
| 336 |
Metric::Object(s) => { |
| 337 |
serde_json::from_str(s).expect("object storage should have been json") |
| 338 |
} |
| 339 |
} |
| 340 |
} |
| 341 |
} |
| 342 |
|
| 343 |
macro_rules! impl_malloc_size_of_for_metric { |
| 344 |
($ty:ident) => { |
| 345 |
impl ::malloc_size_of::MallocSizeOf for $ty { |
| 346 |
fn size_of(&self, ops: &mut malloc_size_of::MallocSizeOfOps) -> usize { |
| 347 |
// Note: `meta` is likely s behind an `Arc`. |
| 348 |
// `size_of` should only be called from a single thread to avoid double-counting. |
| 349 |
self.meta().size_of(ops) |
| 350 |
} |
| 351 |
} |
| 352 |
}; |
| 353 |
} |
| 354 |
|
| 355 |
impl_malloc_size_of_for_metric!(BooleanMetric); |
| 356 |
impl_malloc_size_of_for_metric!(CounterMetric); |
| 357 |
impl_malloc_size_of_for_metric!(CustomDistributionMetric); |
| 358 |
impl_malloc_size_of_for_metric!(DatetimeMetric); |
| 359 |
impl_malloc_size_of_for_metric!(DenominatorMetric); |
| 360 |
impl_malloc_size_of_for_metric!(EventMetric); |
| 361 |
impl_malloc_size_of_for_metric!(ExperimentMetric); |
| 362 |
impl_malloc_size_of_for_metric!(MemoryDistributionMetric); |
| 363 |
impl_malloc_size_of_for_metric!(NumeratorMetric); |
| 364 |
impl_malloc_size_of_for_metric!(ObjectMetric); |
| 365 |
impl_malloc_size_of_for_metric!(QuantityMetric); |
| 366 |
impl_malloc_size_of_for_metric!(RateMetric); |
| 367 |
impl_malloc_size_of_for_metric!(StringMetric); |
| 368 |
impl_malloc_size_of_for_metric!(StringListMetric); |
| 369 |
impl_malloc_size_of_for_metric!(TextMetric); |
| 370 |
impl_malloc_size_of_for_metric!(TimespanMetric); |
| 371 |
impl_malloc_size_of_for_metric!(UrlMetric); |
| 372 |
impl_malloc_size_of_for_metric!(UuidMetric); |