veecle-telemetry 0.1.0

Veecle OS telemetry
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
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
//! Distributed tracing spans for tracking units of work.
//!
//! This module provides the core span implementation for distributed tracing.
//! Spans represent units of work within a trace and can be nested to show
//! relationships between different operations.
//!
//! # Key Concepts
//!
//! - **Span**: A unit of work within a trace, with a name and optional attributes
//! - **Span Context**: The trace and span IDs that identify a span within a trace
//! - **Span Guards**: RAII guards that automatically handle span entry/exit
//! - **Current Span**: Thread-local tracking of the currently active span
//!
//! # Basic Usage
//!
//! ```rust
//! use veecle_telemetry::{CurrentSpan, span};
//!
//! // Create and enter a span
//! let span = span!("operation", user_id = 123);
//! let _guard = span.entered();
//!
//! // Add events to the current span
//! CurrentSpan::add_event("checkpoint", &[]);
//!
//! // Span is automatically exited when guard is dropped
//! ```
//!
//! # Span Lifecycle
//!
//! 1. **Creation**: Spans are created with a name and optional attributes
//! 2. **Entry**: Spans are entered to make them the current active span
//! 3. **Events**: Events and attributes can be added to active spans
//! 4. **Exit**: Spans are exited when no longer active
//! 5. **Close**: Spans are closed when their work is complete
//!
//! # Nesting
//!
//! Spans can be nested to show relationships:
//!
//! ```rust
//! use veecle_telemetry::span;
//!
//! let parent = span!("parent_operation");
//! let _parent_guard = parent.entered();
//!
//! // This span will automatically be a child of the parent
//! let child = span!("child_operation");
//! let _child_guard = child.entered();
//! ```

#[cfg(feature = "enable")]
use core::cell::Cell;
use core::marker::PhantomData;
#[cfg(all(feature = "std", feature = "enable"))]
use std::thread_local;

use crate::SpanContext;
#[cfg(feature = "enable")]
use crate::collector::get_collector;
use crate::id::SpanId;
#[cfg(feature = "enable")]
use crate::protocol::{
    SpanAddEventMessage, SpanAddLinkMessage, SpanCloseMessage, SpanCreateMessage, SpanEnterMessage,
    SpanExitMessage, SpanSetAttributeMessage,
};
#[cfg(feature = "enable")]
use crate::time::now;
use crate::value::KeyValue;

#[cfg(feature = "enable")]
thread_local! {
    pub(crate) static CURRENT_SPAN: Cell<Option<SpanContext>> = const { Cell::new(None) };
}

/// A distributed tracing span representing a unit of work.
///
/// Spans are the fundamental building blocks of distributed tracing.
/// They represent a unit of work within a trace and can be nested to show relationships between different operations.
///
/// # Examples
///
/// ```rust
/// use veecle_telemetry::{KeyValue, Span, Value};
///
/// // Create a span with attributes
/// let span = Span::new("database_query", &[
///     KeyValue::new("table", Value::String("users".into())),
///     KeyValue::new("operation", Value::String("SELECT".into())),
/// ]);
///
/// // Enter the span to make it active
/// let _guard = span.enter();
///
/// // Add events to the span
/// span.add_event("query_executed", &[]);
/// ```
///
/// # Conditional Compilation
///
/// When the `enable` feature is disabled, spans compile to no-ops with zero runtime overhead.
#[must_use]
#[derive(Default, Debug)]
pub struct Span {
    #[cfg(feature = "enable")]
    pub(crate) inner: Option<SpanInner>,
}

#[cfg(feature = "enable")]
#[derive(Debug)]
pub(crate) struct SpanInner {
    pub(crate) context: SpanContext,
}

/// Utilities for working with the currently active span.
///
/// This struct provides static methods for interacting with the current span
/// in the thread-local context.
/// It allows adding events, links, and attributes to the currently active span without needing a direct reference to
/// it.
///
/// # Examples
///
/// ```rust
/// use veecle_telemetry::{CurrentSpan, span};
///
/// let span = span!("operation");
/// let _guard = span.entered();
///
/// // Add an event to the current span
/// CurrentSpan::add_event("milestone", &[]);
/// ```
#[derive(Default, Debug)]
pub struct CurrentSpan;

impl Span {
    /// Creates a no-op span that performs no tracing operations.
    ///
    /// This is useful for creating spans that may be conditionally enabled
    /// or when telemetry is completely disabled.
    #[inline]
    pub fn noop() -> Self {
        Self {
            #[cfg(feature = "enable")]
            inner: None,
        }
    }

