annotation.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. "encoding/json"
  17. "errors"
  18. "time"
  19. )
  20. // ErrValidTimestampRequired error
  21. var ErrValidTimestampRequired = errors.New("valid annotation timestamp required")
  22. // Annotation associates an event that explains latency with a timestamp.
  23. type Annotation struct {
  24. Timestamp time.Time
  25. Value string
  26. }
  27. // MarshalJSON implements custom JSON encoding
  28. func (a *Annotation) MarshalJSON() ([]byte, error) {
  29. return json.Marshal(&struct {
  30. Timestamp int64 `json:"timestamp"`
  31. Value string `json:"value"`
  32. }{
  33. Timestamp: a.Timestamp.Round(time.Microsecond).UnixNano() / 1e3,
  34. Value: a.Value,
  35. })
  36. }
  37. // UnmarshalJSON implements custom JSON decoding
  38. func (a *Annotation) UnmarshalJSON(b []byte) error {
  39. type Alias Annotation
  40. annotation := &struct {
  41. TimeStamp uint64 `json:"timestamp"`
  42. *Alias
  43. }{
  44. Alias: (*Alias)(a),
  45. }
  46. if err := json.Unmarshal(b, &annotation); err != nil {
  47. return err
  48. }
  49. if annotation.TimeStamp < 1 {
  50. return ErrValidTimestampRequired
  51. }
  52. a.Timestamp = time.Unix(0, int64(annotation.TimeStamp)*1e3)
  53. return nil
  54. }