map.go 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. // Copyright 2017, 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. //
  15. package tag
  16. import (
  17. "bytes"
  18. "context"
  19. "fmt"
  20. "sort"
  21. )
  22. // Tag is a key value pair that can be propagated on wire.
  23. type Tag struct {
  24. Key Key
  25. Value string
  26. }
  27. type tagContent struct {
  28. value string
  29. m metadatas
  30. }
  31. // Map is a map of tags. Use New to create a context containing
  32. // a new Map.
  33. type Map struct {
  34. m map[Key]tagContent
  35. }
  36. // Value returns the value for the key if a value for the key exists.
  37. func (m *Map) Value(k Key) (string, bool) {
  38. if m == nil {
  39. return "", false
  40. }
  41. v, ok := m.m[k]
  42. return v.value, ok
  43. }
  44. func (m *Map) String() string {
  45. if m == nil {
  46. return "nil"
  47. }
  48. keys := make([]Key, 0, len(m.m))
  49. for k := range m.m {
  50. keys = append(keys, k)
  51. }
  52. sort.Slice(keys, func(i, j int) bool { return keys[i].Name() < keys[j].Name() })
  53. var buffer bytes.Buffer
  54. buffer.WriteString("{ ")
  55. for _, k := range keys {
  56. buffer.WriteString(fmt.Sprintf("{%v %v}", k.name, m.m[k]))
  57. }
  58. buffer.WriteString(" }")
  59. return buffer.String()
  60. }
  61. func (m *Map) insert(k Key, v string, md metadatas) {
  62. if _, ok := m.m[k]; ok {
  63. return
  64. }
  65. m.m[k] = tagContent{value: v, m: md}
  66. }
  67. func (m *Map) update(k Key, v string, md metadatas) {
  68. if _, ok := m.m[k]; ok {
  69. m.m[k] = tagContent{value: v, m: md}
  70. }
  71. }
  72. func (m *Map) upsert(k Key, v string, md metadatas) {
  73. m.m[k] = tagContent{value: v, m: md}
  74. }
  75. func (m *Map) delete(k Key) {
  76. delete(m.m, k)
  77. }
  78. func newMap() *Map {
  79. return &Map{m: make(map[Key]tagContent)}
  80. }
  81. // Mutator modifies a tag map.
  82. type Mutator interface {
  83. Mutate(t *Map) (*Map, error)
  84. }
  85. // Insert returns a mutator that inserts a
  86. // value associated with k. If k already exists in the tag map,
  87. // mutator doesn't update the value.
  88. // Metadata applies metadata to the tag. It is optional.
  89. // Metadatas are applied in the order in which it is provided.
  90. // If more than one metadata updates the same attribute then
  91. // the update from the last metadata prevails.
  92. func Insert(k Key, v string, mds ...Metadata) Mutator {
  93. return &mutator{
  94. fn: func(m *Map) (*Map, error) {
  95. if !checkValue(v) {
  96. return nil, errInvalidValue
  97. }
  98. m.insert(k, v, createMetadatas(mds...))
  99. return m, nil
  100. },
  101. }
  102. }
  103. // Update returns a mutator that updates the
  104. // value of the tag associated with k with v. If k doesn't
  105. // exists in the tag map, the mutator doesn't insert the value.
  106. // Metadata applies metadata to the tag. It is optional.
  107. // Metadatas are applied in the order in which it is provided.
  108. // If more than one metadata updates the same attribute then
  109. // the update from the last metadata prevails.
  110. func Update(k Key, v string, mds ...Metadata) Mutator {
  111. return &mutator{
  112. fn: func(m *Map) (*Map, error) {
  113. if !checkValue(v) {
  114. return nil, errInvalidValue
  115. }
  116. m.update(k, v, createMetadatas(mds...))
  117. return m, nil
  118. },
  119. }
  120. }
  121. // Upsert returns a mutator that upserts the
  122. // value of the tag associated with k with v. It inserts the
  123. // value if k doesn't exist already. It mutates the value
  124. // if k already exists.
  125. // Metadata applies metadata to the tag. It is optional.
  126. // Metadatas are applied in the order in which it is provided.
  127. // If more than one metadata updates the same attribute then
  128. // the update from the last metadata prevails.
  129. func Upsert(k Key, v string, mds ...Metadata) Mutator {
  130. return &mutator{
  131. fn: func(m *Map) (*Map, error) {
  132. if !checkValue(v) {
  133. return nil, errInvalidValue
  134. }
  135. m.upsert(k, v, createMetadatas(mds...))
  136. return m, nil
  137. },
  138. }
  139. }
  140. func createMetadatas(mds ...Metadata) metadatas {
  141. var metas metadatas
  142. if len(mds) > 0 {
  143. for _, md := range mds {
  144. if md != nil {
  145. md(&metas)
  146. }
  147. }
  148. } else {
  149. WithTTL(TTLUnlimitedPropagation)(&metas)
  150. }
  151. return metas
  152. }
  153. // Delete returns a mutator that deletes
  154. // the value associated with k.
  155. func Delete(k Key) Mutator {
  156. return &mutator{
  157. fn: func(m *Map) (*Map, error) {
  158. m.delete(k)
  159. return m, nil
  160. },
  161. }
  162. }
  163. // New returns a new context that contains a tag map
  164. // originated from the incoming context and modified
  165. // with the provided mutators.
  166. func New(ctx context.Context, mutator ...Mutator) (context.Context, error) {
  167. m := newMap()
  168. orig := FromContext(ctx)
  169. if orig != nil {
  170. for k, v := range orig.m {
  171. if !checkKeyName(k.Name()) {
  172. return ctx, fmt.Errorf("key:%q: %v", k, errInvalidKeyName)
  173. }
  174. if !checkValue(v.value) {
  175. return ctx, fmt.Errorf("key:%q value:%q: %v", k.Name(), v, errInvalidValue)
  176. }
  177. m.insert(k, v.value, v.m)
  178. }
  179. }
  180. var err error
  181. for _, mod := range mutator {
  182. m, err = mod.Mutate(m)
  183. if err != nil {
  184. return ctx, err
  185. }
  186. }
  187. return NewContext(ctx, m), nil
  188. }
  189. // Do is similar to pprof.Do: a convenience for installing the tags
  190. // from the context as Go profiler labels. This allows you to
  191. // correlated runtime profiling with stats.
  192. //
  193. // It converts the key/values from the given map to Go profiler labels
  194. // and calls pprof.Do.
  195. //
  196. // Do is going to do nothing if your Go version is below 1.9.
  197. func Do(ctx context.Context, f func(ctx context.Context)) {
  198. do(ctx, f)
  199. }
  200. type mutator struct {
  201. fn func(t *Map) (*Map, error)
  202. }
  203. func (m *mutator) Mutate(t *Map) (*Map, error) {
  204. return m.fn(t)
  205. }