    /// Creates a new span as a child of the current span.
    ///
    /// If there is no current span, this returns a no-op span.
    /// Uses [`Span::root`] to create a root span with a specific context.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the span
    /// * `attributes` - Key-value attributes to attach to the span
    ///
    /// # Examples
    ///
    /// ```rust
    /// use veecle_telemetry::{KeyValue, Span, Value};
    ///
    /// let span = Span::new("operation", &[KeyValue::new("user_id", Value::I64(123))]);
    /// ```
    pub fn new(name: &'static str, attributes: &'_ [KeyValue<'static>]) -> Self {
        #[cfg(not(feature = "enable"))]
        {
            let _ = (name, attributes);
            Self::noop()
        }

        #[cfg(feature = "enable")]
        {
            if let Some(parent) = CURRENT_SPAN.get() {
                Self::new_inner(name, parent, attributes)
            } else {
                Self::noop()
            }
        }
    }

    /// Creates a new root span with the given context.
    ///
    /// Unlike `new()`, this method does not use the current span from `CURRENT_SPAN`
    /// and creates a true root span with no parent using the provided `SpanContext` directly.
    ///
    /// # Examples
    ///
    /// ```
    /// use veecle_telemetry::{Span, SpanContext};
    ///
    /// let context = SpanContext::generate();
    /// let span = Span::root("root_span", context, &[]);
    /// ```
    pub fn root(
        name: &'static str,
        mut span_context: SpanContext,
        attributes: &'_ [KeyValue<'static>],
    ) -> Self {
        // Ensure no parent_id will be set.
        span_context.span_id = SpanId(0);

        #[cfg(not(feature = "enable"))]
        {
            let _ = (name, attributes);
            Self::noop()
        }

        #[cfg(feature = "enable")]
        {
            Self::new_inner(name, span_context, attributes)
        }
    }

