Skip to content

Commit

Permalink
fix: fix bug in query result marshaling for invalid utf8 characters (#…
Browse files Browse the repository at this point in the history
…14585)

Signed-off-by: Callum Styan <[email protected]>
  • Loading branch information
cstyan authored Oct 28, 2024
1 parent 99c423a commit f411a07
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 0 deletions.
16 changes: 16 additions & 0 deletions pkg/util/marshal/query.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
package marshal

import (
"bytes"
"fmt"
"strconv"
"strings"
"unicode/utf8"
"unsafe"

jsoniter "github.com/json-iterator/go"
Expand All @@ -20,6 +23,16 @@ import (
"github.com/grafana/loki/v3/pkg/util/httpreq"
)

var (
// The rune error replacement is rejected by Prometheus hence replacing them with space.
removeInvalidUtf = func(r rune) rune {
if r == utf8.RuneError {
return 32 // rune value for space
}
return r
}
)

// NewResultValue constructs a ResultValue from a promql.Value
func NewResultValue(v parser.Value) (loghttp.ResultValue, error) {
var err error
Expand Down Expand Up @@ -77,6 +90,9 @@ func NewStreams(s logqlmodel.Streams) (loghttp.Streams, error) {
ret := make([]loghttp.Stream, len(s))

for i, stream := range s {
if strings.ContainsRune(stream.Labels, utf8.RuneError) {
stream.Labels = string(bytes.Map(removeInvalidUtf, []byte(stream.Labels)))
}
ret[i], err = NewStream(stream)

if err != nil {
Expand Down
19 changes: 19 additions & 0 deletions pkg/util/marshal/query_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package marshal

import (
"testing"

"github.com/stretchr/testify/require"

"github.com/grafana/loki/v3/pkg/logqlmodel"
)

func TestNewStreams(t *testing.T) {
s, err := NewStreams(logqlmodel.Streams{
{
Labels: "{asdf=\"\"}",
},
})
require.NoError(t, err)
require.Equal(t, " ", s[0].Labels["asdf"], "expected only a space for label who only contained invalid UTF8 rune")
}

0 comments on commit f411a07

Please sign in to comment.