Skip to content
Open
Show file tree
Hide file tree
Changes from all 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
55 changes: 47 additions & 8 deletions internal/datastreams/propagator.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"encoding/binary"
"errors"
"time"
"unsafe"

"github.com/DataDog/sketches-go/ddsketch/encoding"
)
Expand All @@ -24,13 +25,20 @@ const (
PropagationKeyBase64 = "dd-pathway-ctx-base64"
)

// appendEncoded appends the binary encoding of p to dst.
// Maximum encoded length is 8 (hash) + 10 (pathwayStart varint) + 10 (edgeStart varint) = 28 bytes.
// binary.AppendVarint uses the same zig-zag varint encoding as ddsketch/encoding.EncodeVarint64
// without taking a *[]byte pointer, allowing callers' stack buffers to stay on the stack.
func (p Pathway) appendEncoded(dst []byte) []byte {
dst = binary.LittleEndian.AppendUint64(dst, p.hash)
dst = binary.AppendVarint(dst, p.pathwayStart.UnixNano()/int64(time.Millisecond))
dst = binary.AppendVarint(dst, p.edgeStart.UnixNano()/int64(time.Millisecond))
return dst
}

// Encode encodes the pathway
func (p Pathway) Encode() []byte {
data := make([]byte, 8, 20)
binary.LittleEndian.PutUint64(data, p.hash)
encoding.EncodeVarint64(&data, p.pathwayStart.UnixNano()/int64(time.Millisecond))
encoding.EncodeVarint64(&data, p.edgeStart.UnixNano()/int64(time.Millisecond))
return data
return p.appendEncoded(make([]byte, 0, 28))
}

// Decode decodes a pathway
Expand All @@ -55,22 +63,50 @@ func Decode(ctx context.Context, data []byte) (p Pathway, outCtx context.Context

// EncodeBase64 encodes a pathway context into a string using base64 encoding.
func (p Pathway) EncodeBase64() string {
b := p.Encode()
return base64.StdEncoding.EncodeToString(b)
var rawBuf [28]byte
raw := p.appendEncoded(rawBuf[:0])
var b64Buf [40]byte
n := base64.StdEncoding.EncodedLen(len(raw))
base64.StdEncoding.Encode(b64Buf[:n], raw)
return string(b64Buf[:n])
}

// DecodeBase64 decodes a pathway context from a string using base64 encoding.
func DecodeBase64(ctx context.Context, str string) (p Pathway, outCtx context.Context, err error) {
if len(str) <= 64 {
var rawBuf [48]byte
src := unsafe.Slice(unsafe.StringData(str), len(str))
n, decErr := base64.StdEncoding.Decode(rawBuf[:], src)
if decErr != nil {
return p, ctx, decErr
}
return Decode(ctx, rawBuf[:n])
}
data, err := base64.StdEncoding.DecodeString(str)
if err != nil {
return p, ctx, err
}
return Decode(ctx, data)
}

type pathwayContext struct {
context.Context
pathway Pathway
}

func (c *pathwayContext) Value(key any) any {
if key == activePathwayKey {
return c.pathway

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

P2 Avoid boxing the pathway on every wrapped-context lookup

When a pathway context is wrapped with context.WithCancel, context.WithValue, or tracer.ContextWithSpan, PathwayFromContext misses its direct assertion and reaches this return. Converting c.pathway to any allocates a fresh boxed copy on every lookup; previously, context.WithValue reused the value boxed during insertion. Repeated injection, merging, and checkpoint lookups therefore incur an additional allocation, undermining this hot-path optimization. Return an internal reference here and update PathwayFromContext to dereference it.

React: 👍 useful · 👎 wrong · 😕 unclear · 👀 right, but not acting on it

What each reaction means
  • 👍 Useful: correct, and you're fixing it or will.
  • 👎 Wrong: the finding is incorrect, for example the bug can't happen or the code was misread.
  • 😕 Unclear: you can't tell what it means or why it matters.
  • 👀 Right, not acting: correct, but intended, out of scope for this PR, a known risk, or too minor.

🤖 Bits Code Review · Open Bits AI session

}
return c.Context.Value(key)
}

// ContextWithPathway returns a copy of the given context which includes the pathway p.
func ContextWithPathway(ctx context.Context, p Pathway) context.Context {
return context.WithValue(ctx, activePathwayKey, p)
if ctx == nil {
panic("cannot create context from nil parent")
}
return &pathwayContext{Context: ctx, pathway: p}
}

// PathwayFromContext returns the pathway contained in the given context, and whether a
Expand All @@ -79,6 +115,9 @@ func PathwayFromContext(ctx context.Context) (p Pathway, ok bool) {
if ctx == nil {
return p, false
}
if pc, ok := ctx.(*pathwayContext); ok {
return pc.pathway, true
}
v := ctx.Value(activePathwayKey)
if p, ok := v.(Pathway); ok {
return p, true
Expand Down
27 changes: 27 additions & 0 deletions internal/datastreams/propagator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,3 +37,30 @@ func TestEncodeBase64(t *testing.T) {
assert.Nil(t, err)
assert.Equal(t, p, decoded)
}

func BenchmarkEncodeBase64(b *testing.B) {
p := testPathway()
b.ReportAllocs()
b.ResetTimer()
for b.Loop() {
_ = p.EncodeBase64()
}
}

func BenchmarkDecodeBase64(b *testing.B) {
p := testPathway()
encoded := p.EncodeBase64()
ctx := context.Background()
b.ReportAllocs()
b.ResetTimer()
for b.Loop() {
_, _, _ = DecodeBase64(ctx, encoded)
}
}

func BenchmarkPathwayHash(b *testing.B) {
b.ReportAllocs()
for b.Loop() {
_ = pathwayHash(123456789, 987654321)
}
}
Loading