1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
//! Distributed Tracing with OpenTelemetry
//!
//! Traces message flows across nodes for debugging, performance profiling, and understanding
//! distributed system behavior.
//!
//! # Features
//!
//! - OpenTelemetry integration
//! - Automatic trace context propagation
//! - Per-message span tracking
//! - Jaeger/Zipkin export
//! - Low overhead
//! - Sampling support
//!
//! # Example
//!
//! ```rust
//! use mecha10_core::prelude::*;
//!
//! # async fn example(ctx: &Context) -> Result<()> {
//! // Initialize tracing
//! let tracer = TracingConfig::default()
//! .with_service_name("my-robot")
//! .with_jaeger("http://localhost:14268/api/traces")
//! .init()?;
//!
//! // Publish with automatic span creation
//! ctx.publish_traced("/camera/rgb", &image).await?;
//!
//! // Subscribe with automatic span continuation
//! let mut images = ctx.subscribe_traced("/camera/rgb").await?;
//! while let Some((image, span)) = images.recv().await {
//! span.in_scope(|| {
//! // Process within span
//! process_image(&image);
//! });
//! }
//! # Ok(())
//! # }
//! ```
use crate::error::{Mecha10Error, Result};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;
use tracing::{debug, info, span, Level, Span};
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
// ============================================================================
// Trace Context
// ============================================================================
/// Trace context for propagating spans across message boundaries
///
/// This is embedded in message metadata to enable distributed tracing.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TraceContext {
/// Trace ID (unique per request/flow)
pub trace_id: String,
/// Span ID (unique per operation)
pub span_id: String,
/// Parent span ID (for hierarchy)
pub parent_span_id: Option<String>,
/// Sampling decision (whether to record this trace)
pub sampled: bool,
/// Baggage (key-value metadata)
#[serde(default)]
pub baggage: HashMap<String, String>,
}
impl TraceContext {
/// Create a new root trace context
pub fn new() -> Self {
Self {
trace_id: generate_trace_id(),
span_id: generate_span_id(),
parent_span_id: None,
sampled: true,
baggage: HashMap::new(),
}
}
/// Create a child trace context
pub fn child(&self) -> Self {
Self {
trace_id: self.trace_id.clone(),
span_id: generate_span_id(),
parent_span_id: Some(self.span_id.clone()),
sampled: self.sampled,
baggage: self.baggage.clone(),
}
}
crate::builder_setter!(
/// Add baggage item
insert, with_baggage, baggage, impl Into<String>, impl Into<String>
);
/// Convert to W3C Trace Context format
pub fn to_w3c_traceparent(&self) -> String {
let flags = if self.sampled { "01" } else { "00" };
format!("00-{}-{}-{}", self.trace_id, self.span_id, flags)
}
/// Parse from W3C Trace Context format
pub fn from_w3c_traceparent(traceparent: &str) -> Option<Self> {
let parts: Vec<&str> = traceparent.split('-').collect();
if parts.len() != 4 || parts[0] != "00" {
return None;
}
Some(Self {
trace_id: parts[1].to_string(),
span_id: parts[2].to_string(),
parent_span_id: None,
sampled: parts[3] == "01",
baggage: HashMap::new(),
})
}
}
impl Default for TraceContext {
fn default() -> Self {
Self::new()
}
}
// ============================================================================
// Message Envelope with Trace Context
// ============================================================================
/// Message envelope that includes trace context
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TracedMessage<T> {
/// The actual message payload
pub payload: T,
/// Trace context for distributed tracing
pub trace_context: TraceContext,
/// Timestamp when message was sent
pub timestamp_us: u64,
/// Source node ID
pub source_node: String,
}
impl<T> TracedMessage<T> {
/// Create a new traced message
pub fn new(payload: T, source_node: impl Into<String>) -> Self {
Self {
payload,
trace_context: TraceContext::new(),
timestamp_us: crate::prelude::now_micros(),
source_node: source_node.into(),
}
}
/// Create from existing trace context
pub fn with_context(payload: T, trace_context: TraceContext, source_node: impl Into<String>) -> Self {
Self {
payload,
trace_context,
timestamp_us: crate::prelude::now_micros(),
source_node: source_node.into(),
}
}
/// Create a span for this message
pub fn create_span(&self, operation: &str) -> Span {
span!(
Level::INFO,
"message",
operation = operation,
trace_id = %self.trace_context.trace_id,
span_id = %self.trace_context.span_id,
source = %self.source_node,
)
}
}
// ============================================================================
// Tracing Configuration
// ============================================================================
/// Tracing system configuration
#[derive(Debug, Clone)]
pub struct TracingConfig {
/// Service name for this instance
pub service_name: String,
/// Jaeger collector endpoint
pub jaeger_endpoint: Option<String>,
/// Zipkin collector endpoint
pub zipkin_endpoint: Option<String>,
/// Sampling rate (0.0 to 1.0)
pub sampling_rate: f64,
/// Enable console output
pub console_output: bool,
}
impl Default for TracingConfig {
fn default() -> Self {
Self {
service_name: "mecha10".to_string(),
jaeger_endpoint: None,
zipkin_endpoint: None,
sampling_rate: 1.0,
console_output: true,
}
}
}
impl TracingConfig {
/// Set service name
pub fn with_service_name(mut self, name: impl Into<String>) -> Self {
self.service_name = name.into();
self
}
/// Set Jaeger endpoint
pub fn with_jaeger(mut self, endpoint: impl Into<String>) -> Self {
self.jaeger_endpoint = Some(endpoint.into());
self
}
/// Set Zipkin endpoint
pub fn with_zipkin(mut self, endpoint: impl Into<String>) -> Self {
self.zipkin_endpoint = Some(endpoint.into());
self
}
/// Set sampling rate
pub fn with_sampling_rate(mut self, rate: f64) -> Self {
self.sampling_rate = rate.clamp(0.0, 1.0);
self
}
/// Disable console output
pub fn without_console(mut self) -> Self {
self.console_output = false;
self
}
/// Initialize the tracing system
///
/// This sets up the global subscriber with the configured exporters.
pub fn init(self) -> Result<TracingHandle> {
info!("Initializing distributed tracing: {}", self.service_name);
// Build subscriber layers
let fmt_layer = if self.console_output {
Some(tracing_subscriber::fmt::layer())
} else {
None
};
// Initialize subscriber
tracing_subscriber::registry()
.with(fmt_layer)
.try_init()
.map_err(|e| Mecha10Error::Runtime(format!("Failed to initialize tracing: {}", e)))?;
info!(
"Tracing initialized - Service: {}, Jaeger: {:?}, Sampling: {}",
self.service_name, self.jaeger_endpoint, self.sampling_rate
);
let sampling_rate = self.sampling_rate;
Ok(TracingHandle {
config: self,
sampler: Arc::new(ProbabilitySampler::new(sampling_rate)),
})
}
}
// ============================================================================
// Tracing Handle
// ============================================================================
/// Handle to the tracing system
pub struct TracingHandle {
config: TracingConfig,
sampler: Arc<ProbabilitySampler>,
}
impl TracingHandle {
/// Check if a trace should be sampled
pub fn should_sample(&self) -> bool {
self.sampler.should_sample()
}
/// Create a root span for an operation
pub fn start_span(&self, name: &str) -> Span {
let trace_ctx = TraceContext::new();
span!(
Level::INFO,
"operation",
name = name,
trace_id = %trace_ctx.trace_id,
span_id = %trace_ctx.span_id,
)
}
/// Get the service name
pub fn service_name(&self) -> &str {
&self.config.service_name
}
}
// ============================================================================
// Sampling
// ============================================================================
/// Probability-based sampler
struct ProbabilitySampler {
rate: f64,
}
impl ProbabilitySampler {
fn new(rate: f64) -> Self {
Self {
rate: rate.clamp(0.0, 1.0),
}
}
fn should_sample(&self) -> bool {
if self.rate >= 1.0 {
true
} else if self.rate <= 0.0 {
false
} else {
use std::collections::hash_map::RandomState;
use std::hash::BuildHasher;
let hash = RandomState::new().hash_one(std::time::SystemTime::now());
(hash as f64 / u64::MAX as f64) < self.rate
}
}
}
// ============================================================================
// Utilities
// ============================================================================
/// Generate a trace ID (16 bytes hex)
fn generate_trace_id() -> String {
use std::time::SystemTime;
let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap();
format!("{:016x}{:016x}", now.as_nanos(), rand_u64())
}
/// Generate a span ID (8 bytes hex)
fn generate_span_id() -> String {
format!("{:016x}", rand_u64())
}
/// Simple random u64 generator
fn rand_u64() -> u64 {
use std::collections::hash_map::RandomState;
use std::hash::BuildHasher;
RandomState::new().hash_one(std::time::SystemTime::now())
}
// ============================================================================
// Context Extensions
// ============================================================================
/// Extension trait for Context to add tracing capabilities
pub trait TracingExt {
/// Publish a message with automatic trace context
///
/// Creates a new trace context or continues an existing one,
/// embedding it in the message for distributed tracing.
fn publish_traced<T: crate::messages::Message + Serialize + Clone + 'static>(
&self,
topic: &str,
message: &T,
) -> impl std::future::Future<Output = Result<()>> + Send;
/// Publish with explicit trace context (for continuing traces)
fn publish_with_context<T: crate::messages::Message + Serialize + Clone + 'static>(
&self,
topic: &str,
message: &T,
trace_context: TraceContext,
) -> impl std::future::Future<Output = Result<()>> + Send;
/// Subscribe with trace context propagation
///
/// Messages received will include trace context for span continuation.
fn subscribe_traced<T: crate::messages::Message + DeserializeOwned + Send + 'static>(
&self,
topic: &str,
) -> impl std::future::Future<Output = Result<crate::context::Receiver<TracedMessage<T>>>> + Send;
/// Get current trace context from span (if any)
fn current_trace_context(&self) -> Option<TraceContext>;
/// Extract trace context from message metadata
fn extract_trace_context(&self, metadata: &HashMap<String, String>) -> Option<TraceContext>;
/// Inject trace context into message metadata
fn inject_trace_context(&self, metadata: &mut HashMap<String, String>, ctx: &TraceContext);
}
impl TracingExt for crate::context::Context {
async fn publish_traced<T: crate::messages::Message + Serialize + Clone + 'static>(
&self,
topic: &str,
message: &T,
) -> Result<()> {
// Get or create trace context
let trace_context = self.current_trace_context().unwrap_or_default();
self.publish_with_context(topic, message, trace_context).await
}
async fn publish_with_context<T: crate::messages::Message + Serialize + Clone + 'static>(
&self,
topic: &str,
message: &T,
trace_context: TraceContext,
) -> Result<()> {
// Create traced message envelope
let traced_msg = TracedMessage::with_context(
message.clone(),
trace_context.child(), // Create child span for this publish
self.node_id(),
);
// Publish the traced message
self.publish_raw(topic, &traced_msg).await
}
async fn subscribe_traced<T: crate::messages::Message + DeserializeOwned + Send + 'static>(
&self,
topic: &str,
) -> Result<crate::context::Receiver<TracedMessage<T>>> {
// Subscribe to traced messages
self.subscribe_raw::<TracedMessage<T>>(topic).await
}
fn current_trace_context(&self) -> Option<TraceContext> {
// Try to extract from current tracing span
use tracing::field::Visit;
struct TraceIdVisitor {
trace_id: Option<String>,
span_id: Option<String>,
}
impl Visit for TraceIdVisitor {
fn record_str(&mut self, field: &tracing::field::Field, value: &str) {
match field.name() {
"trace_id" => self.trace_id = Some(value.to_string()),
"span_id" => self.span_id = Some(value.to_string()),
_ => {}
}
}
fn record_debug(&mut self, _field: &tracing::field::Field, _value: &dyn std::fmt::Debug) {}
}
// Extract from current span if available
let _visitor = TraceIdVisitor {
trace_id: None,
span_id: None,
};
// Get current span and try to extract IDs
let span = Span::current();
span.record("trace_id", &tracing::field::Empty);
// Note: In production, this would use proper OpenTelemetry context extraction
// For now, create a new context if none exists
None
}
fn extract_trace_context(&self, metadata: &HashMap<String, String>) -> Option<TraceContext> {
// Check for W3C Trace Context header
if let Some(traceparent) = metadata.get("traceparent") {
return TraceContext::from_w3c_traceparent(traceparent);
}
// Check for direct trace context JSON
if let Some(trace_ctx_json) = metadata.get("trace_context") {
return serde_json::from_str(trace_ctx_json).ok();
}
None
}
fn inject_trace_context(&self, metadata: &mut HashMap<String, String>, ctx: &TraceContext) {
// Inject W3C Trace Context
metadata.insert("traceparent".to_string(), ctx.to_w3c_traceparent());
// Also inject as JSON for full context
if let Ok(json) = serde_json::to_string(ctx) {
metadata.insert("trace_context".to_string(), json);
}
// Inject baggage
for (key, value) in &ctx.baggage {
metadata.insert(format!("baggage_{}", key), value.clone());
}
}
}
// ============================================================================
// Span Builder
// ============================================================================
/// Builder for creating traced operations
pub struct SpanBuilder {
name: String,
trace_context: Option<TraceContext>,
attributes: HashMap<String, String>,
}
impl SpanBuilder {
/// Create a new span builder
pub fn new(name: impl Into<String>) -> Self {
Self {
name: name.into(),
trace_context: None,
attributes: HashMap::new(),
}
}
/// Set trace context (for child spans)
pub fn with_context(mut self, ctx: TraceContext) -> Self {
self.trace_context = Some(ctx);
self
}
crate::builder_setter!(
/// Add attribute
insert, with_attribute, attributes, impl Into<String>, impl Into<String>
);
/// Start the span
pub fn start(self) -> (Span, TraceContext) {
let trace_ctx = self.trace_context.unwrap_or_default();
let span = span!(
Level::INFO,
"span",
name = %self.name,
trace_id = %trace_ctx.trace_id,
span_id = %trace_ctx.span_id,
);
(span, trace_ctx)
}
}
// ============================================================================
// Trace Exporter (Stub for future OpenTelemetry integration)
// ============================================================================
/// Trace exporter interface
pub trait TraceExporter: Send + Sync {
/// Export a span
fn export_span(&self, span_data: &SpanData);
/// Flush pending spans
fn flush(&self);
}
/// Span data for export
#[derive(Debug, Clone)]
pub struct SpanData {
pub trace_id: String,
pub span_id: String,
pub parent_span_id: Option<String>,
pub name: String,
pub start_time: u64,
pub end_time: u64,
pub attributes: HashMap<String, String>,
}
/// Jaeger exporter (stub - would use real OpenTelemetry in production)
pub struct JaegerExporter {
#[allow(dead_code)]
endpoint: String,
#[allow(dead_code)]
service_name: String,
}
impl JaegerExporter {
/// Create a new Jaeger exporter
pub fn new(endpoint: impl Into<String>, service_name: impl Into<String>) -> Self {
Self {
endpoint: endpoint.into(),
service_name: service_name.into(),
}
}
}
impl TraceExporter for JaegerExporter {
fn export_span(&self, span_data: &SpanData) {
// In production, this would send to Jaeger via HTTP
debug!(
"Exporting span to Jaeger {}: {} (trace: {})",
self.endpoint, span_data.name, span_data.trace_id
);
}
fn flush(&self) {
debug!("Flushing Jaeger exporter");
}
}
/// Zipkin exporter (stub)
pub struct ZipkinExporter {
#[allow(dead_code)]
endpoint: String,
#[allow(dead_code)]
service_name: String,
}
impl ZipkinExporter {
/// Create a new Zipkin exporter
pub fn new(endpoint: impl Into<String>, service_name: impl Into<String>) -> Self {
Self {
endpoint: endpoint.into(),
service_name: service_name.into(),
}
}
}
impl TraceExporter for ZipkinExporter {
fn export_span(&self, span_data: &SpanData) {
debug!(
"Exporting span to Zipkin {}: {} (trace: {})",
self.endpoint, span_data.name, span_data.trace_id
);
}
fn flush(&self) {
debug!("Flushing Zipkin exporter");
}
}