Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
6b48923
feat: http client integration
aldy505 Aug 27, 2024
fd66575
chore(httpclient): variable naming according to linter
aldy505 Aug 27, 2024
439e98b
Merge branch 'master' into feat/httpclient
aldy505 Sep 3, 2024
5f4c5ae
chore: add changelog entry
aldy505 Sep 3, 2024
5214ea5
fix(httpclient): dont iterate over map
aldy505 Sep 3, 2024
ed105c1
feat(examples): add httpclient
aldy505 Sep 3, 2024
4e55daa
Merge branch 'master' into feat/httpclient
ribice Sep 3, 2024
15aa59a
feat(spans): only start 'http.client' op as a child span
aldy505 Sep 4, 2024
099dad4
chore: lint
aldy505 Sep 4, 2024
7d9555d
Merge branch 'master' into feat/httpclient
aldy505 Sep 15, 2024
f018dde
chore: remove GetSpanFromContext and replace it with SpanFromContext
aldy505 Oct 18, 2024
d6f2663
Merge branch 'master' into feat/httpclient
aldy505 Oct 18, 2024
6af10bf
feat(httpclient): use baggage and traceparent from hub
aldy505 Nov 2, 2024
c5ad7e4
Merge remote-tracking branch 'origin/master' into feat/httpclient
aldy505 Nov 2, 2024
081fc0b
feat(httpclient): trace propagation targets
aldy505 Nov 6, 2024
a3a6367
chore: remove trace options request
aldy505 Nov 16, 2024
2cb97af
Merge branch 'master' into feat/httpclient
aldy505 Nov 25, 2024
ce3d4ea
Merge branch 'master' into feat/httpclient
aldy505 Apr 23, 2025
1075de4
Update sentryhttpclient.go
aldy505 Apr 24, 2025
ae861f3
feat(httpclient): use WithDescription instead of WithTransactionName
aldy505 Apr 25, 2025
a5eb96f
Update _examples/httpclient/main.go
aldy505 Apr 28, 2025
791feb5
chore: lint errors
aldy505 May 2, 2025
c912fe9
chore: omit variable name
aldy505 May 2, 2025
3e9a23b
Merge branch 'master' into feat/httpclient
giortzisg May 2, 2025
912797f
Update CHANGELOG.md
cleptric May 6, 2025
0e21a00
Merge branch 'master' into feat/httpclient
cleptric May 6, 2025
b31001c
Merge branch 'master' into feat/httpclient
giortzisg Jun 3, 2025
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
4 changes: 4 additions & 0 deletions client.go
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,10 @@ type ClientOptions struct {
TracesSampleRate float64
// Used to customize the sampling of traces, overrides TracesSampleRate.
TracesSampler TracesSampler
// Control with URLs trace propagation should be enabled. Does not support regex patterns.
TracePropagationTargets []string
// When set to true, the SDK will start a span for outgoing HTTP OPTIONS requests.
TraceOptionsRequests bool
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why did you add this option?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Saw it on the dev docs. Should I not implement that?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Link?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

When set to true transactions should be created for HTTP OPTIONS requests.

This option does not apply to outgoing HTTP requests.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay. Will update that later.

// The sample rate for profiling traces in the range [0.0, 1.0].
// This is relative to TracesSampleRate - it is a ratio of profiled traces out of all sampled traces.
ProfilesSampleRate float64
Expand Down
62 changes: 51 additions & 11 deletions httpclient/sentryhttpclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,26 +14,30 @@ package sentryhttpclient
import (
"fmt"
"net/http"
"strings"

"github.com/getsentry/sentry-go"
)

// SentryRoundTripTracerOption provides a specific type in which defines the option for SentryRoundTripper.
type SentryRoundTripTracerOption func(*SentryRoundTripper)

// WithTags allows the RoundTripper to includes additional tags.
func WithTags(tags map[string]string) SentryRoundTripTracerOption {
// WithTracePropagationTargets configures additional trace propagation targets URL for the RoundTripper.
// Does not support regex patterns.
func WithTracePropagationTargets(targets []string) SentryRoundTripTracerOption {
return func(t *SentryRoundTripper) {
for k, v := range tags {
t.tags[k] = v
if t.tracePropagationTargets == nil {
t.tracePropagationTargets = targets
} else {
t.tracePropagationTargets = append(t.tracePropagationTargets, targets...)
}
}
}

// WithTag allows the RoundTripper to includes additional tag.
func WithTag(key, value string) SentryRoundTripTracerOption {
// WithTraceOptionsRequests overrides the default options for whether the tracer should trace OPTIONS requests.
func WithTraceOptionsRequests(traceOptionsRequests bool) SentryRoundTripTracerOption {
return func(t *SentryRoundTripper) {
t.tags[key] = value
t.traceOptionsRequests = traceOptionsRequests
}
}

Expand All @@ -45,9 +49,25 @@ func NewSentryRoundTripper(originalRoundTripper http.RoundTripper, opts ...Sentr
originalRoundTripper = http.DefaultTransport
}

// Configure trace propagation targets
var tracePropagationTargets []string
var traceOptionsRequests bool
if hub := sentry.CurrentHub(); hub != nil {
client := hub.Client()
if client != nil {
clientOptions := client.Options()
if clientOptions.TracePropagationTargets != nil {
tracePropagationTargets = clientOptions.TracePropagationTargets
}

traceOptionsRequests = clientOptions.TraceOptionsRequests
}
}

t := &SentryRoundTripper{
originalRoundTripper: originalRoundTripper,
tags: make(map[string]string),
originalRoundTripper: originalRoundTripper,
tracePropagationTargets: tracePropagationTargets,
traceOptionsRequests: traceOptionsRequests,
}

for _, opt := range opts {
Expand All @@ -63,10 +83,31 @@ func NewSentryRoundTripper(originalRoundTripper http.RoundTripper, opts ...Sentr
type SentryRoundTripper struct {
originalRoundTripper http.RoundTripper

tags map[string]string
tracePropagationTargets []string
traceOptionsRequests bool
}

func (s *SentryRoundTripper) RoundTrip(request *http.Request) (*http.Response, error) {
if request.Method == http.MethodOptions && !s.traceOptionsRequests {
return s.originalRoundTripper.RoundTrip(request)
}

// Respect trace propagation targets
if len(s.tracePropagationTargets) > 0 {
requestURL := request.URL.String()
foundMatch := false
for _, target := range s.tracePropagationTargets {
if strings.Contains(requestURL, target) {
foundMatch = true
break
}
}

if !foundMatch {
return s.originalRoundTripper.RoundTrip(request)
}
}

// Only create the `http.client` span only if there is a parent span.
parentSpan := sentry.SpanFromContext(request.Context())
if parentSpan == nil {
Expand All @@ -81,7 +122,6 @@ func (s *SentryRoundTripper) RoundTrip(request *http.Request) (*http.Response, e
cleanRequestURL := request.URL.Redacted()

span := parentSpan.StartChild("http.client", sentry.WithTransactionName(fmt.Sprintf("%s %s", request.Method, cleanRequestURL)))
span.Tags = s.tags
defer span.Finish()

span.SetData("http.query", request.URL.Query().Encode())
Expand Down
163 changes: 153 additions & 10 deletions httpclient/sentryhttpclient_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,6 @@ func TestIntegration(t *testing.T) {
},
Name: "GET https://example.com/foo",
Op: "http.client",
Tags: map[string]string{},
Origin: "manual",
Sampled: sentry.SampledTrue,
Status: sentry.SpanStatusOK,
Expand All @@ -103,7 +102,6 @@ func TestIntegration(t *testing.T) {
},
Name: "GET https://example.com:443/foo/bar?baz=123#readme",
Op: "http.client",
Tags: map[string]string{},
Origin: "manual",
Sampled: sentry.SampledTrue,
Status: sentry.SpanStatusOK,
Expand All @@ -112,7 +110,7 @@ func TestIntegration(t *testing.T) {
{
RequestMethod: "HEAD",
RequestURL: "https://example.com:8443/foo?bar=123&abc=def",
TracerOptions: []sentryhttpclient.SentryRoundTripTracerOption{sentryhttpclient.WithTag("user", "def"), sentryhttpclient.WithTags(map[string]string{"domain": "example.com"})},
TracerOptions: []sentryhttpclient.SentryRoundTripTracerOption{},
WantStatus: 400,
WantResponseLength: 0,
WantSpan: &sentry.Span{
Expand All @@ -125,10 +123,7 @@ func TestIntegration(t *testing.T) {
"server.address": string("example.com"),
"server.port": string("8443"),
},
Tags: map[string]string{
"user": "def",
"domain": "example.com",
},

Name: "HEAD https://example.com:8443/foo?bar=123&abc=def",
Op: "http.client",
Origin: "manual",
Expand All @@ -153,7 +148,6 @@ func TestIntegration(t *testing.T) {
},
Name: "POST https://john:[email protected]:4321/secret",
Op: "http.client",
Tags: map[string]string{},
Origin: "manual",
Sampled: sentry.SampledTrue,
Status: sentry.SpanStatusOK,
Expand All @@ -173,12 +167,72 @@ func TestIntegration(t *testing.T) {
},
Name: "POST https://example.com",
Op: "http.client",
Tags: map[string]string{},
Origin: "manual",
Sampled: sentry.SampledTrue,
Status: sentry.SpanStatusInternalError,
},
},
{
RequestMethod: "OPTIONS",
RequestURL: "https://example.com",
WantError: false,
WantSpan: nil,
},
{
RequestMethod: "OPTIONS",
RequestURL: "https://example.com",
TracerOptions: []sentryhttpclient.SentryRoundTripTracerOption{sentryhttpclient.WithTraceOptionsRequests(true)},
WantStatus: 204,
WantResponseLength: 0,
WantSpan: &sentry.Span{
Data: map[string]interface{}{
"http.fragment": string(""),
"http.query": string(""),
"http.request.method": string("OPTIONS"),
"http.response.status_code": int(204),
"http.response_content_length": int64(0),
"server.address": string("example.com"),
"server.port": string(""),
},

Name: "OPTIONS https://example.com",
Op: "http.client",
Origin: "manual",
Sampled: sentry.SampledTrue,
Status: sentry.SpanStatusOK,
},
},
{
RequestMethod: "GET",
RequestURL: "https://example.com/foo/bar?baz=123#readme",
TracerOptions: []sentryhttpclient.SentryRoundTripTracerOption{sentryhttpclient.WithTracePropagationTargets([]string{"example.com"}), sentryhttpclient.WithTracePropagationTargets([]string{"example.org"})},
WantStatus: 200,
WantResponseLength: 0,
WantSpan: &sentry.Span{
Data: map[string]interface{}{
"http.fragment": string("readme"),
"http.query": string("baz=123"),
"http.request.method": string("GET"),
"http.response.status_code": int(200),
"http.response_content_length": int64(0),
"server.address": string("example.com"),
"server.port": string(""),
},
Name: "GET https://example.com/foo/bar?baz=123#readme",
Op: "http.client",
Origin: "manual",
Sampled: sentry.SampledTrue,
Status: sentry.SpanStatusOK,
},
},
{
RequestMethod: "GET",
RequestURL: "https://example.net/foo/bar?baz=123#readme",
TracerOptions: []sentryhttpclient.SentryRoundTripTracerOption{sentryhttpclient.WithTracePropagationTargets([]string{"example.com"})},
WantStatus: 200,
WantResponseLength: 0,
WantSpan: nil,
},
}

spansCh := make(chan []*sentry.Span, len(tests))
Expand Down Expand Up @@ -258,12 +312,101 @@ func TestIntegration(t *testing.T) {
}
}

if !foundMatch {
if tt.WantSpan != nil && !foundMatch {
t.Errorf("Span mismatch (-want +got):\n%s", strings.Join(diffs, "\n"))
} else if tt.WantSpan == nil && foundMatch {
t.Errorf("Expected no span, got %+v", gotSpans)
}
}
}

func TestIntegration_GlobalClientOptions(t *testing.T) {
spansCh := make(chan []*sentry.Span, 1)

err := sentry.Init(sentry.ClientOptions{
EnableTracing: true,
TracePropagationTargets: []string{"example.com"},
TraceOptionsRequests: false,
TracesSampleRate: 1.0,
BeforeSendTransaction: func(event *sentry.Event, hint *sentry.EventHint) *sentry.Event {
spansCh <- event.Spans
return event
},
})
if err != nil {
t.Fatal(err)
}

ctx := sentry.SetHubOnContext(context.Background(), sentry.CurrentHub())
span := sentry.StartSpan(ctx, "fake_parent", sentry.WithTransactionName("Fake Parent"))
ctx = span.Context()

request, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://example.com", nil)
if err != nil {
t.Fatal(err)
}

roundTripper := &noopRoundTripper{
ExpectResponseStatus: 200,
ExpectResponseLength: 48,
ExpectError: false,
}

client := &http.Client{
Transport: sentryhttpclient.NewSentryRoundTripper(roundTripper),
}

response, err := client.Do(request)
if err != nil {
t.Fatal(err)
}

if response != nil && response.Body != nil {
response.Body.Close()
}
span.Finish()

if ok := sentry.Flush(testutils.FlushTimeout()); !ok {
t.Fatal("sentry.Flush timed out")
}
close(spansCh)

var got []*sentry.Span
for e := range spansCh {
got = append(got, e...)
}

optstrans := cmp.Options{
cmpopts.IgnoreFields(
sentry.Span{},
"TraceID", "SpanID", "ParentSpanID", "StartTime", "EndTime",
"mu", "parent", "sampleRate", "ctx", "dynamicSamplingContext", "recorder", "finishOnce", "collectProfile", "contexts",
),
}

gotSpan := got[0]
wantSpan := &sentry.Span{
Data: map[string]interface{}{
"http.fragment": string(""),
"http.query": string(""),
"http.request.method": string("POST"),
"http.response.status_code": int(200),
"http.response_content_length": int64(48),
"server.address": string("example.com"),
"server.port": string(""),
},
Name: "POST https://example.com",
Op: "http.client",
Origin: "manual",
Sampled: sentry.SampledTrue,
Status: sentry.SpanStatusOK,
}

if diff := cmp.Diff(wantSpan, gotSpan, optstrans); diff != "" {
t.Errorf("Span mismatch (-want +got):\n%s", diff)
}
}

func TestIntegration_NoParentSpan(t *testing.T) {
spansCh := make(chan []*sentry.Span, 1)

Expand Down
Loading