Skip to main content

oxirs_cluster/
distributed_tracing.rs

1//! Distributed Tracing with OpenTelemetry Integration
2//!
3//! This module provides comprehensive distributed tracing capabilities for the OxiRS cluster,
4//! enabling visibility into distributed operations, performance profiling, and debugging
5//! across multiple nodes.
6//!
7//! # Features
8//!
9//! - **OpenTelemetry Integration**: Industry-standard distributed tracing
10//! - **OTLP Export**: Export traces to Jaeger, Zipkin, or any OTLP-compatible backend
11//! - **Automatic Context Propagation**: Trace contexts propagate across service boundaries
12//! - **Performance Profiling**: Detailed timing information for operations
13//! - **Custom Attributes**: Rich metadata for debugging and analysis
14//! - **Sampling Strategies**: Configurable sampling to control overhead
15//!
16//! # Example
17//!
18//! ```rust,no_run
19//! use oxirs_cluster::distributed_tracing::{TracingConfig, TracingManager};
20//!
21//! # async fn example() -> anyhow::Result<()> {
22//! let config = TracingConfig::default()
23//!     .with_service_name("oxirs-cluster")
24//!     .with_otlp_endpoint("http://localhost:4317");
25//!
26//! let tracing_manager = TracingManager::new(config).await?;
27//! tracing_manager.start().await?;
28//!
29//! // Traces are automatically collected and exported
30//! # Ok(())
31//! # }
32//! ```
33
34use 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/// Errors that can occur during distributed tracing operations
53#[derive(Debug, Error)]
54pub enum TracingError {
55    /// OpenTelemetry initialization error
56    #[error("OpenTelemetry initialization failed: {0}")]
57    InitializationError(String),
58
59    /// Configuration error
60    #[error("Configuration error: {0}")]
61    ConfigError(String),
62
63    /// Export error
64    #[error("Failed to export traces: {0}")]
65    ExportError(String),
66
67    /// Other errors
68    #[error("Tracing error: {0}")]
69    Other(String),
70}
71
72pub type Result<T> = std::result::Result<T, TracingError>;
73
74/// Sampling strategy for distributed tracing
75#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
76pub enum SamplingStrategy {
77    /// Always sample all traces
78    AlwaysOn,
79    /// Never sample any traces
80    AlwaysOff,
81    /// Sample based on a ratio (0.0 to 1.0)
82    TraceIdRatioBased(f64),
83    /// Parent-based sampling with fallback
84    ParentBased {
85        /// Root sampler when there is no parent
86        root: Box<SamplingStrategy>,
87    },
88}
89
90impl Default for SamplingStrategy {
91    fn default() -> Self {
92        Self::TraceIdRatioBased(0.1) // 10% sampling by default
93    }
94}
95
96/// Configuration for distributed tracing
97#[derive(Debug, Clone, Serialize, Deserialize)]
98pub struct TracingConfig {
99    /// Service name for tracing
100    pub service_name: String,
101
102    /// Service version
103    pub service_version: String,
104
105    /// OTLP endpoint for exporting traces
106    pub otlp_endpoint: Option<String>,
107
108    /// Enable tracing
109    pub enabled: bool,
110
111    /// Sampling strategy
112    pub sampling_strategy: SamplingStrategy,
113
114    /// Batch export timeout (milliseconds)
115    pub batch_timeout_ms: u64,
116
117    /// Maximum batch size
118    pub max_batch_size: usize,
119
120    /// Export timeout (milliseconds)
121    pub export_timeout_ms: u64,
122
123    /// Enable console output
124    pub console_output: bool,
125
126    /// Enable JSON formatting
127    pub json_format: bool,
128
129    /// Environment filter (e.g., "info,oxirs_cluster=debug")
130    pub env_filter: String,
131
132    /// Custom resource attributes
133    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    /// Set the service name
157    pub fn with_service_name(mut self, name: impl Into<String>) -> Self {
158        self.service_name = name.into();
159        self
160    }
161
162    /// Set the OTLP endpoint
163    pub fn with_otlp_endpoint(mut self, endpoint: impl Into<String>) -> Self {
164        self.otlp_endpoint = Some(endpoint.into());
165        self
166    }
167
168    /// Set the sampling strategy
169    pub fn with_sampling_strategy(mut self, strategy: SamplingStrategy) -> Self {
170        self.sampling_strategy = strategy;
171        self
172    }
173
174    /// Enable or disable tracing
175    pub fn with_enabled(mut self, enabled: bool) -> Self {
176        self.enabled = enabled;
177        self
178    }
179
180    /// Add a custom resource attribute
181    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
191/// Distributed tracing manager
192pub struct TracingManager {
193    config: TracingConfig,
194    tracer_provider: Arc<RwLock<Option<TracerProvider>>>,
195    initialized: Arc<RwLock<bool>>,
196}
197
198impl TracingManager {
199    /// Create a new tracing manager with the given configuration
200    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    /// Start the tracing manager and initialize OpenTelemetry
217    #[allow(deprecated)] // Temporarily using deprecated API until version compatibility is resolved
218    #[allow(unused_variables)] // batch_config will be used when OTLP export is re-enabled
219    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        // Build resource with all attributes
231        let mut all_attrs = vec![KeyValue::new(
232            semconv::resource::SERVICE_VERSION,
233            self.config.service_version.clone(),
234        )];
235
236        // Add custom resource attributes
237        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        // Create sampler based on strategy
247        let sampler = self.create_sampler(&self.config.sampling_strategy);
248
249        // Create tracer provider
250        let provider = if let Some(otlp_endpoint) = &self.config.otlp_endpoint {
251            // Create OTLP exporter using HTTP (tonic support removed in 0.31)
252            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            // No OTLP endpoint, use simple provider
271            TracerProvider::builder()
272                .with_resource(resource)
273                .with_sampler(sampler)
274                .with_id_generator(RandomIdGenerator::default())
275                .build()
276        };
277
278        // Set global tracer provider
279        global::set_tracer_provider(provider.clone());
280
281        // Store provider
282        let mut tracer_provider = self.tracer_provider.write().await;
283        *tracer_provider = Some(provider);
284
285        // Initialize tracing subscriber
286        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    /// Stop the tracing manager and flush pending traces
300    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        // Shutdown tracer provider
308        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        // Note: In OpenTelemetry 0.31, global shutdown is handled automatically
316        // when the provider is dropped or explicitly shut down
317
318        let mut initialized = self.initialized.write().await;
319        *initialized = false;
320
321        Ok(())
322    }
323
324    /// Check if tracing is initialized
325    pub async fn is_initialized(&self) -> bool {
326        *self.initialized.read().await
327    }
328
329    /// Get the current configuration
330    pub fn config(&self) -> &TracingConfig {
331        &self.config
332    }
333
334    /// Create a sampler based on the strategy
335    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    /// Initialize tracing subscriber
348    fn init_tracing_subscriber(&self) -> Result<()> {
349        // Create env filter
350        let env_filter = EnvFilter::try_from_default_env()
351            .unwrap_or_else(|_| EnvFilter::new(&self.config.env_filter));
352
353        // Build and initialize subscriber
354        // Note: OpenTelemetry layer integration is temporarily disabled due to version compatibility issues
355        // between tracing-opentelemetry and opentelemetry crates. This is a known issue in the ecosystem.
356        // The integration will be re-enabled automatically when upstream dependencies release compatible versions.
357        // Current workaround: Using JSON-formatted tracing output which can be ingested by most observability platforms.
358        // Related: https://github.com/tokio-rs/tracing-opentelemetry/issues
359        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
402/// Helper functions for creating spans with common attributes
403pub mod span_helpers {
404    use super::*;
405
406    /// Create a span for a consensus operation
407    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    /// Create a span for a replication operation
422    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    /// Create a span for a query operation
437    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    /// Create a span for a storage operation
451    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    /// Mark a span as successful
465    pub fn mark_success(span: &mut impl Span) {
466        span.set_status(Status::Ok);
467    }
468
469    /// Mark a span as failed with an error message
470    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/// Tracing context for distributed operations
478#[derive(Debug, Clone)]
479pub struct TracingContext {
480    /// Trace ID
481    pub trace_id: String,
482    /// Span ID
483    pub span_id: String,
484    /// Parent span ID (if any)
485    pub parent_span_id: Option<String>,
486    /// Trace flags
487    pub trace_flags: u8,
488}
489
490impl TracingContext {
491    /// Extract tracing context from the current OpenTelemetry context
492    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    /// Serialize to headers for propagation
510    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/// Statistics about distributed tracing
520#[derive(Debug, Clone, Serialize, Deserialize)]
521pub struct TracingStatistics {
522    /// Total number of spans created
523    pub total_spans_created: u64,
524    /// Total number of spans exported
525    pub total_spans_exported: u64,
526    /// Total number of export errors
527    pub total_export_errors: u64,
528    /// Current sampling rate
529    pub current_sampling_rate: f64,
530    /// Average span duration (milliseconds)
531    pub avg_span_duration_ms: f64,
532    /// Is tracing active
533    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}