Skip to content

Commit

Permalink
bugfix: API: encode empty Vector/Matrix as []
Browse files Browse the repository at this point in the history
If the underlying data is `nil` the default encoding
will render `"null"` which is not accepted by
(some) Prometheus client libraries.

Signed-off-by: Bryan Boreham <bjboreham@gmail.com>
  • Loading branch information
bboreham committed Apr 28, 2024
1 parent 5bc08f7 commit b04fc88
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions web/api/v1/json_codec.go
Expand Up @@ -25,6 +25,8 @@ import (
)

func init() {
jsoniter.RegisterTypeEncoderFunc("promql.Vector", unsafeMarshalVectorJSON, neverEmpty)
jsoniter.RegisterTypeEncoderFunc("promql.Matrix", unsafeMarshalMatrixJSON, neverEmpty)
jsoniter.RegisterTypeEncoderFunc("promql.Series", unsafeMarshalSeriesJSON, neverEmpty)
jsoniter.RegisterTypeEncoderFunc("promql.Sample", unsafeMarshalSampleJSON, neverEmpty)
jsoniter.RegisterTypeEncoderFunc("promql.FPoint", unsafeMarshalFPointJSON, neverEmpty)
Expand Down Expand Up @@ -234,3 +236,23 @@ func labelsIsEmpty(ptr unsafe.Pointer) bool {
labelsPtr := (*labels.Labels)(ptr)
return labelsPtr.IsEmpty()
}

// Marshal a Vector as `[sample,sample,...]` - empty Vector is `[]`.
func unsafeMarshalVectorJSON(ptr unsafe.Pointer, stream *jsoniter.Stream) {
v := *((*promql.Vector)(ptr))
stream.WriteArrayStart()
for _, s := range v {
marshalSampleJSON(s, stream)
}
stream.WriteArrayEnd()
}

// Marshal a Matrix as `[series,series,...]` - empty Matrix is `[]`.
func unsafeMarshalMatrixJSON(ptr unsafe.Pointer, stream *jsoniter.Stream) {
m := *((*promql.Matrix)(ptr))
stream.WriteArrayStart()
for _, s := range m {
marshalSeriesJSON(s, stream)
}
stream.WriteArrayEnd()
}

0 comments on commit b04fc88

Please sign in to comment.