Skip to content
This repository has been archived by the owner on Oct 23, 2023. It is now read-only.

Commit

Permalink
Optionally pass trace context in http response via Server-Timing. (#34)
Browse files Browse the repository at this point in the history
If SIGNALFX_SERVER_TIMING_CONTEXT is turned on, pass trace context
in traceparent form over a Server-Timing header.

https://www.w3.org/TR/server-timing/
https://www.w3.org/TR/trace-context/#traceparent-header
  • Loading branch information
johnbley authored Jul 9, 2020
1 parent bd5b492 commit bba6a83
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
9 changes: 9 additions & 0 deletions contrib/internal/httputil/trace.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ import (
"fmt"
"net/http"
"net/url"
"os"
"strconv"
"strings"

"github.com/signalfx/signalfx-go-tracing/ddtrace"
"github.com/signalfx/signalfx-go-tracing/ddtrace/ext"
Expand Down Expand Up @@ -41,6 +43,13 @@ func TraceAndServe(h http.Handler, w http.ResponseWriter, r *http.Request, servi

w = wrapResponseWriter(w, span)

if strings.EqualFold("true", os.Getenv("SIGNALFX_SERVER_TIMING_CONTEXT")) {
if traceParent, ok := tracer.FormatAsTraceParent(span.Context()); ok {
w.Header().Add("Access-Control-Expose-Headers", "Server-Timing")
w.Header().Add("Server-Timing", traceParent)
}
}

h.ServeHTTP(w, r.WithContext(ctx))
}

Expand Down
15 changes: 15 additions & 0 deletions ddtrace/tracer/traceparent.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package tracer

import (
"fmt"
"github.com/signalfx/signalfx-go-tracing/ddtrace"
)

func FormatAsTraceParent(context ddtrace.SpanContext) (string,bool) {
ctx, ok := context.(*spanContext)
if !ok || ctx.traceID == 0 || ctx.spanID == 0 {
return "",false
}
answer := fmt.Sprintf("traceparent;desc=\"00-%032x-%016x-01\"", ctx.traceID, ctx.spanID)
return answer,true
}
19 changes: 19 additions & 0 deletions ddtrace/tracer/traceparent_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package tracer

import (
"testing"
"regexp"

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

func TestTraceParent(t *testing.T) {
tracer := newTracer()
span := tracer.StartSpan("web.request").(*span)
traceParent,ok := FormatAsTraceParent(span.Context())

assert := assert.New(t)
assert.True(ok)
matched,_ := regexp.MatchString("^traceparent;desc=\"00-[0-9a-f]{32}-[0-9a-f]{16}-01\"$", traceParent)
assert.True(matched)
}

0 comments on commit bba6a83

Please sign in to comment.