tryExtractTraceContext function

TraceContext? tryExtractTraceContext(
  1. String traceContextHeaderValue
)

Attempts to extract a valid traceId & spanId from a W3C traceparent header.

Expected format (lowercase hex): 00-<32 hex traceId>-<16 hex spanId>-<2 hex flags>

Returns a TraceContext with the extracted ids if valid and non-zero; otherwise returns null.

Implementation

TraceContext? tryExtractTraceContext(String traceContextHeaderValue) {
  if (traceContextHeaderValue.isEmpty) return null;
  final match = _traceparentRegex.firstMatch(traceContextHeaderValue.trim());
  if (match == null) return null;

  final traceId = match.group(1);
  final spanId = match.group(2);
  if (traceId == null || spanId == null) return null;
  if (_isAllZeros(traceId) || _isAllZeros(spanId)) return null;
  return TraceContext(traceId: traceId, spanId: spanId);
}