Copyright The OpenTelemetry Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

package trace

import (
	
	
	

	
)

Default B3 Header names.
	b3ContextHeader      = "b3"
	b3DebugFlagHeader    = "x-b3-flags"
	b3TraceIDHeader      = "x-b3-traceid"
	b3SpanIDHeader       = "x-b3-spanid"
	b3SampledHeader      = "x-b3-sampled"
	b3ParentSpanIDHeader = "x-b3-parentspanid"

	b3TraceIDPadding = "0000000000000000"
B3 Single Header encoding widths.
	separatorWidth      = 1       // Single "-" character.
	samplingWidth       = 1       // Single hex character.
	traceID64BitsWidth  = 64 / 4  // 16 hex character Trace ID.
	traceID128BitsWidth = 128 / 4 // 32 hex character Trace ID.
	spanIDWidth         = 16      // 16 hex character ID.
	parentSpanIDWidth   = 16      // 16 hex character ID.
)

var (
	empty = EmptySpanContext()

	errInvalidSampledByte        = errors.New("invalid B3 Sampled found")
	errInvalidSampledHeader      = errors.New("invalid B3 Sampled header found")
	errInvalidTraceIDHeader      = errors.New("invalid B3 TraceID header found")
	errInvalidSpanIDHeader       = errors.New("invalid B3 SpanID header found")
	errInvalidParentSpanIDHeader = errors.New("invalid B3 ParentSpanID header found")
	errInvalidScope              = errors.New("require either both TraceID and SpanID or none")
	errInvalidScopeParent        = errors.New("ParentSpanID requires both TraceID and SpanID to be available")
	errInvalidScopeParentSingle  = errors.New("ParentSpanID requires TraceID, SpanID and Sampled to be available")
	errEmptyContext              = errors.New("empty request context")
	errInvalidTraceIDValue       = errors.New("invalid B3 TraceID value found")
	errInvalidSpanIDValue        = errors.New("invalid B3 SpanID value found")
	errInvalidParentSpanIDValue  = errors.New("invalid B3 ParentSpanID value found")
)
B3Encoding is a bitmask representation of the B3 encoding type.
supports returns if e has o bit(s) set.
func ( B3Encoding) ( B3Encoding) bool {
	return & == 
}

