1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
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());
}
}