-
Notifications
You must be signed in to change notification settings - Fork 416
/
meta_struct.go
88 lines (73 loc) · 2.49 KB
/
meta_struct.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
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016 Datadog, Inc.
package tracer
import (
"github.com/tinylib/msgp/msgp"
)
var (
_ msgp.Encodable = (*metaStructMap)(nil)
_ msgp.Decodable = (*metaStructMap)(nil)
_ msgp.Sizer = (*metaStructMap)(nil)
)
// metaStructMap is a map of string to any of metadata embedded in each span
// We export special messagepack methods to handle the encoding and decoding of the map
// Because the agent expects the metadata to be a map of string to byte array, we have to create sub-messages of messagepack for each value
type metaStructMap map[string]any
// EncodeMsg transforms the map[string]any into a map[string][]byte agent-side (which is parsed back into a map[string]any in the backend)
func (m *metaStructMap) EncodeMsg(en *msgp.Writer) error {
err := en.WriteMapHeader(uint32(len(*m)))
if err != nil {
return msgp.WrapError(err, "MetaStruct")
}
for key, value := range *m {
err = en.WriteString(key)
if err != nil {
return msgp.WrapError(err, "MetaStruct")
}
// Wrap the encoded value in a byte array that will not be parsed by the agent
msg, err := msgp.AppendIntf(nil, value)
if err != nil {
return msgp.WrapError(err, "MetaStruct", key)
}
err = en.WriteBytes(msg)
if err != nil {
return msgp.WrapError(err, "MetaStruct", key)
}
}
return nil
}
// DecodeMsg transforms the map[string][]byte agent-side into a map[string]any where values are sub-messages in messagepack
func (m *metaStructMap) DecodeMsg(de *msgp.Reader) error {
header, err := de.ReadMapHeader()
if err != nil {
return msgp.WrapError(err, "MetaStruct")
}
*m = make(metaStructMap, header)
for i := uint32(0); i < header; i++ {
var key string
key, err = de.ReadString()
if err != nil {
return msgp.WrapError(err, "MetaStruct")
}
subMsg, err := de.ReadBytes(nil)
if err != nil {
return msgp.WrapError(err, "MetaStruct", key)
}
(*m)[key], _, err = msgp.ReadIntfBytes(subMsg)
if err != nil {
return msgp.WrapError(err, "MetaStruct", key)
}
}
return nil
}
// Msgsize returns an upper bound estimate of the number of bytes occupied by the serialized message
func (m *metaStructMap) Msgsize() int {
size := msgp.MapHeaderSize
for key, value := range *m {
size += msgp.StringPrefixSize + len(key)
size += msgp.BytesPrefixSize + msgp.GuessSize(value)
}
return size
}