a3s-gateway 0.2.5

A3S Gateway - AI-native API gateway with reverse proxy, routing, and agent orchestration
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
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
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
//! OpenTelemetry tracing — distributed trace context propagation
//!
//! Provides trace context extraction, injection, and span management
//! for distributed tracing across gateway hops. Supports W3C Trace Context
//! and B3 propagation formats.

#![allow(dead_code)]
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;
use std::time::Instant;

/// W3C Trace Context header name
const TRACEPARENT_HEADER: &str = "traceparent";
/// W3C Trace State header name
const TRACESTATE_HEADER: &str = "tracestate";
/// B3 single header
const B3_HEADER: &str = "b3";
/// B3 trace ID header
const B3_TRACE_ID_HEADER: &str = "x-b3-traceid";
/// B3 span ID header
const B3_SPAN_ID_HEADER: &str = "x-b3-spanid";
/// B3 sampled header
const B3_SAMPLED_HEADER: &str = "x-b3-sampled";

/// Trace context — carries distributed trace information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TraceContext {
    /// Trace ID (128-bit hex string)
    pub trace_id: String,
    /// Parent span ID (64-bit hex string)
    pub parent_span_id: String,
    /// Current span ID (64-bit hex string)
    pub span_id: String,
    /// Trace flags (sampled, etc.)
    pub trace_flags: u8,
    /// Optional trace state (vendor-specific key-value pairs)
    pub trace_state: Option<String>,
}

impl TraceContext {
    /// Create a new root trace context with random IDs
    pub fn new_root() -> Self {
        Self {
            trace_id: generate_trace_id(),
            parent_span_id: String::new(),
            span_id: generate_span_id(),
            trace_flags: 1, // sampled by default
            trace_state: None,
        }
    }

    /// Create a child span from this context
    pub fn child(&self) -> Self {
        Self {
            trace_id: self.trace_id.clone(),
            parent_span_id: self.span_id.clone(),
            span_id: generate_span_id(),
            trace_flags: self.trace_flags,
            trace_state: self.trace_state.clone(),
        }
    }

    /// Check if this trace is sampled
    pub fn is_sampled(&self) -> bool {
        self.trace_flags & 0x01 != 0
    }

    /// Format as W3C traceparent header value
    /// Format: version-trace_id-parent_id-flags
    pub fn to_traceparent(&self) -> String {
        format!(
            "00-{}-{}-{:02x}",
            self.trace_id, self.span_id, self.trace_flags
        )
    }

    /// Parse from W3C traceparent header value
    pub fn from_traceparent(value: &str) -> Option<Self> {
        let parts: Vec<&str> = value.trim().split('-').collect();
        if parts.len() != 4 {
            return None;
        }

        let version = parts[0];
        if version != "00" {
            return None;
        }

        let trace_id = parts[1];
        let parent_span_id = parts[2];
        let flags_str = parts[3];

        // Validate lengths
        if trace_id.len() != 32 || parent_span_id.len() != 16 || flags_str.len() != 2 {
            return None;
        }

        // Validate hex
        if !is_hex(trace_id) || !is_hex(parent_span_id) || !is_hex(flags_str) {
            return None;
        }

        let trace_flags = u8::from_str_radix(flags_str, 16).ok()?;

        Some(Self {
            trace_id: trace_id.to_string(),
            parent_span_id: parent_span_id.to_string(),
            span_id: generate_span_id(),
            trace_flags,
            trace_state: None,
        })
    }

    /// Format as B3 single header value
    /// Format: {trace_id}-{span_id}-{sampled}-{parent_span_id}
    pub fn to_b3_single(&self) -> String {
        let sampled = if self.is_sampled() { "1" } else { "0" };
        if self.parent_span_id.is_empty() {
            format!("{}-{}-{}", self.trace_id, self.span_id, sampled)
        } else {
            format!(
                "{}-{}-{}-{}",
                self.trace_id, self.span_id, sampled, self.parent_span_id
            )
        }
    }

