You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

148 lines
4.6 KiB

  1. // Copyright 2018, OpenCensus 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 tracestate implements support for the Tracestate header of the
  15. // W3C TraceContext propagation format.
  16. package tracestate
  17. import (
  18. "fmt"
  19. "regexp"
  20. )
  21. const (
  22. keyMaxSize = 256
  23. valueMaxSize = 256
  24. maxKeyValuePairs = 32
  25. )
  26. const (
  27. keyWithoutVendorFormat = `[a-z][_0-9a-z\-\*\/]{0,255}`
  28. keyWithVendorFormat = `[a-z][_0-9a-z\-\*\/]{0,240}@[a-z][_0-9a-z\-\*\/]{0,13}`
  29. keyFormat = `(` + keyWithoutVendorFormat + `)|(` + keyWithVendorFormat + `)`
  30. valueFormat = `[\x20-\x2b\x2d-\x3c\x3e-\x7e]{0,255}[\x21-\x2b\x2d-\x3c\x3e-\x7e]`
  31. )
  32. var keyValidationRegExp = regexp.MustCompile(`^(` + keyFormat + `)$`)
  33. var valueValidationRegExp = regexp.MustCompile(`^(` + valueFormat + `)$`)
  34. // Tracestate represents tracing-system specific context in a list of key-value pairs. Tracestate allows different
  35. // vendors propagate additional information and inter-operate with their legacy Id formats.
  36. type Tracestate struct {
  37. entries []Entry
  38. }
  39. // Entry represents one key-value pair in a list of key-value pair of Tracestate.
  40. type Entry struct {
  41. // Key is an opaque string up to 256 characters printable. It MUST begin with a lowercase letter,
  42. // and can only contain lowercase letters a-z, digits 0-9, underscores _, dashes -, asterisks *, and
  43. // forward slashes /.
  44. Key string
  45. // Value is an opaque string up to 256 characters printable ASCII RFC0020 characters (i.e., the
  46. // range 0x20 to 0x7E) except comma , and =.
  47. Value string
  48. }
  49. // Entries returns a slice of Entry.
  50. func (ts *Tracestate) Entries() []Entry {
  51. if ts == nil {
  52. return nil
  53. }
  54. return ts.entries
  55. }
  56. func (ts *Tracestate) remove(key string) *Entry {
  57. for index, entry := range ts.entries {
  58. if entry.Key == key {
  59. ts.entries = append(ts.entries[:index], ts.entries[index+1:]...)
  60. return &entry
  61. }
  62. }
  63. return nil
  64. }
  65. func (ts *Tracestate) add(entries []Entry) error {
  66. for _, entry := range entries {
  67. ts.remove(entry.Key)
  68. }
  69. if len(ts.entries)+len(entries) > maxKeyValuePairs {
  70. return fmt.Errorf("adding %d key-value pairs to current %d pairs exceeds the limit of %d",
  71. len(entries), len(ts.entries), maxKeyValuePairs)
  72. }
  73. ts.entries = append(entries, ts.entries...)
  74. return nil
  75. }
  76. func isValid(entry Entry) bool {
  77. return keyValidationRegExp.MatchString(entry.Key) &&
  78. valueValidationRegExp.MatchString(entry.Value)
  79. }
  80. func containsDuplicateKey(entries ...Entry) (string, bool) {
  81. keyMap := make(map[string]int)
  82. for _, entry := range entries {
  83. if _, ok := keyMap[entry.Key]; ok {
  84. return entry.Key, true
  85. }
  86. keyMap[entry.Key] = 1
  87. }
  88. return "", false
  89. }
  90. func areEntriesValid(entries ...Entry) (*Entry, bool) {
  91. for _, entry := range entries {
  92. if !isValid(entry) {
  93. return &entry, false
  94. }
  95. }
  96. return nil, true
  97. }
  98. // New creates a Tracestate object from a parent and/or entries (key-value pair).
  99. // Entries from the parent are copied if present. The entries passed to this function
  100. // are inserted in front of those copied from the parent. If an entry copied from the
  101. // parent contains the same key as one of the entry in entries then the entry copied
  102. // from the parent is removed. See add func.
  103. //
  104. // An error is returned with nil Tracestate if
  105. // 1. one or more entry in entries is invalid.
  106. // 2. two or more entries in the input entries have the same key.
  107. // 3. the number of entries combined from the parent and the input entries exceeds maxKeyValuePairs.
  108. // (duplicate entry is counted only once).
  109. func New(parent *Tracestate, entries ...Entry) (*Tracestate, error) {
  110. if parent == nil && len(entries) == 0 {
  111. return nil, nil
  112. }
  113. if entry, ok := areEntriesValid(entries...); !ok {
  114. return nil, fmt.Errorf("key-value pair {%s, %s} is invalid", entry.Key, entry.Value)
  115. }
  116. if key, duplicate := containsDuplicateKey(entries...); duplicate {
  117. return nil, fmt.Errorf("contains duplicate keys (%s)", key)
  118. }
  119. tracestate := Tracestate{}
  120. if parent != nil && len(parent.entries) > 0 {
  121. tracestate.entries = append([]Entry{}, parent.entries...)
  122. }
  123. err := tracestate.add(entries)
  124. if err != nil {
  125. return nil, err
  126. }
  127. return &tracestate, nil
  128. }