Skip to content

Commit 8a0a64e

Browse files
authored
Merge pull request #86 from dreadnode/bugfix/otel-distributed-trace-fix
fix: distributed propagation
2 parents 8872f4a + 44ebcd2 commit 8a0a64e

1 file changed

Lines changed: 18 additions & 2 deletions

File tree

dreadnode/tracing/span.py

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
from opentelemetry import trace as trace_api
2424
from opentelemetry.sdk.trace import ReadableSpan
2525
from opentelemetry.trace import Tracer
26+
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
2627
from opentelemetry.util import types as otel_types
2728
from ulid import ULID
2829

@@ -358,8 +359,23 @@ def __enter__(self) -> te.Self:
358359
raise RuntimeError("You cannot start a run span within another run")
359360

360361
if self._remote_context is not None:
361-
otel_context = propagate.extract(carrier=self._remote_context)
362-
self._remote_token = context_api.attach(otel_context)
362+
# If the global propagator is a NoExtract instance, we can't continue
363+
# a trace, so we'll bypass it and use the W3C propagator directly.
364+
global_propagator = propagate.get_global_textmap()
365+
if "NoExtract" in type(global_propagator).__name__:
366+
w3c_propagator = TraceContextTextMapPropagator()
367+
otel_context = w3c_propagator.extract(carrier=self._remote_context)
368+
else:
369+
otel_context = propagate.extract(carrier=self._remote_context)
370+
371+
span_context = trace_api.get_current_span(otel_context).get_span_context()
372+
373+
# If we have a valid trace_id, we can attach the context and continue the trace.
374+
if span_context.trace_id != 0:
375+
self._remote_token = context_api.attach(otel_context)
376+
else:
377+
# Fall back to creating a new span if the context is invalid.
378+
super().__enter__()
363379
else:
364380
super().__enter__()
365381

0 commit comments

Comments
 (0)