mabi-core 1.6.1

Mabinogion - Core abstractions and utilities for industrial protocol simulator
Documentation
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
//! Structured context propagation for distributed tracing.
//!
//! This module provides utilities for propagating context information
//! across async boundaries and between services. It supports:
//!
//! - Request/correlation IDs for tracing requests across components
//! - Device context for device-specific operations
//! - Protocol context for protocol-specific logging
//! - Custom context fields for application-specific needs
//!
//! # Example
//!
//! ```rust,ignore
//! use mabi_core::logging::context::{TraceContext, RequestContext};
//!
//! // Create a trace context for a request
//! let ctx = TraceContext::new()
//!     .with_request_id("req-12345")
//!     .with_device_id("device-001")
//!     .with_protocol("modbus");
//!
//! // Use in a span
//! let span = ctx.create_span("handle_request");
//! let _guard = span.enter();
//!
//! // Or use the request_span! macro
//! request_span!(ctx, "handle_request", {
//!     // Your code here
//! });
//! ```

use std::collections::HashMap;
use std::sync::Arc;

use serde::{Deserialize, Serialize};
use tracing::{span, Level, Span};
use uuid::Uuid;

/// Trace context for distributed tracing.
///
/// This struct carries context information that should be propagated
/// across async boundaries and potentially across service boundaries.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TraceContext {
    /// Unique request/correlation ID.
    pub request_id: String,

    /// Trace ID (for distributed tracing systems).
    #[serde(default)]
    pub trace_id: Option<String>,

    /// Span ID (for distributed tracing systems).
    #[serde(default)]
    pub span_id: Option<String>,

    /// Parent span ID.
    #[serde(default)]
    pub parent_span_id: Option<String>,

    /// Device ID (if applicable).
    #[serde(default)]
    pub device_id: Option<String>,

    /// Protocol name (if applicable).
    #[serde(default)]
    pub protocol: Option<String>,

    /// Operation name.
    #[serde(default)]
    pub operation: Option<String>,

    /// Custom fields.
    #[serde(default)]
    pub fields: HashMap<String, String>,

    /// Timestamp when context was created.
    #[serde(default = "default_timestamp")]
    pub created_at: u64,
}

fn default_timestamp() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_millis() as u64)
        .unwrap_or(0)
}

impl Default for TraceContext {
    fn default() -> Self {
        Self::new()
    }
}

impl TraceContext {
    /// Create a new trace context with a generated request ID.
    pub fn new() -> Self {
        Self {
            request_id: Uuid::new_v4().to_string(),
            trace_id: None,
            span_id: None,
            parent_span_id: None,
            device_id: None,
            protocol: None,
            operation: None,
            fields: HashMap::new(),
            created_at: default_timestamp(),
        }
    }

    /// Create a trace context with a specific request ID.
    pub fn with_request_id(request_id: impl Into<String>) -> Self {
        Self {
            request_id: request_id.into(),
            ..Self::new()
        }
    }

    /// Create a child context (new span under same trace).
    pub fn child(&self) -> Self {
        Self {
            request_id: self.request_id.clone(),
            trace_id: self.trace_id.clone(),
            span_id: Some(Uuid::new_v4().to_string()),
            parent_span_id: self.span_id.clone(),
            device_id: self.device_id.clone(),
            protocol: self.protocol.clone(),
            operation: None,
            fields: self.fields.clone(),
            created_at: default_timestamp(),
        }
    }

    /// Set the device ID.
    pub fn with_device_id(mut self, device_id: impl Into<String>) -> Self {
        self.device_id = Some(device_id.into());
        self
    }

    /// Set the protocol.
    pub fn with_protocol(mut self, protocol: impl Into<String>) -> Self {
        self.protocol = Some(protocol.into());
        self
    }

    /// Set the operation name.
    pub fn with_operation(mut self, operation: impl Into<String>) -> Self {
        self.operation = Some(operation.into());
        self
    }

