diff --git a/otlp/traces.go b/otlp/traces.go index 658d9c4..806701b 100644 --- a/otlp/traces.go +++ b/otlp/traces.go @@ -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) } diff --git a/otlp/traces_test.go b/otlp/traces_test.go index 9fb4820..f732f1b 100644 --- a/otlp/traces_test.go +++ b/otlp/traces_test.go @@ -2,6 +2,7 @@ package otlp import ( "bytes" + "encoding/base64" "encoding/hex" "io" "math" @@ -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) + } + }) + } +}