|
| 1 | +"""Explicit W3C correlation values; no ambient tracing state.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import re |
| 6 | +from collections.abc import Mapping |
| 7 | +from dataclasses import dataclass, field |
| 8 | +from typing import cast |
| 9 | + |
| 10 | +_PARENT = re.compile(r"([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})") |
| 11 | +_KEY = re.compile( |
| 12 | + r"(?:[a-z][a-z0-9_*/-]{0,255}|[a-z0-9][a-z0-9_*/-]{0,240}@[a-z][a-z0-9_*/-]{0,12})" |
| 13 | +) |
| 14 | + |
| 15 | + |
| 16 | +@dataclass(frozen=True, kw_only=True) |
| 17 | +class TraceContext: |
| 18 | + """An immutable W3C parent carrier, independent of any tracing provider. |
| 19 | +
|
| 20 | + The traceparent has an SDK limit of 512 ASCII characters. Trace IDs and span |
| 21 | + IDs must be nonzero lowercase hex. Version 00 accepts defined flags 00 or |
| 22 | + 01. Future versions retain their opaque suffix; native execution interprets |
| 23 | + the known prefix. Tracestate accepts at most 32 members, each with a key and |
| 24 | + value of at most 256 ASCII characters. The native propagator limits the |
| 25 | + system ID after @ to 13 characters. Optional whitespace and empty members |
| 26 | + are normalized. These limits define the supported native carrier profile. |
| 27 | + Put no credentials or private content in either header. This value does |
| 28 | + not keep a span alive, create spans, or propagate baggage. |
| 29 | + """ |
| 30 | + |
| 31 | + traceparent: str = field(repr=False) |
| 32 | + tracestate: str | None = field(default=None, repr=False) |
| 33 | + |
| 34 | + def __post_init__(self) -> None: |
| 35 | + parent = self.traceparent |
| 36 | + if not isinstance(parent, str): |
| 37 | + raise TypeError("traceparent must be a string") |
| 38 | + match = _PARENT.match(parent) |
| 39 | + if ( |
| 40 | + match is None |
| 41 | + or len(parent) > 512 |
| 42 | + or match[1] == "ff" |
| 43 | + or int(match[2], 16) == 0 |
| 44 | + or int(match[3], 16) == 0 |
| 45 | + or (match[1] == "00" and len(parent) != 55) |
| 46 | + or (match[1] == "00" and match[4] not in ("00", "01")) |
| 47 | + or (len(parent) > 55 and parent[55] != "-") |
| 48 | + or any(not 0x21 <= ord(char) <= 0x7E for char in parent) |
| 49 | + ): |
| 50 | + raise ValueError("Invalid W3C traceparent") |
| 51 | + state = self.tracestate |
| 52 | + if state is None: |
| 53 | + return |
| 54 | + if not isinstance(state, str): |
| 55 | + raise TypeError("tracestate must be a string or None") |
| 56 | + if len(state.split(",")) > 32: |
| 57 | + raise ValueError("Invalid W3C tracestate") |
| 58 | + members: dict[str, str] = {} |
| 59 | + for member in state.split(","): |
| 60 | + member = member.strip(" \t") |
| 61 | + if not member: |
| 62 | + continue |
| 63 | + key, separator, value = member.partition("=") |
| 64 | + if ( |
| 65 | + not separator |
| 66 | + or _KEY.fullmatch(key) is None |
| 67 | + or key in members |
| 68 | + or not 1 <= len(value) <= 256 |
| 69 | + or any(not 0x20 <= ord(char) <= 0x7E or char in ",=" for char in value) |
| 70 | + ): |
| 71 | + raise ValueError("Invalid W3C tracestate") |
| 72 | + members[key] = value |
| 73 | + object.__setattr__( |
| 74 | + self, "tracestate", ",".join(f"{k}={v}" for k, v in members.items()) or None |
| 75 | + ) |
| 76 | + |
| 77 | + def to_headers(self) -> dict[str, str]: |
| 78 | + """Return a new lowercase header map containing only this carrier.""" |
| 79 | + headers = {"traceparent": self.traceparent} |
| 80 | + if self.tracestate is not None: |
| 81 | + headers["tracestate"] = self.tracestate |
| 82 | + return headers |
| 83 | + |
| 84 | + |
| 85 | +def _trace_context(value: TraceContext | Mapping[str, str | None] | None) -> TraceContext | None: |
| 86 | + """Normalize once at public admission, before runtime effects.""" |
| 87 | + if value is None or isinstance(value, TraceContext): |
| 88 | + return value |
| 89 | + if not isinstance(value, Mapping): |
| 90 | + raise TypeError("parent_trace must be TraceContext, a carrier mapping, or None") |
| 91 | + if "traceparent" not in value or any(key not in ("traceparent", "tracestate") for key in value): |
| 92 | + raise ValueError("A trace carrier requires traceparent and optional tracestate only") |
| 93 | + return TraceContext( |
| 94 | + traceparent=cast(str, value["traceparent"]), tracestate=value.get("tracestate") |
| 95 | + ) |
| 96 | + |
| 97 | + |
| 98 | +def _native_trace_context(value: Mapping[str, str | None] | None) -> TraceContext | None: |
| 99 | + # Native tracing can inherit settings outside the public carrier profile. |
| 100 | + # Optional correlation metadata must not turn a valid tool into a failure. |
| 101 | + try: |
| 102 | + return _trace_context(value) |
| 103 | + except (TypeError, ValueError): |
| 104 | + return None |
0 commit comments