traceid.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. // Copyright 2022 The OpenZipkin 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 model
  15. import (
  16. "fmt"
  17. "strconv"
  18. )
  19. // TraceID is a 128 bit number internally stored as 2x uint64 (high & low).
  20. // In case of 64 bit traceIDs, the value can be found in Low.
  21. type TraceID struct {
  22. High uint64
  23. Low uint64
  24. }
  25. // Empty returns if TraceID has zero value.
  26. func (t TraceID) Empty() bool {
  27. return t.Low == 0 && t.High == 0
  28. }
  29. // String outputs the 128-bit traceID as hex string.
  30. func (t TraceID) String() string {
  31. if t.High == 0 {
  32. return fmt.Sprintf("%016x", t.Low)
  33. }
  34. return fmt.Sprintf("%016x%016x", t.High, t.Low)
  35. }
  36. // TraceIDFromHex returns the TraceID from a hex string.
  37. func TraceIDFromHex(h string) (t TraceID, err error) {
  38. if len(h) > 16 {
  39. if t.High, err = strconv.ParseUint(h[0:len(h)-16], 16, 64); err != nil {
  40. return
  41. }
  42. t.Low, err = strconv.ParseUint(h[len(h)-16:], 16, 64)
  43. return
  44. }
  45. t.Low, err = strconv.ParseUint(h, 16, 64)
  46. return
  47. }
  48. // MarshalJSON custom JSON serializer to export the TraceID in the required
  49. // zero padded hex representation.
  50. func (t TraceID) MarshalJSON() ([]byte, error) {
  51. return []byte(fmt.Sprintf("%q", t.String())), nil
  52. }
  53. // UnmarshalJSON custom JSON deserializer to retrieve the traceID from the hex
  54. // encoded representation.
  55. func (t *TraceID) UnmarshalJSON(traceID []byte) error {
  56. if len(traceID) < 3 {
  57. return ErrValidTraceIDRequired
  58. }
  59. // A valid JSON string is encoded wrapped in double quotes. We need to trim
  60. // these before converting the hex payload.
  61. tID, err := TraceIDFromHex(string(traceID[1 : len(traceID)-1]))
  62. if err != nil {
  63. return err
  64. }
  65. *t = tID
  66. return nil
  67. }