Files
mtusi2026lab6/app/trace_context.py
T

41 lines
1.6 KiB
Python

"""W3C context carried durably alongside a job, never its HTTP credentials.
The upload transaction stores ``carrier()``; publisher and retries restore it
with ``parent_context``. Only a new producer/consumer span changes the parent
span ID. Context-less legacy jobs deliberately start a new trace.
"""
from __future__ import annotations
from collections.abc import Mapping
from opentelemetry.context import Context
from opentelemetry.trace import get_current_span
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
_PROPAGATOR = TraceContextTextMapPropagator()
_FIELDS = ("traceparent", "tracestate")
def carrier() -> dict[str, str]:
"""Return the active span's W3C fields, or {} outside a valid span."""
headers: dict[str, str] = {}
_PROPAGATOR.inject(headers)
return {name: headers[name] for name in _FIELDS if headers.get(name)}
def parent_context(row_or_job: Mapping | None) -> Context:
"""Extract nullable DB/envelope fields without inheriting ambient context.
W3C parsing validates version, nonzero trace/span IDs, flags and tracestate.
Malformed or missing parent IDs become a new root, even if a publisher's
unrelated maintenance span happens to be active.
"""
headers: dict[str, str] = {}
if isinstance(row_or_job, Mapping):
for name in _FIELDS:
value = row_or_job.get(name)
if isinstance(value, str) and value:
headers[name] = value
context = _PROPAGATOR.extract(headers, context=Context())
return context if get_current_span(context).get_span_context().is_valid else Context()