Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: implement tracing without composition #30

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
18 changes: 15 additions & 3 deletions httptrace/trace.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,24 @@ func ContextClientTrace(ctx context.Context) *ClientTrace {
// registered with ctx. Any hooks defined in the provided trace will
// be called first.
func WithClientTrace(ctx context.Context, trace *ClientTrace) context.Context {
return withClientTrace(ctx, trace, true)
}

// WithClientTraceWithoutComposition is like WithClientTrace except that
// we're not going to compose with any old trace there may be inside of the
// chain of contexts. This API seems useful to implement OONI Probe.
func WithClientTraceWithoutComposition(ctx context.Context, trace *ClientTrace) context.Context {
return withClientTrace(ctx, trace, false)
}

func withClientTrace(ctx context.Context, trace *ClientTrace, compose bool) context.Context {
if trace == nil {
panic("nil trace")
}
old := ContextClientTrace(ctx)
trace.compose(old)

if compose {
old := ContextClientTrace(ctx)
trace.compose(old)
}
ctx = context.WithValue(ctx, clientEventContextKey{}, trace)
return ctx
}
Expand Down
26 changes: 26 additions & 0 deletions httptrace/trace_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,3 +87,29 @@ func TestCompose(t *testing.T) {
}

}

func TestClientTraceWithoutComposition(t *testing.T) {
unexpectedFlag := false
oldTrace := &ClientTrace{
GetConn: func(hostPort string) {
unexpectedFlag = true
},
}
ctx := context.Background()
ctx = WithClientTraceWithoutComposition(ctx, oldTrace)
expectedFlag := false
newTrace := &ClientTrace{
GetConn: func(hostPort string) {
expectedFlag = true
},
}
ctx = WithClientTraceWithoutComposition(ctx, newTrace)
maybeCompoundTrace := ContextClientTrace(ctx)
maybeCompoundTrace.GetConn("1.2.3.4")
if unexpectedFlag {
t.Fatal("should be false")
}
if !expectedFlag {
t.Fatal("should be true")
}
}