use std::convert::TryFrom;
use std::sync::atomic::{AtomicU8, Ordering};
use crate::error::{Error, ErrorKind};
use crate::metrics::labeled::validate_dynamic_label;
use crate::Glean;
use serde::{Deserialize, Serialize};
#[derive(Copy, Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
#[repr(i32)] #[serde(rename_all = "lowercase")]
pub enum Lifetime {
Ping,
Application,
User,
}
impl Default for Lifetime {
fn default() -> Self {
Lifetime::Ping
}
}
impl Lifetime {
pub fn as_str(self) -> &'static str {
match self {
Lifetime::Ping => "ping",
Lifetime::Application => "app",
Lifetime::User => "user",
}
}
}
impl TryFrom<i32> for Lifetime {
type Error = Error;
fn try_from(value: i32) -> Result<Lifetime, Self::Error> {
match value {
0 => Ok(Lifetime::Ping),
1 => Ok(Lifetime::Application),
2 => Ok(Lifetime::User),
e => Err(ErrorKind::Lifetime(e).into()),
}
}
}
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
pub struct CommonMetricData {
pub name: String,
pub category: String,
pub send_in_pings: Vec<String>,
pub lifetime: Lifetime,
pub disabled: bool,
pub dynamic_label: Option<String>,
}
#[derive(Default, Debug)]
pub struct CommonMetricDataInternal {
pub inner: CommonMetricData,
pub disabled: AtomicU8,
}
impl Clone for CommonMetricDataInternal {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
disabled: AtomicU8::new(self.disabled.load(Ordering::Relaxed)),
}
}
}
impl From<CommonMetricData> for CommonMetricDataInternal {
fn from(input_data: CommonMetricData) -> Self {
Self {
inner: input_data.clone(),
disabled: AtomicU8::new(u8::from(input_data.disabled)),
}
}
}
impl CommonMetricDataInternal {
pub fn new<A: Into<String>, B: Into<String>, C: Into<String>>(
category: A,
name: B,
ping_name: C,
) -> CommonMetricDataInternal {
CommonMetricDataInternal {
inner: CommonMetricData {
name: name.into(),
category: category.into(),
send_in_pings: vec![ping_name.into()],
..Default::default()
},
disabled: AtomicU8::new(0),
}
}
pub(crate) fn base_identifier(&self) -> String {
if self.inner.category.is_empty() {
self.inner.name.clone()
} else {
format!("{}.{}", self.inner.category, self.inner.name)
}
}
pub(crate) fn identifier(&self, glean: &Glean) -> String {
let base_identifier = self.base_identifier();
if let Some(label) = &self.inner.dynamic_label {
validate_dynamic_label(glean, self, &base_identifier, label)
} else {
base_identifier
}
}
pub fn storage_names(&self) -> &[String] {
&self.inner.send_in_pings
}
}