Skip to content

Commit

Permalink
Fix: TraceClient crashed in absense of a parentSpan in Context
Browse files Browse the repository at this point in the history
Added TestTraceClientNoContextSpan to test for this situation
  • Loading branch information
basvanbeek committed Jul 8, 2016
1 parent 4c2dfa9 commit d881d98
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 deletions.
14 changes: 9 additions & 5 deletions tracing/opentracing/endpoint.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,15 @@ func TraceServer(tracer opentracing.Tracer, operationName string) endpoint.Middl
func TraceClient(tracer opentracing.Tracer, operationName string) endpoint.Middleware {
return func(next endpoint.Endpoint) endpoint.Endpoint {
return func(ctx context.Context, request interface{}) (interface{}, error) {
parentSpan := opentracing.SpanFromContext(ctx)
clientSpan := tracer.StartSpan(
operationName,
opentracing.ChildOf(parentSpan.Context()),
)
var clientSpan opentracing.Span
if parentSpan := opentracing.SpanFromContext(ctx); parentSpan != nil {
clientSpan = tracer.StartSpan(
operationName,
opentracing.ChildOf(parentSpan.Context()),
)
} else {
clientSpan = tracer.StartSpan(operationName)
}
defer clientSpan.Finish()
otext.SpanKind.Set(clientSpan, otext.SpanKindRPCClient)
ctx = opentracing.ContextWithSpan(ctx, clientSpan)
Expand Down
21 changes: 21 additions & 0 deletions tracing/opentracing/endpoint_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,24 @@ func TestTraceClient(t *testing.T) {
t.Errorf("Want ParentID %q, have %q", want, have)
}
}

func TestTraceClientNoContextSpan(t *testing.T) {
tracer := mocktracer.New()

// Empty/background context.
tracedEndpoint := kitot.TraceClient(tracer, "testOp")(endpoint.Nop)
if _, err := tracedEndpoint(context.Background(), struct{}{}); err != nil {
t.Fatal(err)
}

// tracedEndpoint created a new Span.
finishedSpans := tracer.GetFinishedSpans()
if want, have := 1, len(finishedSpans); want != have {
t.Fatalf("Want %v span(s), found %v", want, have)
}

endpointSpan := finishedSpans[0]
if want, have := "testOp", endpointSpan.OperationName; want != have {
t.Fatalf("Want %q, have %q", want, have)
}
}

0 comments on commit d881d98

Please sign in to comment.