| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
package 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 |
|
| 21 |
|
| 22 |
const binaryHeader = "grpc-trace-bin" |
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
type Binary struct{} |
| 28 |
|
| 29 |
var _ propagation.TextMapPropagator = Binary{} |
| 30 |
|
| 31 |
|
| 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 |
|
| 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 |
|
| 73 |
func (Binary) Fields() []string { |
| 74 |
return []string{binaryHeader} |
| 75 |
} |