Skip to main content

dekopon_telemetry/
lib.rs

1#![cfg_attr(test, allow(clippy::unwrap_used))]
2#![cfg_attr(
3    test,
4    allow(
5        clippy::disallowed_methods,
6        clippy::disallowed_types,
7        reason = "tests spawn, join and drain freely; production sites carry their own expectation"
8    )
9)]
10#[cfg(feature = "exporter")]
11mod exporter;
12#[cfg(feature = "exporter")]
13mod install;
14
15use opentelemetry::{
16    Context,
17    trace::{SpanContext, TraceContextExt as _, TraceFlags, TraceState},
18};
19use tracing_opentelemetry::OpenTelemetrySpanExt as _;
20
21#[cfg(feature = "exporter")]
22pub use exporter::{CA_CERTIFICATE_ENV, ExporterSettings, TelemetryError, Transport};
23#[cfg(all(unix, feature = "cli"))]
24pub use install::LogFileArgs;
25#[cfg(feature = "exporter")]
26pub use install::{
27    Console, ConsoleFilter, ConsoleFormat, ConsoleWriter, Install, InstallError, ShutdownError,
28    TelemetryGuard, optional_logger_provider,
29};
30#[cfg(all(unix, feature = "exporter"))]
31pub use install::{LogFile, LogFileError, LogFileOperation};
32
33#[derive(Clone, Debug)]
34pub struct EventStringArray<V = String> {
35    pub name: &'static str,
36    pub values: Vec<V>,
37}
38
39type EventStringArrays = Vec<EventStringArray<opentelemetry::Value>>;
40
41pub fn with_event_string_array<T, V: ToOwned + ?Sized>(
42    name: &'static str,
43    values: &[&V],
44    emit: impl FnOnce() -> T,
45) -> T
46where
47    V::Owned: Clone + std::fmt::Debug + Into<opentelemetry::Value> + Send + Sync + 'static,
48{
49    let current = Context::current();
50    let mut arrays = current
51        .get::<EventStringArrays>()
52        .cloned()
53        .unwrap_or_default();
54    let array = EventStringArray {
55        name,
56        values: values.iter().map(|value| (*value).to_owned()).collect(),
57    };
58    arrays.retain(|existing| existing.name != name);
59    arrays.push(EventStringArray {
60        name,
61        values: array.values.iter().cloned().map(Into::into).collect(),
62    });
63    let context = current.with_value(arrays).with_value(array);
64    let _scope = context.attach();
65    emit()
66}
67
68pub fn link_span(execution: &tracing::Span, receipt: &tracing::Span) {
69    let context = receipt.context();
70    let span = context.span();
71    if span.span_context().is_valid() {
72        execution.add_link(span.span_context().clone());
73    }
74}
75
76pub fn link_remote(execution: &tracing::Span, parts: TraceContextParts) {
77    let context = remote_context(parts);
78    let span = context.span();
79    execution.add_link(span.span_context().clone());
80}
81
82pub fn parent_remote(
83    span: &tracing::Span,
84    parts: TraceContextParts,
85) -> Result<(), tracing_opentelemetry::SetParentError> {
86    span.set_parent(remote_context(parts))
87}
88
89#[derive(Clone, Copy, Debug, Eq, PartialEq)]
90pub struct TraceContextParts {
91    pub trace_id: [u8; 16],
92    pub span_id: [u8; 8],
93    pub flags: u8,
94}
95
96#[must_use]
97pub fn current_trace_context() -> Option<TraceContextParts> {
98    span_trace_context(&tracing::Span::current())
99}
100
101#[must_use]
102pub fn span_trace_context(span: &tracing::Span) -> Option<TraceContextParts> {
103    let context = span.context();
104    let span = context.span();
105    let span_context = span.span_context();
106    if !span_context.is_valid() {
107        return None;
108    }
109    Some(TraceContextParts {
110        trace_id: span_context.trace_id().to_bytes(),
111        span_id: span_context.span_id().to_bytes(),
112        flags: span_context.trace_flags().to_u8(),
113    })
114}
115
116#[must_use]
117pub fn remote_context(parts: TraceContextParts) -> Context {
118    let span_context = SpanContext::new(
119        opentelemetry::trace::TraceId::from_bytes(parts.trace_id),
120        opentelemetry::trace::SpanId::from_bytes(parts.span_id),
121        TraceFlags::new(parts.flags),
122        true,
123        TraceState::default(),
124    );
125    Context::new().with_remote_span_context(span_context)
126}
127
128#[cfg(test)]
129mod tests {
130    use super::{TraceContextParts, remote_context};
131    use opentelemetry::trace::TraceContextExt as _;
132
133    #[test]
134    fn remote_context_preserves_identifiers_and_marks_them_remote() {
135        let parts = TraceContextParts {
136            trace_id: [
137                0x4b, 0xf9, 0x2f, 0x35, 0x77, 0xb3, 0x4d, 0xa6, 0xa3, 0xce, 0x92, 0x9d, 0x0e, 0x0e,
138                0x47, 0x36,
139            ],
140            span_id: [0x00, 0xf0, 0x67, 0xaa, 0x0b, 0xa9, 0x02, 0xb7],
141            flags: 1,
142        };
143
144        let context = remote_context(parts);
145        let span_context = context.span().span_context().clone();
146
147        assert!(span_context.is_valid());
148        assert!(span_context.is_remote());
149        assert_eq!(span_context.trace_id().to_bytes(), parts.trace_id);
150        assert_eq!(span_context.span_id().to_bytes(), parts.span_id);
151        assert_eq!(span_context.trace_flags().to_u8(), 1);
152    }
153}
154
155#[cfg(test)]
156mod span_sink {
157    use opentelemetry_sdk::{
158        error::OTelSdkResult,
159        trace::{SdkTracerProvider, SpanData, SpanExporter},
160    };
161    use parking_lot::Mutex;
162    use std::sync::Arc;
163
164    #[derive(Clone, Debug, Default)]
165    pub(crate) struct SpanSink(pub(crate) Arc<Mutex<Vec<SpanData>>>);
166
167    impl SpanExporter for SpanSink {
168        async fn export(&self, batch: Vec<SpanData>) -> OTelSdkResult {
169            self.0.lock().extend(batch);
170            Ok(())
171        }
172    }
173
174    pub(crate) fn exporting_provider() -> (SdkTracerProvider, SpanSink) {
175        let sink = SpanSink::default();
176        let provider = SdkTracerProvider::builder()
177            .with_simple_exporter(sink.clone())
178            .build();
179        (provider, sink)
180    }
181}
182
183#[cfg(test)]
184mod aggregation_tests {
185    use opentelemetry::trace::TracerProvider as _;
186    use tracing_subscriber::prelude::*;
187
188    use crate::span_sink::exporting_provider;
189
190    #[test]
191    fn collected_execution_exports_lead_parent_and_every_constituent_link() {
192        let (provider, exported) = exporting_provider();
193        let subscriber = tracing_subscriber::registry()
194            .with(tracing_opentelemetry::layer().with_tracer(provider.tracer("aggregation-test")));
195        tracing::subscriber::with_default(subscriber, || {
196            let lead = tracing::info_span!(parent: None, "receipt.lead");
197            let second = tracing::info_span!(parent: None, "receipt.second");
198            let third = tracing::info_span!(parent: None, "receipt.third");
199            let execution = tracing::info_span!(parent: &lead, "gateway.message");
200            for receipt in [&lead, &second, &third] {
201                super::link_span(&execution, receipt);
202            }
203        });
204        provider.force_flush().expect("flush");
205        let spans = exported.0.lock();
206        let execution = spans
207            .iter()
208            .find(|span| span.name == "gateway.message")
209            .expect("execution exported");
210        let receipts: Vec<_> = spans
211            .iter()
212            .filter(|span| span.name.starts_with("receipt."))
213            .collect();
214        assert_eq!(receipts.len(), 3);
215        assert_eq!(execution.links.links.len(), 3);
216        for receipt in &receipts {
217            assert!(
218                execution
219                    .links
220                    .links
221                    .iter()
222                    .any(|link| link.span_context == receipt.span_context)
223            );
224        }
225        let lead = receipts
226            .iter()
227            .find(|span| span.name == "receipt.lead")
228            .expect("lead");
229        assert_eq!(execution.parent_span_id, lead.span_context.span_id());
230        assert_eq!(
231            execution.span_context.trace_id(),
232            lead.span_context.trace_id()
233        );
234        drop(spans);
235        provider.shutdown().expect("shutdown");
236    }
237}