Skip to content

Commit

Permalink
[opentracing] add SpanContext implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
Emanuele Palazzetti committed Dec 1, 2017
1 parent 8d966a0 commit 00e7898
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 2 deletions.
30 changes: 28 additions & 2 deletions opentracing/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,36 @@ package opentracing
// SpanContext represents Span state that must propagate to descendant Spans
// and across process boundaries.
type SpanContext struct {
traceID uint64
spanID uint64
parentID uint64
sampled bool
baggage map[string]string
}

// ForeachBaggageItem grants access to all baggage items stored in the
// SpanContext
func (n SpanContext) ForeachBaggageItem(handler func(k, v string) bool) {
// TODO: implementation required
func (c SpanContext) ForeachBaggageItem(handler func(k, v string) bool) {
for k, v := range c.baggage {
if !handler(k, v) {
break
}
}
}

// WithBaggageItem returns an entirely new SpanContext with the
// given key:value baggage pair set.
func (c SpanContext) WithBaggageItem(key, val string) SpanContext {
var newBaggage map[string]string
if c.baggage == nil {
newBaggage = map[string]string{key: val}
} else {
newBaggage = make(map[string]string, len(c.baggage)+1)
for k, v := range c.baggage {
newBaggage[k] = v
}
newBaggage[key] = val
}
// Use positional parameters so the compiler will help catch new fields.
return SpanContext{c.traceID, c.spanID, c.parentID, c.sampled, newBaggage}
}
29 changes: 29 additions & 0 deletions opentracing/context_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
package opentracing

import (
"testing"

"github.com/stretchr/testify/assert"
)

func TestSpanContextBaggage(t *testing.T) {
assert := assert.New(t)

ctx := SpanContext{}
ctx = ctx.WithBaggageItem("key", "value")
assert.Equal("value", ctx.baggage["key"])
}

func TestSpanContextIterator(t *testing.T) {
assert := assert.New(t)

baggageIterator := make(map[string]string)
ctx := SpanContext{baggage: map[string]string{"key": "value"}}
ctx.ForeachBaggageItem(func(k, v string) bool {
baggageIterator[k] = v
return true
})

assert.Len(baggageIterator, 1)
assert.Equal("value", baggageIterator["key"])
}

0 comments on commit 00e7898

Please sign in to comment.