use crate::telemetry::{ContextTags, Properties};
use crate::TelemetryConfig;
#[derive(Clone)]
pub struct TelemetryContext {
pub(crate) i_key: String,
pub(crate) tags: ContextTags,
pub(crate) properties: Properties,
}
impl TelemetryContext {
pub fn from_config(config: &TelemetryConfig) -> Self {
let i_key = config.i_key().into();
let sdk_version = format!("rust:{}", env!("CARGO_PKG_VERSION"));
let os_version = if cfg!(target_os = "linux") {
"linux"
} else if cfg!(target_os = "windows") {
"windows"
} else if cfg!(target_os = "macos") {
"macos"
} else {
"unknown"
};
let mut tags = ContextTags::default();
tags.internal_mut().set_sdk_version(sdk_version);
tags.device_mut().set_os_version(os_version.into());
if let Ok(Ok(host)) = &hostname::get().map(|host| host.into_string()) {
tags.device_mut().set_id(host.into());
tags.cloud_mut().set_role_instance(host.into());
}
let properties = Properties::default();
Self::new(i_key, tags, properties)
}
pub fn new(i_key: String, tags: ContextTags, properties: Properties) -> Self {
Self {
i_key,
tags,
properties,
}
}
pub fn properties_mut(&mut self) -> &mut Properties {
&mut self.properties
}
pub fn properties(&self) -> &Properties {
&self.properties
}
pub fn tags_mut(&mut self) -> &mut ContextTags {
&mut self.tags
}
pub fn tags(&self) -> &ContextTags {
&self.tags
}
}
#[cfg(test)]
mod tests {
use matches::assert_matches;
use super::*;
#[test]
fn it_updates_common_properties() {
let config = TelemetryConfig::new("instrumentation".into());
let mut context = TelemetryContext::from_config(&config);
context.properties_mut().insert("Resource Group".into(), "my-rg".into());
assert_eq!(context.properties().len(), 1);
assert_eq!(context.properties().get("Resource Group"), Some(&"my-rg".to_string()));
}
#[test]
fn it_creates_a_context_with_default_values() {
let config = TelemetryConfig::new("instrumentation".into());
let context = TelemetryContext::from_config(&config);
assert_eq!(&context.i_key, "instrumentation");
assert_matches!(&context.tags().internal().sdk_version(), Some(_));
assert_matches!(&context.tags().device().os_version(), Some(_));
assert_matches!(&context.tags().device().id(), Some(_));
assert_matches!(&context.tags().cloud().role_instance(), Some(_));
assert!(context.properties().is_empty());
}
}