tracestate.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. // Copyright The OpenTelemetry Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package trace // import "go.opentelemetry.io/otel/trace"
  15. import (
  16. "encoding/json"
  17. "fmt"
  18. "regexp"
  19. "strings"
  20. )
  21. const (
  22. maxListMembers = 32
  23. listDelimiter = ","
  24. // based on the W3C Trace Context specification, see
  25. // https://www.w3.org/TR/trace-context-1/#tracestate-header
  26. noTenantKeyFormat = `[a-z][_0-9a-z\-\*\/]{0,255}`
  27. withTenantKeyFormat = `[a-z0-9][_0-9a-z\-\*\/]{0,240}@[a-z][_0-9a-z\-\*\/]{0,13}`
  28. valueFormat = `[\x20-\x2b\x2d-\x3c\x3e-\x7e]{0,255}[\x21-\x2b\x2d-\x3c\x3e-\x7e]`
  29. errInvalidKey errorConst = "invalid tracestate key"
  30. errInvalidValue errorConst = "invalid tracestate value"
  31. errInvalidMember errorConst = "invalid tracestate list-member"
  32. errMemberNumber errorConst = "too many list-members in tracestate"
  33. errDuplicate errorConst = "duplicate list-member in tracestate"
  34. )
  35. var (
  36. keyRe = regexp.MustCompile(`^((` + noTenantKeyFormat + `)|(` + withTenantKeyFormat + `))$`)
  37. valueRe = regexp.MustCompile(`^(` + valueFormat + `)$`)
  38. memberRe = regexp.MustCompile(`^\s*((` + noTenantKeyFormat + `)|(` + withTenantKeyFormat + `))=(` + valueFormat + `)\s*$`)
  39. )
  40. type member struct {
  41. Key string
  42. Value string
  43. }
  44. func newMember(key, value string) (member, error) {
  45. if !keyRe.MatchString(key) {
  46. return member{}, fmt.Errorf("%w: %s", errInvalidKey, key)
  47. }
  48. if !valueRe.MatchString(value) {
  49. return member{}, fmt.Errorf("%w: %s", errInvalidValue, value)
  50. }
  51. return member{Key: key, Value: value}, nil
  52. }
  53. func parseMember(m string) (member, error) {
  54. matches := memberRe.FindStringSubmatch(m)
  55. if len(matches) != 5 {
  56. return member{}, fmt.Errorf("%w: %s", errInvalidMember, m)
  57. }
  58. return member{
  59. Key: matches[1],
  60. Value: matches[4],
  61. }, nil
  62. }
  63. // String encodes member into a string compliant with the W3C Trace Context
  64. // specification.
  65. func (m member) String() string {
  66. return fmt.Sprintf("%s=%s", m.Key, m.Value)
  67. }
  68. // TraceState provides additional vendor-specific trace identification
  69. // information across different distributed tracing systems. It represents an
  70. // immutable list consisting of key/value pairs, each pair is referred to as a
  71. // list-member.
  72. //
  73. // TraceState conforms to the W3C Trace Context specification
  74. // (https://www.w3.org/TR/trace-context-1). All operations that create or copy
  75. // a TraceState do so by validating all input and will only produce TraceState
  76. // that conform to the specification. Specifically, this means that all
  77. // list-member's key/value pairs are valid, no duplicate list-members exist,
  78. // and the maximum number of list-members (32) is not exceeded.
  79. type TraceState struct { //nolint:revive // revive complains about stutter of `trace.TraceState`
  80. // list is the members in order.
  81. list []member
  82. }
  83. var _ json.Marshaler = TraceState{}
  84. // ParseTraceState attempts to decode a TraceState from the passed
  85. // string. It returns an error if the input is invalid according to the W3C
  86. // Trace Context specification.
  87. func ParseTraceState(tracestate string) (TraceState, error) {
  88. if tracestate == "" {
  89. return TraceState{}, nil
  90. }
  91. wrapErr := func(err error) error {
  92. return fmt.Errorf("failed to parse tracestate: %w", err)
  93. }
  94. var members []member
  95. found := make(map[string]struct{})
  96. for _, memberStr := range strings.Split(tracestate, listDelimiter) {
  97. if len(memberStr) == 0 {
  98. continue
  99. }
  100. m, err := parseMember(memberStr)
  101. if err != nil {
  102. return TraceState{}, wrapErr(err)
  103. }
  104. if _, ok := found[m.Key]; ok {
  105. return TraceState{}, wrapErr(errDuplicate)
  106. }
  107. found[m.Key] = struct{}{}
  108. members = append(members, m)
  109. if n := len(members); n > maxListMembers {
  110. return TraceState{}, wrapErr(errMemberNumber)
  111. }
  112. }
  113. return TraceState{list: members}, nil
  114. }
  115. // MarshalJSON marshals the TraceState into JSON.
  116. func (ts TraceState) MarshalJSON() ([]byte, error) {
  117. return json.Marshal(ts.String())
  118. }
  119. // String encodes the TraceState into a string compliant with the W3C
  120. // Trace Context specification. The returned string will be invalid if the
  121. // TraceState contains any invalid members.
  122. func (ts TraceState) String() string {
  123. members := make([]string, len(ts.list))
  124. for i, m := range ts.list {
  125. members[i] = m.String()
  126. }
  127. return strings.Join(members, listDelimiter)
  128. }
  129. // Get returns the value paired with key from the corresponding TraceState
  130. // list-member if it exists, otherwise an empty string is returned.
  131. func (ts TraceState) Get(key string) string {
  132. for _, member := range ts.list {
  133. if member.Key == key {
  134. return member.Value
  135. }
  136. }
  137. return ""
  138. }
  139. // Insert adds a new list-member defined by the key/value pair to the
  140. // TraceState. If a list-member already exists for the given key, that
  141. // list-member's value is updated. The new or updated list-member is always
  142. // moved to the beginning of the TraceState as specified by the W3C Trace
  143. // Context specification.
  144. //
  145. // If key or value are invalid according to the W3C Trace Context
  146. // specification an error is returned with the original TraceState.
  147. //
  148. // If adding a new list-member means the TraceState would have more members
  149. // then is allowed, the new list-member will be inserted and the right-most
  150. // list-member will be dropped in the returned TraceState.
  151. func (ts TraceState) Insert(key, value string) (TraceState, error) {
  152. m, err := newMember(key, value)
  153. if err != nil {
  154. return ts, err
  155. }
  156. cTS := ts.Delete(key)
  157. if cTS.Len()+1 <= maxListMembers {
  158. cTS.list = append(cTS.list, member{})
  159. }
  160. // When the number of members exceeds capacity, drop the "right-most".
  161. copy(cTS.list[1:], cTS.list)
  162. cTS.list[0] = m
  163. return cTS, nil
  164. }
  165. // Delete returns a copy of the TraceState with the list-member identified by
  166. // key removed.
  167. func (ts TraceState) Delete(key string) TraceState {
  168. members := make([]member, ts.Len())
  169. copy(members, ts.list)
  170. for i, member := range ts.list {
  171. if member.Key == key {
  172. members = append(members[:i], members[i+1:]...)
  173. // TraceState should contain no duplicate members.
  174. break
  175. }
  176. }
  177. return TraceState{list: members}
  178. }
  179. // Len returns the number of list-members in the TraceState.
  180. func (ts TraceState) Len() int {
  181. return len(ts.list)
  182. }