1
0
mirror of https://github.com/open-telemetry/opentelemetry-go.git synced 2025-04-13 11:30:31 +02:00

improve trace_context performance (#4721)

* improve trace_context performance

* using strings.Builder instead of fmt.Sprint

* using strings.Cut instead of strings.Split

* using hex.Decode instead of hex.DecodeString

* avoid use regexp

* fix code style

* fix build

* update changelog

* refine code

* update comment

---------

Co-authored-by: Chester Cheung <cheung.zhy.csu@gmail.com>
Co-authored-by: Robert Pająk <pellared@hotmail.com>
This commit is contained in:
xiehuc 2023-11-30 01:32:27 +08:00 committed by GitHub
parent 204be6157f
commit 04054929f1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 55 additions and 45 deletions

View File

@ -8,6 +8,10 @@ This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.htm
## [Unreleased] ## [Unreleased]
### Changed
- Improve `go.opentelemetry.io/otel/propagation.TraceContext`'s performance. (#4721)
## [1.21.0/0.44.0] 2023-11-16 ## [1.21.0/0.44.0] 2023-11-16
### Removed ### Removed

View File

@ -18,7 +18,7 @@ import (
"context" "context"
"encoding/hex" "encoding/hex"
"fmt" "fmt"
"regexp" "strings"
"go.opentelemetry.io/otel/trace" "go.opentelemetry.io/otel/trace"
) )
@ -28,6 +28,7 @@ const (
maxVersion = 254 maxVersion = 254
traceparentHeader = "traceparent" traceparentHeader = "traceparent"
tracestateHeader = "tracestate" tracestateHeader = "tracestate"
delimiter = "-"
) )
// TraceContext is a propagator that supports the W3C Trace Context format // TraceContext is a propagator that supports the W3C Trace Context format
@ -41,8 +42,8 @@ const (
type TraceContext struct{} type TraceContext struct{}
var ( var (
_ TextMapPropagator = TraceContext{} _ TextMapPropagator = TraceContext{}
traceCtxRegExp = regexp.MustCompile("^(?P<version>[0-9a-f]{2})-(?P<traceID>[a-f0-9]{32})-(?P<spanID>[a-f0-9]{16})-(?P<traceFlags>[a-f0-9]{2})(?:-.*)?$") versionPart = fmt.Sprintf("%.2X", supportedVersion)
) )
// Inject set tracecontext from the Context into the carrier. // Inject set tracecontext from the Context into the carrier.
@ -59,12 +60,19 @@ func (tc TraceContext) Inject(ctx context.Context, carrier TextMapCarrier) {
// Clear all flags other than the trace-context supported sampling bit. // Clear all flags other than the trace-context supported sampling bit.
flags := sc.TraceFlags() & trace.FlagsSampled flags := sc.TraceFlags() & trace.FlagsSampled
h := fmt.Sprintf("%.2x-%s-%s-%s", var sb strings.Builder
supportedVersion, sb.Grow(2 + 32 + 16 + 2 + 3)
sc.TraceID(), _, _ = sb.WriteString(versionPart)
sc.SpanID(), traceID := sc.TraceID()
flags) spanID := sc.SpanID()
carrier.Set(traceparentHeader, h) flagByte := [1]byte{byte(flags)}
var buf [32]byte
for _, src := range [][]byte{traceID[:], spanID[:], flagByte[:]} {
_ = sb.WriteByte(delimiter[0])
n := hex.Encode(buf[:], src)
_, _ = sb.Write(buf[:n])
}
carrier.Set(traceparentHeader, sb.String())
} }
// Extract reads tracecontext from the carrier into a returned Context. // Extract reads tracecontext from the carrier into a returned Context.
@ -86,21 +94,8 @@ func (tc TraceContext) extract(carrier TextMapCarrier) trace.SpanContext {
return trace.SpanContext{} return trace.SpanContext{}
} }
matches := traceCtxRegExp.FindStringSubmatch(h) var ver [1]byte
if !extractPart(ver[:], &h, 2) {
if len(matches) == 0 {
return trace.SpanContext{}
}
if len(matches) < 5 { // four subgroups plus the overall match
return trace.SpanContext{}
}
if len(matches[1]) != 2 {
return trace.SpanContext{}
}
ver, err := hex.DecodeString(matches[1])
if err != nil {
return trace.SpanContext{} return trace.SpanContext{}
} }
version := int(ver[0]) version := int(ver[0])
@ -108,36 +103,24 @@ func (tc TraceContext) extract(carrier TextMapCarrier) trace.SpanContext {
return trace.SpanContext{} return trace.SpanContext{}
} }
if version == 0 && len(matches) != 5 { // four subgroups plus the overall match
return trace.SpanContext{}
}
if len(matches[2]) != 32 {
return trace.SpanContext{}
}
var scc trace.SpanContextConfig var scc trace.SpanContextConfig
if !extractPart(scc.TraceID[:], &h, 32) {
scc.TraceID, err = trace.TraceIDFromHex(matches[2][:32]) return trace.SpanContext{}
if err != nil { }
if !extractPart(scc.SpanID[:], &h, 16) {
return trace.SpanContext{} return trace.SpanContext{}
} }
if len(matches[3]) != 16 { var opts [1]byte
if !extractPart(opts[:], &h, 2) {
return trace.SpanContext{} return trace.SpanContext{}
} }
scc.SpanID, err = trace.SpanIDFromHex(matches[3]) if version == 0 && (h != "" || opts[0] > 2) {
if err != nil { // version 0 not allow extra
// version 0 not allow other flag
return trace.SpanContext{} return trace.SpanContext{}
} }
if len(matches[4]) != 2 {
return trace.SpanContext{}
}
opts, err := hex.DecodeString(matches[4])
if err != nil || len(opts) < 1 || (version == 0 && opts[0] > 2) {
return trace.SpanContext{}
}
// Clear all flags other than the trace-context supported sampling bit. // Clear all flags other than the trace-context supported sampling bit.
scc.TraceFlags = trace.TraceFlags(opts[0]) & trace.FlagsSampled scc.TraceFlags = trace.TraceFlags(opts[0]) & trace.FlagsSampled
@ -155,6 +138,29 @@ func (tc TraceContext) extract(carrier TextMapCarrier) trace.SpanContext {
return sc return sc
} }
// upperHex detect hex is upper case Unicode characters.
func upperHex(v string) bool {
for _, c := range v {
if c >= 'A' && c <= 'F' {
return true
}
}
return false
}
func extractPart(dst []byte, h *string, n int) bool {
part, left, _ := strings.Cut(*h, delimiter)
*h = left
// hex.Decode decodes unsupported upper-case characters, so exclude explicitly.
if len(part) != n || upperHex(part) {
return false
}
if p, err := hex.Decode(dst, []byte(part)); err != nil || p != n/2 {
return false
}
return true
}
// Fields returns the keys who's values are set with Inject. // Fields returns the keys who's values are set with Inject.
func (tc TraceContext) Fields() []string { func (tc TraceContext) Fields() []string {
return []string{traceparentHeader, tracestateHeader} return []string{traceparentHeader, tracestateHeader}