set.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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 attribute // import "go.opentelemetry.io/otel/attribute"
  15. import (
  16. "encoding/json"
  17. "reflect"
  18. "sort"
  19. )
  20. type (
  21. // Set is the representation for a distinct attribute set. It manages an
  22. // immutable set of attributes, with an internal cache for storing
  23. // attribute encodings.
  24. //
  25. // This type supports the Equivalent method of comparison using values of
  26. // type Distinct.
  27. Set struct {
  28. equivalent Distinct
  29. }
  30. // Distinct wraps a variable-size array of KeyValue, constructed with keys
  31. // in sorted order. This can be used as a map key or for equality checking
  32. // between Sets.
  33. Distinct struct {
  34. iface interface{}
  35. }
  36. // Filter supports removing certain attributes from attribute sets. When
  37. // the filter returns true, the attribute will be kept in the filtered
  38. // attribute set. When the filter returns false, the attribute is excluded
  39. // from the filtered attribute set, and the attribute instead appears in
  40. // the removed list of excluded attributes.
  41. Filter func(KeyValue) bool
  42. // Sortable implements sort.Interface, used for sorting KeyValue. This is
  43. // an exported type to support a memory optimization. A pointer to one of
  44. // these is needed for the call to sort.Stable(), which the caller may
  45. // provide in order to avoid an allocation. See NewSetWithSortable().
  46. Sortable []KeyValue
  47. )
  48. var (
  49. // keyValueType is used in computeDistinctReflect.
  50. keyValueType = reflect.TypeOf(KeyValue{})
  51. // emptySet is returned for empty attribute sets.
  52. emptySet = &Set{
  53. equivalent: Distinct{
  54. iface: [0]KeyValue{},
  55. },
  56. }
  57. )
  58. // EmptySet returns a reference to a Set with no elements.
  59. //
  60. // This is a convenience provided for optimized calling utility.
  61. func EmptySet() *Set {
  62. return emptySet
  63. }
  64. // reflect abbreviates reflect.ValueOf.
  65. func (d Distinct) reflect() reflect.Value {
  66. return reflect.ValueOf(d.iface)
  67. }
  68. // Valid returns true if this value refers to a valid Set.
  69. func (d Distinct) Valid() bool {
  70. return d.iface != nil
  71. }
  72. // Len returns the number of attributes in this set.
  73. func (l *Set) Len() int {
  74. if l == nil || !l.equivalent.Valid() {
  75. return 0
  76. }
  77. return l.equivalent.reflect().Len()
  78. }
  79. // Get returns the KeyValue at ordered position idx in this set.
  80. func (l *Set) Get(idx int) (KeyValue, bool) {
  81. if l == nil {
  82. return KeyValue{}, false
  83. }
  84. value := l.equivalent.reflect()
  85. if idx >= 0 && idx < value.Len() {
  86. // Note: The Go compiler successfully avoids an allocation for
  87. // the interface{} conversion here:
  88. return value.Index(idx).Interface().(KeyValue), true
  89. }
  90. return KeyValue{}, false
  91. }
  92. // Value returns the value of a specified key in this set.
  93. func (l *Set) Value(k Key) (Value, bool) {
  94. if l == nil {
  95. return Value{}, false
  96. }
  97. rValue := l.equivalent.reflect()
  98. vlen := rValue.Len()
  99. idx := sort.Search(vlen, func(idx int) bool {
  100. return rValue.Index(idx).Interface().(KeyValue).Key >= k
  101. })
  102. if idx >= vlen {
  103. return Value{}, false
  104. }
  105. keyValue := rValue.Index(idx).Interface().(KeyValue)
  106. if k == keyValue.Key {
  107. return keyValue.Value, true
  108. }
  109. return Value{}, false
  110. }
  111. // HasValue tests whether a key is defined in this set.
  112. func (l *Set) HasValue(k Key) bool {
  113. if l == nil {
  114. return false
  115. }
  116. _, ok := l.Value(k)
  117. return ok
  118. }
  119. // Iter returns an iterator for visiting the attributes in this set.
  120. func (l *Set) Iter() Iterator {
  121. return Iterator{
  122. storage: l,
  123. idx: -1,
  124. }
  125. }
  126. // ToSlice returns the set of attributes belonging to this set, sorted, where
  127. // keys appear no more than once.
  128. func (l *Set) ToSlice() []KeyValue {
  129. iter := l.Iter()
  130. return iter.ToSlice()
  131. }
  132. // Equivalent returns a value that may be used as a map key. The Distinct type
  133. // guarantees that the result will equal the equivalent. Distinct value of any
  134. // attribute set with the same elements as this, where sets are made unique by
  135. // choosing the last value in the input for any given key.
  136. func (l *Set) Equivalent() Distinct {
  137. if l == nil || !l.equivalent.Valid() {
  138. return emptySet.equivalent
  139. }
  140. return l.equivalent
  141. }
  142. // Equals returns true if the argument set is equivalent to this set.
  143. func (l *Set) Equals(o *Set) bool {
  144. return l.Equivalent() == o.Equivalent()
  145. }
  146. // Encoded returns the encoded form of this set, according to encoder.
  147. func (l *Set) Encoded(encoder Encoder) string {
  148. if l == nil || encoder == nil {
  149. return ""
  150. }
  151. return encoder.Encode(l.Iter())
  152. }
  153. func empty() Set {
  154. return Set{
  155. equivalent: emptySet.equivalent,
  156. }
  157. }
  158. // NewSet returns a new Set. See the documentation for
  159. // NewSetWithSortableFiltered for more details.
  160. //
  161. // Except for empty sets, this method adds an additional allocation compared
  162. // with calls that include a Sortable.
  163. func NewSet(kvs ...KeyValue) Set {
  164. // Check for empty set.
  165. if len(kvs) == 0 {
  166. return empty()
  167. }
  168. s, _ := NewSetWithSortableFiltered(kvs, new(Sortable), nil)
  169. return s
  170. }
  171. // NewSetWithSortable returns a new Set. See the documentation for
  172. // NewSetWithSortableFiltered for more details.
  173. //
  174. // This call includes a Sortable option as a memory optimization.
  175. func NewSetWithSortable(kvs []KeyValue, tmp *Sortable) Set {
  176. // Check for empty set.
  177. if len(kvs) == 0 {
  178. return empty()
  179. }
  180. s, _ := NewSetWithSortableFiltered(kvs, tmp, nil)
  181. return s
  182. }
  183. // NewSetWithFiltered returns a new Set. See the documentation for
  184. // NewSetWithSortableFiltered for more details.
  185. //
  186. // This call includes a Filter to include/exclude attribute keys from the
  187. // return value. Excluded keys are returned as a slice of attribute values.
  188. func NewSetWithFiltered(kvs []KeyValue, filter Filter) (Set, []KeyValue) {
  189. // Check for empty set.
  190. if len(kvs) == 0 {
  191. return empty(), nil
  192. }
  193. return NewSetWithSortableFiltered(kvs, new(Sortable), filter)
  194. }
  195. // NewSetWithSortableFiltered returns a new Set.
  196. //
  197. // Duplicate keys are eliminated by taking the last value. This
  198. // re-orders the input slice so that unique last-values are contiguous
  199. // at the end of the slice.
  200. //
  201. // This ensures the following:
  202. //
  203. // - Last-value-wins semantics
  204. // - Caller sees the reordering, but doesn't lose values
  205. // - Repeated call preserve last-value wins.
  206. //
  207. // Note that methods are defined on Set, although this returns Set. Callers
  208. // can avoid memory allocations by:
  209. //
  210. // - allocating a Sortable for use as a temporary in this method
  211. // - allocating a Set for storing the return value of this constructor.
  212. //
  213. // The result maintains a cache of encoded attributes, by attribute.EncoderID.
  214. // This value should not be copied after its first use.
  215. //
  216. // The second []KeyValue return value is a list of attributes that were
  217. // excluded by the Filter (if non-nil).
  218. func NewSetWithSortableFiltered(kvs []KeyValue, tmp *Sortable, filter Filter) (Set, []KeyValue) {
  219. // Check for empty set.
  220. if len(kvs) == 0 {
  221. return empty(), nil
  222. }
  223. *tmp = kvs
  224. // Stable sort so the following de-duplication can implement
  225. // last-value-wins semantics.
  226. sort.Stable(tmp)
  227. *tmp = nil
  228. position := len(kvs) - 1
  229. offset := position - 1
  230. // The requirements stated above require that the stable
  231. // result be placed in the end of the input slice, while
  232. // overwritten values are swapped to the beginning.
  233. //
  234. // De-duplicate with last-value-wins semantics. Preserve
  235. // duplicate values at the beginning of the input slice.
  236. for ; offset >= 0; offset-- {
  237. if kvs[offset].Key == kvs[position].Key {
  238. continue
  239. }
  240. position--
  241. kvs[offset], kvs[position] = kvs[position], kvs[offset]
  242. }
  243. if filter != nil {
  244. return filterSet(kvs[position:], filter)
  245. }
  246. return Set{
  247. equivalent: computeDistinct(kvs[position:]),
  248. }, nil
  249. }
  250. // filterSet reorders kvs so that included keys are contiguous at the end of
  251. // the slice, while excluded keys precede the included keys.
  252. func filterSet(kvs []KeyValue, filter Filter) (Set, []KeyValue) {
  253. var excluded []KeyValue
  254. // Move attributes that do not match the filter so they're adjacent before
  255. // calling computeDistinct().
  256. distinctPosition := len(kvs)
  257. // Swap indistinct keys forward and distinct keys toward the
  258. // end of the slice.
  259. offset := len(kvs) - 1
  260. for ; offset >= 0; offset-- {
  261. if filter(kvs[offset]) {
  262. distinctPosition--
  263. kvs[offset], kvs[distinctPosition] = kvs[distinctPosition], kvs[offset]
  264. continue
  265. }
  266. }
  267. excluded = kvs[:distinctPosition]
  268. return Set{
  269. equivalent: computeDistinct(kvs[distinctPosition:]),
  270. }, excluded
  271. }
  272. // Filter returns a filtered copy of this Set. See the documentation for
  273. // NewSetWithSortableFiltered for more details.
  274. func (l *Set) Filter(re Filter) (Set, []KeyValue) {
  275. if re == nil {
  276. return Set{
  277. equivalent: l.equivalent,
  278. }, nil
  279. }
  280. // Note: This could be refactored to avoid the temporary slice
  281. // allocation, if it proves to be expensive.
  282. return filterSet(l.ToSlice(), re)
  283. }
  284. // computeDistinct returns a Distinct using either the fixed- or
  285. // reflect-oriented code path, depending on the size of the input. The input
  286. // slice is assumed to already be sorted and de-duplicated.
  287. func computeDistinct(kvs []KeyValue) Distinct {
  288. iface := computeDistinctFixed(kvs)
  289. if iface == nil {
  290. iface = computeDistinctReflect(kvs)
  291. }
  292. return Distinct{
  293. iface: iface,
  294. }
  295. }
  296. // computeDistinctFixed computes a Distinct for small slices. It returns nil
  297. // if the input is too large for this code path.
  298. func computeDistinctFixed(kvs []KeyValue) interface{} {
  299. switch len(kvs) {
  300. case 1:
  301. ptr := new([1]KeyValue)
  302. copy((*ptr)[:], kvs)
  303. return *ptr
  304. case 2:
  305. ptr := new([2]KeyValue)
  306. copy((*ptr)[:], kvs)
  307. return *ptr
  308. case 3:
  309. ptr := new([3]KeyValue)
  310. copy((*ptr)[:], kvs)
  311. return *ptr
  312. case 4:
  313. ptr := new([4]KeyValue)
  314. copy((*ptr)[:], kvs)
  315. return *ptr
  316. case 5:
  317. ptr := new([5]KeyValue)
  318. copy((*ptr)[:], kvs)
  319. return *ptr
  320. case 6:
  321. ptr := new([6]KeyValue)
  322. copy((*ptr)[:], kvs)
  323. return *ptr
  324. case 7:
  325. ptr := new([7]KeyValue)
  326. copy((*ptr)[:], kvs)
  327. return *ptr
  328. case 8:
  329. ptr := new([8]KeyValue)
  330. copy((*ptr)[:], kvs)
  331. return *ptr
  332. case 9:
  333. ptr := new([9]KeyValue)
  334. copy((*ptr)[:], kvs)
  335. return *ptr
  336. case 10:
  337. ptr := new([10]KeyValue)
  338. copy((*ptr)[:], kvs)
  339. return *ptr
  340. default:
  341. return nil
  342. }
  343. }
  344. // computeDistinctReflect computes a Distinct using reflection, works for any
  345. // size input.
  346. func computeDistinctReflect(kvs []KeyValue) interface{} {
  347. at := reflect.New(reflect.ArrayOf(len(kvs), keyValueType)).Elem()
  348. for i, keyValue := range kvs {
  349. *(at.Index(i).Addr().Interface().(*KeyValue)) = keyValue
  350. }
  351. return at.Interface()
  352. }
  353. // MarshalJSON returns the JSON encoding of the Set.
  354. func (l *Set) MarshalJSON() ([]byte, error) {
  355. return json.Marshal(l.equivalent.iface)
  356. }
  357. // MarshalLog is the marshaling function used by the logging system to represent this exporter.
  358. func (l Set) MarshalLog() interface{} {
  359. kvs := make(map[string]string)
  360. for _, kv := range l.ToSlice() {
  361. kvs[string(kv.Key)] = kv.Value.Emit()
  362. }
  363. return kvs
  364. }
  365. // Len implements sort.Interface.
  366. func (l *Sortable) Len() int {
  367. return len(*l)
  368. }
  369. // Swap implements sort.Interface.
  370. func (l *Sortable) Swap(i, j int) {
  371. (*l)[i], (*l)[j] = (*l)[j], (*l)[i]
  372. }
  373. // Less implements sort.Interface.
  374. func (l *Sortable) Less(i, j int) bool {
  375. return (*l)[i].Key < (*l)[j].Key
  376. }