1use opentelemetry::{
35 global,
36 trace::{Span, SpanKind, Status, TraceContextExt, Tracer},
37 Context, KeyValue,
38};
39use opentelemetry_otlp::WithExportConfig;
40use opentelemetry_sdk::{
41 trace::{RandomIdGenerator, Sampler, SdkTracerProvider as TracerProvider},
42 Resource,
43};
44use opentelemetry_semantic_conventions as semconv;
45use serde::{Deserialize, Serialize};
46use std::sync::Arc;
47use std::time::Duration;
48use thiserror::Error;
49use tokio::sync::RwLock;
50use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, EnvFilter};
51
52#[derive(Debug, Error)]
54pub enum TracingError {
55 #[error("OpenTelemetry initialization failed: {0}")]
57 InitializationError(String),
58
59 #[error("Configuration error: {0}")]
61 ConfigError(String),
62
63 #[error("Failed to export traces: {0}")]
65 ExportError(String),
66
67 #[error("Tracing error: {0}")]
69 Other(String),
70}
71
72pub type Result<T> = std::result::Result<T, TracingError>;
73
74#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
76pub enum SamplingStrategy {
77 AlwaysOn,
79 AlwaysOff,
81 TraceIdRatioBased(f64),
83 ParentBased {
85 root: Box<SamplingStrategy>,
87 },
88}
89
90impl Default for SamplingStrategy {
91 fn default() -> Self {
92 Self::TraceIdRatioBased(0.1) }
94}
95
96#[derive(Debug, Clone, Serialize, Deserialize)]
98pub struct TracingConfig {
99 pub service_name: String,
101
102 pub service_version: String,
104
105 pub otlp_endpoint: Option<String>,
107
108 pub enabled: bool,
110
111 pub sampling_strategy: SamplingStrategy,
113
114 pub batch_timeout_ms: u64,
116
117 pub max_batch_size: usize,
119
120 pub export_timeout_ms: u64,
122
123 pub console_output: bool,
125
126 pub json_format: bool,
128
129 pub env_filter: String,
131
132 pub resource_attributes: Vec<(String, String)>,
134}
135
136impl Default for TracingConfig {
137 fn default() -> Self {
138 Self {
139 service_name: "oxirs-cluster".to_string(),
140 service_version: env!("CARGO_PKG_VERSION").to_string(),
141 otlp_endpoint: Some("http://localhost:4317".to_string()),
142 enabled: true,
143 sampling_strategy: SamplingStrategy::default(),
144 batch_timeout_ms: 5000,
145 max_batch_size: 512,
146 export_timeout_ms: 30000,
147 console_output: true,
148 json_format: false,
149 env_filter: "info".to_string(),
150 resource_attributes: Vec::new(),
151 }
152 }
153}
154
155impl TracingConfig {
156 pub fn with_service_name(mut self, name: impl Into<String>) -> Self {
158 self.service_name = name.into();
159 self
160 }
161
162 pub fn with_otlp_endpoint(mut self, endpoint: impl Into<String>) -> Self {
164 self.otlp_endpoint = Some(endpoint.into());
165 self
166 }
167
168 pub fn with_sampling_strategy(mut self, strategy: SamplingStrategy) -> Self {
170 self.sampling_strategy = strategy;
171 self
172 }
173
174 pub fn with_enabled(mut self, enabled: bool) -> Self {
176 self.enabled = enabled;
177 self
178 }
179
180 pub fn add_resource_attribute(
182 mut self,
183 key: impl Into<String>,
184 value: impl Into<String>,
185 ) -> Self {
186 self.resource_attributes.push((key.into(), value.into()));
187 self
188 }
189}
190
191pub struct TracingManager {
193 config: TracingConfig,
194 tracer_provider: Arc<RwLock<Option<TracerProvider>>>,
195 initialized: Arc<RwLock<bool>>,
196}
197
198impl TracingManager {
199 pub async fn new(config: TracingConfig) -> Result<Self> {
201 if !config.enabled {
202 return Ok(Self {
203 config,
204 tracer_provider: Arc::new(RwLock::new(None)),
205 initialized: Arc::new(RwLock::new(false)),
206 });
207 }
208
209 Ok(Self {
210 config,
211 tracer_provider: Arc::new(RwLock::new(None)),
212 initialized: Arc::new(RwLock::new(false)),
213 })
214 }
215
216 #[allow(deprecated)] #[allow(unused_variables)] pub async fn start(&self) -> Result<()> {
220 if !self.config.enabled {
221 tracing::info!("Distributed tracing is disabled");
222 return Ok(());
223 }
224
225 let mut initialized = self.initialized.write().await;
226 if *initialized {
227 return Ok(());
228 }
229
230 let mut all_attrs = vec![KeyValue::new(
232 semconv::resource::SERVICE_VERSION,
233 self.config.service_version.clone(),
234 )];
235
236 for (key, value) in &self.config.resource_attributes {
238 all_attrs.push(KeyValue::new(key.clone(), value.clone()));
239 }
240
241 let resource = Resource::builder_empty()
242 .with_service_name(self.config.service_name.clone())
243 .with_attributes(all_attrs)
244 .build();
245
246 let sampler = self.create_sampler(&self.config.sampling_strategy);
248
249 let provider = if let Some(otlp_endpoint) = &self.config.otlp_endpoint {
251 let exporter = opentelemetry_otlp::SpanExporter::builder()
253 .with_http()
254 .with_endpoint(otlp_endpoint.clone())
255 .with_timeout(Duration::from_millis(self.config.export_timeout_ms))
256 .build()
257 .map_err(|e| {
258 TracingError::InitializationError(format!(
259 "Failed to create OTLP exporter: {e}"
260 ))
261 })?;
262
263 TracerProvider::builder()
264 .with_batch_exporter(exporter)
265 .with_resource(resource)
266 .with_sampler(sampler)
267 .with_id_generator(RandomIdGenerator::default())
268 .build()
269 } else {
270 TracerProvider::builder()
272 .with_resource(resource)
273 .with_sampler(sampler)
274 .with_id_generator(RandomIdGenerator::default())
275 .build()
276 };
277
278 global::set_tracer_provider(provider.clone());
280
281 let mut tracer_provider = self.tracer_provider.write().await;
283 *tracer_provider = Some(provider);
284
285 self.init_tracing_subscriber()?;
287
288 *initialized = true;
289
290 tracing::info!(
291 service_name = %self.config.service_name,
292 otlp_endpoint = ?self.config.otlp_endpoint,
293 "Distributed tracing initialized"
294 );
295
296 Ok(())
297 }
298
299 pub async fn stop(&self) -> Result<()> {
301 if !*self.initialized.read().await {
302 return Ok(());
303 }
304
305 tracing::info!("Shutting down distributed tracing");
306
307 let mut provider = self.tracer_provider.write().await;
309 if let Some(provider) = provider.take() {
310 if let Err(e) = provider.shutdown() {
311 tracing::error!("Failed to shutdown tracer provider: {}", e);
312 }
313 }
314
315 let mut initialized = self.initialized.write().await;
319 *initialized = false;
320
321 Ok(())
322 }
323
324 pub async fn is_initialized(&self) -> bool {
326 *self.initialized.read().await
327 }
328
329 pub fn config(&self) -> &TracingConfig {
331 &self.config
332 }
333
334 fn create_sampler(&self, strategy: &SamplingStrategy) -> Sampler {
336 match strategy {
337 SamplingStrategy::AlwaysOn => Sampler::AlwaysOn,
338 SamplingStrategy::AlwaysOff => Sampler::AlwaysOff,
339 SamplingStrategy::TraceIdRatioBased(ratio) => Sampler::TraceIdRatioBased(*ratio),
340 SamplingStrategy::ParentBased { root } => {
341 let root_sampler = self.create_sampler(root);
342 Sampler::ParentBased(Box::new(root_sampler))
343 }
344 }
345 }
346
347 fn init_tracing_subscriber(&self) -> Result<()> {
349 let env_filter = EnvFilter::try_from_default_env()
351 .unwrap_or_else(|_| EnvFilter::new(&self.config.env_filter));
352
353 if self.config.console_output {
360 if self.config.json_format {
361 let json_layer = tracing_subscriber::fmt::layer().json();
362 tracing_subscriber::registry()
363 .with(env_filter)
364 .with(json_layer)
365 .try_init()
366 .map_err(|e| {
367 TracingError::InitializationError(format!(
368 "Failed to initialize subscriber: {e}"
369 ))
370 })?;
371 } else {
372 let fmt_layer = tracing_subscriber::fmt::layer();
373 tracing_subscriber::registry()
374 .with(env_filter)
375 .with(fmt_layer)
376 .try_init()
377 .map_err(|e| {
378 TracingError::InitializationError(format!(
379 "Failed to initialize subscriber: {e}"
380 ))
381 })?;
382 }
383 } else {
384 tracing_subscriber::registry()
385 .with(env_filter)
386 .try_init()
387 .map_err(|e| {
388 TracingError::InitializationError(format!(
389 "Failed to initialize subscriber: {e}"
390 ))
391 })?;
392 }
393
394 tracing::warn!(
395 "OpenTelemetry integration temporarily disabled due to version compatibility"
396 );
397
398 Ok(())
399 }
400}
401
402pub mod span_helpers {
404 use super::*;
405
406 pub fn consensus_span(operation: &str, node_id: u64, term: u64) -> impl Span {
408 let tracer = global::tracer("oxirs-cluster");
409 let mut span = tracer
410 .span_builder(format!("consensus.{}", operation))
411 .with_kind(SpanKind::Internal)
412 .start(&tracer);
413
414 span.set_attribute(KeyValue::new("node.id", node_id as i64));
415 span.set_attribute(KeyValue::new("consensus.term", term as i64));
416 span.set_attribute(KeyValue::new("operation.type", "consensus"));
417
418 span
419 }
420
421 pub fn replication_span(operation: &str, source_node: u64, target_node: u64) -> impl Span {
423 let tracer = global::tracer("oxirs-cluster");
424 let mut span = tracer
425 .span_builder(format!("replication.{}", operation))
426 .with_kind(SpanKind::Internal)
427 .start(&tracer);
428
429 span.set_attribute(KeyValue::new("source.node.id", source_node as i64));
430 span.set_attribute(KeyValue::new("target.node.id", target_node as i64));
431 span.set_attribute(KeyValue::new("operation.type", "replication"));
432
433 span
434 }
435
436 pub fn query_span(query_type: &str, node_id: u64) -> impl Span {
438 let tracer = global::tracer("oxirs-cluster");
439 let mut span = tracer
440 .span_builder(format!("query.{}", query_type))
441 .with_kind(SpanKind::Server)
442 .start(&tracer);
443
444 span.set_attribute(KeyValue::new("node.id", node_id as i64));
445 span.set_attribute(KeyValue::new("operation.type", "query"));
446
447 span
448 }
449
450 pub fn storage_span(operation: &str, node_id: u64) -> impl Span {
452 let tracer = global::tracer("oxirs-cluster");
453 let mut span = tracer
454 .span_builder(format!("storage.{}", operation))
455 .with_kind(SpanKind::Internal)
456 .start(&tracer);
457
458 span.set_attribute(KeyValue::new("node.id", node_id as i64));
459 span.set_attribute(KeyValue::new("operation.type", "storage"));
460
461 span
462 }
463
464 pub fn mark_success(span: &mut impl Span) {
466 span.set_status(Status::Ok);
467 }
468
469 pub fn mark_error(span: &mut impl Span, error: &str) {
471 span.set_status(Status::error(error.to_string()));
472 span.set_attribute(KeyValue::new("error", true));
473 span.set_attribute(KeyValue::new("error.message", error.to_string()));
474 }
475}
476
477#[derive(Debug, Clone)]
479pub struct TracingContext {
480 pub trace_id: String,
482 pub span_id: String,
484 pub parent_span_id: Option<String>,
486 pub trace_flags: u8,
488}
489
490impl TracingContext {
491 pub fn current() -> Option<Self> {
493 let context = Context::current();
494 let span = context.span();
495 let span_context = span.span_context();
496
497 if span_context.is_valid() {
498 Some(Self {
499 trace_id: span_context.trace_id().to_string(),
500 span_id: span_context.span_id().to_string(),
501 parent_span_id: None,
502 trace_flags: span_context.trace_flags().to_u8(),
503 })
504 } else {
505 None
506 }
507 }
508
509 pub fn to_headers(&self) -> Vec<(String, String)> {
511 vec![
512 ("x-trace-id".to_string(), self.trace_id.clone()),
513 ("x-span-id".to_string(), self.span_id.clone()),
514 ("x-trace-flags".to_string(), self.trace_flags.to_string()),
515 ]
516 }
517}
518
519#[derive(Debug, Clone, Serialize, Deserialize)]
521pub struct TracingStatistics {
522 pub total_spans_created: u64,
524 pub total_spans_exported: u64,
526 pub total_export_errors: u64,
528 pub current_sampling_rate: f64,
530 pub avg_span_duration_ms: f64,
532 pub is_active: bool,
534}
535
536#[cfg(test)]
537mod tests {
538 use super::*;
539
540 #[test]
541 fn test_tracing_config_default() {
542 let config = TracingConfig::default();
543 assert_eq!(config.service_name, "oxirs-cluster");
544 assert!(config.enabled);
545 assert_eq!(
546 config.sampling_strategy,
547 SamplingStrategy::TraceIdRatioBased(0.1)
548 );
549 }
550
551 #[test]
552 fn test_tracing_config_builder() {
553 let config = TracingConfig::default()
554 .with_service_name("test-service")
555 .with_otlp_endpoint("http://test:4317")
556 .with_sampling_strategy(SamplingStrategy::AlwaysOn)
557 .with_enabled(false);
558
559 assert_eq!(config.service_name, "test-service");
560 assert_eq!(config.otlp_endpoint, Some("http://test:4317".to_string()));
561 assert_eq!(config.sampling_strategy, SamplingStrategy::AlwaysOn);
562 assert!(!config.enabled);
563 }
564
565 #[test]
566 fn test_sampling_strategies() {
567 let always_on = SamplingStrategy::AlwaysOn;
568 let always_off = SamplingStrategy::AlwaysOff;
569 let ratio = SamplingStrategy::TraceIdRatioBased(0.5);
570
571 assert!(matches!(always_on, SamplingStrategy::AlwaysOn));
572 assert!(matches!(always_off, SamplingStrategy::AlwaysOff));
573 if let SamplingStrategy::TraceIdRatioBased(r) = ratio {
574 assert_eq!(r, 0.5);
575 }
576 }
577
578 #[tokio::test]
579 async fn test_tracing_manager_creation() {
580 let config = TracingConfig::default().with_enabled(false);
581 let manager = TracingManager::new(config).await;
582 assert!(manager.is_ok());
583 }
584
585 #[tokio::test]
586 async fn test_tracing_manager_disabled() {
587 let config = TracingConfig::default().with_enabled(false);
588 let manager = TracingManager::new(config).await.unwrap();
589
590 let result = manager.start().await;
591 assert!(result.is_ok());
592 assert!(!manager.is_initialized().await);
593 }
594}