-
Notifications
You must be signed in to change notification settings - Fork 214
/
propagation_context.go
90 lines (74 loc) · 2.04 KB
/
propagation_context.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
package sentry
import (
"crypto/rand"
"encoding/json"
)
type PropagationContext struct {
TraceID TraceID `json:"trace_id"`
SpanID SpanID `json:"span_id"`
ParentSpanID SpanID `json:"parent_span_id"`
DynamicSamplingContext DynamicSamplingContext `json:"-"`
}
func (p PropagationContext) MarshalJSON() ([]byte, error) {
type propagationContext PropagationContext
var parentSpanID string
if p.ParentSpanID != zeroSpanID {
parentSpanID = p.ParentSpanID.String()
}
return json.Marshal(struct {
*propagationContext
ParentSpanID string `json:"parent_span_id,omitempty"`
}{
propagationContext: (*propagationContext)(&p),
ParentSpanID: parentSpanID,
})
}
func (p PropagationContext) Map() map[string]interface{} {
m := map[string]interface{}{
"trace_id": p.TraceID,
"span_id": p.SpanID,
}
if p.ParentSpanID != zeroSpanID {
m["parent_span_id"] = p.ParentSpanID
}
return m
}
func NewPropagationContext() PropagationContext {
p := PropagationContext{}
if _, err := rand.Read(p.TraceID[:]); err != nil {
panic(err)
}
if _, err := rand.Read(p.SpanID[:]); err != nil {
panic(err)
}
return p
}
func PropagationContextFromHeaders(trace, baggage string) (PropagationContext, error) {
p := NewPropagationContext()
if _, err := rand.Read(p.SpanID[:]); err != nil {
panic(err)
}
hasTrace := false
if trace != "" {
if tpc, valid := ParseTraceParentContext([]byte(trace)); valid {
hasTrace = true
p.TraceID = tpc.TraceID
p.ParentSpanID = tpc.ParentSpanID
}
}
if baggage != "" {
dsc, err := DynamicSamplingContextFromHeader([]byte(baggage))
if err != nil {
return PropagationContext{}, err
}
p.DynamicSamplingContext = dsc
}
// In case a sentry-trace header is present but there are no sentry-related
// values in the baggage, create an empty, frozen DynamicSamplingContext.
if hasTrace && !p.DynamicSamplingContext.HasEntries() {
p.DynamicSamplingContext = DynamicSamplingContext{
Frozen: true,
}
}
return p, nil
}