-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathpropagation_text.go
114 lines (99 loc) · 2.4 KB
/
propagation_text.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
package lightstep
import (
"strconv"
"strings"
"github.com/opentracing/opentracing-go"
)
const (
prefixBaggage = "ot-baggage-"
tracerStateFieldCount = 3
)
var theTextMapPropagator textMapPropagator
type traceIDParser func(string) (uint64, uint64, error)
type textMapPropagator struct {
traceIDKey string
traceID string
spanIDKey string
spanID string
sampledKey string
sampled string
parseTraceID traceIDParser
}
func (p textMapPropagator) Inject(
spanContext opentracing.SpanContext,
opaqueCarrier interface{},
) error {
sc, ok := spanContext.(SpanContext)
if !ok {
return opentracing.ErrInvalidSpanContext
}
carrier, ok := opaqueCarrier.(opentracing.TextMapWriter)
if !ok {
return opentracing.ErrInvalidCarrier
}
carrier.Set(p.traceIDKey, p.traceID)
carrier.Set(p.spanIDKey, p.spanID)
if len(p.sampled) > 0 {
carrier.Set(p.sampledKey, p.sampled)
} else {
carrier.Set(p.sampledKey, "true")
}
for k, v := range sc.Baggage {
carrier.Set(prefixBaggage+k, v)
}
return nil
}
func (p textMapPropagator) Extract(
opaqueCarrier interface{},
) (opentracing.SpanContext, error) {
carrier, ok := opaqueCarrier.(opentracing.TextMapReader)
if !ok {
return nil, opentracing.ErrInvalidCarrier
}
requiredFieldCount := 0
var traceIDUpper, traceIDLower, spanID uint64
var sampled string
var err error
decodedBaggage := map[string]string{}
err = carrier.ForeachKey(func(k, v string) error {
switch strings.ToLower(k) {
case p.traceIDKey:
traceIDLower, traceIDUpper, err = p.parseTraceID(v)
if err != nil {
return opentracing.ErrSpanContextCorrupted
}
requiredFieldCount++
case p.spanIDKey:
spanID, err = strconv.ParseUint(v, 16, 64)
if err != nil {
return opentracing.ErrSpanContextCorrupted
}
requiredFieldCount++
case p.sampledKey:
sampled = v
requiredFieldCount++
default:
lowercaseK := strings.ToLower(k)
if strings.HasPrefix(lowercaseK, prefixBaggage) {
decodedBaggage[strings.TrimPrefix(lowercaseK, prefixBaggage)] = v
}
}
return nil
})
if err != nil {
return nil, err
}
if requiredFieldCount < tracerStateFieldCount {
if requiredFieldCount == 0 {
return nil, opentracing.ErrSpanContextNotFound
}
return nil, opentracing.ErrSpanContextCorrupted
}
return SpanContext{
TraceIDUpper: traceIDUpper,
TraceID: traceIDLower,
SpanID: spanID,
Sampled: sampled,
Baggage: decodedBaggage,
}, nil
}