Skip to content

Commit 78585cf

Browse files
committed
fix(protobuf): Correctly decode multi-messages streams
Signed-off-by: Sven Rebhan <[email protected]>
1 parent 3dec13c commit 78585cf

File tree

3 files changed

+30
-3
lines changed

3 files changed

+30
-3
lines changed

expfmt/decode.go

+3-3
Original file line numberDiff line numberDiff line change
@@ -75,22 +75,22 @@ func ResponseFormat(h http.Header) Format {
7575
func NewDecoder(r io.Reader, format Format) Decoder {
7676
switch format.FormatType() {
7777
case TypeProtoDelim:
78-
return &protoDecoder{r: r}
78+
return &protoDecoder{r: bufio.NewReader(r)}
7979
}
8080
return &textDecoder{r: r}
8181
}
8282

8383
// protoDecoder implements the Decoder interface for protocol buffers.
8484
type protoDecoder struct {
85-
r io.Reader
85+
r protodelim.Reader
8686
}
8787

8888
// Decode implements the Decoder interface.
8989
func (d *protoDecoder) Decode(v *dto.MetricFamily) error {
9090
opts := protodelim.UnmarshalOptions{
9191
MaxSize: -1,
9292
}
93-
if err := opts.UnmarshalFrom(bufio.NewReader(d.r), v); err != nil {
93+
if err := opts.UnmarshalFrom(d.r, v); err != nil {
9494
return err
9595
}
9696
if !model.IsValidMetricName(model.LabelValue(v.GetName())) {

expfmt/decode_test.go

+27
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,12 @@ package expfmt
1515

1616
import (
1717
"bufio"
18+
"bytes"
1819
"errors"
1920
"io"
2021
"math"
2122
"net/http"
23+
"os"
2224
"reflect"
2325
"sort"
2426
"strings"
@@ -414,6 +416,31 @@ func TestProtoDecoder(t *testing.T) {
414416
}
415417
}
416418

419+
func TestProtoMultiMessageDecoder(t *testing.T) {
420+
data, err := os.ReadFile("testdata/protobuf-multimessage")
421+
if err != nil {
422+
t.Fatalf("Reading file failed: %v", err)
423+
}
424+
425+
buf := bytes.NewReader(data)
426+
decoder := NewDecoder(buf, fmtProtoDelim)
427+
var metrics []*dto.MetricFamily
428+
for {
429+
var mf dto.MetricFamily
430+
if err := decoder.Decode(&mf); err != nil {
431+
if errors.Is(err, io.EOF) {
432+
break
433+
}
434+
t.Fatalf("Unmarshalling failed: %v", err)
435+
}
436+
metrics = append(metrics, &mf)
437+
}
438+
439+
if len(metrics) != 6 {
440+
t.Fatalf("Expected %d metrics but got %d!", 6, len(metrics))
441+
}
442+
}
443+
417444
func testDiscriminatorHTTPHeader(t testing.TB) {
418445
scenarios := []struct {
419446
input map[string]string

expfmt/testdata/protobuf-multimessage

414 Bytes
Binary file not shown.

0 commit comments

Comments
 (0)