v0.166.0
 1from dataclasses import dataclass
 2
 3from opentelemetry import trace
 4from opentelemetry.trace import format_trace_id
 5
 6
 7@dataclass(frozen=True)
 8class CurrentTrace:
 9    """The active request's OpenTelemetry trace, as connect needs it.
10
11    `trace_id` is the 32-char hex id, or "" when there is no valid trace —
12    connect only installs an SDK tracer provider when export is configured,
13    so without a token requests get no-op spans with an all-zero id.
14
15    `sampled` is the final sampling decision (so a sub-1.0
16    CONNECT_TRACE_SAMPLE_RATE is accounted for here for free), or None when
17    there is no valid trace.
18    """
19
20    trace_id: str
21    sampled: bool | None
22
23
24def current_trace() -> CurrentTrace:
25    """Read the active span's trace id and sampling decision."""
26    span_context = trace.get_current_span().get_span_context()
27    if not span_context.is_valid:
28        return CurrentTrace(trace_id="", sampled=None)
29    return CurrentTrace(
30        trace_id=format_trace_id(span_context.trace_id),
31        sampled=span_context.trace_flags.sampled,
32    )