    /// Parse from B3 single header value
    pub fn from_b3_single(value: &str) -> Option<Self> {
        let parts: Vec<&str> = value.trim().split('-').collect();
        if parts.len() < 3 {
            return None;
        }

        let trace_id = parts[0];
        let span_id = parts[1];
        let sampled = parts[2];

        if !is_hex(trace_id) || !is_hex(span_id) {
            return None;
        }

        let trace_flags = if sampled == "1" || sampled == "true" {
            1
        } else {
            0
        };

        let parent_span_id = if parts.len() >= 4 {
            parts[3].to_string()
        } else {
            String::new()
        };

        Some(Self {
            trace_id: trace_id.to_string(),
            parent_span_id,
            span_id: generate_span_id(),
            trace_flags,
            trace_state: None,
        })
    }
}

impl fmt::Display for TraceContext {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "trace_id={} span_id={} sampled={}",
            self.trace_id,
            self.span_id,
            self.is_sampled()
        )
    }
}

/// Propagation format
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PropagationFormat {
    /// W3C Trace Context (traceparent/tracestate)
    W3C,
    /// Zipkin B3 (single or multi-header)
    B3,
}

/// Extract trace context from request headers.
///
/// Accepts `&http::HeaderMap` directly — avoids the HashMap<String,String>
/// allocation that was previously needed to convert hyper headers.
pub fn extract_trace_context(headers: &http::HeaderMap) -> Option<TraceContext> {
    let hdr = |name: &str| -> Option<&str> { headers.get(name).and_then(|v| v.to_str().ok()) };

    // Try W3C traceparent first
    if let Some(traceparent) = hdr(TRACEPARENT_HEADER) {
        if let Some(mut ctx) = TraceContext::from_traceparent(traceparent) {
            ctx.trace_state = hdr(TRACESTATE_HEADER).map(|s| s.to_string());
            return Some(ctx);
        }
    }

    // Try B3 single header
    if let Some(b3) = hdr(B3_HEADER) {
        return TraceContext::from_b3_single(b3);
    }

    // Try B3 multi-header
    if let Some(trace_id) = hdr(B3_TRACE_ID_HEADER) {
        if let Some(span_id) = hdr(B3_SPAN_ID_HEADER) {
            let sampled = hdr(B3_SAMPLED_HEADER)
                .map(|s| s == "1" || s == "true")
                .unwrap_or(true);

            return Some(TraceContext {
                trace_id: trace_id.to_string(),
                parent_span_id: span_id.to_string(),
                span_id: generate_span_id(),
                trace_flags: if sampled { 1 } else { 0 },
                trace_state: None,
            });
        }
    }

    None
}

/// Inject trace context into request headers
pub fn inject_trace_context(
    ctx: &TraceContext,
    headers: &mut HashMap<String, String>,
    format: PropagationFormat,
) {
    match format {
        PropagationFormat::W3C => {
            headers.insert(TRACEPARENT_HEADER.to_string(), ctx.to_traceparent());
            if let Some(ref state) = ctx.trace_state {
                headers.insert(TRACESTATE_HEADER.to_string(), state.clone());
            }
        }
        PropagationFormat::B3 => {
            headers.insert(B3_HEADER.to_string(), ctx.to_b3_single());
        }
    }
}

/// A gateway span — tracks timing for a single operation
#[derive(Debug, Clone)]
pub struct GatewaySpan {
    /// Span name (e.g., "gateway.proxy", "gateway.middleware.auth")
    pub name: String,
    /// Trace context
    pub trace_context: TraceContext,
    /// Start time
    pub start: Instant,
    /// End time (set when span is finished)
    pub end: Option<Instant>,
    /// Span attributes
    pub attributes: HashMap<String, String>,
    /// Span status
    pub status: SpanStatus,
}

impl GatewaySpan {
    /// Create a new span
    pub fn new(name: impl Into<String>, trace_context: TraceContext) -> Self {
        Self {
            name: name.into(),
            trace_context,
            start: Instant::now(),
            end: None,
            attributes: HashMap::new(),
            status: SpanStatus::Unset,
        }
    }

    /// Set an attribute
    pub fn set_attribute(&mut self, key: impl Into<String>, value: impl Into<String>) {
        self.attributes.insert(key.into(), value.into());
    }

