otelite_core/telemetry/
resource.rs1use serde::{Deserialize, Serialize};
4use std::collections::HashMap;
5
6#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
8pub struct Resource {
9 pub attributes: HashMap<String, String>,
11}
12
13impl Resource {
14 pub fn new() -> Self {
16 Self {
17 attributes: HashMap::new(),
18 }
19 }
20
21 pub fn with_service_name(name: impl Into<String>) -> Self {
23 let mut resource = Self::new();
24 resource
25 .attributes
26 .insert("service.name".to_string(), name.into());
27 resource
28 }
29
30 pub fn with_attribute(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
32 self.attributes.insert(key.into(), value.into());
33 self
34 }
35
36 pub fn get_attribute(&self, key: &str) -> Option<&String> {
38 self.attributes.get(key)
39 }
40
41 pub fn service_name(&self) -> Option<&String> {
43 self.get_attribute("service.name")
44 }
45}
46
47impl Default for Resource {
48 fn default() -> Self {
49 Self::new()
50 }
51}
52
53#[cfg(test)]
54mod tests {
55 use super::*;
56
57 #[test]
58 fn test_resource_creation() {
59 let resource = Resource::new();
60 assert!(resource.attributes.is_empty());
61 }
62
63 #[test]
64 fn test_resource_with_service_name() {
65 let resource = Resource::with_service_name("my-service");
66 assert_eq!(resource.service_name(), Some(&"my-service".to_string()));
67 }
68
69 #[test]
70 fn test_resource_with_attributes() {
71 let resource = Resource::with_service_name("my-service")
72 .with_attribute("service.version", "1.0.0")
73 .with_attribute("deployment.environment", "production")
74 .with_attribute("host.name", "server-01");
75
76 assert_eq!(resource.attributes.len(), 4);
77 assert_eq!(
78 resource.get_attribute("service.version"),
79 Some(&"1.0.0".to_string())
80 );
81 assert_eq!(
82 resource.get_attribute("deployment.environment"),
83 Some(&"production".to_string())
84 );
85 }
86
87 #[test]
88 fn test_resource_get_nonexistent_attribute() {
89 let resource = Resource::with_service_name("my-service");
90 assert_eq!(resource.get_attribute("nonexistent"), None);
91 }
92}