From 5c8ffaa77ccf53a813e890066491a23f4965dd3f Mon Sep 17 00:00:00 2001 From: Bryan Boreham Date: Sun, 28 Apr 2024 20:35:01 +0100 Subject: [PATCH] bugfix: API: encode empty Vector/Matrix as [] 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 --- web/api/v1/json_codec.go | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/web/api/v1/json_codec.go b/web/api/v1/json_codec.go index df3af66f0..dfcdf78f8 100644 --- a/web/api/v1/json_codec.go +++ b/web/api/v1/json_codec.go @@ -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) @@ -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() +}