Skip to content

Commit f466395

Browse files
committed
feat(sentry): add http instrumentation
1 parent 07ba21e commit f466395

7 files changed

Lines changed: 356 additions & 11 deletions

File tree

‎internal/cli/cli.go‎

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -13,9 +13,10 @@ import (
1313
)
1414

1515
type root struct {
16-
Verbose bool `help:"Enable debug mode."`
17-
SentryDSN *url.URL `help:"Sentry DSN for error reporting."`
18-
SentryAppName string `help:"Application name for error reporting." env:"RELEASE_MIRROR_SENTRY_APP_NAME,DEPLOIO_APP_NAME"`
16+
Verbose bool `help:"Enable debug mode."`
17+
SentryDSN *url.URL `help:"Sentry DSN for error reporting."`
18+
SentryAppName string `help:"Application name for error reporting." env:"RELEASE_MIRROR_SENTRY_APP_NAME,DEPLOIO_APP_NAME"`
19+
SentryTracesSampleRate float64 `help:"Fraction of requests traced and reported to Sentry (0 disables tracing)." default:"0"`
1920

2021
Serve ServeCmd `cmd:"" default:"withargs" help:"Serve the release mirror."`
2122
HealthCheck HealthCheckCmd `cmd:"" help:"Check whether the server is healthy."`
@@ -45,14 +46,20 @@ func Run(ctx context.Context, logger *slog.Logger, lvl *slog.LevelVar, info *Bui
4546
lvl.Set(slog.LevelDebug)
4647
}
4748

48-
cleanup, sentryHandler := initSentry(cli.SentryDSN, cli.Verbose, cli.SentryAppName, info, logger.WithGroup("sentry"))
49+
cleanup, sentryHandler := initSentry(sentryOptions{
50+
dsn: cli.SentryDSN,
51+
debug: cli.Verbose,
52+
appName: cli.SentryAppName,
53+
tracesSampleRate: cli.SentryTracesSampleRate,
54+
}, info, logger.WithGroup("sentry"))
4955
defer cleanup()
5056

5157
// Defers run LIFO: reportPanic executes before Sentry flush cleanup.
5258
defer reportPanic()
5359

5460
if sentryHandler != nil {
5561
c.logger = slog.New(fanoutHandler{handlers: []slog.Handler{logger.Handler(), sentryHandler}})
62+
c.sentry = true
5663
}
5764

5865
logger.InfoContext(ctx, "starting",
@@ -69,4 +76,5 @@ type cmd struct {
6976
logger *slog.Logger
7077
build BuildInfo
7178
w io.Writer
79+
sentry bool
7280
}

‎internal/cli/sentry.go‎

Lines changed: 20 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,22 +15,35 @@ import (
1515
slogsentry "github.com/samber/slog-sentry/v2"
1616
)
1717

18+
// sentryOptions carries the Sentry configuration collected from the CLI flags.
19+
type sentryOptions struct {
20+
dsn *url.URL
21+
debug bool
22+
appName string
23+
tracesSampleRate float64
24+
}
25+
1826
// initSentry initializes Sentry and returns a cleanup flush func and an error-level slog.Handler.
19-
func initSentry(dsn *url.URL, debug bool, appName string, info *BuildInfo, logger *slog.Logger) (func(), slog.Handler) {
20-
if dsn == nil || dsn.String() == "" {
21-
logger.Debug("no DSN provided", "dsn", dsn)
27+
func initSentry(o sentryOptions, info *BuildInfo, logger *slog.Logger) (func(), slog.Handler) {
28+
if o.dsn == nil || o.dsn.String() == "" {
29+
logger.Debug("no DSN provided", "dsn", o.dsn)
2230
return func() {}, nil
2331
}
2432

25-
logger.Debug("initializing", "debug", debug)
33+
logger.Debug("initializing", "debug", o.debug, "traces_sample_rate", o.tracesSampleRate)
2634
if err := sentry.Init(sentry.ClientOptions{
27-
Dsn: dsn.String(),
28-
Debug: debug,
35+
Dsn: o.dsn.String(),
36+
Debug: o.debug,
2937
DebugWriter: sentryLogWriter{logger: logger, lvl: slog.LevelDebug},
3038
DataCollection: &sentry.DataCollection{},
31-
ServerName: appName,
39+
ServerName: o.appName,
3240
Release: info.Commit,
3341
AttachStacktrace: true,
42+
// Performance data is opt-in: without a sample rate the HTTP
43+
// instrumentation still scopes and reports errors, but transactions
44+
// are dropped before delivery.
45+
EnableTracing: o.tracesSampleRate > 0,
46+
TracesSampleRate: o.tracesSampleRate,
3447
HTTPClient: &http.Client{
3548
Timeout: 5 * time.Second,
3649
Transport: gzhttp.Transport(http.DefaultTransport),

‎internal/cli/serve.go‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,9 @@ func (s *ServeCmd) Run(ctx context.Context, c *cmd) error {
5353
if metricsEnabled {
5454
opts = append(opts, server.WithMetrics())
5555
}
56+
if c.sentry {
57+
opts = append(opts, server.WithSentry(s.traceTargets()...))
58+
}
5659
srv, err := server.New(opts...)
5760
if err != nil {
5861
return fmt.Errorf("create server: %w", err)
@@ -172,6 +175,18 @@ func (s *ServeCmd) mirror(ctx context.Context, srv *server.Server, logger *slog.
172175
return m, nil
173176
}
174177

178+
// traceTargets returns the hosts Sentry may propagate a trace to. Only the
179+
// object store qualifies: every other outgoing request fetches an asset from an
180+
// upstream release host, which is a third party and has no use for our trace.
181+
// An unparsable endpoint yields no target and is reported by the S3 client.
182+
func (s *ServeCmd) traceTargets() []string {
183+
host, _, err := s.endpoint()
184+
if err != nil {
185+
return nil
186+
}
187+
return []string{host}
188+
}
189+
175190
func (s *ServeCmd) address() string {
176191
return cmp.Or(s.Bind, os.Getenv("ADDR"), ":"+cmp.Or(os.Getenv("PORT"), "8080"))
177192
}

‎internal/server/client.go‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package server
33
import (
44
"net/http"
55

6+
sentryhttpclient "github.com/getsentry/sentry-go/httpclient"
67
"github.com/go-chi/metrics"
78
"github.com/go-chi/traceid"
89
"github.com/go-chi/transport"
@@ -17,12 +18,33 @@ func (s *Server) HTTPClient() *http.Client {
1718
}
1819
}
1920

21+
// noTracePropagation is a target that cannot occur in a request URL. It disables
22+
// trace propagation, which sentryhttpclient has no explicit option for: it reads
23+
// an empty target list as "every host is a target".
24+
const noTracePropagation = "\x00"
25+
2026
// Transport returns an [http.RoundTripper] configured with user agent, trace ID, and metrics.
27+
// With [WithSentry] it also records an http.client span per outgoing request to a
28+
// trace propagation target and propagates the trace to it.
2129
func (s *Server) Transport() http.RoundTripper {
30+
// Chain drops nil middlewares, so a disabled Sentry adds nothing to the chain.
31+
var sentryTransport func(http.RoundTripper) http.RoundTripper
32+
if s.sentry {
33+
targets := s.sentryTargets
34+
if len(targets) == 0 {
35+
targets = []string{noTracePropagation}
36+
}
37+
sentryTransport = func(next http.RoundTripper) http.RoundTripper {
38+
return sentryhttpclient.NewSentryRoundTripper(next,
39+
sentryhttpclient.WithTracePropagationTargets(targets))
40+
}
41+
}
42+
2243
return transport.Chain(
2344
gzhttp.Transport(http.DefaultTransport),
2445
transport.SetHeader("User-Agent", s.buildInfo.Name+"/"+s.buildInfo.Version),
2546
traceid.Transport,
2647
metrics.Transport(metrics.TransportOpts{Host: true}),
48+
sentryTransport,
2749
)
2850
}

‎internal/server/sentry.go‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
package server
2+
3+
import (
4+
"net/http"
5+
6+
"github.com/getsentry/sentry-go"
7+
sentryhttp "github.com/getsentry/sentry-go/http"
8+
"github.com/go-chi/chi/v5"
9+
)
10+
11+
// sentryHandler returns the Sentry request middleware.
12+
func sentryHandler() func(http.Handler) http.Handler {
13+
return sentryhttp.New(sentryhttp.Options{Repanic: true}).Handle
14+
}
15+
16+
// sentryRouteName names the transaction after the matched chi route pattern.
17+
func sentryRouteName(next http.Handler) http.Handler {
18+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
19+
// The pattern is only known once routing has run, so rename on the way out.
20+
// This defer runs before sentryhttp finishes the transaction.
21+
defer nameTransaction(r)
22+
23+
next.ServeHTTP(w, r)
24+
})
25+
}
26+
27+
// nameTransaction replaces the transaction name of r with its chi route pattern.
28+
// It is a no-op when r is not instrumented or did not match a route.
29+
func nameTransaction(r *http.Request) {
30+
ctx := r.Context()
31+
tx := sentry.TransactionFromContext(ctx)
32+
rctx := chi.RouteContext(ctx)
33+
if tx == nil || rctx == nil {
34+
return
35+
}
36+
pattern := rctx.RoutePattern()
37+
if pattern == "" {
38+
return
39+
}
40+
tx.Name = r.Method + " " + pattern
41+
tx.Source = sentry.SourceRoute
42+
}

0 commit comments

Comments
 (0)