    /// Set the trace ID (for integration with distributed tracing).
    pub fn with_trace_id(mut self, trace_id: impl Into<String>) -> Self {
        self.trace_id = Some(trace_id.into());
        self
    }

    /// Add a custom field.
    pub fn with_field(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.fields.insert(key.into(), value.into());
        self
    }

    /// Add multiple custom fields.
    pub fn with_fields(mut self, fields: impl IntoIterator<Item = (String, String)>) -> Self {
        self.fields.extend(fields);
        self
    }

    /// Create a tracing span with this context.
    pub fn create_span(&self, name: &'static str) -> Span {
        let span = span!(
            Level::INFO,
            "request",
            request_id = %self.request_id,
            operation = name,
        );

        // Add optional fields
        if let Some(ref device_id) = self.device_id {
            span.record("device_id", device_id.as_str());
        }
        if let Some(ref protocol) = self.protocol {
            span.record("protocol", protocol.as_str());
        }
        if let Some(ref trace_id) = self.trace_id {
            span.record("trace_id", trace_id.as_str());
        }

        span
    }

    /// Create a debug-level span (for less critical operations).
    pub fn create_debug_span(&self, name: &'static str) -> Span {
        span!(
            Level::DEBUG,
            "operation",
            request_id = %self.request_id,
            operation = name,
            device_id = self.device_id.as_deref().unwrap_or(""),
        )
    }

    /// Get the age of this context in milliseconds.
    pub fn age_ms(&self) -> u64 {
        default_timestamp().saturating_sub(self.created_at)
    }

    /// Check if this context is older than the given milliseconds.
    pub fn is_older_than_ms(&self, ms: u64) -> bool {
        self.age_ms() > ms
    }

    /// Convert to a map for logging or serialization.
    pub fn to_map(&self) -> HashMap<String, String> {
        let mut map = HashMap::new();
        map.insert("request_id".to_string(), self.request_id.clone());

        if let Some(ref trace_id) = self.trace_id {
            map.insert("trace_id".to_string(), trace_id.clone());
        }
        if let Some(ref device_id) = self.device_id {
            map.insert("device_id".to_string(), device_id.clone());
        }
        if let Some(ref protocol) = self.protocol {
            map.insert("protocol".to_string(), protocol.clone());
        }
        if let Some(ref operation) = self.operation {
            map.insert("operation".to_string(), operation.clone());
        }

        map.extend(self.fields.clone());
        map
    }

    /// Parse from HTTP headers (for distributed tracing).
    pub fn from_headers(headers: &HashMap<String, String>) -> Self {
        let mut ctx = Self::new();

        if let Some(request_id) = headers
            .get("x-request-id")
            .or(headers.get("x-correlation-id"))
        {
            ctx.request_id = request_id.clone();
        }
        if let Some(trace_id) = headers.get("x-trace-id").or(headers.get("traceparent")) {
            ctx.trace_id = Some(trace_id.clone());
        }
        if let Some(span_id) = headers.get("x-span-id") {
            ctx.span_id = Some(span_id.clone());
        }
        if let Some(device_id) = headers.get("x-device-id") {
            ctx.device_id = Some(device_id.clone());
        }

        ctx
    }

    /// Convert to HTTP headers (for distributed tracing).
    pub fn to_headers(&self) -> HashMap<String, String> {
        let mut headers = HashMap::new();

        headers.insert("x-request-id".to_string(), self.request_id.clone());

        if let Some(ref trace_id) = self.trace_id {
            headers.insert("x-trace-id".to_string(), trace_id.clone());
        }
        if let Some(ref span_id) = self.span_id {
            headers.insert("x-span-id".to_string(), span_id.clone());
        }
        if let Some(ref device_id) = self.device_id {
            headers.insert("x-device-id".to_string(), device_id.clone());
        }

        headers
    }
}

/// Request context for protocol operations.
///
/// This is a specialized context for protocol-level requests.
#[derive(Debug, Clone)]
pub struct RequestContext {
    /// Base trace context.
    pub trace: TraceContext,

