Repository navigation
feat(otel): add request context to application spans #375
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
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
5f51aea
feat(otel): add request context to application spans
pauldambra 56f84cf
fix: stop context enrichment after processor shutdown
pauldambra 40432bb
fix: skip span context for disabled clients
pauldambra e5f4ade
Merge remote-tracking branch 'origin/main' into posthog/go-http-span-…
pauldambra File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| "posthog-go": minor | ||
| --- | ||
|
|
||
| Add an optional OpenTelemetry context processor and HTTP middleware for session and person IDs on application spans. Both take the PostHog client and add no IDs when that client is nil, disabled, or closed. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,114 @@ | ||
| package posthogotel | ||
|
|
||
| import ( | ||
| "context" | ||
| "net/http" | ||
| "sync/atomic" | ||
|
|
||
| "github.com/posthog/posthog-go" | ||
| "go.opentelemetry.io/otel/attribute" | ||
| sdktrace "go.opentelemetry.io/otel/sdk/trace" | ||
| "go.opentelemetry.io/otel/trace" | ||
| ) | ||
|
|
||
| // ContextSpanProcessor adds PostHog IDs to spans from the application's provider. | ||
| // Register it before processors that consume attributes in OnStart. It does not export spans. | ||
| type ContextSpanProcessor struct { | ||
| client contextClient | ||
| shutdown atomic.Bool | ||
| } | ||
|
|
||
| var _ sdktrace.SpanProcessor = (*ContextSpanProcessor)(nil) | ||
|
|
||
| // NewContextSpanProcessor creates an optional bridge for general application spans. | ||
| // It adds IDs only while client is enabled, so a nil, disabled, or closed client adds none. | ||
| // A client wrapper can implement IsEnabled() bool to report its state; otherwise it counts as enabled. | ||
| func NewContextSpanProcessor(client posthog.Client) *ContextSpanProcessor { | ||
| return &ContextSpanProcessor{client: newContextClient(client)} | ||
| } | ||
|
|
||
| func (p *ContextSpanProcessor) OnStart(ctx context.Context, span sdktrace.ReadWriteSpan) { | ||
| if !p.shutdown.Load() { | ||
| enrichContextSpan(ctx, span, p.client) | ||
| } | ||
| } | ||
|
|
||
| func (*ContextSpanProcessor) OnEnd(sdktrace.ReadOnlySpan) {} | ||
| func (p *ContextSpanProcessor) Shutdown(context.Context) error { | ||
| p.shutdown.Store(true) | ||
| return nil | ||
| } | ||
| func (*ContextSpanProcessor) ForceFlush(context.Context) error { return nil } | ||
|
|
||
| type contextClient struct { | ||
| present bool | ||
| enabled interface{ IsEnabled() bool } | ||
| } | ||
|
|
||
| func newContextClient(client posthog.Client) contextClient { | ||
| enabled, _ := client.(interface{ IsEnabled() bool }) | ||
| return contextClient{present: client != nil, enabled: enabled} | ||
| } | ||
|
|
||
| func (c contextClient) isEnabled() bool { | ||
| return c.present && (c.enabled == nil || c.enabled.IsEnabled()) | ||
| } | ||
|
|
||
| type contextSpanRequestKey struct{} | ||
| type contextSpanRequest struct{ active atomic.Bool } | ||
|
|
||
| func enrichContextSpan(ctx context.Context, span trace.Span, client contextClient) { | ||
| if !client.present || ctx == nil || span == nil || !span.IsRecording() { | ||
| return | ||
| } | ||
| if request, ok := ctx.Value(contextSpanRequestKey{}).(*contextSpanRequest); ok && !request.active.Load() { | ||
| return | ||
| } | ||
| if !client.isEnabled() { | ||
| return | ||
| } | ||
| readable, ok := span.(interface{ Attributes() []attribute.KeyValue }) | ||
| if !ok { | ||
| return | ||
| } | ||
| request, ok := posthog.RequestContextFromContext(ctx) | ||
| if !ok { | ||
| return | ||
| } | ||
| hasDistinctID, hasSessionID := false, false | ||
| for _, attr := range readable.Attributes() { | ||
| switch string(attr.Key) { | ||
| case "posthogDistinctId": | ||
| hasDistinctID = true | ||
| case "sessionId": | ||
| hasSessionID = true | ||
| } | ||
| } | ||
| attrs := make([]attribute.KeyValue, 0, 2) | ||
| if request.DistinctId != "" && !hasDistinctID { | ||
| attrs = append(attrs, attribute.String("posthogDistinctId", request.DistinctId)) | ||
| } | ||
| if request.SessionId != "" && !hasSessionID { | ||
| attrs = append(attrs, attribute.String("sessionId", request.SessionId)) | ||
| } | ||
| span.SetAttributes(attrs...) | ||
| } | ||
|
|
||
| // NewRequestContextMiddleware also enriches the existing request span after header extraction. | ||
| // It adds IDs to spans only while client is enabled, like NewContextSpanProcessor. | ||
| // It accepts the core middleware options. Spans started from an inherited request context | ||
| // after the handler returns omit request IDs. Register ContextSpanProcessor for child spans. | ||
| func NewRequestContextMiddleware(client posthog.Client, next http.Handler, opts ...posthog.RequestContextOption) http.Handler { | ||
| spanClient := newContextClient(client) | ||
| if next == nil { | ||
| return posthog.NewRequestContextMiddleware(nil, opts...) | ||
| } | ||
| return posthog.NewRequestContextMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
| request := &contextSpanRequest{} | ||
| request.active.Store(true) | ||
| defer request.active.Store(false) | ||
| ctx := context.WithValue(r.Context(), contextSpanRequestKey{}, request) | ||
| enrichContextSpan(ctx, trace.SpanFromContext(ctx), spanClient) | ||
| next.ServeHTTP(w, r.WithContext(ctx)) | ||
| }), opts...) | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.