Skip to main content

otelite_core/telemetry/
resource.rs

1//! Resource types for telemetry data
2
3use serde::{Deserialize, Serialize};
4use std::collections::HashMap;
5
6/// Represents a resource (source of telemetry)
7#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
8pub struct Resource {
9    /// Resource attributes (key-value pairs)
10    pub attributes: HashMap<String, String>,
11}
12
13impl Resource {
14    /// Create a new empty resource
15    pub fn new() -> Self {
16        Self {
17            attributes: HashMap::new(),
18        }
19    }
20
21    /// Create a resource with service name
22    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    /// Add an attribute to the resource
31    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    /// Get an attribute value
37    pub fn get_attribute(&self, key: &str) -> Option<&String> {
38        self.attributes.get(key)
39    }
40
41    /// Get the service name
42    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}