getTracingHeaders function

Map<String, String> getTracingHeaders(
  1. TracingContext context,
  2. TracingHeaderType headersType
)

Implementation

Map<String, String> getTracingHeaders(
  TracingContext context,
  TracingHeaderType headersType,
) {
  var headers = <String, String>{};

  final sampledString = context.sampled ? '1' : '0';

  switch (headersType) {
    case TracingHeaderType.datadog:
      if (context.sampled) {
        headers[DatadogHttpTracingHeaders.traceId] =
            context.traceId.asString(TraceIdRepresentation.decimal);
        headers[DatadogHttpTracingHeaders.parentId] =
            context.spanId.asString(TraceIdRepresentation.decimal);
      }
      headers[DatadogHttpTracingHeaders.origin] = 'rum';
      headers[DatadogHttpTracingHeaders.samplingPriority] = sampledString;
      break;
    case TracingHeaderType.b3:
      if (context.sampled) {
        final headerValue = [
          context.traceId.asString(TraceIdRepresentation.hex32Chars),
          context.spanId.asString(TraceIdRepresentation.hex16Chars),
          sampledString,
          context.parentSpanId?.asString(TraceIdRepresentation.hex16Chars),
        ].whereType<String>().join('-');
        headers[OTelHttpTracingHeaders.singleB3] = headerValue;
      } else {
        headers[OTelHttpTracingHeaders.singleB3] = sampledString;
      }
      break;
    case TracingHeaderType.b3multi:
      headers[OTelHttpTracingHeaders.multipleSampled] = sampledString;

      if (context.sampled) {
        headers[OTelHttpTracingHeaders.multipleTraceId] =
            context.traceId.asString(TraceIdRepresentation.hex32Chars);
        headers[OTelHttpTracingHeaders.multipleSpanId] =
            context.spanId.asString(TraceIdRepresentation.hex16Chars);
        if (context.parentSpanId != null) {
          headers[OTelHttpTracingHeaders.multipleParentId] =
              context.parentSpanId!.asString(TraceIdRepresentation.hex16Chars);
        }
      }
      break;
    case TracingHeaderType.tracecontext:
      final headerValue = [
        '00', // Version Code
        context.traceId.asString(TraceIdRepresentation.hex32Chars),
        context.spanId.asString(TraceIdRepresentation.hex16Chars),
        context.sampled ? '01' : '00'
      ].join('-');
      headers[W3CTracingHeaders.traceparent] = headerValue;
      break;
  }

  return headers;
}