    /// Request start time.
    pub start_time: std::time::Instant,

    /// Request timeout (if set).
    pub timeout: Option<std::time::Duration>,

    /// Whether this request should be logged at debug level.
    pub debug_request: bool,
}

impl RequestContext {
    /// Create a new request context.
    pub fn new() -> Self {
        Self {
            trace: TraceContext::new(),
            start_time: std::time::Instant::now(),
            timeout: None,
            debug_request: false,
        }
    }

    /// Create with an existing trace context.
    pub fn with_trace(trace: TraceContext) -> Self {
        Self {
            trace,
            start_time: std::time::Instant::now(),
            timeout: None,
            debug_request: false,
        }
    }

    /// Set the device ID.
    pub fn device(mut self, device_id: impl Into<String>) -> Self {
        self.trace = self.trace.with_device_id(device_id);
        self
    }

    /// Set the protocol.
    pub fn protocol(mut self, protocol: impl Into<String>) -> Self {
        self.trace = self.trace.with_protocol(protocol);
        self
    }

    /// Set the operation.
    pub fn operation(mut self, operation: impl Into<String>) -> Self {
        self.trace = self.trace.with_operation(operation);
        self
    }

    /// Set a timeout.
    pub fn with_timeout(mut self, timeout: std::time::Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Mark as a debug request (logged at debug level).
    pub fn debug(mut self) -> Self {
        self.debug_request = true;
        self
    }

    /// Get elapsed time since request started.
    pub fn elapsed(&self) -> std::time::Duration {
        self.start_time.elapsed()
    }

    /// Check if the request has timed out.
    pub fn is_timed_out(&self) -> bool {
        self.timeout.map(|t| self.elapsed() > t).unwrap_or(false)
    }

    /// Get remaining time before timeout.
    pub fn remaining_timeout(&self) -> Option<std::time::Duration> {
        self.timeout.and_then(|t| t.checked_sub(self.elapsed()))
    }

    /// Get the request ID.
    pub fn request_id(&self) -> &str {
        &self.trace.request_id
    }

    /// Create a span for this request.
    pub fn span(&self, name: &'static str) -> Span {
        if self.debug_request {
            self.trace.create_debug_span(name)
        } else {
            self.trace.create_span(name)
        }
    }
}

impl Default for RequestContext {
    fn default() -> Self {
        Self::new()
    }
}

/// Shared trace context for passing across threads.
pub type SharedTraceContext = Arc<TraceContext>;

/// Create a shared trace context.
pub fn shared_context(ctx: TraceContext) -> SharedTraceContext {
    Arc::new(ctx)
}

/// Device context for device-specific operations.
#[derive(Debug, Clone)]
pub struct DeviceContext {
    /// Device ID.
    pub device_id: String,

    /// Protocol.
    pub protocol: String,

    /// Base trace context.
    pub trace: TraceContext,
}

impl DeviceContext {
    /// Create a new device context.
    pub fn new(device_id: impl Into<String>, protocol: impl Into<String>) -> Self {
        let device_id = device_id.into();
        let protocol = protocol.into();

        Self {
            device_id: device_id.clone(),
            protocol: protocol.clone(),
            trace: TraceContext::new()
                .with_device_id(device_id)
                .with_protocol(protocol),
        }
    }

    /// Create with an existing trace context.
    pub fn with_trace(
        device_id: impl Into<String>,
        protocol: impl Into<String>,
        trace: TraceContext,
    ) -> Self {
        let device_id = device_id.into();
        let protocol = protocol.into();

        Self {
            device_id: device_id.clone(),
            protocol: protocol.clone(),
            trace: trace.with_device_id(device_id).with_protocol(protocol),
        }
    }

    /// Create a span for a device operation.
    pub fn span(&self, operation: &'static str) -> Span {
        span!(
            Level::DEBUG,
            "device_operation",
            device_id = %self.device_id,
            protocol = %self.protocol,
            operation = operation,
            request_id = %self.trace.request_id,
        )
    }