    /// Enters this span, making it the current active span.
    ///
    /// This method returns a guard that will automatically exit the span when dropped.
    /// The guard borrows the span, so the span must remain alive while the guard exists.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use veecle_telemetry::Span;
    ///
    /// let span = Span::new("operation", &[]);
    /// let _guard = span.enter();
    /// // span is now active
    /// // span is automatically exited when _guard is dropped
    /// ```
    pub fn enter(&'_ self) -> SpanGuardRef<'_> {
        #[cfg(not(feature = "enable"))]
        {
            SpanGuardRef::noop()
        }

        #[cfg(feature = "enable")]
        {
            let Some(context) = self.inner.as_ref().map(|inner| inner.context) else {
                return SpanGuardRef::noop();
            };

            self.do_enter();
            CURRENT_SPAN
                .try_with(|current| {
                    let parent = current.get();
                    current.set(Some(context));

                    SpanGuardRef::new(self, parent)
                })
                .unwrap_or(SpanGuardRef::noop())
        }
    }

    /// Enters this span by taking ownership of it.
    ///
    /// This method consumes the span and returns a guard that owns the span.
    /// The span will be automatically exited and closed when the guard is dropped.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use veecle_telemetry::Span;
    ///
    /// let span = Span::new("operation", &[]);
    /// let _guard = span.entered();
    /// // span is now active and owned by the guard
    /// // span is automatically exited and closed when _guard is dropped
    /// ```
    pub fn entered(self) -> SpanGuard {
        #[cfg(not(feature = "enable"))]
        {
            SpanGuard::noop()
        }

        #[cfg(feature = "enable")]
        {
            let Some(context) = self.inner.as_ref().map(|inner| inner.context) else {
                return SpanGuard::noop();
            };

            self.do_enter();
            CURRENT_SPAN
                .try_with(|current| {
                    let parent = current.get();
                    current.set(Some(context));

                    SpanGuard::new(self, parent)
                })
                .unwrap_or(SpanGuard::noop())
        }
    }

    /// Adds an event to this span.
    ///
    /// Events represent point-in-time occurrences within a span's lifetime.
    /// They can include additional attributes for context.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the event
    /// * `attributes` - Key-value attributes providing additional context
    ///
    /// # Examples
    ///
    /// ```rust
    /// use veecle_telemetry::{KeyValue, Span, Value};
    ///
    /// let span = Span::new("database_query", &[]);
    /// span.add_event("query_started", &[]);
    /// span.add_event("query_completed", &[KeyValue::new("rows_returned", Value::I64(42))]);
    /// ```
    pub fn add_event(&self, name: &'static str, attributes: &'_ [KeyValue<'static>]) {
        #[cfg(not(feature = "enable"))]
        {
            let _ = (name, attributes);
        }

        #[cfg(feature = "enable")]
        {
            if let Some(inner) = &self.inner {
                get_collector().span_event(SpanAddEventMessage {
                    trace_id: inner.context.trace_id,
                    span_id: inner.context.span_id,
                    name: name.into(),
                    time_unix_nano: now().as_nanos(),
                    attributes: attributes.into(),
                });
            }
        }
    }

    /// Creates a link from this span to another span.
    ///
    /// Links connect spans across different traces, allowing you to represent
    /// relationships between spans that are not parent-child relationships.
    ///
    /// # Examples
    ///
    /// ```
    /// use veecle_telemetry::{Span, SpanContext, SpanId, TraceId};
    ///
    /// let span = Span::new("my_span", &[]);
    /// let external_context = SpanContext::new(TraceId(0x123), SpanId(0x456));
    /// span.add_link(external_context);
    /// ```
    pub fn add_link(&self, link: SpanContext) {
        #[cfg(not(feature = "enable"))]
        {
            let _ = link;
        }

        #[cfg(feature = "enable")]
        {
            if let Some(inner) = self.inner.as_ref() {
                get_collector().span_link(SpanAddLinkMessage {
                    trace_id: inner.context.trace_id,
                    span_id: inner.context.span_id,
                    link,
                });
            }
        }
    }

    /// Adds an attribute to this span.
    ///
    /// Attributes provide additional context about the work being performed
    /// in the span. They can be set at any time during the span's lifetime.
    ///
    /// # Arguments
    ///
    /// * `attribute` - The key-value attribute to set
    ///
    /// # Examples
    ///
    /// ```rust
    /// use veecle_telemetry::{KeyValue, Span, Value};
    ///
    /// let span = Span::new("user_operation", &[]);
    /// span.set_attribute(KeyValue::new("user_id", Value::I64(123)));
    /// span.set_attribute(KeyValue::new("operation_type", Value::String("update".into())));
    /// ```
    pub fn set_attribute(&self, attribute: KeyValue<'static>) {
        #[cfg(not(feature = "enable"))]
        {
            let _ = attribute;
        }

        #[cfg(feature = "enable")]
        {
            if let Some(inner) = self.inner.as_ref() {
                get_collector().span_attribute(SpanSetAttributeMessage {
                    trace_id: inner.context.trace_id,
                    span_id: inner.context.span_id,
                    attribute,
                });
            }
        }
    }
}

impl CurrentSpan {
    /// Adds an event to the current span.
    ///
    /// Events represent point-in-time occurrences within a span's lifetime.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the event
    /// * `attributes` - Key-value attributes providing additional context
    ///
    /// # Examples
    ///
    /// ```rust
    /// use veecle_telemetry::{CurrentSpan, KeyValue, Value, span};
    ///
    /// let _guard = span!("operation").entered();
    /// CurrentSpan::add_event("checkpoint", &[]);
    /// CurrentSpan::add_event("milestone", &[KeyValue::new("progress", 75)]);
    /// ```
    ///
    /// Does nothing if there's no active span.
    pub fn add_event(name: &'static str, attributes: &'_ [KeyValue<'static>]) {
        #[cfg(not(feature = "enable"))]
        {
            let _ = (name, attributes);
        }

        #[cfg(feature = "enable")]
        {
            if let Some(context) = SpanContext::current() {
                get_collector().span_event(SpanAddEventMessage {
                    trace_id: context.trace_id,
                    span_id: context.span_id,
                    name: name.into(),
                    time_unix_nano: now().as_nanos(),
                    attributes: attributes.into(),
                });
            }
        }
    }

    /// Creates a link from the current span to another span.
    /// Does nothing if there's no active span.
    ///
    /// Links connect spans across different traces, allowing you to represent
    /// relationships between spans that are not parent-child relationships.
    ///
    /// # Examples
    ///
    /// ```
    /// use veecle_telemetry::{CurrentSpan, Span, SpanContext, SpanId, TraceId};
    ///
    /// let _guard = Span::new("my_span", &[]).entered();
    ///
    /// let external_context = SpanContext::new(TraceId(0x123), SpanId(0x456));
    /// CurrentSpan::add_link(external_context);
    /// ```
    pub fn add_link(link: SpanContext) {
        #[cfg(not(feature = "enable"))]
        {
            let _ = link;
        }

        #[cfg(feature = "enable")]
        {
            if let Some(context) = SpanContext::current() {
                get_collector().span_link(SpanAddLinkMessage {
                    trace_id: context.trace_id,
                    span_id: context.span_id,
                    link,
                });
            }
        }
    }

    /// Sets an attribute on the current span.
    ///
    /// Attributes provide additional context about the work being performed
    /// in the span.
    ///
    /// # Arguments
    ///
    /// * `attribute` - The key-value attribute to set
    ///
    /// # Examples
    ///
    /// ```rust
    /// use veecle_telemetry::{CurrentSpan, KeyValue, Value, span};
    ///
    /// let _guard = span!("operation").entered();
    /// CurrentSpan::set_attribute(KeyValue::new("user_id", 123));
    /// CurrentSpan::set_attribute(KeyValue::new("status", "success"));
    /// ```
    ///
    /// Does nothing if there's no active span.
    pub fn set_attribute(attribute: KeyValue<'static>) {
        #[cfg(not(feature = "enable"))]
        {
            let _ = attribute;
        }

        #[cfg(feature = "enable")]
        {
            if let Some(context) = SpanContext::current() {
                get_collector().span_attribute(SpanSetAttributeMessage {
                    trace_id: context.trace_id,
                    span_id: context.span_id,
                    attribute,
                });
            }
        }
    }
}

#[cfg(feature = "enable")]
impl Span {
    fn new_inner(
        name: &'static str,
        parent: SpanContext,
        attributes: &'_ [KeyValue<'static>],
    ) -> Self {
        let span_id = SpanId::next_id();
        let context = SpanContext::new(parent.trace_id, span_id);

        let parent_id = if parent.span_id == SpanId(0) {
            None
        } else {
            Some(parent.span_id)
        };

        get_collector().new_span(SpanCreateMessage {
            trace_id: context.trace_id,
            span_id: context.span_id,
            parent_span_id: parent_id,
            name: name.into(),
            start_time_unix_nano: now().as_nanos(),
            attributes: attributes.into(),
        });

        Self {
            inner: Some(SpanInner { context }),
        }
    }

    fn do_enter(&self) {
        #[cfg(feature = "enable")]
        if let Some(inner) = self.inner.as_ref() {
            let timestamp = now();
            get_collector().enter_span(SpanEnterMessage {
                trace_id: inner.context.trace_id,
                span_id: inner.context.span_id,
                time_unix_nano: timestamp.0,
            });
        }
    }

    fn do_exit(&self) {
        #[cfg(feature = "enable")]
        if let Some(inner) = self.inner.as_ref() {
            let timestamp = now();
            get_collector().exit_span(SpanExitMessage {
                trace_id: inner.context.trace_id,
                span_id: inner.context.span_id,
                time_unix_nano: timestamp.0,
            });
        }
    }
}

impl Drop for Span {
    fn drop(&mut self) {
        #[cfg(feature = "enable")]
        if let Some(inner) = self.inner.take() {
            let timestamp = now();
            get_collector().close_span(SpanCloseMessage {
                trace_id: inner.context.trace_id,
                span_id: inner.context.span_id,
                end_time_unix_nano: timestamp.0,
            });
        }
    }
}

/// Exits and drops the span when this is dropped.
#[derive(Debug)]
pub struct SpanGuard {
    #[cfg(feature = "enable")]
    pub(crate) inner: Option<SpanGuardInner>,

    /// ```compile_fail
    /// use veecle_telemetry::span::*;
    /// trait AssertSend: Send {}
    ///
    /// impl AssertSend for SpanGuard {}
    /// ```
    _not_send: PhantomNotSend,
}

#[cfg(feature = "enable")]
#[derive(Debug)]
pub(crate) struct SpanGuardInner {
    span: Span,
    parent: Option<SpanContext>,
}

impl SpanGuard {
    pub(crate) fn noop() -> Self {
        Self {
            #[cfg(feature = "enable")]
            inner: None,
            _not_send: PhantomNotSend,
        }
    }

    #[cfg(feature = "enable")]
    pub(crate) fn new(span: Span, parent: Option<SpanContext>) -> Self {
        Self {
            #[cfg(feature = "enable")]
            inner: Some(SpanGuardInner { span, parent }),
            _not_send: PhantomNotSend,
        }
    }
}

impl Drop for SpanGuard {
    fn drop(&mut self) {
        #[cfg(feature = "enable")]
        if let Some(inner) = self.inner.take() {
            let _ = CURRENT_SPAN.try_with(|current| current.replace(inner.parent));
            inner.span.do_exit();
        }
    }
}

/// Exits the span when dropped.
#[derive(Debug)]
pub struct SpanGuardRef<'a> {
    #[cfg(feature = "enable")]
    pub(crate) inner: Option<SpanGuardRefInner<'a>>,

    _phantom: PhantomData<&'a ()>,
}

#[cfg(feature = "enable")]
#[derive(Debug)]
pub(crate) struct SpanGuardRefInner<'a> {
    span: &'a Span,
    parent: Option<SpanContext>,
}

