Skip to content
Open
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
36 changes: 25 additions & 11 deletions crosstest/http_link_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -180,13 +180,12 @@ func TestHTTPFamilyIntegrationsLinkManualErrorsLogsMetricsAndPanicsToOTel(t *tes
t.Parallel()
f := sentrytest.NewFixture(t, otelOpts()...)
const identifier = "fiber"
baseCtx := sentry.SetHubOnContext(context.Background(), f.Hub)
baseCtx := f.NewContext(context.Background())
logger := sentry.NewLogger(baseCtx)
meter := sentry.NewMeter(baseCtx)
app := fiber.New()
app.Use(func(c *fiber.Ctx) error {
c.SetUserContext(sentry.SetHubOnContext(otelCtx, f.Hub))
sentryfiber.SetHubOnContext(c, f.Hub)
c.SetUserContext(f.NewContext(otelCtx))
return c.Next()
})
app.Use(sentryfiber.New(sentryfiber.Options{WaitForDelivery: true}))
Expand All @@ -211,13 +210,12 @@ func TestHTTPFamilyIntegrationsLinkManualErrorsLogsMetricsAndPanicsToOTel(t *tes
t.Parallel()
f := sentrytest.NewFixture(t, otelOpts()...)
const identifier = "fiberv3"
baseCtx := sentry.SetHubOnContext(context.Background(), f.Hub)
baseCtx := f.NewContext(context.Background())
logger := sentry.NewLogger(baseCtx)
meter := sentry.NewMeter(baseCtx)
app := fiberv3.New()
app.Use(func(c fiberv3.Ctx) error {
c.SetContext(sentry.SetHubOnContext(otelCtx, f.Hub))
sentryfiberv3.SetHubOnContext(c, f.Hub)
c.SetContext(f.NewContext(otelCtx))
return c.Next()
})
app.Use(sentryfiberv3.New(sentryfiberv3.Options{WaitForDelivery: true}))
Expand All @@ -237,10 +235,26 @@ func TestHTTPFamilyIntegrationsLinkManualErrorsLogsMetricsAndPanicsToOTel(t *tes
f.Flush()
requireRequestSignalsLinked(t, f.Events(), traceID, spanID, identifier)
})
}

func TestFastHTTPOTelValidationGap(t *testing.T) {
_ = sentryfasthttp.New
_ = fasthttp.RequestCtx{}
t.Skip("fasthttp does not preserve a standard request context that the OTel integration can resolve automatically today")
t.Run("fasthttp", func(t *testing.T) {
t.Parallel()
sentrytest.Run(t, func(t *testing.T, f *sentrytest.Fixture) {
const identifier = "fasthttp"
baseCtx := f.NewContext(context.Background())
logger := sentry.NewLogger(baseCtx)
meter := sentry.NewMeter(baseCtx)
handler := sentryfasthttp.New(sentryfasthttp.Options{WaitForDelivery: true}).Handle(func(ctx *fasthttp.RequestCtx) {
sendContextSignals(sentryfasthttp.GetContext(ctx), identifier, logger, meter)
})

ctx := &fasthttp.RequestCtx{}
ctx.Request.SetRequestURI("http://example.com/test")
ctx.Request.Header.SetMethod(http.MethodGet)
sentryfasthttp.SetContext(f.NewContext(otelCtx), ctx)
handler(ctx)

f.Flush()
requireRequestSignalsLinked(t, f.Events(), traceID, spanID, identifier)
}, otelOpts()...)
})
}
20 changes: 7 additions & 13 deletions fasthttp/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,18 +69,15 @@ Timeout time.Duration

## Usage

