Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
28 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
389ca62
Merge branch 'master' into feat/httpclient
aldy505 Oct 23, 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
Prev Previous commit
Next Next commit
feat(spans): only start 'http.client' op as a child span
  • Loading branch information
aldy505 committed Sep 4, 2024
commit 15aa59a64d9636c15483d91f8d7dce1d73bec8d4
9 changes: 7 additions & 2 deletions httpclient/sentryhttpclient.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,15 @@ type SentryRoundTripper struct {
}

func (s *SentryRoundTripper) RoundTrip(request *http.Request) (*http.Response, error) {
ctx := request.Context()
// Only create the `http.client` span only if there is a parent span.
parentSpan := sentry.GetSpanFromContext(request.Context())
if parentSpan == nil {
return s.originalRoundTripper.RoundTrip(request)
}
Comment on lines 95 to 104
Copy link
Contributor Author

Choose a reason for hiding this comment

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

A quick note why I prefer this instead of creating a sentry.WithOnlyIfParentExists() (a SpanOption type):

I used the JS SDK a lot at work lately, and I've been wondering the entire week, on their startSpan function, they have this as an option: https://github.com/getsentry/sentry-javascript/blob/216aaeba1ee27cce8a4876e1f9212ba374eb30b3/packages/types/src/startSpanOptions.ts#L14-L15

Should the Go SDK move forward with that, as a SpanOption or not?

We could to the SpanOption thing, but it feels really weird since the way Go SDK handles scopes/hubs with span is to add the span pointer into the scope. See

sentry-go/tracing.go

Lines 196 to 199 in a6acd05

if clientOptions.EnableTracing {
hub := hubFromContext(ctx)
hub.Scope().SetSpan(&span)
}

Although we could just not call the scope.SetSpan() function, I don't know about the behavior if this span that we're creating will ever have a child span being created manually by the user.


cleanRequestURL := request.URL.Redacted()

span := sentry.StartSpan(ctx, "http.client", sentry.WithTransactionName(fmt.Sprintf("%s %s", request.Method, cleanRequestURL)))
span := parentSpan.StartChild("http.client", sentry.WithTransactionName(fmt.Sprintf("%s %s", request.Method, cleanRequestURL)))
span.Tags = s.tags
Copy link
Member

Choose a reason for hiding this comment

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

Why are we setting span tags here?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Is it not ideal? Should I remove it?

Copy link
Member

Choose a reason for hiding this comment

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

What info is in there?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Decided to just remove it.

defer span.Finish()

Expand Down
109 changes: 64 additions & 45 deletions httpclient/sentryhttpclient_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"io"
"net/http"
"strconv"
"strings"
"testing"

"github.com/getsentry/sentry-go"
Expand Down Expand Up @@ -52,15 +53,15 @@ func TestIntegration(t *testing.T) {
TracerOptions []sentryhttpclient.SentryRoundTripTracerOption
WantStatus int
WantResponseLength int
WantTransaction *sentry.Event
WantSpan *sentry.Span
}{
{
RequestMethod: "GET",
RequestURL: "https://example.com/foo",
WantStatus: 200,
WantResponseLength: 0,
WantTransaction: &sentry.Event{
Extra: map[string]interface{}{
WantSpan: &sentry.Span{
Data: map[string]interface{}{
"http.fragment": string(""),
"http.query": string(""),
"http.request.method": string("GET"),
Expand All @@ -69,11 +70,12 @@ func TestIntegration(t *testing.T) {
"server.address": string("example.com"),
"server.port": string(""),
},
Level: sentry.LevelInfo,
Transaction: "GET https://example.com/foo",
Type: "transaction",
TransactionInfo: &sentry.TransactionInfo{Source: "custom"},
Tags: map[string]string{},
Name: "GET https://example.com/foo",
Op: "http.client",
Tags: map[string]string{},
Origin: "manual",
Sampled: sentry.SampledTrue,
Status: sentry.SpanStatusOK,
},
},
{
Expand All @@ -82,8 +84,8 @@ func TestIntegration(t *testing.T) {
TracerOptions: []sentryhttpclient.SentryRoundTripTracerOption{nil, nil, nil},
WantStatus: 200,
WantResponseLength: 0,
WantTransaction: &sentry.Event{
Extra: map[string]interface{}{
WantSpan: &sentry.Span{
Data: map[string]interface{}{
"http.fragment": string("readme"),
"http.query": string("baz=123"),
"http.request.method": string("GET"),
Expand All @@ -92,11 +94,12 @@ func TestIntegration(t *testing.T) {
"server.address": string("example.com"),
"server.port": string("443"),
},
Level: sentry.LevelInfo,
Transaction: "GET https://example.com:443/foo/bar?baz=123#readme",
Type: "transaction",
TransactionInfo: &sentry.TransactionInfo{Source: "custom"},
Tags: map[string]string{},
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 @@ -105,8 +108,8 @@ func TestIntegration(t *testing.T) {
TracerOptions: []sentryhttpclient.SentryRoundTripTracerOption{sentryhttpclient.WithTag("user", "def"), sentryhttpclient.WithTags(map[string]string{"domain": "example.com"})},
WantStatus: 400,
WantResponseLength: 0,
WantTransaction: &sentry.Event{
Extra: map[string]interface{}{
WantSpan: &sentry.Span{
Data: map[string]interface{}{
"http.fragment": string(""),
"http.query": string("abc=def&bar=123"),
"http.request.method": string("HEAD"),
Expand All @@ -119,19 +122,20 @@ func TestIntegration(t *testing.T) {
"user": "def",
"domain": "example.com",
},
Level: sentry.LevelInfo,
Transaction: "HEAD https://example.com:8443/foo?bar=123&abc=def",
Type: "transaction",
TransactionInfo: &sentry.TransactionInfo{Source: "custom"},
Name: "HEAD https://example.com:8443/foo?bar=123&abc=def",
Op: "http.client",
Origin: "manual",
Sampled: sentry.SampledTrue,
Status: sentry.SpanStatusInvalidArgument,
},
},
{
RequestMethod: "POST",
RequestURL: "https://john:[email protected]:4321/secret",
WantStatus: 200,
WantResponseLength: 1024,
WantTransaction: &sentry.Event{
Extra: map[string]interface{}{
WantSpan: &sentry.Span{
Data: map[string]interface{}{
"http.fragment": string(""),
"http.query": string(""),
"http.request.method": string("POST"),
Expand All @@ -140,33 +144,35 @@ func TestIntegration(t *testing.T) {
"server.address": string("example.com"),
"server.port": string("4321"),
},
Level: sentry.LevelInfo,
Transaction: "POST https://john:[email protected]:4321/secret",
Type: "transaction",
TransactionInfo: &sentry.TransactionInfo{Source: "custom"},
Tags: map[string]string{},
Name: "POST https://john:[email protected]:4321/secret",
Op: "http.client",
Tags: map[string]string{},
Origin: "manual",
Sampled: sentry.SampledTrue,
Status: sentry.SpanStatusOK,
},
},
}

transactionsCh := make(chan *sentry.Event, len(tests))
spansCh := make(chan []*sentry.Span, len(tests))

sentryClient, err := sentry.NewClient(sentry.ClientOptions{
EnableTracing: true,
TracesSampleRate: 1.0,
BeforeSendTransaction: func(event *sentry.Event, hint *sentry.EventHint) *sentry.Event {
transactionsCh <- event
spansCh <- event.Spans
return event
},
})
if err != nil {
t.Fatal(err)
}

var want []*sentry.Event
for _, tt := range tests {
hub := sentry.NewHub(sentryClient, sentry.NewScope())
ctx := sentry.SetHubOnContext(context.Background(), hub)
span := sentry.StartSpan(ctx, "fake_parent", sentry.WithTransactionName("Fake Parent"))
ctx = span.Context()

request, err := http.NewRequestWithContext(ctx, tt.RequestMethod, tt.RequestURL, nil)
if err != nil {
Expand All @@ -188,32 +194,45 @@ func TestIntegration(t *testing.T) {
}

response.Body.Close()
want = append(want, tt.WantTransaction)
span.Finish()
}

if ok := sentryClient.Flush(testutils.FlushTimeout()); !ok {
t.Fatal("sentry.Flush timed out")
}
close(transactionsCh)
var got []*sentry.Event
for e := range transactionsCh {
close(spansCh)

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

optstrans := cmp.Options{
cmpopts.IgnoreFields(
sentry.Event{},
"Contexts", "EventID", "Platform", "Modules",
"Release", "Sdk", "ServerName", "Timestamp",
"sdkMetaData", "StartTime", "Spans",
),
cmpopts.IgnoreFields(
sentry.Request{},
"Env",
sentry.Span{},
"TraceID", "SpanID", "ParentSpanID", "StartTime", "EndTime",
"mu", "parent", "sampleRate", "ctx", "dynamicSamplingContext", "recorder", "finishOnce", "collectProfile", "contexts",
),
}
if diff := cmp.Diff(want, got, optstrans); diff != "" {
t.Fatalf("Transaction mismatch (-want +got):\n%s", diff)
for i, tt := range tests {
var foundMatch = false
gotSpans := got[i]

var diffs []string
for _, gotSpan := range gotSpans {
if diff := cmp.Diff(tt.WantSpan, gotSpan, optstrans); diff != "" {
diffs = append(diffs, diff)
} else {
foundMatch = true
break
}
}

if foundMatch {
continue
} else {
t.Errorf("Span mismatch (-want +got):\n%s", strings.Join(diffs, "\n"))
}
}
}

Expand Down
11 changes: 11 additions & 0 deletions tracing.go
Original file line number Diff line number Diff line change
Expand Up @@ -206,6 +206,17 @@ func StartSpan(ctx context.Context, operation string, options ...SpanOption) *Sp
return &span
}

// GetSpanFromContext retrieves attached *sentry.Span instance from context.Context.
// If there are no spans, it will return nil.
func GetSpanFromContext(ctx context.Context) *Span {
span, ok := ctx.Value(spanContextKey{}).(*Span)
if ok {
return span
}

return nil
}

// Finish sets the span's end time, unless already set. If the span is the root
// of a span tree, Finish sends the span tree to Sentry as a transaction.
//
Expand Down
22 changes: 22 additions & 0 deletions tracing_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1091,3 +1091,25 @@ func TestSpanFinishConcurrentlyWithoutRaces(_ *testing.T) {

time.Sleep(50 * time.Millisecond)
}

func TestGetSpanFromContext(t *testing.T) {
t.Run("Exists", func(t *testing.T) {
span := StartSpan(context.Background(), "something")

value := GetSpanFromContext(span.Context())
if value == nil {
t.Error("expecting `value` to be not nil")
} else {
if span.Op != "something" {
t.Errorf("expecting `span.Op` to be 'something', instead got %q", span.Op)
}
}
})

t.Run("Nil", func(t *testing.T) {
value := GetSpanFromContext(context.Background())
if value != nil {
t.Error("expecting `value` to be nil")
}
})
}