Skip to content

Commit

Permalink
Continue to use json-iterator to improve marshalling of SampleHistogr…
Browse files Browse the repository at this point in the history
…amPair

Signed-off-by: Jeanette Tan <jeanette.tan@grafana.com>
  • Loading branch information
zenador committed Feb 1, 2023
1 parent eda7de1 commit f71df30
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 10 deletions.
26 changes: 16 additions & 10 deletions model/value_histogram.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (

func init() {
jsoniter.RegisterTypeEncoderFunc("model.HistogramBucket", marshalHistogramBucketJSON, marshalHistogramBucketJSONIsEmpty)
jsoniter.RegisterTypeEncoderFunc("model.SampleHistogramPair", marshalSampleHistogramPairJSON, marshalSampleHistogramPairJSONIsEmpty)
}

type FloatString float64
Expand Down Expand Up @@ -136,20 +137,25 @@ type SampleHistogramPair struct {
Histogram *SampleHistogram
}

// marshalSampleHistogramPairJSON writes `[ts, "val"]`.
func marshalSampleHistogramPairJSON(ptr unsafe.Pointer, stream *jsoniter.Stream) {
p := *((*SampleHistogramPair)(ptr))
stream.WriteArrayStart()
MarshalTimestamp(int64(p.Timestamp), stream)
stream.WriteMore()
MarshalHistogram(*p.Histogram, stream)
stream.WriteArrayEnd()
}

func marshalSampleHistogramPairJSONIsEmpty(ptr unsafe.Pointer) bool {
return false
}

func (s SampleHistogramPair) MarshalJSON() ([]byte, error) {
jsoni := jsoniter.ConfigCompatibleWithStandardLibrary
t, err := jsoni.Marshal(s.Timestamp)
if err != nil {
return nil, err
}
if s.Histogram == nil {
return nil, fmt.Errorf("histogram is nil")
}
v, err := jsoni.Marshal(s.Histogram)
if err != nil {
return nil, err
}
return []byte(fmt.Sprintf("[%s,%s]", t, v)), nil
return jsoniter.ConfigCompatibleWithStandardLibrary.Marshal(s)
}

func (s *SampleHistogramPair) UnmarshalJSON(buf []byte) error {
Expand Down
28 changes: 28 additions & 0 deletions model/value_marshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,3 +76,31 @@ func MarshalHistogramBucket(b HistogramBucket, stream *jsoniter.Stream) {
MarshalValue(b.Count, stream)
stream.WriteArrayEnd()
}

// adapted from https://github.com/prometheus/prometheus/blob/main/web/api/v1/api.go
func MarshalHistogram(h SampleHistogram, stream *jsoniter.Stream) {
stream.WriteObjectStart()
stream.WriteObjectField(`count`)
MarshalValue(h.Count, stream)
stream.WriteMore()
stream.WriteObjectField(`sum`)
MarshalValue(h.Sum, stream)

bucketFound := false
for _, bucket := range h.Buckets {
if bucket.Count == 0 {
continue // No need to expose empty buckets in JSON.
}
stream.WriteMore()
if !bucketFound {
stream.WriteObjectField(`buckets`)
stream.WriteArrayStart()
}
bucketFound = true
MarshalHistogramBucket(*bucket, stream)
}
if bucketFound {
stream.WriteArrayEnd()
}
stream.WriteObjectEnd()
}

0 comments on commit f71df30

Please sign in to comment.