Skip to content

Commit

Permalink
fix: Fix bug in BytesToTraceID, add test for it. (#182)
Browse files Browse the repository at this point in the history
## Which problem is this PR solving?

- The bug fix in #179 had a bug, and it was found by a test in an
internal library before deploy.

## Short description of the changes

- Fix bug in BytesToTraceID
- Add a test that would have found the bug, and more test cases for the
new stuff

This requires a release to v0.22.1.
  • Loading branch information
kentquirk authored Mar 8, 2023
1 parent 0ddbf9c commit 12686bd
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 1 deletion.
3 changes: 2 additions & 1 deletion otlp/traces.go
Original file line number Diff line number Diff line change
Expand Up @@ -224,10 +224,11 @@ func BytesToTraceID(traceID []byte) string {
// The spec says that traceID and spanID should be encoded as hex, but
// the protobuf system is interpreting them as b64, so we need to
// reverse them back to b64 and then reencode as hex.
encoded := make([]byte, base64.StdEncoding.EncodedLen(len(traceID)))
encoded = make([]byte, base64.StdEncoding.EncodedLen(len(traceID)))
base64.StdEncoding.Encode(encoded, traceID)
default:
encoded = make([]byte, len(traceID)*2)
hex.Encode(encoded, traceID)
}
return string(encoded)
}
Expand Down
61 changes: 61 additions & 0 deletions otlp/traces_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package otlp

import (
"bytes"
"encoding/base64"
"encoding/hex"
"io"
"math"
Expand Down Expand Up @@ -1063,3 +1064,63 @@ func TestKnownInstrumentationPrefixesReturnTrue(t *testing.T) {
})
}
}

func Test_BytesToTraceID(t *testing.T) {
tests := []struct {
name string
traceID string
b64 bool
want string
}{
{
name: "64-bit traceID",
traceID: "cbe4decd12429177",
want: "cbe4decd12429177",
},
{
name: "128-bit zero-padded traceID",
traceID: "0000000000000000cbe4decd12429177",
want: "cbe4decd12429177",
},
{
name: "128-bit non-zero-padded traceID",
traceID: "f23b42eac289a0fdcde48fcbe3ab1a32",
want: "f23b42eac289a0fdcde48fcbe3ab1a32",
},
{
name: "Non-hex traceID",
traceID: "foobar1",
want: "666f6f62617231",
},
{
name: "Longer non-hex traceID",
traceID: "foobarbaz",
want: "666f6f62617262617a",
},
{
name: "traceID munged by browser",
traceID: "6e994e8673e93a51200c137330aeddad",
b64: true,
want: "6e994e8673e93a51200c137330aeddad",
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var traceID []byte
var err error
if tt.b64 {
traceID, err = base64.StdEncoding.DecodeString(tt.traceID)
} else {
traceID, err = hex.DecodeString(tt.traceID)
}
if err != nil {
traceID = []byte(tt.traceID)
}
got := BytesToTraceID(traceID)
if got != tt.want {
t.Errorf("got: %#v\n\twant: %#v", got, tt.want)
}
})
}
}

0 comments on commit 12686bd

Please sign in to comment.