    /// Finish the span
    pub fn finish(&mut self) {
        self.end = Some(Instant::now());
    }

    /// Finish with error status
    pub fn finish_with_error(&mut self, message: impl Into<String>) {
        self.status = SpanStatus::Error(message.into());
        self.end = Some(Instant::now());
    }

    /// Get the duration (if finished)
    pub fn duration(&self) -> Option<std::time::Duration> {
        self.end.map(|end| end.duration_since(self.start))
    }

    /// Check if the span is finished
    pub fn is_finished(&self) -> bool {
        self.end.is_some()
    }
}

/// Span status
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SpanStatus {
    /// Status not set
    Unset,
    /// Operation completed successfully
    Ok,
    /// Operation failed
    Error(String),
}

impl fmt::Display for SpanStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Unset => write!(f, "UNSET"),
            Self::Ok => write!(f, "OK"),
            Self::Error(msg) => write!(f, "ERROR: {}", msg),
        }
    }
}

/// Tracing configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TracingConfig {
    /// OTLP endpoint for exporting traces
    #[serde(default)]
    pub otlp_endpoint: Option<String>,
    /// Propagation format
    #[serde(default = "default_propagation")]
    pub propagation: String,
    /// Sampling rate (0.0 to 1.0)
    #[serde(default = "default_sample_rate")]
    pub sample_rate: f64,
    /// Service name for traces
    #[serde(default = "default_service_name")]
    pub service_name: String,
}

fn default_propagation() -> String {
    "w3c".to_string()
}

fn default_sample_rate() -> f64 {
    1.0
}

fn default_service_name() -> String {
    "a3s-gateway".to_string()
}

impl Default for TracingConfig {
    fn default() -> Self {
        Self {
            otlp_endpoint: None,
            propagation: default_propagation(),
            sample_rate: default_sample_rate(),
            service_name: default_service_name(),
        }
    }
}

impl TracingConfig {
    /// Get the propagation format
    pub fn propagation_format(&self) -> PropagationFormat {
        match self.propagation.to_lowercase().as_str() {
            "b3" | "zipkin" => PropagationFormat::B3,
            _ => PropagationFormat::W3C,
        }
    }

    /// Check if tracing export is enabled
    pub fn is_export_enabled(&self) -> bool {
        self.otlp_endpoint.is_some()
    }
}

/// Generate a random 128-bit trace ID (32 hex chars)
fn generate_trace_id() -> String {
    format!("{:032x}", uuid::Uuid::new_v4().as_u128())
}

/// Generate a random 64-bit span ID (16 hex chars)
fn generate_span_id() -> String {
    let bytes: [u8; 8] = rand_bytes();
    hex_encode(&bytes)
}

/// Generate random bytes using a simple approach
fn rand_bytes() -> [u8; 8] {
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default();
    let seed = now.as_nanos() as u64;
    seed.to_le_bytes()
}

/// Encode bytes as hex string
fn hex_encode(bytes: &[u8]) -> String {
    bytes.iter().map(|b| format!("{:02x}", b)).collect()
}

