...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package tracestate
18
19 import (
20 "fmt"
21 "regexp"
22 )
23
24 const (
25 keyMaxSize = 256
26 valueMaxSize = 256
27 maxKeyValuePairs = 32
28 )
29
30 const (
31 keyWithoutVendorFormat = `[a-z][_0-9a-z\-\*\/]{0,255}`
32 keyWithVendorFormat = `[a-z][_0-9a-z\-\*\/]{0,240}@[a-z][_0-9a-z\-\*\/]{0,13}`
33 keyFormat = `(` + keyWithoutVendorFormat + `)|(` + keyWithVendorFormat + `)`
34 valueFormat = `[\x20-\x2b\x2d-\x3c\x3e-\x7e]{0,255}[\x21-\x2b\x2d-\x3c\x3e-\x7e]`
35 )
36
37 var keyValidationRegExp = regexp.MustCompile(`^(` + keyFormat + `)$`)
38 var valueValidationRegExp = regexp.MustCompile(`^(` + valueFormat + `)$`)
39
40
41
42 type Tracestate struct {
43 entries []Entry
44 }
45
46
47 type Entry struct {
48
49
50
51 Key string
52
53
54
55 Value string
56 }
57
58
59 func (ts *Tracestate) Entries() []Entry {
60 if ts == nil {
61 return nil
62 }
63 return ts.entries
64 }
65
66 func (ts *Tracestate) remove(key string) *Entry {
67 for index, entry := range ts.entries {
68 if entry.Key == key {
69 ts.entries = append(ts.entries[:index], ts.entries[index+1:]...)
70 return &entry
71 }
72 }
73 return nil
74 }
75
76 func (ts *Tracestate) add(entries []Entry) error {
77 for _, entry := range entries {
78 ts.remove(entry.Key)
79 }
80 if len(ts.entries)+len(entries) > maxKeyValuePairs {
81 return fmt.Errorf("adding %d key-value pairs to current %d pairs exceeds the limit of %d",
82 len(entries), len(ts.entries), maxKeyValuePairs)
83 }
84 ts.entries = append(entries, ts.entries...)
85 return nil
86 }
87
88 func isValid(entry Entry) bool {
89 return keyValidationRegExp.MatchString(entry.Key) &&
90 valueValidationRegExp.MatchString(entry.Value)
91 }
92
93 func containsDuplicateKey(entries ...Entry) (string, bool) {
94 keyMap := make(map[string]int)
95 for _, entry := range entries {
96 if _, ok := keyMap[entry.Key]; ok {
97 return entry.Key, true
98 }
99 keyMap[entry.Key] = 1
100 }
101 return "", false
102 }
103
104 func areEntriesValid(entries ...Entry) (*Entry, bool) {
105 for _, entry := range entries {
106 if !isValid(entry) {
107 return &entry, false
108 }
109 }
110 return nil, true
111 }
112
113
114
115
116
117
118
119
120
121
122
123
124 func New(parent *Tracestate, entries ...Entry) (*Tracestate, error) {
125 if parent == nil && len(entries) == 0 {
126 return nil, nil
127 }
128 if entry, ok := areEntriesValid(entries...); !ok {
129 return nil, fmt.Errorf("key-value pair {%s, %s} is invalid", entry.Key, entry.Value)
130 }
131
132 if key, duplicate := containsDuplicateKey(entries...); duplicate {
133 return nil, fmt.Errorf("contains duplicate keys (%s)", key)
134 }
135
136 tracestate := Tracestate{}
137
138 if parent != nil && len(parent.entries) > 0 {
139 tracestate.entries = append([]Entry{}, parent.entries...)
140 }
141
142 err := tracestate.add(entries)
143 if err != nil {
144 return nil, err
145 }
146 return &tracestate, nil
147 }
148
View as plain text