use std::fmt;
#[derive(Debug, Clone)]
pub struct TelemetryConfig {
pub service_name: String,
pub otlp_endpoint: String,
pub prometheus_port: u16,
pub enable_traces: bool,
pub enable_metrics: bool,
}
impl TelemetryConfig {
pub fn new(service_name: String, otlp_endpoint: String) -> Self {
Self {
service_name,
otlp_endpoint,
prometheus_port: 9090,
enable_traces: true,
enable_metrics: true,
}
}
pub fn with_prometheus_port(mut self, port: u16) -> Self {
self.prometheus_port = port;
self
}
pub fn with_traces_enabled(mut self, enabled: bool) -> Self {
self.enable_traces = enabled;
self
}
pub fn with_metrics_enabled(mut self, enabled: bool) -> Self {
self.enable_metrics = enabled;
self
}
pub fn validate(&self) -> Result<(), String> {
if self.service_name.is_empty() {
return Err("service_name cannot be empty".to_string());
}
if self.otlp_endpoint.is_empty() {
return Err("otlp_endpoint cannot be empty".to_string());
}
if self.prometheus_port == 0 {
return Err("prometheus_port must be between 1 and 65535".to_string());
}
Ok(())
}
}
impl Default for TelemetryConfig {
fn default() -> Self {
Self {
service_name: "absurdersql".to_string(),
otlp_endpoint: "http://localhost:4317".to_string(),
prometheus_port: 9090,
enable_traces: true,
enable_metrics: true,
}
}
}
impl fmt::Display for TelemetryConfig {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"TelemetryConfig {{ service: {}, otlp: {}, prom_port: {}, traces: {}, metrics: {} }}",
self.service_name,
self.otlp_endpoint,
self.prometheus_port,
self.enable_traces,
self.enable_metrics
)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_config_builder_pattern() {
let config = TelemetryConfig::new("test".to_string(), "http://test:4317".to_string())
.with_prometheus_port(8080)
.with_traces_enabled(false);
assert_eq!(config.service_name, "test");
assert_eq!(config.prometheus_port, 8080);
assert!(!config.enable_traces);
}
#[test]
fn test_validate_success() {
let config = TelemetryConfig::default();
assert!(config.validate().is_ok());
}
#[test]
fn test_validate_empty_service_name() {
let config = TelemetryConfig {
service_name: "".to_string(),
..Default::default()
};
assert!(config.validate().is_err());
}
}