-
Notifications
You must be signed in to change notification settings - Fork 3
/
tracing.go
84 lines (77 loc) · 1.74 KB
/
tracing.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
package rrpc
import (
"bufio"
"bytes"
"encoding/binary"
"github.com/opentracing/opentracing-go"
"github.com/pkg/errors"
)
var (
errEmptyTracing = errors.New("rrpc.tracing: tracing is empty")
errBadTracing = errors.New("rrpc.tracing: invalid tracing format")
)
type Tracer opentracing.Tracer
type SpanContext opentracing.SpanContext
func MarshallTracing(carrier map[string]string) (b []byte, err error) {
bf := &bytes.Buffer{}
for k, v := range carrier {
err = binary.Write(bf, binary.BigEndian, uint16(len(k)))
if err != nil {
return
}
_, err = bf.WriteString(k)
if err != nil {
return
}
err = binary.Write(bf, binary.BigEndian, uint16(len(v)))
if err != nil {
return
}
_, err = bf.WriteString(v)
if err != nil {
return
}
}
b = bf.Bytes()
return
}
func UnmarshallTracingCarrier(tracing []byte) (map[string]string, error) {
if len(tracing) < 1 {
return nil, errEmptyTracing
}
scanner := bufio.NewScanner(bytes.NewReader(tracing))
scanner.Split(func(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF {
return
}
if len(data) < 2 {
return
}
kvLen := int(binary.BigEndian.Uint16(data))
if kvLen < 1 {
err = errBadTracing
return
}
kvSize := kvLen + 2
if kvSize <= len(data) {
return kvSize, data[2:kvSize], nil
}
return
})
var pairs []string
for scanner.Scan() {
pairs = append(pairs, scanner.Text())
}
m := make(map[string]string)
for i, l := 0, len(pairs); i < l; i += 2 {
m[pairs[i]] = pairs[i+1]
}
return m, nil
}
func UnmarshallTracing(tracer Tracer, tracing []byte) (SpanContext, error) {
m, err := UnmarshallTracingCarrier(tracing)
if err != nil {
return nil, err
}
return tracer.Extract(opentracing.TextMap, opentracing.TextMapCarrier(m))
}