    /// Get the request ID.
    pub fn request_id(&self) -> &str {
        &self.trace.request_id
    }

    /// Create a child context for a sub-operation.
    pub fn child(&self) -> Self {
        Self {
            device_id: self.device_id.clone(),
            protocol: self.protocol.clone(),
            trace: self.trace.child(),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_trace_context_creation() {
        let ctx = TraceContext::new();
        assert!(!ctx.request_id.is_empty());
        assert!(ctx.device_id.is_none());
        assert!(ctx.protocol.is_none());
    }

    #[test]
    fn test_trace_context_builder() {
        let ctx = TraceContext::new()
            .with_device_id("device-001")
            .with_protocol("modbus")
            .with_operation("read")
            .with_field("unit_id", "1");

        assert_eq!(ctx.device_id, Some("device-001".to_string()));
        assert_eq!(ctx.protocol, Some("modbus".to_string()));
        assert_eq!(ctx.operation, Some("read".to_string()));
        assert_eq!(ctx.fields.get("unit_id"), Some(&"1".to_string()));
    }

    #[test]
    fn test_trace_context_child() {
        let parent = TraceContext::new()
            .with_device_id("device-001")
            .with_trace_id("trace-123");

        let child = parent.child();

        assert_eq!(child.request_id, parent.request_id);
        assert_eq!(child.trace_id, parent.trace_id);
        assert_eq!(child.device_id, parent.device_id);
        assert_eq!(child.parent_span_id, parent.span_id);
    }

    #[test]
    fn test_trace_context_to_map() {
        let ctx = TraceContext::new()
            .with_device_id("device-001")
            .with_protocol("modbus");

        let map = ctx.to_map();
        assert!(map.contains_key("request_id"));
        assert_eq!(map.get("device_id"), Some(&"device-001".to_string()));
        assert_eq!(map.get("protocol"), Some(&"modbus".to_string()));
    }

    #[test]
    fn test_trace_context_headers() {
        let ctx = TraceContext::new()
            .with_device_id("device-001")
            .with_trace_id("trace-123");

        let headers = ctx.to_headers();
        assert!(headers.contains_key("x-request-id"));
        assert_eq!(headers.get("x-trace-id"), Some(&"trace-123".to_string()));
        assert_eq!(headers.get("x-device-id"), Some(&"device-001".to_string()));

        // Round-trip
        let parsed = TraceContext::from_headers(&headers);
        assert_eq!(parsed.request_id, ctx.request_id);
        assert_eq!(parsed.trace_id, ctx.trace_id);
        assert_eq!(parsed.device_id, ctx.device_id);
    }

    #[test]
    fn test_request_context() {
        let ctx = RequestContext::new()
            .device("device-001")
            .protocol("modbus")
            .operation("read")
            .with_timeout(std::time::Duration::from_secs(5));

        assert!(!ctx.request_id().is_empty());
        assert!(!ctx.is_timed_out());
        assert!(ctx.remaining_timeout().is_some());
    }

    #[test]
    fn test_device_context() {
        let ctx = DeviceContext::new("device-001", "modbus");

        assert_eq!(ctx.device_id, "device-001");
        assert_eq!(ctx.protocol, "modbus");
        assert!(!ctx.request_id().is_empty());

        let child = ctx.child();
        assert_eq!(child.request_id(), ctx.request_id());
    }

    #[test]
    fn test_trace_context_age() {
        let ctx = TraceContext::new();
        std::thread::sleep(std::time::Duration::from_millis(10));

        assert!(ctx.age_ms() >= 10);
        assert!(ctx.is_older_than_ms(5));
        assert!(!ctx.is_older_than_ms(1000));
    }

    #[test]
    fn test_shared_context() {
        let ctx = TraceContext::new().with_device_id("device-001");
        let shared = shared_context(ctx);

        assert_eq!(shared.device_id, Some("device-001".to_string()));
    }
}