`sentryfasthttp` attaches an instance of `*sentry.Hub` (https://pkg.go.dev/github.com/getsentry/sentry-go#Hub) to the request's context, which makes it available throughout the rest of the request's lifetime.
You can access it by using the `sentryfasthttp.GetHubFromContext()` method on the context itself in any of your proceeding middleware and routes.
And it should be used instead of the global `sentry.CaptureMessage`, `sentry.CaptureException`, or any other calls, as it keeps the separation of data between the requests.
`sentryfasthttp` stores a request-specific standard Go context containing a `*sentry.Scope` and transaction on `fasthttp.RequestCtx`. Pass `sentryfasthttp.GetContext(ctx)` to capture functions such as `sentry.CaptureMessage` and `sentry.CaptureException` so request data, custom scope data, and trace information are applied to the event.
Use `sentry.ScopeFromContext(sentryfasthttp.GetContext(ctx))` when you need to add data that should be available to captures made during the request.

**Keep in mind that `*sentry.Hub` won't be available in middleware attached before to `sentryfasthttp`!**
**Keep in mind that the request scope won't be available in middleware attached before `sentryfasthttp`!**

```go
func enhanceSentryEvent(handler fasthttp.RequestHandler) fasthttp.RequestHandler {
return func(ctx *fasthttp.RequestCtx) {
if hub := sentryfasthttp.GetHubFromContext(ctx); hub != nil {
hub.Scope().SetTag("someRandomTag", "maybeYouNeedIt")
}
sentry.ScopeFromContext(sentryfasthttp.GetContext(ctx)).SetTag("someRandomTag", "maybeYouNeedIt")
handler(ctx)
}
}
Expand All @@ -92,12 +89,9 @@ sentryHandler := sentryfasthttp.New(sentryfasthttp.Options{
})

defaultHandler := func(ctx *fasthttp.RequestCtx) {
if hub := sentryfasthttp.GetHubFromContext(ctx); hub != nil {
hub.WithScope(func(scope *sentry.Scope) {
scope.SetTag("unwantedQuery", "someQueryDataMaybe")
hub.CaptureMessage("User provided unwanted query string, but we recovered just fine")
})
}
scope := sentry.ScopeFromContext(sentryfasthttp.GetContext(ctx))
scope.SetTag("unwantedQuery", "someQueryDataMaybe")
sentry.CaptureMessage(sentryfasthttp.GetContext(ctx), "User provided unwanted query string, but we recovered just fine")
ctx.SetStatusCode(fasthttp.StatusOK)
}

Expand Down
5 changes: 5 additions & 0 deletions fasthttp/go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,18 @@ replace github.com/getsentry/sentry-go => ../
require (
github.com/getsentry/sentry-go v0.49.0
github.com/google/go-cmp v0.7.0
github.com/stretchr/testify v1.11.1
github.com/valyala/fasthttp v1.71.0
)

require (
github.com/andybalholm/brotli v1.2.1 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/klauspost/compress v1.18.6 // indirect
github.com/kr/text v0.2.0 // indirect
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
golang.org/x/sys v0.47.0 // indirect
golang.org/x/text v0.41.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
10 changes: 10 additions & 0 deletions fasthttp/go.sum
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
github.com/andybalholm/brotli v1.2.1 h1:R+f5xP285VArJDRgowrfb9DqL18yVK0gKAW/F+eTWro=
github.com/andybalholm/brotli v1.2.1/go.mod h1:rzTDkvFWvIrjDXZHkuS16NPggd91W3kUSvPlQ1pLaKY=
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/go-errors/errors v1.4.2 h1:J6MZopCL4uSllY1OfXM374weqZFFItUbrImctkmUxIA=
Expand All @@ -8,12 +9,18 @@ github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
github.com/klauspost/compress v1.18.6 h1:2jupLlAwFm95+YDR+NwD2MEfFO9d4z4Prjl1XXDjuao=
github.com/klauspost/compress v1.18.6/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/pingcap/errors v0.11.4 h1:lFuQV/oaUMGcD2tqt+01ROSmJs75VG1ToEOkZIZ4nE4=
github.com/pingcap/errors v0.11.4/go.mod h1:Oi8TUi2kEtXXLMJk9l1cGmz20kV3TaQ0usTwv5KuLY8=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
Expand All @@ -28,5 +35,8 @@ golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
126 changes: 75 additions & 51 deletions fasthttp/sentryfasthttp.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,19 +10,26 @@ import (

"github.com/getsentry/sentry-go"
"github.com/getsentry/sentry-go/internal/debuglog"
"github.com/getsentry/sentry-go/internal/traceutils"
"github.com/valyala/fasthttp"
)

const (
// sdkIdentifier is the identifier of the FastHTTP SDK.
sdkIdentifier = "sentry.go.fasthttp"
// sdkIdentifier is the identifier of the FastHTTP SDK.
const sdkIdentifier = "sentry.go.fasthttp"

// valuesKey is used as a key to store the Sentry Hub instance on the fasthttp.RequestCtx.
valuesKey = "sentry"
type contextKey struct{}

// transactionKey is used as a key to store the Sentry transaction on the fasthttp.RequestCtx.
transactionKey = "sentry_transaction"
)
type storedContext struct {
ctx context.Context
cancel context.CancelFunc
active bool
}

// Close lets fasthttp release the request context when it resets user values.
func (ctx *storedContext) Close() error {
ctx.cancel()
return nil
}

type Handler struct {
repanic bool
Expand Down Expand Up @@ -59,85 +66,102 @@ func New(options Options) *Handler {
// Handle wraps fasthttp.RequestHandler and recovers from caught panics.
func (h *Handler) Handle(handler fasthttp.RequestHandler) fasthttp.RequestHandler {
return func(ctx *fasthttp.RequestCtx) {
hub := GetHubFromContext(ctx)
if hub == nil {
hub = sentry.CurrentHub().Clone()
parentCtx := GetContext(ctx)
created := sentry.SpanFromContext(parentCtx) == nil
previous, _ := ctx.UserValue(contextKey{}).(*storedContext)
if previous != nil && !previous.active {
previous.cancel()
parentCtx = context.Background()
created = true
Comment thread
cursor[bot] marked this conversation as resolved.
}
requestCtx, cancel := context.WithCancel(parentCtx)
storedCtx := &storedContext{ctx: requestCtx, cancel: cancel, active: true}
ctx.SetUserValue(contextKey{}, storedCtx)
Comment thread
giortzisg marked this conversation as resolved.
defer func() {
storedCtx.active = false
if previous != nil && previous.active {
ctx.SetUserValue(contextKey{}, previous)
}
}()
defer func() {
if ctx.LastTimeoutErrorResponse() != nil {
cancel()
}
}()
requestCtx, scope := sentry.WithIsolationScope(requestCtx)

if client := hub.Client(); client != nil {
client.SetSDKIdentifier(sdkIdentifier)
}
sentry.ClientFromContext(requestCtx).SetSDKIdentifier(sdkIdentifier)

r := convert(ctx)

options := []sentry.SpanOption{
sentry.ContinueTrace(r.Header.Get(sentry.SentryTraceHeader), r.Header.Get(sentry.SentryBaggageHeader)),
traceutils.ContinueFromRequest(r),
sentry.WithOpName("http.server"),
sentry.WithTransactionSource(sentry.SourceURL),
sentry.WithSpanOrigin(sentry.SpanOriginFastHTTP),
}

transaction := sentry.StartTransaction(
sentry.SetHubOnContext(ctx, hub),
requestCtx,
fmt.Sprintf("%s %s", r.Method, string(ctx.Path())),
options...,
)
defer func() {
status := ctx.Response.StatusCode()
transaction.Status = sentry.HTTPtoSpanStatus(status)
transaction.SetData("http.response.status_code", status)
transaction.Finish()
}()

transaction.SetData("http.request.method", r.Method)
if created {
requestCtx = transaction.Context()
transaction.SetData("http.request.method", r.Method)
defer func() {
status := ctx.Response.StatusCode()
transaction.Status = sentry.HTTPtoSpanStatus(status)
transaction.SetData("http.response.status_code", status)
transaction.Finish()
}()
}
storedCtx.ctx = requestCtx
r = r.WithContext(requestCtx)

scope := hub.Scope()
scope.SetRequest(r)
scope.SetRequestBody(bytes.Clone(ctx.Request.Body()))
ctx.SetUserValue(valuesKey, hub)
ctx.SetUserValue(transactionKey, transaction)
defer h.recoverWithSentry(hub, ctx)
defer h.recoverWithSentry(requestCtx, ctx, cancel)

handler(ctx)
}
}

func (h *Handler) recoverWithSentry(hub *sentry.Hub, ctx *fasthttp.RequestCtx) {
func (h *Handler) recoverWithSentry(requestCtx context.Context, ctx *fasthttp.RequestCtx, cancel context.CancelFunc) {
if err := recover(); err != nil {
eventID := hub.RecoverWithContext(
context.WithValue(context.Background(), sentry.RequestContextKey, ctx),
err,
)
requestCtx = context.WithValue(requestCtx, sentry.RequestContextKey, ctx)
eventID := sentry.Recover(requestCtx, err)
if eventID != nil && h.waitForDelivery {
hub.Flush(h.timeout)
sentry.ClientFromContext(requestCtx).Flush(h.timeout)
}
if h.repanic {
cancel()
panic(err)
}
}
}

// GetHubFromContext retrieves attached *sentry.Hub instance from fasthttp.RequestCtx.
func GetHubFromContext(ctx *fasthttp.RequestCtx) *sentry.Hub {
hub := ctx.UserValue(valuesKey)
if hub, ok := hub.(*sentry.Hub); ok {
return hub
// GetContext retrieves the request context from fasthttp.RequestCtx.
func GetContext(ctx *fasthttp.RequestCtx) context.Context {
if storedCtx, ok := ctx.UserValue(contextKey{}).(*storedContext); ok {
return storedCtx.ctx
}
return nil
}

// SetHubOnContext attaches the *sentry.Hub instance to the fasthttp.RequestCtx.
func SetHubOnContext(ctx *fasthttp.RequestCtx, hub *sentry.Hub) {
ctx.SetUserValue(valuesKey, hub)
if requestCtx, ok := ctx.UserValue(contextKey{}).(context.Context); ok {
return requestCtx
}
return context.Background()
}

// GetSpanFromContext retrieves attached *sentry.Span instance from *fasthttp.RequestCtx.
// If there is no transaction on *fasthttp.RequestCtx, it will return nil.
func GetSpanFromContext(ctx *fasthttp.RequestCtx) *sentry.Span {
if span, ok := ctx.UserValue(transactionKey).(*sentry.Span); ok {
return span
// SetContext attaches a request context to fasthttp.RequestCtx.
func SetContext(requestCtx context.Context, ctx *fasthttp.RequestCtx) {
if storedCtx, ok := ctx.UserValue(contextKey{}).(*storedContext); ok {
if storedCtx.active {
storedCtx.ctx = requestCtx
return
}
storedCtx.cancel()
}
return nil
ctx.SetUserValue(contextKey{}, requestCtx)
}

func convert(ctx *fasthttp.RequestCtx) *http.Request {
Expand Down
Loading
Loading