Skip to content

Commit

Permalink
feat(interceptor.go): add logging of span context trace ID and span ID
Browse files Browse the repository at this point in the history
refactor(connect_service.go): rename GetBalance method to Call to improve semantics
feat(utils.go): add utility functions to convert span context to and from binary format for tracing purposes
  • Loading branch information
shumkovdenis committed May 16, 2023
1 parent c993336 commit f8136b1
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 2 deletions.
5 changes: 4 additions & 1 deletion connect/interceptor.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@ func InjectTraceContext() connect.UnaryInterceptorFunc {
) (connect.AnyResponse, error) {
if !req.Spec().IsClient {
log.Println(req.Header())
log.Println(req.Header().Get(trace.TraceparentHeader))
log.Println(req.Header().Get(trace.GrpcTraceBinHeader))
t := req.Header().Get(trace.GrpcTraceBinHeader)
sc, ok := trace.SpanContextFromBinary([]byte(t))
log.Println(sc.TraceID(), sc.SpanID(), ok)
}
return next(ctx, req)
})
Expand Down
2 changes: 1 addition & 1 deletion connect_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func NewConnectService(cfg Config, caller Callee) error {
)
}

func (s *connectService) GetBalance(
func (s *connectService) Call(
ctx context.Context,
req *connect.Request[example.CallRequest],
) (*connect.Response[example.CallResponse], error) {
Expand Down
50 changes: 50 additions & 0 deletions trace/utils.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package trace

import "go.opentelemetry.io/otel/trace"

var emptySpanContext trace.SpanContext

// BinaryFromSpanContext returns the binary format representation of a SpanContext.
//
// If sc is the zero value, Binary returns nil.
func BinaryFromSpanContext(sc trace.SpanContext) []byte {
traceID := sc.TraceID()
spanID := sc.SpanID()
traceFlags := sc.TraceFlags()
if sc.Equal(emptySpanContext) {
return nil
}
var b [29]byte
copy(b[2:18], traceID[:])
b[18] = 1
copy(b[19:27], spanID[:])
b[27] = 2
b[28] = uint8(traceFlags)
return b[:]
}

// SpanContextFromBinary returns the SpanContext represented by b.
//
// If b has an unsupported version ID or contains no TraceID, SpanContextFromBinary returns with ok==false.
func SpanContextFromBinary(b []byte) (sc trace.SpanContext, ok bool) {
var scConfig trace.SpanContextConfig
if len(b) == 0 || b[0] != 0 {
return trace.SpanContext{}, false
}
b = b[1:]
if len(b) >= 17 && b[0] == 0 {
copy(scConfig.TraceID[:], b[1:17])
b = b[17:]
} else {
return trace.SpanContext{}, false
}
if len(b) >= 9 && b[0] == 1 {
copy(scConfig.SpanID[:], b[1:9])
b = b[9:]
}
if len(b) >= 2 && b[0] == 2 {
scConfig.TraceFlags = trace.TraceFlags(b[1])
}
sc = trace.NewSpanContext(scConfig)
return sc, true
}

0 comments on commit f8136b1

Please sign in to comment.