Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: fix bug in query result marshaling for invalid utf8 characters #14585

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions pkg/util/marshal/query.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package marshal

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

jsoniter "github.com/json-iterator/go"
Expand Down Expand Up @@ -77,6 +79,14 @@ func NewStreams(s logqlmodel.Streams) (loghttp.Streams, error) {
ret := make([]loghttp.Stream, len(s))

for i, stream := range s {
// The rune error replacement is rejected by Prometheus hence replacing them with space.
removeInvalidUtf := func(r rune) rune {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can be moved to global vars to initialize once

if r == utf8.RuneError {
return 32 // rune value for space
}
return r
}
stream.Labels = string(bytes.Map(removeInvalidUtf, []byte(stream.Labels)))
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it's better to use bytes.Map() only if []byte(stream.Labels) contains utf8.RuneError .
more details here

ret[i], err = NewStream(stream)

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

import (
"github.com/grafana/loki/v3/pkg/logqlmodel"
"github.com/stretchr/testify/require"
"testing"
)

func TestNewStreams(t *testing.T) {
_, err := NewStreams(logqlmodel.Streams{
{
Labels: "{asdf=\"�\"}",
},
})
require.NoError(t, err)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it would be useful to assert the result as well

}
Loading