impl<'a> SpanGuardRef<'a> {
    pub(crate) fn noop() -> Self {
        Self {
            #[cfg(feature = "enable")]
            inner: None,
            _phantom: PhantomData,
        }
    }

    #[cfg(feature = "enable")]
    pub(crate) fn new(span: &'a Span, parent: Option<SpanContext>) -> Self {
        Self {
            #[cfg(feature = "enable")]
            inner: Some(SpanGuardRefInner { span, parent }),
            _phantom: PhantomData,
        }
    }
}

impl Drop for SpanGuardRef<'_> {
    fn drop(&mut self) {
        #[cfg(feature = "enable")]
        if let Some(inner) = self.inner.take() {
            let _ = CURRENT_SPAN.try_with(|current| current.replace(inner.parent));
            inner.span.do_exit();
        }
    }
}

/// Technically, `SpanGuard` _can_ implement both `Send` *and*
/// `Sync` safely. It doesn't, because it has a `PhantomNotSend` field,
/// specifically added in order to make it `!Send`.
///
/// Sending an `SpanGuard` guard between threads cannot cause memory unsafety.
/// However, it *would* result in incorrect behavior, so we add a
/// `PhantomNotSend` to prevent it from being sent between threads. This is
/// because it must be *dropped* on the same thread that it was created;
/// otherwise, the span will never be exited on the thread where it was entered,
/// and it will attempt to exit the span on a thread that may never have entered
/// it. However, we still want them to be `Sync` so that a struct holding an
/// `Entered` guard can be `Sync`.
///
/// Thus, this is totally safe.
#[derive(Debug)]
struct PhantomNotSend {
    ghost: PhantomData<*mut ()>,
}

