Debian Codegraph @

propagators/opencensus/binary.go

raw symbols SCIP
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 // Package opencensus provides an OpenCensus trace context propagator.
5 package opencensus // import "go.opentelemetry.io/contrib/propagators/opencensus"
6
7 import (
8 "context"
9
10 ocpropagation "go.opencensus.io/trace/propagation"
11 "go.opentelemetry.io/otel/bridge/opencensus"
12 "go.opentelemetry.io/otel/propagation"
13 "go.opentelemetry.io/otel/trace"
14 )
15
16 type key uint
17
18 const binaryKey key = 0
19
20 // binaryHeader is the same as traceContextKey is in opencensus:
21 // https://github.com/census-instrumentation/opencensus-go/blob/3fb168f674736c026e623310bfccb0691e6dec8a/plugin/ocgrpc/trace_common.go#L30
22 const binaryHeader = "grpc-trace-bin"
23
24 // Binary is an OpenTelemetry implementation of the OpenCensus grpc binary format.
25 // Binary propagation was temporarily removed from opentelemetry. See
26 // https://github.com/open-telemetry/opentelemetry-specification/issues/437
27 type Binary struct{}
28
29 var _ propagation.TextMapPropagator = Binary{}
30
31 // Inject injects context into the TextMapCarrier.
32 func (Binary) Inject(ctx context.Context, carrier propagation.TextMapCarrier) {
33 binaryContext := ctx.Value(binaryKey)
34 if state, ok := binaryContext.(string); binaryContext != nil && ok {
35 carrier.Set(binaryHeader, state)
36 }
37
38 sc := trace.SpanContextFromContext(ctx)
39 if !sc.IsValid() {
40 return
41 }
42 h := ocpropagation.Binary(opencensus.OTelSpanContextToOC(sc))
43 carrier.Set(binaryHeader, string(h))
44 }
45
46 // Extract extracts the SpanContext from the TextMapCarrier.
47 func (b Binary) Extract(ctx context.Context, carrier propagation.TextMapCarrier) context.Context {
48 state := carrier.Get(binaryHeader)
49 if state != "" {
50 ctx = context.WithValue(ctx, binaryKey, state)
51 }
52
53 sc := b.extract(carrier)
54 if !sc.IsValid() {
55 return ctx
56 }
57 return trace.ContextWithRemoteSpanContext(ctx, sc)
58 }
59
60 func (Binary) extract(carrier propagation.TextMapCarrier) trace.SpanContext {
61 h := carrier.Get(binaryHeader)
62 if h == "" {
63 return trace.SpanContext{}
64 }
65 ocContext, ok := ocpropagation.FromBinary([]byte(h))
66 if !ok {
67 return trace.SpanContext{}
68 }
69 return opencensus.OCSpanContextToOTel(ocContext)
70 }
71
72 // Fields returns the fields that this propagator modifies.
73 func (Binary) Fields() []string {
74 return []string{binaryHeader}
75 }