B3MultipleHeader is a B3 encoding that uses multiple headers to transmit tracing information all prefixed with `x-b3-`.
B3SingleHeader is a B3 encoding that uses a single header named `b3` to transmit tracing information.
B3Unspecified is an unspecified B3 encoding.
B3 propagator serializes SpanContext to/from B3 Headers. This propagator supports both versions of B3 headers, 1. Single Header: b3: {TraceId}-{SpanId}-{SamplingState}-{ParentSpanId} 2. Multiple Headers: x-b3-traceid: {TraceId} x-b3-parentspanid: {ParentSpanId} x-b3-spanid: {SpanId} x-b3-sampled: {SamplingState} x-b3-flags: {DebugFlag}
InjectEncoding are the B3 encodings used when injecting trace information. If no encoding is specified (i.e. `B3Unspecified`) `B3MultipleHeader` will be used as the default.
Inject injects a context into the supplier as B3 headers. The parent span ID is omitted because it is not tracked in the SpanContext.
func ( B3) ( context.Context,  propagation.HTTPSupplier) {
	 := SpanFromContext().SpanContext()

	if .InjectEncoding.supports(B3SingleHeader) {
		 := []string{}
		if .TraceID.IsValid() && .SpanID.IsValid() {
			 = append(, .TraceID.String(), .SpanID.String())
		}

		if .isDebug() {
			 = append(, "d")
		} else if !.isDeferred() {
			if .IsSampled() {
				 = append(, "1")
			} else {
				 = append(, "0")
			}
		}

		.Set(b3ContextHeader, strings.Join(, "-"))
	}

	if .InjectEncoding.supports(B3MultipleHeader) || .InjectEncoding == B3Unspecified {
		if .TraceID.IsValid() && .SpanID.IsValid() {
			.Set(b3TraceIDHeader, .TraceID.String())
			.Set(b3SpanIDHeader, .SpanID.String())
		}

Since Debug implies deferred, don't also send "X-B3-Sampled".
			.Set(b3DebugFlagHeader, "1")
		} else if !.isDeferred() {
			if .IsSampled() {
				.Set(b3SampledHeader, "1")
			} else {
				.Set(b3SampledHeader, "0")
			}
		}
	}
}
Extract extracts a context from the supplier if it contains B3 headers.
func ( B3) ( context.Context,  propagation.HTTPSupplier) context.Context {
	var (
		  SpanContext
		 error
	)
Default to Single Header if a valid value exists.
	if  := .Get(b3ContextHeader);  != "" {
		,  = extractSingle()
		if  == nil && .IsValid() {
			return ContextWithRemoteSpanContext(, )
The Single Header value was invalid, fallback to Multiple Header.
	}

	var (
		      = .Get(b3TraceIDHeader)
		       = .Get(b3SpanIDHeader)
		 = .Get(b3ParentSpanIDHeader)
		      = .Get(b3SampledHeader)
		    = .Get(b3DebugFlagHeader)
	)
	,  = extractMultiple(, , , , )
	if  != nil || !.IsValid() {
		return 
	}
	return ContextWithRemoteSpanContext(, )
}

func ( B3) () []string {
	 := []string{}
	if .InjectEncoding.supports(B3SingleHeader) {
		 = append(, b3ContextHeader)
	}
	if .InjectEncoding.supports(B3MultipleHeader) || .InjectEncoding == B3Unspecified {
		 = append(, b3TraceIDHeader, b3SpanIDHeader, b3SampledHeader, b3DebugFlagHeader)
	}
	return 
}
extractMultiple reconstructs a SpanContext from header values based on B3 Multiple header. It is based on the implementation found here: https://github.com/openzipkin/zipkin-go/blob/v0.2.2/propagation/b3/spancontext.go and adapted to support a SpanContext.
func (, , , ,  string) (SpanContext, error) {
	var (
		           error
		 int
		            = SpanContext{}
	)
correct values for an existing sampled header are "0" and "1". For legacy support and being lenient to other tracing implementations we allow "true" and "false" as inputs for interop purposes.
	switch strings.ToLower() {
Zero value for TraceFlags sample bit is unset.
	case "1", "true":
		.TraceFlags = FlagsSampled
	case "":
		.TraceFlags = FlagsDeferred
	default:
		return empty, errInvalidSampledHeader
	}
The only accepted value for Flags is "1". This will set Debug to true. All other values and omission of header will be ignored.
	if  == "1" {
		.TraceFlags |= FlagsDebug
	}

	if  != "" {
		++
		 := 
Pad 64-bit trace IDs.
			 = b3TraceIDPadding + 
		}
		if .TraceID,  = IDFromHex();  != nil {
			return empty, errInvalidTraceIDHeader
		}
	}

	if  != "" {
		++
		if .SpanID,  = SpanIDFromHex();  != nil {
			return empty, errInvalidSpanIDHeader
		}
	}

	if  != 0 &&  != 2 {
		return empty, errInvalidScope
	}

	if  != "" {
		if  == 0 {
			return empty, errInvalidScopeParent
Validate parent span ID but we do not use it so do not save it.
		if _,  = SpanIDFromHex();  != nil {
			return empty, errInvalidParentSpanIDHeader
		}
	}

	return , nil
}
extractSingle reconstructs a SpanContext from contextHeader based on a B3 Single header. It is based on the implementation found here: https://github.com/openzipkin/zipkin-go/blob/v0.2.2/propagation/b3/spancontext.go and adapted to support a SpanContext.
func ( string) (SpanContext, error) {
	if  == "" {
		return empty, errEmptyContext
	}

	var (
		       = SpanContext{}
		 string
	)

	 := len()

	if  == samplingWidth {
		 = 
Trace ID by itself is invalid.
		return empty, errInvalidScope
	} else if  >= traceID64BitsWidth+spanIDWidth+separatorWidth {
		 := 0
		var  string
traceID must be 64 bits
			 += traceID64BitsWidth // {traceID}
			 = b3TraceIDPadding + string([0:])
traceID must be 128 bits
			 += traceID128BitsWidth // {traceID}
			 = string([0:])
		} else {
			return empty, errInvalidTraceIDValue
		}
		var  error
		.TraceID,  = IDFromHex()
		if  != nil {
			return empty, errInvalidTraceIDValue
		}
		 += separatorWidth // {traceID}-

		.SpanID,  = SpanIDFromHex([ : +spanIDWidth])
		if  != nil {
			return empty, errInvalidSpanIDValue
		}
		 += spanIDWidth // {traceID}-{spanID}

		if  >  {
{traceID}-{spanID}- is invalid.
				return empty, errInvalidSampledByte
			}
			 += separatorWidth // {traceID}-{spanID}-

			if  == +samplingWidth {
				 = string([])
{traceID}-{spanID}-{parentSpanID} is invalid.
				return empty, errInvalidScopeParentSingle
			} else if  == +samplingWidth+separatorWidth+parentSpanIDWidth {
				 = string([])
				 += samplingWidth + separatorWidth // {traceID}-{spanID}-{sampling}-
Validate parent span ID but we do not use it so do not save it.
				_,  = SpanIDFromHex([:])
				if  != nil {
					return empty, errInvalidParentSpanIDValue
				}
			} else {
				return empty, errInvalidParentSpanIDValue
			}
		}
	} else {
		return empty, errInvalidTraceIDValue
	}
	switch  {
	case "":
		.TraceFlags = FlagsDeferred
	case "d":
		.TraceFlags = FlagsDebug
	case "1":
		.TraceFlags = FlagsSampled
Zero value for TraceFlags sample bit is unset.
	default:
		return empty, errInvalidSampledByte
	}

	return , nil