#[allow(non_upper_case_globals)]
const PhantomNotSend: PhantomNotSend = PhantomNotSend { ghost: PhantomData };

/// # Safety:
///
/// Trivially safe, as `PhantomNotSend` doesn't have any API.
unsafe impl Sync for PhantomNotSend {}

#[cfg(all(test, feature = "std"))]
mod tests {
    use super::*;
    use crate::{SpanContext, SpanId, TraceId};

    #[test]
    fn span_noop() {
        let span = Span::noop();
        assert!(span.inner.is_none());
    }

    #[test]
    fn span_new_without_parent() {
        CURRENT_SPAN.set(None);

        let span = Span::new("test_span", &[]);
        assert!(span.inner.is_none());
    }

    #[test]
    fn span_new_with_parent() {
        let parent_context = SpanContext::generate();
        CURRENT_SPAN.set(Some(parent_context));

        let span = Span::new("child_span", &[]);
        let inner = span.inner.as_ref().unwrap();
        assert_eq!(inner.context.trace_id, parent_context.trace_id);
        assert_ne!(inner.context.span_id, parent_context.span_id);

        CURRENT_SPAN.set(None);
    }

    #[test]
    fn span_root() {
        let root_context = SpanContext::generate();
        assert_eq!(root_context.span_id, SpanId(0));

        let span = Span::root("root_span", root_context, &[]);
        let inner = span.inner.as_ref().unwrap();
        assert_eq!(inner.context.trace_id, root_context.trace_id);
        assert_ne!(inner.context.span_id, SpanId(0));
    }

    #[test]
    fn span_context_from_span() {
        let root_context = SpanContext::generate();
        let span = Span::root("test_span", root_context, &[]);

        let extracted_context = SpanContext::from_span(&span);
        let context = extracted_context.unwrap();
        assert_eq!(context.trace_id, root_context.trace_id);
    }

