tracestate.go 8.9 KB

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