use std::borrow::Cow;
use std::collections::{hash_map::Entry, HashMap};
use std::sync::{Arc, Mutex};
use crate::common_metric_data::{CommonMetricData, CommonMetricDataInternal};
use crate::error_recording::{record_error, test_get_num_recorded_errors, ErrorType};
use crate::metrics::{BooleanMetric, CounterMetric, Metric, MetricType, StringMetric};
use crate::Glean;
const MAX_LABELS: usize = 16;
const OTHER_LABEL: &str = "__other__";
const MAX_LABEL_LENGTH: usize = 61;
pub type LabeledCounter = LabeledMetric<CounterMetric>;
pub type LabeledBoolean = LabeledMetric<BooleanMetric>;
pub type LabeledString = LabeledMetric<StringMetric>;
fn matches_label_regex(value: &str) -> bool {
let mut iter = value.chars();
loop {
match iter.next() {
Some('_') | Some('a'..='z') => (),
_ => return false,
};
let mut count = 0;
loop {
match iter.next() {
None => return true,
Some('_') | Some('-') | Some('a'..='z') | Some('0'..='9') => (),
Some('.') => break,
_ => return false,
}
count += 1;
if count == 29 {
return false;
}
}
}
}
#[derive(Debug)]
pub struct LabeledMetric<T> {
labels: Option<Vec<Cow<'static, str>>>,
submetric: T,
label_map: Mutex<HashMap<String, Arc<T>>>,
}
mod private {
use crate::{
metrics::BooleanMetric, metrics::CounterMetric, metrics::StringMetric, CommonMetricData,
};
pub trait Sealed {
fn new_inner(meta: crate::CommonMetricData) -> Self;
}
impl Sealed for CounterMetric {
fn new_inner(meta: CommonMetricData) -> Self {
Self::new(meta)
}
}
impl Sealed for BooleanMetric {
fn new_inner(meta: CommonMetricData) -> Self {
Self::new(meta)
}
}
impl Sealed for StringMetric {
fn new_inner(meta: CommonMetricData) -> Self {
Self::new(meta)
}
}
}
pub trait AllowLabeled: MetricType {
fn new_labeled(meta: CommonMetricData) -> Self;
}
impl<T> AllowLabeled for T
where
T: MetricType,
T: private::Sealed,
{
fn new_labeled(meta: CommonMetricData) -> Self {
T::new_inner(meta)
}
}
impl<T> LabeledMetric<T>
where
T: AllowLabeled + Clone,
{
pub fn new(meta: CommonMetricData, labels: Option<Vec<Cow<'static, str>>>) -> LabeledMetric<T> {
let submetric = T::new_labeled(meta);
LabeledMetric::new_inner(submetric, labels)
}
fn new_inner(submetric: T, labels: Option<Vec<Cow<'static, str>>>) -> LabeledMetric<T> {
let label_map = Default::default();
LabeledMetric {
labels,
submetric,
label_map,
}
}
fn new_metric_with_name(&self, name: String) -> T {
self.submetric.with_name(name)
}
fn new_metric_with_dynamic_label(&self, label: String) -> T {
self.submetric.with_dynamic_label(label)
}
fn static_label<'a>(&self, label: &'a str) -> &'a str {
debug_assert!(self.labels.is_some());
let labels = self.labels.as_ref().unwrap();
if labels.iter().any(|l| l == label) {
label
} else {
OTHER_LABEL
}
}
pub fn get<S: AsRef<str>>(&self, label: S) -> Arc<T> {
let label = label.as_ref();
let id = format!("{}/{}", self.submetric.meta().base_identifier(), label);
let mut map = self.label_map.lock().unwrap();
match map.entry(id) {
Entry::Occupied(entry) => Arc::clone(entry.get()),
Entry::Vacant(entry) => {
let metric = match self.labels {
Some(_) => {
let label = self.static_label(label);
self.new_metric_with_name(combine_base_identifier_and_label(
&self.submetric.meta().inner.name,
label,
))
}
None => self.new_metric_with_dynamic_label(label.to_string()),
};
let metric = Arc::new(metric);
entry.insert(Arc::clone(&metric));
metric
}
}
}
pub fn test_get_num_recorded_errors(&self, error: ErrorType) -> i32 {
crate::block_on_dispatcher();
crate::core::with_glean(|glean| {
test_get_num_recorded_errors(glean, self.submetric.meta(), error).unwrap_or(0)
})
}
}
pub fn combine_base_identifier_and_label(base_identifer: &str, label: &str) -> String {
format!("{}/{}", base_identifer, label)
}
pub fn strip_label(identifier: &str) -> &str {
identifier.split_once('/').map_or(identifier, |s| s.0)
}
pub fn validate_dynamic_label(
glean: &Glean,
meta: &CommonMetricDataInternal,
base_identifier: &str,
label: &str,
) -> String {
let key = combine_base_identifier_and_label(base_identifier, label);
for store in &meta.inner.send_in_pings {
if glean.storage().has_metric(meta.inner.lifetime, store, &key) {
return key;
}
}
let mut label_count = 0;
let prefix = &key[..=base_identifier.len()];
let mut snapshotter = |_: &[u8], _: &Metric| {
label_count += 1;
};
let lifetime = meta.inner.lifetime;
for store in &meta.inner.send_in_pings {
glean
.storage()
.iter_store_from(lifetime, store, Some(prefix), &mut snapshotter);
}
let error = if label_count >= MAX_LABELS {
true
} else if label.len() > MAX_LABEL_LENGTH {
let msg = format!(
"label length {} exceeds maximum of {}",
label.len(),
MAX_LABEL_LENGTH
);
record_error(glean, meta, ErrorType::InvalidLabel, msg, None);
true
} else if !matches_label_regex(label) {
let msg = format!("label must be snake_case, got '{}'", label);
record_error(glean, meta, ErrorType::InvalidLabel, msg, None);
true
} else {
false
};
if error {
combine_base_identifier_and_label(base_identifier, OTHER_LABEL)
} else {
key
}
}