    #[test]
    fn span_context_from_noop_span() {
        let span = Span::noop();
        let extracted_context = SpanContext::from_span(&span);
        assert!(extracted_context.is_none());
    }

    #[test]
    fn span_enter_and_current_context() {
        CURRENT_SPAN.set(None);

        assert!(SpanContext::current().is_none());

        let root_context = SpanContext::generate();
        let span = Span::root("test_span", root_context, &[]);

        {
            let _guard = span.enter();
            let current_context = SpanContext::current();
            let context = current_context.unwrap();
            assert_eq!(context.trace_id, root_context.trace_id);
        }

        // After guard is dropped, should be back to no current context
        assert!(SpanContext::current().is_none());
    }

    #[test]
    fn span_entered_guard() {
        CURRENT_SPAN.set(None);

        let root_context = SpanContext::generate();
        let span = Span::root("test_span", root_context, &[]);

        {
            let _guard = span.entered();
            // Should have current context while guard exists
            let current_context = SpanContext::current();
            assert!(current_context.is_some());
        }

        // Should be cleared after guard is dropped
        assert!(SpanContext::current().is_none());
    }

    #[test]
    fn noop_span_operations() {
        let noop_span = Span::noop();

        {
            let _guard = noop_span.enter();
            assert!(SpanContext::current().is_none());
        }

        let _entered_guard = noop_span.entered();
        assert!(SpanContext::current().is_none());
    }

    #[test]
    fn nested_spans() {
        CURRENT_SPAN.set(None);

        let root_context = SpanContext::generate();
        let _root_guard = Span::root("test_span", root_context, &[]).entered();

        let child_span = Span::new("child", &[]);
        let child_inner = child_span.inner.as_ref().unwrap();
        assert_eq!(child_inner.context.trace_id, root_context.trace_id);
        assert_ne!(child_inner.context.span_id, root_context.span_id);
    }

    #[test]
    fn span_event() {
        let context = SpanContext::generate();
        let span = Span::root("test_span", context, &[]);

        let event_attributes = [KeyValue::new("event_key", "event_value")];

        span.add_event("test_event", &event_attributes);

        let noop_span = Span::noop();
        noop_span.add_event("noop_event", &event_attributes);
    }

    #[test]
    fn span_link() {
        let context = SpanContext::generate();
        let span = Span::root("test_span", context, &[]);

        let link_context = SpanContext::new(TraceId(0), SpanId(0));
        span.add_link(link_context);

        let noop_span = Span::noop();
        noop_span.add_link(link_context);
    }

    #[test]
    fn span_attribute() {
        let context = SpanContext::generate();
        let span = Span::root("test_span", context, &[]);

        let attribute = KeyValue::new("test_key", "test_value");
        span.set_attribute(attribute.clone());

        let noop_span = Span::noop();
        noop_span.set_attribute(attribute);
    }

    #[test]
    fn span_methods_with_entered_span() {
        let context = SpanContext::generate();
        let span = Span::root("test_span", context, &[]);

        let _guard = span.enter();

        // All these should work while span is entered
        span.add_event("entered_event", &[]);
        span.add_link(SpanContext::new(TraceId(0), SpanId(0)));
        span.set_attribute(KeyValue::new("entered_key", true));
    }

    #[test]
    fn current_span_event_with_active_span() {
        CURRENT_SPAN.set(None);

        let context = SpanContext::generate();
        let _root_guard = Span::root("test_span", context, &[]).entered();

        let event_attributes = [KeyValue::new("current_event_key", "current_event_value")];
        CurrentSpan::add_event("current_test_event", &event_attributes);
    }

    #[test]
    fn current_span_link_with_active_span() {
        CURRENT_SPAN.set(None);

        let context = SpanContext::generate();
        let _root_guard = Span::root("test_span", context, &[]).entered();

        let link_context = SpanContext::new(TraceId(0), SpanId(0));
        CurrentSpan::add_link(link_context);
    }

    #[test]
    fn current_span_attribute_with_active_span() {
        CURRENT_SPAN.set(None);

        let context = SpanContext::generate();
        let span = Span::root("test_span", context, &[]);

        let _guard = span.enter();
        let attribute = KeyValue::new("current_attr_key", "current_attr_value");
        CurrentSpan::set_attribute(attribute);
    }
}