/// Check if a string is valid hexadecimal
fn is_hex(s: &str) -> bool {
    !s.is_empty() && s.chars().all(|c| c.is_ascii_hexdigit())
}

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

    // --- TraceContext ---

    #[test]
    fn test_new_root() {
        let ctx = TraceContext::new_root();
        assert_eq!(ctx.trace_id.len(), 32);
        assert_eq!(ctx.span_id.len(), 16);
        assert!(ctx.parent_span_id.is_empty());
        assert!(ctx.is_sampled());
    }

    #[test]
    fn test_child_span() {
        let root = TraceContext::new_root();
        let child = root.child();
        assert_eq!(child.trace_id, root.trace_id);
        assert_eq!(child.parent_span_id, root.span_id);
        assert_ne!(child.span_id, root.span_id);
        assert_eq!(child.trace_flags, root.trace_flags);
    }

    #[test]
    fn test_is_sampled() {
        let mut ctx = TraceContext::new_root();
        assert!(ctx.is_sampled());
        ctx.trace_flags = 0;
        assert!(!ctx.is_sampled());
    }

    // --- W3C traceparent ---

    #[test]
    fn test_to_traceparent() {
        let ctx = TraceContext {
            trace_id: "0af7651916cd43dd8448eb211c80319c".to_string(),
            parent_span_id: "00f067aa0ba902b7".to_string(),
            span_id: "b7ad6b7169203331".to_string(),
            trace_flags: 1,
            trace_state: None,
        };
        let tp = ctx.to_traceparent();
        assert!(tp.starts_with("00-0af7651916cd43dd8448eb211c80319c-"));
        assert!(tp.ends_with("-01"));
    }

    #[test]
    fn test_from_traceparent_valid() {
        let tp = "00-0af7651916cd43dd8448eb211c80319c-00f067aa0ba902b7-01";
        let ctx = TraceContext::from_traceparent(tp).unwrap();
        assert_eq!(ctx.trace_id, "0af7651916cd43dd8448eb211c80319c");
        assert_eq!(ctx.parent_span_id, "00f067aa0ba902b7");
        assert!(ctx.is_sampled());
    }

    #[test]
    fn test_from_traceparent_not_sampled() {
        let tp = "00-0af7651916cd43dd8448eb211c80319c-00f067aa0ba902b7-00";
        let ctx = TraceContext::from_traceparent(tp).unwrap();
        assert!(!ctx.is_sampled());
    }

    #[test]
    fn test_from_traceparent_invalid_version() {
        let tp = "01-0af7651916cd43dd8448eb211c80319c-00f067aa0ba902b7-01";
        assert!(TraceContext::from_traceparent(tp).is_none());
    }

    #[test]
    fn test_from_traceparent_invalid_format() {
        assert!(TraceContext::from_traceparent("invalid").is_none());
        assert!(TraceContext::from_traceparent("00-short-id-01").is_none());
        assert!(TraceContext::from_traceparent("").is_none());
    }

    #[test]
    fn test_from_traceparent_invalid_hex() {
        let tp = "00-zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz-00f067aa0ba902b7-01";
        assert!(TraceContext::from_traceparent(tp).is_none());
    }

    // --- B3 format ---

    #[test]
    fn test_to_b3_single_with_parent() {
        let ctx = TraceContext {
            trace_id: "463ac35c9f6413ad48485a3953bb6124".to_string(),
            parent_span_id: "0020000000000001".to_string(),
            span_id: "b7ad6b7169203331".to_string(),
            trace_flags: 1,
            trace_state: None,
        };
        let b3 = ctx.to_b3_single();
        assert!(b3.contains("463ac35c9f6413ad48485a3953bb6124"));
        assert!(b3.contains("-1-"));
    }

    #[test]
    fn test_to_b3_single_no_parent() {
        let ctx = TraceContext {
            trace_id: "463ac35c9f6413ad48485a3953bb6124".to_string(),
            parent_span_id: String::new(),
            span_id: "b7ad6b7169203331".to_string(),
            trace_flags: 0,
            trace_state: None,
        };
        let b3 = ctx.to_b3_single();
        assert!(b3.contains("-0"));
        // Should not have 4th segment
        assert_eq!(b3.split('-').count(), 3);
    }

    #[test]
    fn test_from_b3_single_sampled() {
        let b3 = "463ac35c9f6413ad48485a3953bb6124-0020000000000001-1";
        let ctx = TraceContext::from_b3_single(b3).unwrap();
        assert_eq!(ctx.trace_id, "463ac35c9f6413ad48485a3953bb6124");
        assert!(ctx.is_sampled());
    }

    #[test]
    fn test_from_b3_single_with_parent() {
        let b3 = "463ac35c9f6413ad48485a3953bb6124-0020000000000001-1-00f067aa0ba902b7";
        let ctx = TraceContext::from_b3_single(b3).unwrap();
        assert_eq!(ctx.parent_span_id, "00f067aa0ba902b7");
    }

    #[test]
    fn test_from_b3_single_invalid() {
        assert!(TraceContext::from_b3_single("invalid").is_none());
        assert!(TraceContext::from_b3_single("a-b").is_none());
    }

    // --- Extract/Inject ---

    #[test]
    fn test_extract_w3c() {
        let mut headers = http::HeaderMap::new();
        headers.insert(
            http::header::HeaderName::from_static("traceparent"),
            "00-0af7651916cd43dd8448eb211c80319c-00f067aa0ba902b7-01"
                .parse()
                .unwrap(),
        );
        headers.insert(
            http::header::HeaderName::from_static("tracestate"),
            "vendor=value".parse().unwrap(),
        );

        let ctx = extract_trace_context(&headers).unwrap();
        assert_eq!(ctx.trace_id, "0af7651916cd43dd8448eb211c80319c");
        assert_eq!(ctx.trace_state.as_deref(), Some("vendor=value"));
    }

    #[test]
    fn test_extract_b3_single() {
        let mut headers = http::HeaderMap::new();
        headers.insert(
            http::header::HeaderName::from_static("b3"),
            "463ac35c9f6413ad48485a3953bb6124-0020000000000001-1"
                .parse()
                .unwrap(),
        );

        let ctx = extract_trace_context(&headers).unwrap();
        assert_eq!(ctx.trace_id, "463ac35c9f6413ad48485a3953bb6124");
    }

    #[test]
    fn test_extract_b3_multi() {
        let mut headers = http::HeaderMap::new();
        headers.insert(
            http::header::HeaderName::from_static("x-b3-traceid"),
            "463ac35c9f6413ad48485a3953bb6124".parse().unwrap(),
        );
        headers.insert(
            http::header::HeaderName::from_static("x-b3-spanid"),
            "0020000000000001".parse().unwrap(),
        );
        headers.insert(
            http::header::HeaderName::from_static("x-b3-sampled"),
            "1".parse().unwrap(),
        );

        let ctx = extract_trace_context(&headers).unwrap();
        assert_eq!(ctx.trace_id, "463ac35c9f6413ad48485a3953bb6124");
        assert!(ctx.is_sampled());
    }

    #[test]
    fn test_extract_no_trace() {
        let headers = http::HeaderMap::new();
        assert!(extract_trace_context(&headers).is_none());
    }

    #[test]
    fn test_inject_w3c() {
        let ctx = TraceContext {
            trace_id: "0af7651916cd43dd8448eb211c80319c".to_string(),
            parent_span_id: String::new(),
            span_id: "00f067aa0ba902b7".to_string(),
            trace_flags: 1,
            trace_state: Some("vendor=value".to_string()),
        };
        let mut headers = HashMap::new();
        inject_trace_context(&ctx, &mut headers, PropagationFormat::W3C);

        assert!(headers.contains_key("traceparent"));
        assert_eq!(headers.get("tracestate").unwrap(), "vendor=value");
    }

    #[test]
    fn test_inject_b3() {
        let ctx = TraceContext {
            trace_id: "463ac35c9f6413ad48485a3953bb6124".to_string(),
            parent_span_id: String::new(),
            span_id: "0020000000000001".to_string(),
            trace_flags: 1,
            trace_state: None,
        };
        let mut headers = HashMap::new();
        inject_trace_context(&ctx, &mut headers, PropagationFormat::B3);

        assert!(headers.contains_key("b3"));
    }

    // --- GatewaySpan ---

    #[test]
    fn test_span_new() {
        let ctx = TraceContext::new_root();
        let span = GatewaySpan::new("gateway.proxy", ctx);
        assert_eq!(span.name, "gateway.proxy");
        assert!(!span.is_finished());
        assert!(span.duration().is_none());
        assert_eq!(span.status, SpanStatus::Unset);
    }

    #[test]
    fn test_span_attributes() {
        let ctx = TraceContext::new_root();
        let mut span = GatewaySpan::new("test", ctx);
        span.set_attribute("http.method", "GET");
        span.set_attribute("http.url", "/api/data");
        assert_eq!(span.attributes.get("http.method").unwrap(), "GET");
        assert_eq!(span.attributes.get("http.url").unwrap(), "/api/data");
    }

    #[test]
    fn test_span_finish() {
        let ctx = TraceContext::new_root();
        let mut span = GatewaySpan::new("test", ctx);
        assert!(!span.is_finished());
        span.finish();
        assert!(span.is_finished());
        assert!(span.duration().is_some());
        assert_eq!(span.status, SpanStatus::Unset);
    }

    #[test]
    fn test_span_finish_with_error() {
        let ctx = TraceContext::new_root();
        let mut span = GatewaySpan::new("test", ctx);
        span.finish_with_error("connection refused");
        assert!(span.is_finished());
        assert_eq!(
            span.status,
            SpanStatus::Error("connection refused".to_string())
        );
    }

    // --- SpanStatus ---

    #[test]
    fn test_span_status_display() {
        assert_eq!(SpanStatus::Unset.to_string(), "UNSET");
        assert_eq!(SpanStatus::Ok.to_string(), "OK");
        assert_eq!(
            SpanStatus::Error("fail".to_string()).to_string(),
            "ERROR: fail"
        );
    }

    // --- TracingConfig ---

    #[test]
    fn test_config_default() {
        let config = TracingConfig::default();
        assert!(config.otlp_endpoint.is_none());
        assert_eq!(config.propagation, "w3c");
        assert_eq!(config.sample_rate, 1.0);
        assert_eq!(config.service_name, "a3s-gateway");
        assert!(!config.is_export_enabled());
    }

    #[test]
    fn test_config_propagation_format() {
        let mut config = TracingConfig::default();
        assert_eq!(config.propagation_format(), PropagationFormat::W3C);

        config.propagation = "b3".to_string();
        assert_eq!(config.propagation_format(), PropagationFormat::B3);

        config.propagation = "zipkin".to_string();
        assert_eq!(config.propagation_format(), PropagationFormat::B3);
    }

    #[test]
    fn test_config_export_enabled() {
        let mut config = TracingConfig::default();
        assert!(!config.is_export_enabled());
        config.otlp_endpoint = Some("http://localhost:4317".to_string());
        assert!(config.is_export_enabled());
    }

    #[test]
    fn test_config_serialization() {
        let config = TracingConfig {
            otlp_endpoint: Some("http://localhost:4317".to_string()),
            propagation: "b3".to_string(),
            sample_rate: 0.5,
            service_name: "my-gateway".to_string(),
        };
        let json = serde_json::to_string(&config).unwrap();
        let parsed: TracingConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(
            parsed.otlp_endpoint.as_deref(),
            Some("http://localhost:4317")
        );
        assert_eq!(parsed.sample_rate, 0.5);
    }

    // --- Display ---

    #[test]
    fn test_trace_context_display() {
        let ctx = TraceContext {
            trace_id: "abc123".to_string(),
            parent_span_id: String::new(),
            span_id: "def456".to_string(),
            trace_flags: 1,
            trace_state: None,
        };
        let display = ctx.to_string();
        assert!(display.contains("trace_id=abc123"));
        assert!(display.contains("span_id=def456"));
        assert!(display.contains("sampled=true"));
    }

    // --- Utility functions ---

    #[test]
    fn test_is_hex() {
        assert!(is_hex("0af7651916cd43dd"));
        assert!(is_hex("ABCDEF0123456789"));
        assert!(!is_hex("xyz"));
        assert!(!is_hex(""));
        assert!(!is_hex("0af765-invalid"));
    }

    #[test]
    fn test_hex_encode() {
        assert_eq!(hex_encode(&[0x0a, 0xf7]), "0af7");
        assert_eq!(hex_encode(&[0x00, 0xff]), "00ff");
        assert_eq!(hex_encode(&[]), "");
    }

    #[test]
    fn test_generate_trace_id_length() {
        let id = generate_trace_id();
        assert_eq!(id.len(), 32);
        assert!(is_hex(&id));
    }

    #[test]
    fn test_generate_span_id_length() {
        let id = generate_span_id();
        assert_eq!(id.len(), 16);
        assert!(is_hex(&id));
    }
}