tracestate.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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. "strings"
  19. )
  20. const (
  21. maxListMembers = 32
  22. listDelimiters = ","
  23. memberDelimiter = "="
  24. errInvalidKey errorConst = "invalid tracestate key"
  25. errInvalidValue errorConst = "invalid tracestate value"
  26. errInvalidMember errorConst = "invalid tracestate list-member"
  27. errMemberNumber errorConst = "too many list-members in tracestate"
  28. errDuplicate errorConst = "duplicate list-member in tracestate"
  29. )
  30. type member struct {
  31. Key string
  32. Value string
  33. }
  34. // according to (chr = %x20 / (nblk-char = %x21-2B / %x2D-3C / %x3E-7E) )
  35. // means (chr = %x20-2B / %x2D-3C / %x3E-7E) .
  36. func checkValueChar(v byte) bool {
  37. return v >= '\x20' && v <= '\x7e' && v != '\x2c' && v != '\x3d'
  38. }
  39. // according to (nblk-chr = %x21-2B / %x2D-3C / %x3E-7E) .
  40. func checkValueLast(v byte) bool {
  41. return v >= '\x21' && v <= '\x7e' && v != '\x2c' && v != '\x3d'
  42. }
  43. // based on the W3C Trace Context specification
  44. //
  45. // value = (0*255(chr)) nblk-chr
  46. // nblk-chr = %x21-2B / %x2D-3C / %x3E-7E
  47. // chr = %x20 / nblk-chr
  48. //
  49. // see https://www.w3.org/TR/trace-context-1/#value
  50. func checkValue(val string) bool {
  51. n := len(val)
  52. if n == 0 || n > 256 {
  53. return false
  54. }
  55. for i := 0; i < n-1; i++ {
  56. if !checkValueChar(val[i]) {
  57. return false
  58. }
  59. }
  60. return checkValueLast(val[n-1])
  61. }
  62. func checkKeyRemain(key string) bool {
  63. // ( lcalpha / DIGIT / "_" / "-"/ "*" / "/" )
  64. for _, v := range key {
  65. if isAlphaNum(byte(v)) {
  66. continue
  67. }
  68. switch v {
  69. case '_', '-', '*', '/':
  70. continue
  71. }
  72. return false
  73. }
  74. return true
  75. }
  76. // according to
  77. //
  78. // simple-key = lcalpha (0*255( lcalpha / DIGIT / "_" / "-"/ "*" / "/" ))
  79. // system-id = lcalpha (0*13( lcalpha / DIGIT / "_" / "-"/ "*" / "/" ))
  80. //
  81. // param n is remain part length, should be 255 in simple-key or 13 in system-id.
  82. func checkKeyPart(key string, n int) bool {
  83. if len(key) == 0 {
  84. return false
  85. }
  86. first := key[0] // key's first char
  87. ret := len(key[1:]) <= n
  88. ret = ret && first >= 'a' && first <= 'z'
  89. return ret && checkKeyRemain(key[1:])
  90. }
  91. func isAlphaNum(c byte) bool {
  92. if c >= 'a' && c <= 'z' {
  93. return true
  94. }
  95. return c >= '0' && c <= '9'
  96. }
  97. // according to
  98. //
  99. // tenant-id = ( lcalpha / DIGIT ) 0*240( lcalpha / DIGIT / "_" / "-"/ "*" / "/" )
  100. //
  101. // param n is remain part length, should be 240 exactly.
  102. func checkKeyTenant(key string, n int) bool {
  103. if len(key) == 0 {
  104. return false
  105. }
  106. return isAlphaNum(key[0]) && len(key[1:]) <= n && checkKeyRemain(key[1:])
  107. }
  108. // based on the W3C Trace Context specification
  109. //
  110. // key = simple-key / multi-tenant-key
  111. // simple-key = lcalpha (0*255( lcalpha / DIGIT / "_" / "-"/ "*" / "/" ))
  112. // multi-tenant-key = tenant-id "@" system-id
  113. // tenant-id = ( lcalpha / DIGIT ) (0*240( lcalpha / DIGIT / "_" / "-"/ "*" / "/" ))
  114. // system-id = lcalpha (0*13( lcalpha / DIGIT / "_" / "-"/ "*" / "/" ))
  115. // lcalpha = %x61-7A ; a-z
  116. //
  117. // see https://www.w3.org/TR/trace-context-1/#tracestate-header.
  118. func checkKey(key string) bool {
  119. tenant, system, ok := strings.Cut(key, "@")
  120. if !ok {
  121. return checkKeyPart(key, 255)
  122. }
  123. return checkKeyTenant(tenant, 240) && checkKeyPart(system, 13)
  124. }
  125. func newMember(key, value string) (member, error) {
  126. if !checkKey(key) {
  127. return member{}, errInvalidKey
  128. }
  129. if !checkValue(value) {
  130. return member{}, errInvalidValue
  131. }
  132. return member{Key: key, Value: value}, nil
  133. }
  134. func parseMember(m string) (member, error) {
  135. key, val, ok := strings.Cut(m, memberDelimiter)
  136. if !ok {
  137. return member{}, fmt.Errorf("%w: %s", errInvalidMember, m)
  138. }
  139. key = strings.TrimLeft(key, " \t")
  140. val = strings.TrimRight(val, " \t")
  141. result, e := newMember(key, val)
  142. if e != nil {
  143. return member{}, fmt.Errorf("%w: %s", errInvalidMember, m)
  144. }
  145. return result, nil
  146. }
  147. // String encodes member into a string compliant with the W3C Trace Context
  148. // specification.
  149. func (m member) String() string {
  150. return m.Key + "=" + m.Value
  151. }
  152. // TraceState provides additional vendor-specific trace identification
  153. // information across different distributed tracing systems. It represents an
  154. // immutable list consisting of key/value pairs, each pair is referred to as a
  155. // list-member.
  156. //
  157. // TraceState conforms to the W3C Trace Context specification
  158. // (https://www.w3.org/TR/trace-context-1). All operations that create or copy
  159. // a TraceState do so by validating all input and will only produce TraceState
  160. // that conform to the specification. Specifically, this means that all
  161. // list-member's key/value pairs are valid, no duplicate list-members exist,
  162. // and the maximum number of list-members (32) is not exceeded.
  163. type TraceState struct { //nolint:revive // revive complains about stutter of `trace.TraceState`
  164. // list is the members in order.
  165. list []member
  166. }
  167. var _ json.Marshaler = TraceState{}
  168. // ParseTraceState attempts to decode a TraceState from the passed
  169. // string. It returns an error if the input is invalid according to the W3C
  170. // Trace Context specification.
  171. func ParseTraceState(ts string) (TraceState, error) {
  172. if ts == "" {
  173. return TraceState{}, nil
  174. }
  175. wrapErr := func(err error) error {
  176. return fmt.Errorf("failed to parse tracestate: %w", err)
  177. }
  178. var members []member
  179. found := make(map[string]struct{})
  180. for ts != "" {
  181. var memberStr string
  182. memberStr, ts, _ = strings.Cut(ts, listDelimiters)
  183. if len(memberStr) == 0 {
  184. continue
  185. }
  186. m, err := parseMember(memberStr)
  187. if err != nil {
  188. return TraceState{}, wrapErr(err)
  189. }
  190. if _, ok := found[m.Key]; ok {
  191. return TraceState{}, wrapErr(errDuplicate)
  192. }
  193. found[m.Key] = struct{}{}
  194. members = append(members, m)
  195. if n := len(members); n > maxListMembers {
  196. return TraceState{}, wrapErr(errMemberNumber)
  197. }
  198. }
  199. return TraceState{list: members}, nil
  200. }
  201. // MarshalJSON marshals the TraceState into JSON.
  202. func (ts TraceState) MarshalJSON() ([]byte, error) {
  203. return json.Marshal(ts.String())
  204. }
  205. // String encodes the TraceState into a string compliant with the W3C
  206. // Trace Context specification. The returned string will be invalid if the
  207. // TraceState contains any invalid members.
  208. func (ts TraceState) String() string {
  209. if len(ts.list) == 0 {
  210. return ""
  211. }
  212. var n int
  213. n += len(ts.list) // member delimiters: '='
  214. n += len(ts.list) - 1 // list delimiters: ','
  215. for _, mem := range ts.list {
  216. n += len(mem.Key)
  217. n += len(mem.Value)
  218. }
  219. var sb strings.Builder
  220. sb.Grow(n)
  221. _, _ = sb.WriteString(ts.list[0].Key)
  222. _ = sb.WriteByte('=')
  223. _, _ = sb.WriteString(ts.list[0].Value)
  224. for i := 1; i < len(ts.list); i++ {
  225. _ = sb.WriteByte(listDelimiters[0])
  226. _, _ = sb.WriteString(ts.list[i].Key)
  227. _ = sb.WriteByte('=')
  228. _, _ = sb.WriteString(ts.list[i].Value)
  229. }
  230. return sb.String()
  231. }
  232. // Get returns the value paired with key from the corresponding TraceState
  233. // list-member if it exists, otherwise an empty string is returned.
  234. func (ts TraceState) Get(key string) string {
  235. for _, member := range ts.list {
  236. if member.Key == key {
  237. return member.Value
  238. }
  239. }
  240. return ""
  241. }
  242. // Insert adds a new list-member defined by the key/value pair to the
  243. // TraceState. If a list-member already exists for the given key, that
  244. // list-member's value is updated. The new or updated list-member is always
  245. // moved to the beginning of the TraceState as specified by the W3C Trace
  246. // Context specification.
  247. //
  248. // If key or value are invalid according to the W3C Trace Context
  249. // specification an error is returned with the original TraceState.
  250. //
  251. // If adding a new list-member means the TraceState would have more members
  252. // then is allowed, the new list-member will be inserted and the right-most
  253. // list-member will be dropped in the returned TraceState.
  254. func (ts TraceState) Insert(key, value string) (TraceState, error) {
  255. m, err := newMember(key, value)
  256. if err != nil {
  257. return ts, err
  258. }
  259. n := len(ts.list)
  260. found := n
  261. for i := range ts.list {
  262. if ts.list[i].Key == key {
  263. found = i
  264. }
  265. }
  266. cTS := TraceState{}
  267. if found == n && n < maxListMembers {
  268. cTS.list = make([]member, n+1)
  269. } else {
  270. cTS.list = make([]member, n)
  271. }
  272. cTS.list[0] = m
  273. // When the number of members exceeds capacity, drop the "right-most".
  274. copy(cTS.list[1:], ts.list[0:found])
  275. if found < n {
  276. copy(cTS.list[1+found:], ts.list[found+1:])
  277. }
  278. return cTS, nil
  279. }
  280. // Delete returns a copy of the TraceState with the list-member identified by
  281. // key removed.
  282. func (ts TraceState) Delete(key string) TraceState {
  283. members := make([]member, ts.Len())
  284. copy(members, ts.list)
  285. for i, member := range ts.list {
  286. if member.Key == key {
  287. members = append(members[:i], members[i+1:]...)
  288. // TraceState should contain no duplicate members.
  289. break
  290. }
  291. }
  292. return TraceState{list: members}
  293. }
  294. // Len returns the number of list-members in the TraceState.
  295. func (ts TraceState) Len() int {
  296. return len(ts.list)
  297. }