Update dependencies

This commit is contained in:
eleksir
2026-02-10 20:54:39 +03:00
parent f2fc168abe
commit 170d0d0ed4
559 changed files with 66718 additions and 72415 deletions

View File

@@ -11,3 +11,9 @@ coverage:
default:
# Do not fail the commit status if the coverage was reduced up to this value
threshold: 0.5%
patch:
default:
informational: true
ignore:
- "log_fallback.go"
- "internal/testutils"

View File

@@ -1,5 +1,8 @@
minVersion: 0.35.0
changelogPolicy: simple
minVersion: 2.14.0
changelog:
policy: auto
versioning:
policy: auto
artifactProvider:
name: none
targets:
@@ -8,6 +11,33 @@ targets:
- name: github
tagPrefix: otel/v
tagOnly: true
- name: github
tagPrefix: echo/v
tagOnly: true
- name: github
tagPrefix: fasthttp/v
tagOnly: true
- name: github
tagPrefix: fiber/v
tagOnly: true
- name: github
tagPrefix: gin/v
tagOnly: true
- name: github
tagPrefix: iris/v
tagOnly: true
- name: github
tagPrefix: negroni/v
tagOnly: true
- name: github
tagPrefix: logrus/v
tagOnly: true
- name: github
tagPrefix: slog/v
tagOnly: true
- name: github
tagPrefix: zerolog/v
tagOnly: true
- name: registry
sdks:
github:getsentry/sentry-go:

View File

@@ -12,3 +12,6 @@ TODO.md
# IDE system files
.idea
.vscode
# Local Claude Code settings that should not be committed
.claude/settings.local.json

View File

@@ -1,20 +1,17 @@
version: "2"
linters:
disable-all: true
default: none
enable:
- bodyclose
- dogsled
- dupl
- errcheck
- exportloopref
- gochecknoinits
- goconst
- gocritic
- gocyclo
- godot
- gofmt
- goimports
- gosec
- gosimple
- govet
- ineffassign
- misspell
@@ -22,25 +19,44 @@ linters:
- prealloc
- revive
- staticcheck
- typecheck
- unconvert
- unparam
- unused
- whitespace
issues:
exclude-rules:
- path: _test\.go
linters:
- goconst
- prealloc
- path: _test\.go
text: "G306:"
linters:
- gosec
- path: errors_test\.go
linters:
- unused
- path: http/example_test\.go
linters:
- errcheck
- bodyclose
exclusions:
generated: lax
presets:
- comments
- common-false-positives
- legacy
- std-error-handling
rules:
- linters:
- goconst
- prealloc
path: _test\.go
- linters:
- gosec
path: _test\.go
text: 'G306:'
- linters:
- unused
path: errors_test\.go
- linters:
- bodyclose
- errcheck
path: http/example_test\.go
paths:
- third_party$
- builtin$
- examples$
formatters:
enable:
- gofmt
- goimports
exclusions:
generated: lax
paths:
- third_party$
- builtin$
- examples$

View File

@@ -1,5 +1,583 @@
# Changelog
## 0.42.0
### Breaking Changes 🛠
- refactor Telemetry Processor to use TelemetryItem instead of ItemConvertible by @giortzisg in [#1180](https://github.com/getsentry/sentry-go/pull/1180)
- remove ToEnvelopeItem from single log items
- rename TelemetryBuffer to Telemetry Processor to adhere to spec
- remove unsed ToEnvelopeItem(dsn) from Event.
### New Features ✨
- Add metric support by @aldy505 in [#1151](https://github.com/getsentry/sentry-go/pull/1151)
- support for three metric methods (counter, gauge, distribution)
- custom metric units
- unexport batchlogger
### Internal Changes 🔧
#### Release
- Fix changelog-preview permissions by @BYK in [#1181](https://github.com/getsentry/sentry-go/pull/1181)
- Switch from action-prepare-release to Craft by @BYK in [#1167](https://github.com/getsentry/sentry-go/pull/1167)
#### Other
- (repo) Add Claude Code settings with basic permissions by @philipphofmann in [#1175](https://github.com/getsentry/sentry-go/pull/1175)
- Update release and changelog-preview workflows by @giortzisg in [#1177](https://github.com/getsentry/sentry-go/pull/1177)
- Bump echo to 4.10.1 by @giortzisg in [#1174](https://github.com/getsentry/sentry-go/pull/1174)
## 0.41.0
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.41.0.
### Features
- Add HTTP client integration for distributed tracing via `sentryhttpclient` package ([#876](https://github.com/getsentry/sentry-go/pull/876))
- Provides an `http.RoundTripper` implementation that automatically creates spans for outgoing HTTP requests
- Supports trace propagation targets configuration via `WithTracePropagationTargets` option
- Example usage:
```go
import sentryhttpclient "github.com/getsentry/sentry-go/httpclient"
roundTripper := sentryhttpclient.NewSentryRoundTripper(nil)
client := &http.Client{
Transport: roundTripper,
}
```
- Add `ClientOptions.PropagateTraceparent` option to control W3C `traceparent` header propagation in outgoing HTTP requests ([#1161](https://github.com/getsentry/sentry-go/pull/1161))
- Add `SpanID` field to structured logs ([#1169](https://github.com/getsentry/sentry-go/pull/1169))
## 0.40.0
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.40.0.
### Bug Fixes
- Disable `DisableTelemetryBuffer` flag and noop Telemetry Buffer, to prevent a panic at runtime ([#1149](https://github.com/getsentry/sentry-go/pull/1149)).
## 0.39.0
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.39.0.
### Features
- Drop events from the telemetry buffer when rate-limited or transport is full, allowing the buffer queue to empty itself under load ([#1138](https://github.com/getsentry/sentry-go/pull/1138)).
### Bug Fixes
- Fix scheduler's `hasWork()` method to check if buffers are ready to flush. The previous implementation was causing CPU spikes ([#1143](https://github.com/getsentry/sentry-go/pull/1143)).
## 0.38.0
### Breaking Changes
### Features
- Introduce a new async envelope transport and telemetry buffer to prioritize and batch events ([#1094](https://github.com/getsentry/sentry-go/pull/1094), [#1093](https://github.com/getsentry/sentry-go/pull/1093), [#1107](https://github.com/getsentry/sentry-go/pull/1107)).
- Advantages:
- Prioritized, per-category buffers (errors, transactions, logs, check-ins) reduce starvation and improve resilience under load
- Batching for high-volume logs (up to 100 items or 5s) cuts network overhead
- Bounded memory with eviction policies
- Improved flush behavior with context-aware flushing
- Add `ClientOptions.DisableTelemetryBuffer` to opt out and fall back to the legacy transport layer (`HTTPTransport` / `HTTPSyncTransport`).
```go
err := sentry.Init(sentry.ClientOptions{
Dsn: "__DSN__",
DisableTelemetryBuffer: true, // fallback to legacy transport
})
```
### Notes
- If a custom `Transport` is provided, the SDK automatically disables the telemetry buffer and uses the legacy transport for compatibility.
## 0.37.0
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.37.0.
### Breaking Changes
- Behavioral change for the `TraceIgnoreStatusCodes` option. The option now defaults to ignoring 404 status codes ([#1122](https://github.com/getsentry/sentry-go/pull/1122)).
### Features
- Add `sentry.origin` attribute to structured logs to identify log origin for `slog` and `logrus` integrations (`auto.log.slog`, `auto.log.logrus`) ([#1121](https://github.com/getsentry/sentry-go/pull/1121)).
### Bug Fixes
- Fix `slog` event handler to use the initial context, ensuring events use the correct hub/span when the emission context lacks one ([#1133](https://github.com/getsentry/sentry-go/pull/1133)).
- Improve exception chain processing by checking pointer values when tracking visited errors, avoiding instability for certain wrapped errors ([#1132](https://github.com/getsentry/sentry-go/pull/1132)).
### Misc
- Bump `golang.org/x/net` to v0.38.0 ([#1126](https://github.com/getsentry/sentry-go/pull/1126)).
## 0.36.2
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.36.2.
### Bug Fixes
- Fix context propagation for logs to ensure logger instances correctly inherit span and hub information from their creation context ([#1118](https://github.com/getsentry/sentry-go/pull/1118))
- Logs now properly propagate trace context from the logger's original context, even when emitted in a different context
- The logger will first check the emission context, then fall back to its creation context, and finally to the current hub
## 0.36.1
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.36.1.
### Bug Fixes
- Prevent panic when converting error chains containing non-comparable error types by using a safe fallback for visited detection in exception conversion ([#1113](https://github.com/getsentry/sentry-go/pull/1113))
## 0.36.0
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.36.0.
### Breaking Changes
- Behavioral change for the `MaxBreadcrumbs` client option. Removed the hard limit of 100 breadcrumbs, allowing users to set a larger limit and also changed the default limit from 30 to 100 ([#1106](https://github.com/getsentry/sentry-go/pull/1106)))
- The changes to error handling ([#1075](https://github.com/getsentry/sentry-go/pull/1075)) will affect issue grouping. It is expected that any wrapped and complex errors will be grouped under a new issue group.
### Features
- Add support for improved issue grouping with enhanced error chain handling ([#1075](https://github.com/getsentry/sentry-go/pull/1075))
The SDK now provides better handling of complex error scenarios, particularly when dealing with multiple related errors or error chains. This feature automatically detects and properly structures errors created with Go's `errors.Join()` function and other multi-error patterns.
```go
// Multiple errors are now properly grouped and displayed in Sentry
err1 := errors.New("err1")
err2 := errors.New("err2")
combinedErr := errors.Join(err1, err2)
// When captured, these will be shown as related exceptions in Sentry
sentry.CaptureException(combinedErr)
```
- Add `TraceIgnoreStatusCodes` option to allow filtering of HTTP transactions based on status codes ([#1089](https://github.com/getsentry/sentry-go/pull/1089))
- Configure which HTTP status codes should not be traced by providing single codes or ranges
- Example: `TraceIgnoreStatusCodes: [][]int{{404}, {500, 599}}` ignores 404 and server errors 500-599
### Bug Fixes
- Fix logs being incorrectly filtered by `BeforeSend` callback ([#1109](https://github.com/getsentry/sentry-go/pull/1109))
- Logs now bypass the `processEvent` method and are sent directly to the transport
- This ensures logs are only filtered by `BeforeSendLog`, not by the error/message `BeforeSend` callback
### Misc
- Add support for Go 1.25 and drop support for Go 1.22 ([#1103](https://github.com/getsentry/sentry-go/pull/1103))
## 0.35.3
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.35.3.
### Bug Fixes
- Add missing rate limit categories ([#1082](https://github.com/getsentry/sentry-go/pull/1082))
## 0.35.2
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.35.2.
### Bug Fixes
- Fix OpenTelemetry spans being created as transactions instead of child spans ([#1073](https://github.com/getsentry/sentry-go/pull/1073))
### Misc
- Add `MockTransport` to test clients for improved testing ([#1071](https://github.com/getsentry/sentry-go/pull/1071))
## 0.35.1
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.35.1.
### Bug Fixes
- Fix race conditions when accessing the scope during logging operations ([#1050](https://github.com/getsentry/sentry-go/pull/1050))
- Fix nil pointer dereference with malformed URLs when tracing is enabled in `fasthttp` and `fiber` integrations ([#1055](https://github.com/getsentry/sentry-go/pull/1055))
### Misc
- Bump `github.com/gofiber/fiber/v2` from 2.52.5 to 2.52.9 in `/fiber` ([#1067](https://github.com/getsentry/sentry-go/pull/1067))
## 0.35.0
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.35.0.
### Breaking Changes
- Changes to the logging API ([#1046](https://github.com/getsentry/sentry-go/pull/1046))
The logging API now supports a fluent interface for structured logging with attributes:
```go
// usage before
logger := sentry.NewLogger(ctx)
// attributes weren't being set permanently
logger.SetAttributes(
attribute.String("version", "1.0.0"),
)
logger.Infof(ctx, "Message with parameters %d and %d", 1, 2)
// new behavior
ctx := context.Background()
logger := sentry.NewLogger(ctx)
// Set permanent attributes on the logger
logger.SetAttributes(
attribute.String("version", "1.0.0"),
)
// Chain attributes on individual log entries
logger.Info().
String("key.string", "value").
Int("key.int", 42).
Bool("key.bool", true).
Emitf("Message with parameters %d and %d", 1, 2)
```
### Bug Fixes
- Correctly serialize `FailureIssueThreshold` and `RecoveryThreshold` onto check-in payloads ([#1060](https://github.com/getsentry/sentry-go/pull/1060))
## 0.34.1
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.34.1.
### Bug Fixes
- Allow flush to be used multiple times without issues, particularly for the batch logger ([#1051](https://github.com/getsentry/sentry-go/pull/1051))
- Fix race condition in `Scope.GetSpan()` method by adding proper mutex locking ([#1044](https://github.com/getsentry/sentry-go/pull/1044))
- Guard transport on `Close()` to prevent panic when called multiple times ([#1044](https://github.com/getsentry/sentry-go/pull/1044))
## 0.34.0
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.34.0.
### Breaking Changes
- Logrus structured logging support replaces the `sentrylogrus.Hook` signature from a `*Hook` to an interface.
```go
var hook *sentrylogrus.Hook
hook = sentrylogrus.New(
// ... your setup
)
// should change the definition to
var hook sentrylogrus.Hook
hook = sentrylogrus.New(
// ... your setup
)
```
### Features
- Structured logging support for [slog](https://pkg.go.dev/log/slog). ([#1033](https://github.com/getsentry/sentry-go/pull/1033))
```go
ctx := context.Background()
handler := sentryslog.Option{
EventLevel: []slog.Level{slog.LevelError, sentryslog.LevelFatal}, // Only Error and Fatal as events
LogLevel: []slog.Level{slog.LevelWarn, slog.LevelInfo}, // Only Warn and Info as logs
}.NewSentryHandler(ctx)
logger := slog.New(handler)
logger.Info("hello"))
```
- Structured logging support for [logrus](https://github.com/sirupsen/logrus). ([#1036](https://github.com/getsentry/sentry-go/pull/1036))
```go
logHook, _ := sentrylogrus.NewLogHook(
[]logrus.Level{logrus.InfoLevel, logrus.WarnLevel},
sentry.ClientOptions{
Dsn: "your-dsn",
EnableLogs: true, // Required for log entries
})
defer logHook.Flush(5 * time.Secod)
logrus.RegisterExitHandler(func() {
logHook.Flush(5 * time.Second)
})
logger := logrus.New()
logger.AddHook(logHook)
logger.Infof("hello")
```
- Add support for flushing events with context using `FlushWithContext()`. ([#935](https://github.com/getsentry/sentry-go/pull/935))
```go
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if !sentry.FlushWithContext(ctx) {
// Handle timeout or cancellation
}
```
- Add support for custom fingerprints in slog integration. ([#1039](https://github.com/getsentry/sentry-go/pull/1039))
### Deprecations
- Slog structured logging support replaces `Level` option with `EventLevel` and `LogLevel` options, for specifying fine-grained levels for capturing events and logs.
```go
handler := sentryslog.Option{
EventLevel: []slog.Level{slog.LevelWarn, slog.LevelError, sentryslog.LevelFatal},
LogLevel: []slog.Level{slog.LevelDebug, slog.LevelInfo, slog.LevelWarn, slog.LevelError, sentryslog.LevelFatal},
}.NewSentryHandler(ctx)
```
- Logrus structured logging support replaces `New` and `NewFromClient` functions to `NewEventHook`, `NewEventHookFromClient`, to match the newly added `NewLogHook` functions, and specify the hook type being created each time.
```go
logHook, err := sentrylogrus.NewLogHook(
[]logrus.Level{logrus.InfoLevel},
sentry.ClientOptions{})
eventHook, err := sentrylogrus.NewEventHook([]logrus.Level{
logrus.ErrorLevel,
logrus.FatalLevel,
logrus.PanicLevel,
}, sentry.ClientOptions{})
```
### Bug Fixes
- Fix issue where `ContinueTrace()` would panic when `sentry-trace` header does not exist. ([#1026](https://github.com/getsentry/sentry-go/pull/1026))
- Fix incorrect log level signature in structured logging. ([#1034](https://github.com/getsentry/sentry-go/pull/1034))
- Remove `sentry.origin` attribute from Sentry logger to prevent confusion in spans. ([#1038](https://github.com/getsentry/sentry-go/pull/1038))
- Don't gate user information behind `SendDefaultPII` flag for logs. ([#1032](https://github.com/getsentry/sentry-go/pull/1032))
### Misc
- Add more sensitive HTTP headers to the default list of headers that are scrubbed by default. ([#1008](https://github.com/getsentry/sentry-go/pull/1008))
## 0.33.0
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.33.0.
### Breaking Changes
- Rename the internal `Logger` to `DebugLogger`. This feature was only used when you set `Debug: True` in your `sentry.Init()` call. If you haven't used the Logger directly, no changes are necessary. ([#1012](https://github.com/getsentry/sentry-go/issues/1012))
### Features
- Add support for [Structured Logging](https://docs.sentry.io/product/explore/logs/). ([#1010](https://github.com/getsentry/sentry-go/issues/1010))
```go
logger := sentry.NewLogger(ctx)
logger.Info(ctx, "Hello, Logs!")
```
You can learn more about Sentry Logs on our [docs](https://docs.sentry.io/product/explore/logs/) and the [examples](https://github.com/getsentry/sentry-go/blob/master/_examples/logs/main.go).
- Add new attributes APIs, which are currently only exposed on logs. ([#1007](https://github.com/getsentry/sentry-go/issues/1007))
### Bug Fixes
- Do not push a new scope on `StartSpan`. ([#1013](https://github.com/getsentry/sentry-go/issues/1013))
- Fix an issue where the propagated smapling decision wasn't used. ([#995](https://github.com/getsentry/sentry-go/issues/995))
- [Otel] Prefer `httpRoute` over `httpTarget` for span descriptions. ([#1002](https://github.com/getsentry/sentry-go/issues/1002))
### Misc
- Update `github.com/stretchr/testify` to v1.8.4. ([#988](https://github.com/getsentry/sentry-go/issues/988))
## 0.32.0
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.32.0.
### Breaking Changes
- Bump the minimum Go version to 1.22. The supported versions are 1.22, 1.23 and 1.24. ([#967](https://github.com/getsentry/sentry-go/issues/967))
- Setting any values on `span.Extra` has no effect anymore. Use `SetData(name string, value interface{})` instead. ([#864](https://github.com/getsentry/sentry-go/pull/864))
### Features
- Add a `MockTransport` and `MockScope`. ([#972](https://github.com/getsentry/sentry-go/pull/972))
### Bug Fixes
- Fix writing `*http.Request` in the Logrus JSONFormatter. ([#955](https://github.com/getsentry/sentry-go/issues/955))
### Misc
- Transaction `data` attributes are now seralized as trace context data attributes, allowing you to query these attributes in the [Trace Explorer](https://docs.sentry.io/product/explore/traces/).
## 0.31.1
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.31.1.
### Bug Fixes
- Correct wrong module name for `sentry-go/logrus` ([#950](https://github.com/getsentry/sentry-go/pull/950))
## 0.31.0
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.31.0.
### Breaking Changes
- Remove support for metrics. Read more about the end of the Metrics beta [here](https://sentry.zendesk.com/hc/en-us/articles/26369339769883-Metrics-Beta-Ended-on-October-7th). ([#914](https://github.com/getsentry/sentry-go/pull/914))
- Remove support for profiling. ([#915](https://github.com/getsentry/sentry-go/pull/915))
- Remove `Segment` field from the `User` struct. This field is no longer used in the Sentry product. ([#928](https://github.com/getsentry/sentry-go/pull/928))
- Every integration is now a separate module, reducing the binary size and number of dependencies. Once you update `sentry-go` to latest version, you'll need to `go get` the integration you want to use. For example, if you want to use the `echo` integration, you'll need to run `go get github.com/getsentry/sentry-go/echo` ([#919](github.com/getsentry/sentry-go/pull/919)).
### Features
Add the ability to override `hub` in `context` for integrations that use custom context. ([#931](https://github.com/getsentry/sentry-go/pull/931))
- Add `HubProvider` Hook for `sentrylogrus`, enabling dynamic Sentry hub allocation for each log entry or goroutine. ([#936](https://github.com/getsentry/sentry-go/pull/936))
This change enhances compatibility with Sentry's recommendation of using separate hubs per goroutine. To ensure a separate Sentry hub for each goroutine, configure the `HubProvider` like this:
```go
hook, err := sentrylogrus.New(nil, sentry.ClientOptions{})
if err != nil {
log.Fatalf("Failed to initialize Sentry hook: %v", err)
}
// Set a custom HubProvider to generate a new hub for each goroutine or log entry
hook.SetHubProvider(func() *sentry.Hub {
client, _ := sentry.NewClient(sentry.ClientOptions{})
return sentry.NewHub(client, sentry.NewScope())
})
logrus.AddHook(hook)
```
### Bug Fixes
- Add support for closing worker goroutines started by the `HTTPTranport` to prevent goroutine leaks. ([#894](https://github.com/getsentry/sentry-go/pull/894))
```go
client, _ := sentry.NewClient()
defer client.Close()
```
Worker can be also closed by calling `Close()` method on the `HTTPTransport` instance. `Close` should be called after `Flush` and before terminating the program otherwise some events may be lost.
```go
transport := sentry.NewHTTPTransport()
defer transport.Close()
```
### Misc
- Bump [gin-gonic/gin](https://github.com/gin-gonic/gin) to v1.9.1. ([#946](https://github.com/getsentry/sentry-go/pull/946))
## 0.30.0
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.30.0.
### Features
- Add `sentryzerolog` integration ([#857](https://github.com/getsentry/sentry-go/pull/857))
- Add `sentryslog` integration ([#865](https://github.com/getsentry/sentry-go/pull/865))
- Always set Mechanism Type to generic ([#896](https://github.com/getsentry/sentry-go/pull/897))
### Bug Fixes
- Prevent panic in `fasthttp` and `fiber` integration in case a malformed URL has to be parsed ([#912](https://github.com/getsentry/sentry-go/pull/912))
### Misc
Drop support for Go 1.18, 1.19 and 1.20. The currently supported Go versions are the last 3 stable releases: 1.23, 1.22 and 1.21.
## 0.29.1
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.29.1.
### Bug Fixes
- Correlate errors to the current trace ([#886](https://github.com/getsentry/sentry-go/pull/886))
- Set the trace context when the transaction finishes ([#888](https://github.com/getsentry/sentry-go/pull/888))
### Misc
- Update the `sentrynegroni` integration to use the latest (v3.1.1) version of Negroni ([#885](https://github.com/getsentry/sentry-go/pull/885))
## 0.29.0
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.29.0.
### Breaking Changes
- Remove the `sentrymartini` integration ([#861](https://github.com/getsentry/sentry-go/pull/861))
- The `WrapResponseWriter` has been moved from the `sentryhttp` package to the `internal/httputils` package. If you've imported it previosuly, you'll need to copy the implementation in your project. ([#871](https://github.com/getsentry/sentry-go/pull/871))
### Features
- Add new convenience methods to continue a trace and propagate tracing headers for error-only use cases. ([#862](https://github.com/getsentry/sentry-go/pull/862))
If you are not using one of our integrations, you can manually continue an incoming trace by using `sentry.ContinueTrace()` by providing the `sentry-trace` and `baggage` header received from a downstream SDK.
```go
hub := sentry.CurrentHub()
sentry.ContinueTrace(hub, r.Header.Get(sentry.SentryTraceHeader), r.Header.Get(sentry.SentryBaggageHeader)),
```
You can use `hub.GetTraceparent()` and `hub.GetBaggage()` to fetch the necessary header values for outgoing HTTP requests.
```go
hub := sentry.GetHubFromContext(ctx)
req, _ := http.NewRequest("GET", "http://localhost:3000", nil)
req.Header.Add(sentry.SentryTraceHeader, hub.GetTraceparent())
req.Header.Add(sentry.SentryBaggageHeader, hub.GetBaggage())
```
### Bug Fixes
- Initialize `HTTPTransport.limit` if `nil` ([#844](https://github.com/getsentry/sentry-go/pull/844))
- Fix `sentry.StartTransaction()` returning a transaction with an outdated context on existing transactions ([#854](https://github.com/getsentry/sentry-go/pull/854))
- Treat `Proxy-Authorization` as a sensitive header ([#859](https://github.com/getsentry/sentry-go/pull/859))
- Add support for the `http.Hijacker` interface to the `sentrynegroni` package ([#871](https://github.com/getsentry/sentry-go/pull/871))
- Go version >= 1.23: Use value from `http.Request.Pattern` for HTTP transaction names when using `sentryhttp` & `sentrynegroni` ([#875](https://github.com/getsentry/sentry-go/pull/875))
- Go version >= 1.21: Fix closure functions name grouping ([#877](https://github.com/getsentry/sentry-go/pull/877))
### Misc
- Collect `span` origins ([#849](https://github.com/getsentry/sentry-go/pull/849))
## 0.28.1
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.28.1.
### Bug Fixes
- Implement `http.ResponseWriter` to hook into various parts of the response process ([#837](https://github.com/getsentry/sentry-go/pull/837))
## 0.28.0
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.28.0.
### Features
- Add a `Fiber` performance tracing & error reporting integration ([#795](https://github.com/getsentry/sentry-go/pull/795))
- Add performance tracing to the `Echo` integration ([#722](https://github.com/getsentry/sentry-go/pull/722))
- Add performance tracing to the `FastHTTP` integration ([#732](https://github.com/getsentry/sentry-go/pull/723))
- Add performance tracing to the `Iris` integration ([#809](https://github.com/getsentry/sentry-go/pull/809))
- Add performance tracing to the `Negroni` integration ([#808](https://github.com/getsentry/sentry-go/pull/808))
- Add `FailureIssueThreshold` & `RecoveryThreshold` to `MonitorConfig` ([#775](https://github.com/getsentry/sentry-go/pull/775))
- Use `errors.Unwrap()` to create exception groups ([#792](https://github.com/getsentry/sentry-go/pull/792))
- Add support for matching on strings for `ClientOptions.IgnoreErrors` & `ClientOptions.IgnoreTransactions` ([#819](https://github.com/getsentry/sentry-go/pull/819))
- Add `http.request.method` attribute for performance span data ([#786](https://github.com/getsentry/sentry-go/pull/786))
- Accept `interface{}` for span data values ([#784](https://github.com/getsentry/sentry-go/pull/784))
### Bug Fixes
- Fix missing stack trace for parsing error in `logrusentry` ([#689](https://github.com/getsentry/sentry-go/pull/689))
## 0.27.0
The Sentry SDK team is happy to announce the immediate availability of Sentry Go SDK v0.27.0.

View File

@@ -54,13 +54,23 @@ test-coverage: $(COVERAGE_REPORT_DIR) clean-report-dir ## Test with coverage en
$(GO) tool cover -html=$(COVERAGE_PROFILE) -o coverage.html); \
done;
.PHONY: test-coverage clean-report-dir
test-race-coverage: $(COVERAGE_REPORT_DIR) clean-report-dir ## Run tests with race detection and coverage
set -e ; \
for dir in $(ALL_GO_MOD_DIRS); do \
echo ">>> Running tests with race detection and coverage for module: $${dir}"; \
DIR_ABS=$$(python -c 'import os, sys; print(os.path.realpath(sys.argv[1]))' $${dir}) ; \
REPORT_NAME=$$(basename $${DIR_ABS}); \
(cd "$${dir}" && \
$(GO) test -count=1 -timeout $(TIMEOUT)s -race -coverpkg=./... -covermode=$(COVERAGE_MODE) -coverprofile="$(COVERAGE_PROFILE)" ./... && \
cp $(COVERAGE_PROFILE) "$(COVERAGE_REPORT_DIR_ABS)/$${REPORT_NAME}_$(COVERAGE_PROFILE)" && \
$(GO) tool cover -html=$(COVERAGE_PROFILE) -o coverage.html); \
done;
.PHONY: test-race-coverage
mod-tidy: ## Check go.mod tidiness
set -e ; \
for dir in $(ALL_GO_MOD_DIRS); do \
cd "$${dir}"; \
echo ">>> Running 'go mod tidy' for module: $${dir}"; \
go mod tidy -go=1.18 -compat=1.18; \
(cd "$${dir}" && GOTOOLCHAIN=local go mod tidy -go=1.23.0 -compat=1.23); \
done; \
git diff --exit-code;
.PHONY: mod-tidy
@@ -68,12 +78,12 @@ mod-tidy: ## Check go.mod tidiness
vet: ## Run "go vet"
set -e ; \
for dir in $(ALL_GO_MOD_DIRS); do \
cd "$${dir}"; \
echo ">>> Running 'go vet' for module: $${dir}"; \
go vet ./...; \
(cd "$${dir}" && go vet ./...); \
done;
.PHONY: vet
lint: ## Lint (using "golangci-lint")
golangci-lint run
.PHONY: lint

View File

@@ -10,10 +10,10 @@
# Official Sentry SDK for Go
[![Build Status](https://github.com/getsentry/sentry-go/workflows/go-workflow/badge.svg)](https://github.com/getsentry/sentry-go/actions?query=workflow%3Ago-workflow)
[![Build Status](https://github.com/getsentry/sentry-go/actions/workflows/test.yml/badge.svg)](https://github.com/getsentry/sentry-go/actions/workflows/test.yml)
[![Go Report Card](https://goreportcard.com/badge/github.com/getsentry/sentry-go)](https://goreportcard.com/report/github.com/getsentry/sentry-go)
[![Discord](https://img.shields.io/discord/621778831602221064)](https://discord.gg/Ww9hbqr)
[![GoDoc](https://godoc.org/github.com/getsentry/sentry-go?status.svg)](https://godoc.org/github.com/getsentry/sentry-go)
[![X Follow](https://img.shields.io/twitter/follow/sentry?label=sentry&style=social)](https://x.com/intent/follow?screen_name=sentry)
[![go.dev](https://img.shields.io/badge/go.dev-pkg-007d9c.svg?style=flat)](https://pkg.go.dev/github.com/getsentry/sentry-go)
`sentry-go` provides a Sentry client implementation for the Go programming
@@ -69,23 +69,25 @@ To get started, have a look at one of our [examples](_examples/):
We also provide a [complete API reference](https://pkg.go.dev/github.com/getsentry/sentry-go).
For more detailed information about how to get the most out of `sentry-go`,
checkout the official documentation:
check out the official documentation:
- [Sentry Go SDK documentation](https://docs.sentry.io/platforms/go/)
- Guides:
- [net/http](https://docs.sentry.io/platforms/go/guides/http/)
- [echo](https://docs.sentry.io/platforms/go/guides/echo/)
- [fasthttp](https://docs.sentry.io/platforms/go/guides/fasthttp/)
- [fiber](https://docs.sentry.io/platforms/go/guides/fiber/)
- [gin](https://docs.sentry.io/platforms/go/guides/gin/)
- [iris](https://docs.sentry.io/platforms/go/guides/iris/)
- [martini](https://docs.sentry.io/platforms/go/guides/martini/)
- [logrus](https://docs.sentry.io/platforms/go/guides/logrus/)
- [negroni](https://docs.sentry.io/platforms/go/guides/negroni/)
- [slog](https://docs.sentry.io/platforms/go/guides/slog/)
- [zerolog](https://docs.sentry.io/platforms/go/guides/zerolog/)
## Resources
- [Bug Tracker](https://github.com/getsentry/sentry-go/issues)
- [GitHub Project](https://github.com/getsentry/sentry-go)
- [![GoDoc](https://godoc.org/github.com/getsentry/sentry-go?status.svg)](https://godoc.org/github.com/getsentry/sentry-go)
- [![go.dev](https://img.shields.io/badge/go.dev-pkg-007d9c.svg?style=flat)](https://pkg.go.dev/github.com/getsentry/sentry-go)
- [![Documentation](https://img.shields.io/badge/documentation-sentry.io-green.svg)](https://docs.sentry.io/platforms/go/)
- [![Discussions](https://img.shields.io/github/discussions/getsentry/sentry-go.svg)](https://github.com/getsentry/sentry-go/discussions)

View File

@@ -0,0 +1,36 @@
package attribute
type Builder struct {
Key string
Value Value
}
// String returns a Builder for a string value.
func String(key, value string) Builder {
return Builder{key, StringValue(value)}
}
// Int64 returns a Builder for an int64.
func Int64(key string, value int64) Builder {
return Builder{key, Int64Value(value)}
}
// Int returns a Builder for an int64.
func Int(key string, value int) Builder {
return Builder{key, IntValue(value)}
}
// Float64 returns a Builder for a float64.
func Float64(key string, v float64) Builder {
return Builder{key, Float64Value(v)}
}
// Bool returns a Builder for a boolean.
func Bool(key string, v bool) Builder {
return Builder{key, BoolValue(v)}
}
// Valid checks for valid key and type.
func (b *Builder) Valid() bool {
return len(b.Key) > 0 && b.Value.Type() != INVALID
}

View File

@@ -0,0 +1,49 @@
// Copied from https://github.com/open-telemetry/opentelemetry-go/blob/cc43e01c27892252aac9a8f20da28cdde957a289/attribute/rawhelpers.go
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package attribute
import (
"math"
)
func boolToRaw(b bool) uint64 { // b is not a control flag.
if b {
return 1
}
return 0
}
func rawToBool(r uint64) bool {
return r != 0
}
func int64ToRaw(i int64) uint64 {
// Assumes original was a valid int64 (overflow not checked).
return uint64(i) // nolint: gosec
}
func rawToInt64(r uint64) int64 {
// Assumes original was a valid int64 (overflow not checked).
return int64(r) // nolint: gosec
}
func float64ToRaw(f float64) uint64 {
return math.Float64bits(f)
}
func rawToFloat64(r uint64) float64 {
return math.Float64frombits(r)
}

View File

@@ -0,0 +1,170 @@
// Adapted from https://github.com/open-telemetry/opentelemetry-go/blob/cc43e01c27892252aac9a8f20da28cdde957a289/attribute/value.go
//
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package attribute
import (
"encoding/json"
"fmt"
"strconv"
)
// Type describes the type of the data Value holds.
type Type int // redefines builtin Type.
// Value represents the value part in key-value pairs.
type Value struct {
vtype Type
numeric uint64
stringly string
}
const (
// INVALID is used for a Value with no value set.
INVALID Type = iota
// BOOL is a boolean Type Value.
BOOL
// INT64 is a 64-bit signed integral Type Value.
INT64
// FLOAT64 is a 64-bit floating point Type Value.
FLOAT64
// STRING is a string Type Value.
STRING
)
// BoolValue creates a BOOL Value.
func BoolValue(v bool) Value {
return Value{
vtype: BOOL,
numeric: boolToRaw(v),
}
}
// IntValue creates an INT64 Value.
func IntValue(v int) Value {
return Int64Value(int64(v))
}
// Int64Value creates an INT64 Value.
func Int64Value(v int64) Value {
return Value{
vtype: INT64,
numeric: int64ToRaw(v),
}
}
// Float64Value creates a FLOAT64 Value.
func Float64Value(v float64) Value {
return Value{
vtype: FLOAT64,
numeric: float64ToRaw(v),
}
}
// StringValue creates a STRING Value.
func StringValue(v string) Value {
return Value{
vtype: STRING,
stringly: v,
}
}
// Type returns a type of the Value.
func (v Value) Type() Type {
return v.vtype
}
// AsBool returns the bool value. Make sure that the Value's type is
// BOOL.
func (v Value) AsBool() bool {
return rawToBool(v.numeric)
}
// AsInt64 returns the int64 value. Make sure that the Value's type is
// INT64.
func (v Value) AsInt64() int64 {
return rawToInt64(v.numeric)
}
// AsFloat64 returns the float64 value. Make sure that the Value's
// type is FLOAT64.
func (v Value) AsFloat64() float64 {
return rawToFloat64(v.numeric)
}
// AsString returns the string value. Make sure that the Value's type
// is STRING.
func (v Value) AsString() string {
return v.stringly
}
type unknownValueType struct{}
// AsInterface returns Value's data as interface{}.
func (v Value) AsInterface() interface{} {
switch v.Type() {
case BOOL:
return v.AsBool()
case INT64:
return v.AsInt64()
case FLOAT64:
return v.AsFloat64()
case STRING:
return v.stringly
}
return unknownValueType{}
}
// String returns a string representation of Value's data.
func (v Value) String() string {
switch v.Type() {
case BOOL:
return strconv.FormatBool(v.AsBool())
case INT64:
return strconv.FormatInt(v.AsInt64(), 10)
case FLOAT64:
return fmt.Sprint(v.AsFloat64())
case STRING:
return v.stringly
default:
return "unknown"
}
}
// MarshalJSON returns the JSON encoding of the Value.
func (v Value) MarshalJSON() ([]byte, error) {
var jsonVal struct {
Type string
Value interface{}
}
jsonVal.Type = v.Type().String()
jsonVal.Value = v.AsInterface()
return json.Marshal(jsonVal)
}
func (t Type) String() string {
switch t {
case BOOL:
return "bool"
case INT64:
return "int64"
case FLOAT64:
return "float64"
case STRING:
return "string"
}
return "invalid"
}

View File

@@ -0,0 +1,136 @@
package sentry
import (
"context"
"sync"
"time"
)
const (
batchSize = 100
defaultBatchTimeout = 5 * time.Second
)
type batchProcessor[T any] struct {
sendBatch func([]T)
itemCh chan T
flushCh chan chan struct{}
cancel context.CancelFunc
wg sync.WaitGroup
startOnce sync.Once
shutdownOnce sync.Once
batchTimeout time.Duration
}
func newBatchProcessor[T any](sendBatch func([]T)) *batchProcessor[T] {
return &batchProcessor[T]{
itemCh: make(chan T, batchSize),
flushCh: make(chan chan struct{}),
sendBatch: sendBatch,
batchTimeout: defaultBatchTimeout,
}
}
// WithBatchTimeout sets a custom batch timeout for the processor.
// This is useful for testing or when different timing behavior is needed.
func (p *batchProcessor[T]) WithBatchTimeout(timeout time.Duration) *batchProcessor[T] {
p.batchTimeout = timeout
return p
}
func (p *batchProcessor[T]) Send(item T) bool {
select {
case p.itemCh <- item:
return true
default:
return false
}
}
func (p *batchProcessor[T]) Start() {
p.startOnce.Do(func() {
ctx, cancel := context.WithCancel(context.Background())
p.cancel = cancel
p.wg.Add(1)
go p.run(ctx)
})
}
func (p *batchProcessor[T]) Flush(timeout <-chan struct{}) {
done := make(chan struct{})
select {
case p.flushCh <- done:
select {
case <-done:
case <-timeout:
}
case <-timeout:
}
}
func (p *batchProcessor[T]) Shutdown() {
p.shutdownOnce.Do(func() {
if p.cancel != nil {
p.cancel()
p.wg.Wait()
}
})
}
func (p *batchProcessor[T]) run(ctx context.Context) {
defer p.wg.Done()
var items []T
timer := time.NewTimer(0)
timer.Stop()
defer timer.Stop()
for {
select {
case item := <-p.itemCh:
if len(items) == 0 {
timer.Reset(p.batchTimeout)
}
items = append(items, item)
if len(items) >= batchSize {
p.sendBatch(items)
items = nil
}
case <-timer.C:
if len(items) > 0 {
p.sendBatch(items)
items = nil
}
case done := <-p.flushCh:
flushDrain:
for {
select {
case item := <-p.itemCh:
items = append(items, item)
default:
break flushDrain
}
}
if len(items) > 0 {
p.sendBatch(items)
items = nil
}
close(done)
case <-ctx.Done():
drain:
for {
select {
case item := <-p.itemCh:
items = append(items, item)
default:
break drain
}
}
if len(items) > 0 {
p.sendBatch(items)
}
return
}
}
}

View File

@@ -87,6 +87,10 @@ type MonitorConfig struct { //nolint: maligned // prefer readability over optima
// A tz database string representing the timezone which the monitor's execution schedule is in.
// See: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
Timezone string `json:"timezone,omitempty"`
// The number of consecutive failed check-ins it takes before an issue is created.
FailureIssueThreshold int64 `json:"failure_issue_threshold,omitempty"`
// The number of consecutive OK check-ins it takes before an issue is resolved.
RecoveryThreshold int64 `json:"recovery_threshold,omitempty"`
}
type CheckIn struct { //nolint: maligned // prefer readability over optimal memory layout

View File

@@ -5,7 +5,6 @@ import (
"crypto/x509"
"fmt"
"io"
"log"
"math/rand"
"net/http"
"os"
@@ -15,24 +14,35 @@ import (
"time"
"github.com/getsentry/sentry-go/internal/debug"
"github.com/getsentry/sentry-go/internal/debuglog"
httpInternal "github.com/getsentry/sentry-go/internal/http"
"github.com/getsentry/sentry-go/internal/protocol"
"github.com/getsentry/sentry-go/internal/ratelimit"
"github.com/getsentry/sentry-go/internal/telemetry"
)
// The identifier of the SDK.
const sdkIdentifier = "sentry.go"
// maxErrorDepth is the maximum number of errors reported in a chain of errors.
// This protects the SDK from an arbitrarily long chain of wrapped errors.
//
// An additional consideration is that arguably reporting a long chain of errors
// is of little use when debugging production errors with Sentry. The Sentry UI
// is not optimized for long chains either. The top-level error together with a
// stack trace is often the most useful information.
const maxErrorDepth = 10
const (
// maxErrorDepth is the maximum number of errors reported in a chain of errors.
// This protects the SDK from an arbitrarily long chain of wrapped errors.
//
// An additional consideration is that arguably reporting a long chain of errors
// is of little use when debugging production errors with Sentry. The Sentry UI
// is not optimized for long chains either. The top-level error together with a
// stack trace is often the most useful information.
maxErrorDepth = 100
// defaultMaxSpans limits the default number of recorded spans per transaction. The limit is
// meant to bound memory usage and prevent too large transaction events that
// would be rejected by Sentry.
const defaultMaxSpans = 1000
// defaultMaxSpans limits the default number of recorded spans per transaction. The limit is
// meant to bound memory usage and prevent too large transaction events that
// would be rejected by Sentry.
defaultMaxSpans = 1000
// defaultMaxBreadcrumbs is the default maximum number of breadcrumbs added to
// an event. Can be overwritten with the MaxBreadcrumbs option.
defaultMaxBreadcrumbs = 100
)
// hostname is the host name reported by the kernel. It is precomputed once to
// avoid syscalls when capturing events.
@@ -77,9 +87,9 @@ type usageError struct {
error
}
// Logger is an instance of log.Logger that is use to provide debug information about running Sentry Client
// can be enabled by either using Logger.SetOutput directly or with Debug client option.
var Logger = log.New(io.Discard, "[Sentry] ", log.LstdFlags)
// DebugLogger is an instance of log.Logger that is used to provide debug information about running Sentry Client
// can be enabled by either using debuglog.SetOutput directly or with Debug client option.
var DebugLogger = debuglog.GetLogger()
// EventProcessor is a function that processes an event.
// Event processors are used to change an event before it is sent to Sentry.
@@ -90,7 +100,7 @@ type EventProcessor func(event *Event, hint *EventHint) *Event
// ApplyToEvent changes an event based on external data and/or
// an event hint.
type EventModifier interface {
ApplyToEvent(event *Event, hint *EventHint) *Event
ApplyToEvent(event *Event, hint *EventHint, client *Client) *Event
}
var globalEventProcessors []EventProcessor
@@ -133,9 +143,11 @@ type ClientOptions struct {
TracesSampleRate float64
// Used to customize the sampling of traces, overrides TracesSampleRate.
TracesSampler TracesSampler
// 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
// Control with URLs trace propagation should be enabled. Does not support regex patterns.
TracePropagationTargets []string
// PropagateTraceparent is used to control whether the W3C Trace Context HTTP traceparent header
// is propagated on outgoing http requests.
PropagateTraceparent bool
// List of regexp strings that will be used to match against event's message
// and if applicable, caught errors type and value.
// If the match is found, then a whole event will be dropped.
@@ -147,13 +159,19 @@ type ClientOptions struct {
// By default, no such data is sent.
SendDefaultPII bool
// BeforeSend is called before error events are sent to Sentry.
// Use it to mutate the event or return nil to discard the event.
// You can use it to mutate the event or return nil to discard it.
BeforeSend func(event *Event, hint *EventHint) *Event
// BeforeSendLong is called before log events are sent to Sentry.
// You can use it to mutate the log event or return nil to discard it.
BeforeSendLog func(event *Log) *Log
// BeforeSendTransaction is called before transaction events are sent to Sentry.
// Use it to mutate the transaction or return nil to discard the transaction.
BeforeSendTransaction func(event *Event, hint *EventHint) *Event
// Before breadcrumb add callback.
BeforeBreadcrumb func(breadcrumb *Breadcrumb, hint *BreadcrumbHint) *Breadcrumb
// BeforeSendMetric is called before metric events are sent to Sentry.
// You can use it to mutate the metric or return nil to discard it.
BeforeSendMetric func(metric *Metric) *Metric
// Integrations to be installed on the current Client, receives default
// integrations.
Integrations func([]Integration) []Integration
@@ -226,6 +244,30 @@ type ClientOptions struct {
MaxErrorDepth int
// Default event tags. These are overridden by tags set on a scope.
Tags map[string]string
// EnableLogs controls when logs should be emitted.
EnableLogs bool
// DisableMetrics controls when metrics should be emitted.
DisableMetrics bool
// TraceIgnoreStatusCodes is a list of HTTP status codes that should not be traced.
// Each element can be either:
// - A single-element slice [code] for a specific status code
// - A two-element slice [min, max] for a range of status codes (inclusive)
// When an HTTP request results in a status code that matches any of these codes or ranges,
// the transaction will not be sent to Sentry.
//
// Examples:
// [][]int{{404}} // ignore only status code 404
// [][]int{{400, 405}} // ignore status codes 400-405
// [][]int{{404}, {500}} // ignore status codes 404 and 500
// [][]int{{404}, {400, 405}, {500, 599}} // ignore 404, range 400-405, and range 500-599
//
// By default, this ignores 404 status codes.
//
// IMPORTANT: to not ignore any status codes, the option should be an empty slice and not nil. The nil option is
// used for defaulting to 404 ignores.
TraceIgnoreStatusCodes [][]int
// DisableTelemetryBuffer disables the telemetry buffer layer for prioritizing events and uses the old transport layer.
DisableTelemetryBuffer bool
}
// Client is the underlying processor that is used by the main API and Hub
@@ -240,7 +282,10 @@ type Client struct {
sdkVersion string
// Transport is read-only. Replacing the transport of an existing client is
// not supported, create a new client instead.
Transport Transport
Transport Transport
batchLogger *logBatchProcessor
batchMeter *metricBatchProcessor
telemetryProcessor *telemetry.Processor
}
// NewClient creates and returns an instance of Client configured using
@@ -278,7 +323,7 @@ func NewClient(options ClientOptions) (*Client, error) {
if debugWriter == nil {
debugWriter = os.Stderr
}
Logger.SetOutput(debugWriter)
debuglog.SetOutput(debugWriter)
}
if options.Dsn == "" {
@@ -301,6 +346,10 @@ func NewClient(options ClientOptions) (*Client, error) {
options.MaxSpans = defaultMaxSpans
}
if options.TraceIgnoreStatusCodes == nil {
options.TraceIgnoreStatusCodes = [][]int{{404}}
}
// SENTRYGODEBUG is a comma-separated list of key=value pairs (similar
// to GODEBUG). It is not a supported feature: recognized debug options
// may change any time.
@@ -341,6 +390,21 @@ func NewClient(options ClientOptions) (*Client, error) {
}
client.setupTransport()
// noop Telemetry Buffers and Processor fow now
// if !options.DisableTelemetryBuffer {
// client.setupTelemetryProcessor()
// } else
if options.EnableLogs {
client.batchLogger = newLogBatchProcessor(&client)
client.batchLogger.Start()
}
if !options.DisableMetrics {
client.batchMeter = newMetricBatchProcessor(&client)
client.batchMeter.Start()
}
client.setupIntegrations()
return &client, nil
@@ -354,15 +418,7 @@ func (client *Client) setupTransport() {
if opts.Dsn == "" {
transport = new(noopTransport)
} else {
httpTransport := NewHTTPTransport()
// When tracing is enabled, use larger buffer to
// accommodate more concurrent events.
// TODO(tracing): consider using separate buffers per
// event type.
if opts.EnableTracing {
httpTransport.BufferSize = 1000
}
transport = httpTransport
transport = NewHTTPTransport()
}
}
@@ -370,6 +426,57 @@ func (client *Client) setupTransport() {
client.Transport = transport
}
func (client *Client) setupTelemetryProcessor() { // nolint: unused
if client.options.DisableTelemetryBuffer {
return
}
if client.dsn == nil {
debuglog.Println("Telemetry buffer disabled: no DSN configured")
return
}
// We currently disallow using custom Transport with the new Telemetry Processor, due to the difference in transport signatures.
// The option should be enabled when the new Transport interface signature changes.
if client.options.Transport != nil {
debuglog.Println("Cannot enable Telemetry Processor/Buffers with custom Transport: fallback to old transport")
if client.options.EnableLogs {
client.batchLogger = newLogBatchProcessor(client)
client.batchLogger.Start()
}
if !client.options.DisableMetrics {
client.batchMeter = newMetricBatchProcessor(client)
client.batchMeter.Start()
}
return
}
transport := httpInternal.NewAsyncTransport(httpInternal.TransportOptions{
Dsn: client.options.Dsn,
HTTPClient: client.options.HTTPClient,
HTTPTransport: client.options.HTTPTransport,
HTTPProxy: client.options.HTTPProxy,
HTTPSProxy: client.options.HTTPSProxy,
CaCerts: client.options.CaCerts,
})
client.Transport = &internalAsyncTransportAdapter{transport: transport}
buffers := map[ratelimit.Category]telemetry.Buffer[protocol.TelemetryItem]{
ratelimit.CategoryError: telemetry.NewRingBuffer[protocol.TelemetryItem](ratelimit.CategoryError, 100, telemetry.OverflowPolicyDropOldest, 1, 0),
ratelimit.CategoryTransaction: telemetry.NewRingBuffer[protocol.TelemetryItem](ratelimit.CategoryTransaction, 1000, telemetry.OverflowPolicyDropOldest, 1, 0),
ratelimit.CategoryLog: telemetry.NewRingBuffer[protocol.TelemetryItem](ratelimit.CategoryLog, 10*100, telemetry.OverflowPolicyDropOldest, 100, 5*time.Second),
ratelimit.CategoryMonitor: telemetry.NewRingBuffer[protocol.TelemetryItem](ratelimit.CategoryMonitor, 100, telemetry.OverflowPolicyDropOldest, 1, 0),
ratelimit.CategoryTraceMetric: telemetry.NewRingBuffer[protocol.TelemetryItem](ratelimit.CategoryTraceMetric, 10*100, telemetry.OverflowPolicyDropOldest, 100, 5*time.Second),
}
sdkInfo := &protocol.SdkInfo{
Name: client.sdkIdentifier,
Version: client.sdkVersion,
}
client.telemetryProcessor = telemetry.NewProcessor(buffers, transport, &client.dsn.Dsn, sdkInfo)
}
func (client *Client) setupIntegrations() {
integrations := []Integration{
new(contextifyFramesIntegration),
@@ -386,12 +493,12 @@ func (client *Client) setupIntegrations() {
for _, integration := range integrations {
if client.integrationAlreadyInstalled(integration.Name()) {
Logger.Printf("Integration %s is already installed\n", integration.Name())
debuglog.Printf("Integration %s is already installed\n", integration.Name())
continue
}
client.integrations = append(client.integrations, integration)
integration.SetupOnce(client)
Logger.Printf("Integration installed: %s\n", integration.Name())
debuglog.Printf("Integration installed: %s\n", integration.Name())
}
sort.Slice(client.integrations, func(i, j int) bool {
@@ -440,13 +547,69 @@ func (client *Client) CaptureCheckIn(checkIn *CheckIn, monitorConfig *MonitorCon
// CaptureEvent captures an event on the currently active client if any.
//
// The event must already be assembled. Typically code would instead use
// The event must already be assembled. Typically, code would instead use
// the utility methods like CaptureException. The return value is the
// event ID. In case Sentry is disabled or event was dropped, the return value will be nil.
func (client *Client) CaptureEvent(event *Event, hint *EventHint, scope EventModifier) *EventID {
return client.processEvent(event, hint, scope)
}
func (client *Client) captureLog(log *Log, _ *Scope) bool {
if log == nil {
return false
}
if client.options.BeforeSendLog != nil {
log = client.options.BeforeSendLog(log)
if log == nil {
debuglog.Println("Log dropped due to BeforeSendLog callback.")
return false
}
}
if client.telemetryProcessor != nil {
if !client.telemetryProcessor.Add(log) {
debuglog.Print("Dropping log: telemetry buffer full or category missing")
return false
}
} else if client.batchLogger != nil {
if !client.batchLogger.Send(log) {
debuglog.Printf("Dropping log [%s]: buffer full", log.Level)
return false
}
}
return true
}
func (client *Client) captureMetric(metric *Metric, _ *Scope) bool {
if metric == nil {
return false
}
if client.options.BeforeSendMetric != nil {
metric = client.options.BeforeSendMetric(metric)
if metric == nil {
debuglog.Println("Metric dropped due to BeforeSendMetric callback.")
return false
}
}
if client.telemetryProcessor != nil {
if !client.telemetryProcessor.Add(metric) {
debuglog.Printf("Dropping metric: telemetry buffer full or category missing")
return false
}
} else if client.batchMeter != nil {
if !client.batchMeter.Send(metric) {
debuglog.Printf("Dropping metric %q: buffer full", metric.Name)
return false
}
}
return true
}
// Recover captures a panic.
// Returns EventID if successfully, or nil if there's no error to recover from.
func (client *Client) Recover(err interface{}, hint *EventHint, scope EventModifier) *EventID {
@@ -510,9 +673,56 @@ func (client *Client) RecoverWithContext(
// the network synchronously, configure it to use the HTTPSyncTransport in the
// call to Init.
func (client *Client) Flush(timeout time.Duration) bool {
if client.batchLogger != nil || client.batchMeter != nil || client.telemetryProcessor != nil {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
return client.FlushWithContext(ctx)
}
return client.Transport.Flush(timeout)
}
// FlushWithContext waits until the underlying Transport sends any buffered events
// to the Sentry server, blocking for at most the duration specified by the context.
// It returns false if the context is canceled before the events are sent. In such a case,
// some events may not be delivered.
//
// FlushWithContext should be called before terminating the program to ensure no
// events are unintentionally dropped.
//
// Avoid calling FlushWithContext indiscriminately after each call to CaptureEvent,
// CaptureException, or CaptureMessage. To send events synchronously over the network,
// configure the SDK to use HTTPSyncTransport during initialization with Init.
func (client *Client) FlushWithContext(ctx context.Context) bool {
if client.batchLogger != nil {
client.batchLogger.Flush(ctx.Done())
}
if client.batchMeter != nil {
client.batchMeter.Flush(ctx.Done())
}
if client.telemetryProcessor != nil {
return client.telemetryProcessor.FlushWithContext(ctx)
}
return client.Transport.FlushWithContext(ctx)
}
// Close clean up underlying Transport resources.
//
// Close should be called after Flush and before terminating the program
// otherwise some events may be lost.
func (client *Client) Close() {
if client.telemetryProcessor != nil {
client.telemetryProcessor.Close(5 * time.Second)
}
if client.batchLogger != nil {
client.batchLogger.Shutdown()
}
if client.batchMeter != nil {
client.batchMeter.Shutdown()
}
client.Transport.Close()
}
// EventFromMessage creates an event from the given message string.
func (client *Client) EventFromMessage(message string, level Level) *Event {
if message == "" {
@@ -590,14 +800,6 @@ func (client *Client) GetSDKIdentifier() string {
return client.sdkIdentifier
}
// reverse reverses the slice a in place.
func reverse(a []Exception) {
for i := len(a)/2 - 1; i >= 0; i-- {
opp := len(a) - 1 - i
a[i], a[opp] = a[opp], a[i]
}
}
func (client *Client) processEvent(event *Event, hint *EventHint, scope EventModifier) *EventID {
if event == nil {
err := usageError{fmt.Errorf("%s called with nil event", callerFunctionName())}
@@ -608,7 +810,7 @@ func (client *Client) processEvent(event *Event, hint *EventHint, scope EventMod
// options.TracesSampler when they are started. Other events
// (errors, messages) are sampled here. Does not apply to check-ins.
if event.Type != transactionType && event.Type != checkInType && !sample(client.options.SampleRate) {
Logger.Println("Event dropped due to SampleRate hit.")
debuglog.Println("Event dropped due to SampleRate hit.")
return nil
}
@@ -620,21 +822,31 @@ func (client *Client) processEvent(event *Event, hint *EventHint, scope EventMod
if hint == nil {
hint = &EventHint{}
}
if event.Type == transactionType && client.options.BeforeSendTransaction != nil {
// Transaction events
if event = client.options.BeforeSendTransaction(event, hint); event == nil {
Logger.Println("Transaction dropped due to BeforeSendTransaction callback.")
return nil
switch event.Type {
case transactionType:
if client.options.BeforeSendTransaction != nil {
if event = client.options.BeforeSendTransaction(event, hint); event == nil {
debuglog.Println("Transaction dropped due to BeforeSendTransaction callback.")
return nil
}
}
} else if event.Type != transactionType && event.Type != checkInType && client.options.BeforeSend != nil {
// All other events
if event = client.options.BeforeSend(event, hint); event == nil {
Logger.Println("Event dropped due to BeforeSend callback.")
return nil
case checkInType: // not a default case, since we shouldn't apply BeforeSend on check-in events
default:
if client.options.BeforeSend != nil {
if event = client.options.BeforeSend(event, hint); event == nil {
debuglog.Println("Event dropped due to BeforeSend callback.")
return nil
}
}
}
client.Transport.SendEvent(event)
if client.telemetryProcessor != nil {
if !client.telemetryProcessor.Add(event) {
debuglog.Println("Event dropped: telemetry buffer full or unavailable")
}
} else {
client.Transport.SendEvent(event)
}
return &event.EventID
}
@@ -685,7 +897,7 @@ func (client *Client) prepareEvent(event *Event, hint *EventHint, scope EventMod
}
if scope != nil {
event = scope.ApplyToEvent(event, hint)
event = scope.ApplyToEvent(event, hint, client)
if event == nil {
return nil
}
@@ -695,7 +907,7 @@ func (client *Client) prepareEvent(event *Event, hint *EventHint, scope EventMod
id := event.EventID
event = processor(event, hint)
if event == nil {
Logger.Printf("Event dropped by one of the Client EventProcessors: %s\n", id)
debuglog.Printf("Event dropped by one of the Client EventProcessors: %s\n", id)
return nil
}
}
@@ -704,15 +916,11 @@ func (client *Client) prepareEvent(event *Event, hint *EventHint, scope EventMod
id := event.EventID
event = processor(event, hint)
if event == nil {
Logger.Printf("Event dropped by one of the Global EventProcessors: %s\n", id)
debuglog.Printf("Event dropped by one of the Global EventProcessors: %s\n", id)
return nil
}
}
if event.sdkMetaData.transactionProfile != nil {
event.sdkMetaData.transactionProfile.UpdateFromEvent(event)
}
return event
}

View File

@@ -1,234 +1,37 @@
package sentry
import (
"encoding/json"
"fmt"
"net/url"
"strconv"
"strings"
"time"
"github.com/getsentry/sentry-go/internal/protocol"
)
type scheme string
// Re-export protocol types to maintain public API compatibility
const (
schemeHTTP scheme = "http"
schemeHTTPS scheme = "https"
)
func (scheme scheme) defaultPort() int {
switch scheme {
case schemeHTTPS:
return 443
case schemeHTTP:
return 80
default:
return 80
}
// Dsn is used as the remote address source to client transport.
type Dsn struct {
protocol.Dsn
}
// DsnParseError represents an error that occurs if a Sentry
// DSN cannot be parsed.
type DsnParseError struct {
Message string
}
func (e DsnParseError) Error() string {
return "[Sentry] DsnParseError: " + e.Message
}
// Dsn is used as the remote address source to client transport.
type Dsn struct {
scheme scheme
publicKey string
secretKey string
host string
port int
path string
projectID string
}
type DsnParseError = protocol.DsnParseError
// NewDsn creates a Dsn by parsing rawURL. Most users will never call this
// function directly. It is provided for use in custom Transport
// implementations.
func NewDsn(rawURL string) (*Dsn, error) {
// Parse
parsedURL, err := url.Parse(rawURL)
protocolDsn, err := protocol.NewDsn(rawURL)
if err != nil {
return nil, &DsnParseError{fmt.Sprintf("invalid url: %v", err)}
return nil, err
}
// Scheme
var scheme scheme
switch parsedURL.Scheme {
case "http":
scheme = schemeHTTP
case "https":
scheme = schemeHTTPS
default:
return nil, &DsnParseError{"invalid scheme"}
}
// PublicKey
publicKey := parsedURL.User.Username()
if publicKey == "" {
return nil, &DsnParseError{"empty username"}
}
// SecretKey
var secretKey string
if parsedSecretKey, ok := parsedURL.User.Password(); ok {
secretKey = parsedSecretKey
}
// Host
host := parsedURL.Hostname()
if host == "" {
return nil, &DsnParseError{"empty host"}
}
// Port
var port int
if parsedURL.Port() != "" {
parsedPort, err := strconv.Atoi(parsedURL.Port())
if err != nil {
return nil, &DsnParseError{"invalid port"}
}
port = parsedPort
} else {
port = scheme.defaultPort()
}
// ProjectID
if parsedURL.Path == "" || parsedURL.Path == "/" {
return nil, &DsnParseError{"empty project id"}
}
pathSegments := strings.Split(parsedURL.Path[1:], "/")
projectID := pathSegments[len(pathSegments)-1]
if projectID == "" {
return nil, &DsnParseError{"empty project id"}
}
// Path
var path string
if len(pathSegments) > 1 {
path = "/" + strings.Join(pathSegments[0:len(pathSegments)-1], "/")
}
return &Dsn{
scheme: scheme,
publicKey: publicKey,
secretKey: secretKey,
host: host,
port: port,
path: path,
projectID: projectID,
}, nil
return &Dsn{Dsn: *protocolDsn}, nil
}
// String formats Dsn struct into a valid string url.
func (dsn Dsn) String() string {
var url string
url += fmt.Sprintf("%s://%s", dsn.scheme, dsn.publicKey)
if dsn.secretKey != "" {
url += fmt.Sprintf(":%s", dsn.secretKey)
}
url += fmt.Sprintf("@%s", dsn.host)
if dsn.port != dsn.scheme.defaultPort() {
url += fmt.Sprintf(":%d", dsn.port)
}
if dsn.path != "" {
url += dsn.path
}
url += fmt.Sprintf("/%s", dsn.projectID)
return url
}
// Get the scheme of the DSN.
func (dsn Dsn) GetScheme() string {
return string(dsn.scheme)
}
// Get the public key of the DSN.
func (dsn Dsn) GetPublicKey() string {
return dsn.publicKey
}
// Get the secret key of the DSN.
func (dsn Dsn) GetSecretKey() string {
return dsn.secretKey
}
// Get the host of the DSN.
func (dsn Dsn) GetHost() string {
return dsn.host
}
// Get the port of the DSN.
func (dsn Dsn) GetPort() int {
return dsn.port
}
// Get the path of the DSN.
func (dsn Dsn) GetPath() string {
return dsn.path
}
// Get the project ID of the DSN.
func (dsn Dsn) GetProjectID() string {
return dsn.projectID
}
// GetAPIURL returns the URL of the envelope endpoint of the project
// associated with the DSN.
func (dsn Dsn) GetAPIURL() *url.URL {
var rawURL string
rawURL += fmt.Sprintf("%s://%s", dsn.scheme, dsn.host)
if dsn.port != dsn.scheme.defaultPort() {
rawURL += fmt.Sprintf(":%d", dsn.port)
}
if dsn.path != "" {
rawURL += dsn.path
}
rawURL += fmt.Sprintf("/api/%s/%s/", dsn.projectID, "envelope")
parsedURL, _ := url.Parse(rawURL)
return parsedURL
}
// RequestHeaders returns all the necessary headers that have to be used in the transport when seinding events
// RequestHeaders returns all the necessary headers that have to be used in the transport when sending events
// to the /store endpoint.
//
// Deprecated: This method shall only be used if you want to implement your own transport that sends events to
// the /store endpoint. If you're using the transport provided by the SDK, all necessary headers to authenticate
// against the /envelope endpoint are added automatically.
func (dsn Dsn) RequestHeaders() map[string]string {
auth := fmt.Sprintf("Sentry sentry_version=%s, sentry_timestamp=%d, "+
"sentry_client=sentry.go/%s, sentry_key=%s", apiVersion, time.Now().Unix(), SDKVersion, dsn.publicKey)
if dsn.secretKey != "" {
auth = fmt.Sprintf("%s, sentry_secret=%s", auth, dsn.secretKey)
}
return map[string]string{
"Content-Type": "application/json",
"X-Sentry-Auth": auth,
}
}
// MarshalJSON converts the Dsn struct to JSON.
func (dsn Dsn) MarshalJSON() ([]byte, error) {
return json.Marshal(dsn.String())
}
// UnmarshalJSON converts JSON data to the Dsn struct.
func (dsn *Dsn) UnmarshalJSON(data []byte) error {
var str string
_ = json.Unmarshal(data, &str)
newDsn, err := NewDsn(str)
if err != nil {
return err
}
*dsn = *newDsn
return nil
return dsn.Dsn.RequestHeaders(SDKVersion)
}

View File

@@ -39,8 +39,6 @@ func DynamicSamplingContextFromHeader(header []byte) (DynamicSamplingContext, er
}
func DynamicSamplingContextFromTransaction(span *Span) DynamicSamplingContext {
entries := map[string]string{}
hub := hubFromContext(span.Context())
scope := hub.Scope()
client := hub.Client()
@@ -52,6 +50,8 @@ func DynamicSamplingContextFromTransaction(span *Span) DynamicSamplingContext {
}
}
entries := make(map[string]string)
if traceID := span.TraceID.String(); traceID != "" {
entries["trace_id"] = traceID
}
@@ -60,7 +60,7 @@ func DynamicSamplingContextFromTransaction(span *Span) DynamicSamplingContext {
}
if dsn := client.dsn; dsn != nil {
if publicKey := dsn.publicKey; publicKey != "" {
if publicKey := dsn.GetPublicKey(); publicKey != "" {
entries["public_key"] = publicKey
}
}
@@ -78,20 +78,9 @@ func DynamicSamplingContextFromTransaction(span *Span) DynamicSamplingContext {
}
}
if userSegment := scope.user.Segment; userSegment != "" {
entries["user_segment"] = userSegment
}
entries["sampled"] = strconv.FormatBool(span.Sampled.Bool())
if span.Sampled.Bool() {
entries["sampled"] = "true"
} else {
entries["sampled"] = "false"
}
return DynamicSamplingContext{
Entries: entries,
Frozen: true,
}
return DynamicSamplingContext{Entries: entries, Frozen: true}
}
func (d DynamicSamplingContext) HasEntries() bool {
@@ -111,13 +100,55 @@ func (d DynamicSamplingContext) String() string {
}
members = append(members, member)
}
if len(members) > 0 {
baggage, err := baggage.New(members...)
if err != nil {
return ""
}
return baggage.String()
if len(members) == 0 {
return ""
}
return ""
baggage, err := baggage.New(members...)
if err != nil {
return ""
}
return baggage.String()
}
// Constructs a new DynamicSamplingContext using a scope and client. Accessing
// fields on the scope are not thread safe, and this function should only be
// called within scope methods.
func DynamicSamplingContextFromScope(scope *Scope, client *Client) DynamicSamplingContext {
entries := map[string]string{}
if client == nil || scope == nil {
return DynamicSamplingContext{
Entries: entries,
Frozen: false,
}
}
propagationContext := scope.propagationContext
if traceID := propagationContext.TraceID.String(); traceID != "" {
entries["trace_id"] = traceID
}
if sampleRate := client.options.TracesSampleRate; sampleRate != 0 {
entries["sample_rate"] = strconv.FormatFloat(sampleRate, 'f', -1, 64)
}
if dsn := client.dsn; dsn != nil {
if publicKey := dsn.GetPublicKey(); publicKey != "" {
entries["public_key"] = publicKey
}
}
if release := client.options.Release; release != "" {
entries["release"] = release
}
if environment := client.options.Environment; environment != "" {
entries["environment"] = environment
}
return DynamicSamplingContext{
Entries: entries,
Frozen: true,
}
}

129
vendor/github.com/getsentry/sentry-go/exception.go generated vendored Normal file
View File

@@ -0,0 +1,129 @@
package sentry
import (
"fmt"
"reflect"
"slices"
)
const (
MechanismTypeGeneric string = "generic"
MechanismTypeChained string = "chained"
MechanismTypeUnwrap string = "unwrap"
MechanismSourceCause string = "cause"
)
type visited struct {
ptrs map[uintptr]struct{}
msgs map[string]struct{}
}
func (v *visited) seenError(err error) bool {
t := reflect.ValueOf(err)
if t.Kind() == reflect.Ptr && !t.IsNil() {
ptr := t.Pointer()
if _, ok := v.ptrs[ptr]; ok {
return true
}
v.ptrs[ptr] = struct{}{}
return false
}
key := t.String() + err.Error()
if _, ok := v.msgs[key]; ok {
return true
}
v.msgs[key] = struct{}{}
return false
}
func convertErrorToExceptions(err error, maxErrorDepth int) []Exception {
var exceptions []Exception
vis := &visited{
ptrs: make(map[uintptr]struct{}),
msgs: make(map[string]struct{}),
}
convertErrorDFS(err, &exceptions, nil, "", vis, maxErrorDepth, 0)
// mechanism type is used for debugging purposes, but since we can't really distinguish the origin of who invoked
// captureException, we set it to nil if the error is not chained.
if len(exceptions) == 1 {
exceptions[0].Mechanism = nil
}
slices.Reverse(exceptions)
// Add a trace of the current stack to the top level(outermost) error in a chain if
// it doesn't have a stack trace yet.
// We only add to the most recent error to avoid duplication and because the
// current stack is most likely unrelated to errors deeper in the chain.
if len(exceptions) > 0 && exceptions[len(exceptions)-1].Stacktrace == nil {
exceptions[len(exceptions)-1].Stacktrace = NewStacktrace()
}
return exceptions
}
func convertErrorDFS(err error, exceptions *[]Exception, parentID *int, source string, visited *visited, maxErrorDepth int, currentDepth int) {
if err == nil {
return
}
if visited.seenError(err) {
return
}
_, isExceptionGroup := err.(interface{ Unwrap() []error })
exception := Exception{
Value: err.Error(),
Type: reflect.TypeOf(err).String(),
Stacktrace: ExtractStacktrace(err),
}
currentID := len(*exceptions)
var mechanismType string
if parentID == nil {
mechanismType = MechanismTypeGeneric
source = ""
} else {
mechanismType = MechanismTypeChained
}
exception.Mechanism = &Mechanism{
Type: mechanismType,
ExceptionID: currentID,
ParentID: parentID,
Source: source,
IsExceptionGroup: isExceptionGroup,
}
*exceptions = append(*exceptions, exception)
if maxErrorDepth >= 0 && currentDepth >= maxErrorDepth {
return
}
switch v := err.(type) {
case interface{ Unwrap() []error }:
unwrapped := v.Unwrap()
for i := range unwrapped {
if unwrapped[i] != nil {
childSource := fmt.Sprintf("errors[%d]", i)
convertErrorDFS(unwrapped[i], exceptions, &currentID, childSource, visited, maxErrorDepth, currentDepth+1)
}
}
case interface{ Unwrap() error }:
unwrapped := v.Unwrap()
if unwrapped != nil {
convertErrorDFS(unwrapped, exceptions, &currentID, MechanismTypeUnwrap, visited, maxErrorDepth, currentDepth+1)
}
case interface{ Cause() error }:
cause := v.Cause()
if cause != nil {
convertErrorDFS(cause, exceptions, &currentID, MechanismSourceCause, visited, maxErrorDepth, currentDepth+1)
}
}
}

View File

@@ -2,8 +2,11 @@ package sentry
import (
"context"
"fmt"
"sync"
"time"
"github.com/getsentry/sentry-go/internal/debuglog"
)
type contextKey int
@@ -17,14 +20,6 @@ const (
RequestContextKey = contextKey(2)
)
// defaultMaxBreadcrumbs is the default maximum number of breadcrumbs added to
// an event. Can be overwritten with the maxBreadcrumbs option.
const defaultMaxBreadcrumbs = 30
// maxBreadcrumbs is the absolute maximum number of breadcrumbs added to an
// event. The maxBreadcrumbs option cannot be set higher than this value.
const maxBreadcrumbs = 100
// currentHub is the initial Hub with no Client bound and an empty Scope.
var currentHub = NewHub(nil, NewScope())
@@ -288,13 +283,16 @@ func (hub *Hub) AddBreadcrumb(breadcrumb *Breadcrumb, hint *BreadcrumbHint) {
// If there's no client, just store it on the scope straight away
if client == nil {
hub.Scope().AddBreadcrumb(breadcrumb, maxBreadcrumbs)
hub.Scope().AddBreadcrumb(breadcrumb, defaultMaxBreadcrumbs)
return
}
max := client.options.MaxBreadcrumbs
if max < 0 {
limit := client.options.MaxBreadcrumbs
switch {
case limit < 0:
return
case limit == 0:
limit = defaultMaxBreadcrumbs
}
if client.options.BeforeBreadcrumb != nil {
@@ -302,18 +300,12 @@ func (hub *Hub) AddBreadcrumb(breadcrumb *Breadcrumb, hint *BreadcrumbHint) {
hint = &BreadcrumbHint{}
}
if breadcrumb = client.options.BeforeBreadcrumb(breadcrumb, hint); breadcrumb == nil {
Logger.Println("breadcrumb dropped due to BeforeBreadcrumb callback.")
debuglog.Println("breadcrumb dropped due to BeforeBreadcrumb callback.")
return
}
}
if max == 0 {
max = defaultMaxBreadcrumbs
} else if max > maxBreadcrumbs {
max = maxBreadcrumbs
}
hub.Scope().AddBreadcrumb(breadcrumb, max)
hub.Scope().AddBreadcrumb(breadcrumb, limit)
}
// Recover calls the method of a same name on currently bound Client instance
@@ -365,6 +357,67 @@ func (hub *Hub) Flush(timeout time.Duration) bool {
return client.Flush(timeout)
}
// FlushWithContext waits until the underlying Transport sends any buffered events
// to the Sentry server, blocking for at most the duration specified by the context.
// It returns false if the context is canceled before the events are sent. In such a case,
// some events may not be delivered.
//
// FlushWithContext should be called before terminating the program to ensure no
// events are unintentionally dropped.
//
// Avoid calling FlushWithContext indiscriminately after each call to CaptureEvent,
// CaptureException, or CaptureMessage. To send events synchronously over the network,
// configure the SDK to use HTTPSyncTransport during initialization with Init.
func (hub *Hub) FlushWithContext(ctx context.Context) bool {
client := hub.Client()
if client == nil {
return false
}
return client.FlushWithContext(ctx)
}
// GetTraceparent returns the current Sentry traceparent string, to be used as a HTTP header value
// or HTML meta tag value.
// This function is context aware, as in it either returns the traceparent based
// on the current span, or the scope's propagation context.
func (hub *Hub) GetTraceparent() string {
scope := hub.Scope()
if scope.span != nil {
return scope.span.ToSentryTrace()
}
return fmt.Sprintf("%s-%s", scope.propagationContext.TraceID, scope.propagationContext.SpanID)
}
// GetTraceparentW3C returns the current traceparent string in W3C format.
// This is intended for propagation to downstream services that expect the W3C header.
func (hub *Hub) GetTraceparentW3C() string {
scope := hub.Scope()
if scope.span != nil {
return scope.span.ToTraceparent()
}
return fmt.Sprintf("00-%s-%s-00", scope.propagationContext.TraceID, scope.propagationContext.SpanID)
}
// GetBaggage returns the current Sentry baggage string, to be used as a HTTP header value
// or HTML meta tag value.
// This function is context aware, as in it either returns the baggage based
// on the current span or the scope's propagation context.
func (hub *Hub) GetBaggage() string {
scope := hub.Scope()
if scope.span != nil {
return scope.span.ToBaggage()
}
return scope.propagationContext.DynamicSamplingContext.String()
}
// HasHubOnContext checks whether Hub instance is bound to a given Context struct.
func HasHubOnContext(ctx context.Context) bool {
_, ok := ctx.Value(HubContextKey).(*Hub)

View File

@@ -8,6 +8,8 @@ import (
"runtime/debug"
"strings"
"sync"
"github.com/getsentry/sentry-go/internal/debuglog"
)
// ================================
@@ -32,7 +34,7 @@ func (mi *modulesIntegration) processor(event *Event, _ *EventHint) *Event {
mi.once.Do(func() {
info, ok := debug.ReadBuildInfo()
if !ok {
Logger.Print("The Modules integration is not available in binaries built without module support.")
debuglog.Print("The Modules integration is not available in binaries built without module support.")
return
}
mi.modules = extractModules(info)
@@ -140,8 +142,8 @@ func (iei *ignoreErrorsIntegration) processor(event *Event, _ *EventHint) *Event
for _, suspect := range suspects {
for _, pattern := range iei.ignoreErrors {
if pattern.Match([]byte(suspect)) {
Logger.Printf("Event dropped due to being matched by `IgnoreErrors` option."+
if pattern.Match([]byte(suspect)) || strings.Contains(suspect, pattern.String()) {
debuglog.Printf("Event dropped due to being matched by `IgnoreErrors` option."+
"| Value matched: %s | Filter used: %s", suspect, pattern)
return nil
}
@@ -202,8 +204,8 @@ func (iei *ignoreTransactionsIntegration) processor(event *Event, _ *EventHint)
}
for _, pattern := range iei.ignoreTransactions {
if pattern.Match([]byte(suspect)) {
Logger.Printf("Transaction dropped due to being matched by `IgnoreTransactions` option."+
if pattern.Match([]byte(suspect)) || strings.Contains(suspect, pattern.String()) {
debuglog.Printf("Transaction dropped due to being matched by `IgnoreTransactions` option."+
"| Value matched: %s | Filter used: %s", suspect, pattern)
return nil
}

View File

@@ -6,24 +6,35 @@ import (
"fmt"
"net"
"net/http"
"reflect"
"strings"
"time"
"github.com/getsentry/sentry-go/attribute"
"github.com/getsentry/sentry-go/internal/protocol"
"github.com/getsentry/sentry-go/internal/ratelimit"
)
// eventType is the type of an error event.
const errorType = ""
const eventType = "event"
// transactionType is the type of a transaction event.
const transactionType = "transaction"
// profileType is the type of a profile event.
// currently, profiles are always sent as part of a transaction event.
const profileType = "profile"
// checkInType is the type of a check in event.
const checkInType = "check_in"
var logEvent = struct {
Type string
ContentType string
}{
"log",
"application/vnd.sentry.items.log+json",
}
var traceMetricEvent = struct {
Type string
ContentType string
}{
"trace_metric",
"application/vnd.sentry.items.trace-metric+json",
}
// Level marks the severity of the event.
type Level string
@@ -36,28 +47,9 @@ const (
LevelFatal Level = "fatal"
)
func getSensitiveHeaders() map[string]bool {
return map[string]bool{
"Authorization": true,
"Cookie": true,
"X-Forwarded-For": true,
"X-Real-Ip": true,
}
}
// SdkInfo contains all metadata about about the SDK being used.
type SdkInfo struct {
Name string `json:"name,omitempty"`
Version string `json:"version,omitempty"`
Integrations []string `json:"integrations,omitempty"`
Packages []SdkPackage `json:"packages,omitempty"`
}
// SdkPackage describes a package that was installed.
type SdkPackage struct {
Name string `json:"name,omitempty"`
Version string `json:"version,omitempty"`
}
// SdkInfo contains all metadata about the SDK.
type SdkInfo = protocol.SdkInfo
type SdkPackage = protocol.SdkPackage
// TODO: This type could be more useful, as map of interface{} is too generic
// and requires a lot of type assertions in beforeBreadcrumb calls
@@ -97,7 +89,7 @@ func (b *Breadcrumb) MarshalJSON() ([]byte, error) {
if b.Timestamp.IsZero() {
return json.Marshal(struct {
// Embed all of the fields of Breadcrumb.
// Embed all the fields of Breadcrumb.
*breadcrumb
// Timestamp shadows the original Timestamp field and is meant to
// remain nil, triggering the omitempty behavior.
@@ -107,6 +99,111 @@ func (b *Breadcrumb) MarshalJSON() ([]byte, error) {
return json.Marshal((*breadcrumb)(b))
}
// Logger provides a chaining API for structured logging to Sentry.
type Logger interface {
// Write implements the io.Writer interface. Currently, the [sentry.Hub] is
// context aware, in order to get the correct trace correlation. Using this
// might result in incorrect span association on logs. If you need to use
// Write it is recommended to create a NewLogger so that the associated context
// is passed correctly.
Write(p []byte) (n int, err error)
// SetAttributes allows attaching parameters to the logger using the attribute API.
// These attributes will be included in all subsequent log entries.
SetAttributes(...attribute.Builder)
// Trace defines the [sentry.LogLevel] for the log entry.
Trace() LogEntry
// Debug defines the [sentry.LogLevel] for the log entry.
Debug() LogEntry
// Info defines the [sentry.LogLevel] for the log entry.
Info() LogEntry
// Warn defines the [sentry.LogLevel] for the log entry.
Warn() LogEntry
// Error defines the [sentry.LogLevel] for the log entry.
Error() LogEntry
// Fatal defines the [sentry.LogLevel] for the log entry.
Fatal() LogEntry
// Panic defines the [sentry.LogLevel] for the log entry.
Panic() LogEntry
// GetCtx returns the [context.Context] set on the logger.
GetCtx() context.Context
}
// LogEntry defines the interface for a log entry that supports chaining attributes.
type LogEntry interface {
// WithCtx creates a new LogEntry with the specified context without overwriting the previous one.
WithCtx(ctx context.Context) LogEntry
// String adds a string attribute to the LogEntry.
String(key, value string) LogEntry
// Int adds an int attribute to the LogEntry.
Int(key string, value int) LogEntry
// Int64 adds an int64 attribute to the LogEntry.
Int64(key string, value int64) LogEntry
// Float64 adds a float64 attribute to the LogEntry.
Float64(key string, value float64) LogEntry
// Bool adds a bool attribute to the LogEntry.
Bool(key string, value bool) LogEntry
// Emit emits the LogEntry with the provided arguments.
Emit(args ...interface{})
// Emitf emits the LogEntry using a format string and arguments.
Emitf(format string, args ...interface{})
}
// Meter provides an interface for recording metrics.
type Meter interface {
// WithCtx returns a new Meter that uses the given context for trace/span association.
WithCtx(ctx context.Context) Meter
// SetAttributes allows attaching parameters to the meter using the attribute API.
// These attributes will be included in all subsequent metrics.
SetAttributes(attrs ...attribute.Builder)
// Count records a count metric.
Count(name string, count int64, opts ...MeterOption)
// Gauge records a gauge metric.
Gauge(name string, value float64, opts ...MeterOption)
// Distribution records a distribution metric.
Distribution(name string, sample float64, opts ...MeterOption)
}
// MeterOption configures a metric recording call.
type MeterOption func(*meterOptions)
type meterOptions struct {
unit string
scope *Scope
attributes map[string]Attribute
}
// WithUnit sets the unit for the metric (e.g., "millisecond", "byte").
func WithUnit(unit string) MeterOption {
return func(o *meterOptions) {
o.unit = unit
}
}
// WithScopeOverride sets a custom scope for the metric, overriding the default scope from the hub.
func WithScopeOverride(scope *Scope) MeterOption {
return func(o *meterOptions) {
o.scope = scope
}
}
// WithAttributes sets attributes for the metric.
func WithAttributes(attrs ...attribute.Builder) MeterOption {
return func(o *meterOptions) {
if o.attributes == nil {
o.attributes = make(map[string]Attribute)
}
for _, attr := range attrs {
t, ok := mapTypesToStr[attr.Value.Type()]
if !ok || t == "" {
continue
}
o.attributes[attr.Key] = Attribute{Value: attr.Value.AsInterface(), Type: t}
}
}
}
// Attachment allows associating files with your events to aid in investigation.
// An event may contain one or more attachments.
type Attachment struct {
@@ -123,32 +220,27 @@ type User struct {
IPAddress string `json:"ip_address,omitempty"`
Username string `json:"username,omitempty"`
Name string `json:"name,omitempty"`
Segment string `json:"segment,omitempty"`
Data map[string]string `json:"data,omitempty"`
}
func (u User) IsEmpty() bool {
if len(u.ID) > 0 {
if u.ID != "" {
return false
}
if len(u.Email) > 0 {
if u.Email != "" {
return false
}
if len(u.IPAddress) > 0 {
if u.IPAddress != "" {
return false
}
if len(u.Username) > 0 {
if u.Username != "" {
return false
}
if len(u.Name) > 0 {
return false
}
if len(u.Segment) > 0 {
if u.Name != "" {
return false
}
@@ -170,16 +262,49 @@ type Request struct {
Env map[string]string `json:"env,omitempty"`
}
var sensitiveHeaders = map[string]struct{}{
"_csrf": {},
"_csrf_token": {},
"_session": {},
"_xsrf": {},
"Api-Key": {},
"Apikey": {},
"Auth": {},
"Authorization": {},
"Cookie": {},
"Credentials": {},
"Csrf": {},
"Csrf-Token": {},
"Csrftoken": {},
"Ip-Address": {},
"Passwd": {},
"Password": {},
"Private-Key": {},
"Privatekey": {},
"Proxy-Authorization": {},
"Remote-Addr": {},
"Secret": {},
"Session": {},
"Sessionid": {},
"Token": {},
"User-Session": {},
"X-Api-Key": {},
"X-Csrftoken": {},
"X-Forwarded-For": {},
"X-Real-Ip": {},
"XSRF-TOKEN": {},
}
// NewRequest returns a new Sentry Request from the given http.Request.
//
// NewRequest avoids operations that depend on network access. In particular, it
// does not read r.Body.
func NewRequest(r *http.Request) *Request {
protocol := schemeHTTP
prot := protocol.SchemeHTTP
if r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https" {
protocol = schemeHTTPS
prot = protocol.SchemeHTTPS
}
url := fmt.Sprintf("%s://%s%s", protocol, r.Host, r.URL.Path)
url := fmt.Sprintf("%s://%s%s", prot, r.Host, r.URL.Path)
var cookies string
var env map[string]string
@@ -192,6 +317,7 @@ func NewRequest(r *http.Request) *Request {
// attach more than one Cookie header field.
cookies = r.Header.Get("Cookie")
headers = make(map[string]string, len(r.Header))
for k, v := range r.Header {
headers[k] = strings.Join(v, ",")
}
@@ -200,7 +326,6 @@ func NewRequest(r *http.Request) *Request {
env = map[string]string{"REMOTE_ADDR": addr, "REMOTE_PORT": port}
}
} else {
sensitiveHeaders := getSensitiveHeaders()
for k, v := range r.Header {
if _, ok := sensitiveHeaders[k]; !ok {
headers[k] = strings.Join(v, ",")
@@ -222,18 +347,21 @@ func NewRequest(r *http.Request) *Request {
// Mechanism is the mechanism by which an exception was generated and handled.
type Mechanism struct {
Type string `json:"type,omitempty"`
Description string `json:"description,omitempty"`
HelpLink string `json:"help_link,omitempty"`
Handled *bool `json:"handled,omitempty"`
Data map[string]interface{} `json:"data,omitempty"`
Type string `json:"type"`
Description string `json:"description,omitempty"`
HelpLink string `json:"help_link,omitempty"`
Source string `json:"source,omitempty"`
Handled *bool `json:"handled,omitempty"`
ParentID *int `json:"parent_id,omitempty"`
ExceptionID int `json:"exception_id"`
IsExceptionGroup bool `json:"is_exception_group,omitempty"`
Data map[string]any `json:"data,omitempty"`
}
// SetUnhandled indicates that the exception is an unhandled exception, i.e.
// from a panic.
func (m *Mechanism) SetUnhandled() {
h := false
m.Handled = &h
m.Handled = Pointer(false)
}
// Exception specifies an error that occurred.
@@ -249,8 +377,7 @@ type Exception struct {
// SDKMetaData is a struct to stash data which is needed at some point in the SDK's event processing pipeline
// but which shouldn't get send to Sentry.
type SDKMetaData struct {
dsc DynamicSamplingContext
transactionProfile *profileInfo
dsc DynamicSamplingContext
}
// Contains information about how the name of the transaction was determined.
@@ -331,6 +458,12 @@ type Event struct {
CheckIn *CheckIn `json:"check_in,omitempty"`
MonitorConfig *MonitorConfig `json:"monitor_config,omitempty"`
// The fields below are only relevant for logs
Logs []Log `json:"-"`
// The fields below are only relevant for metrics
Metrics []Metric `json:"-"`
// The fields below are not part of the final JSON payload.
sdkMetaData SDKMetaData
@@ -339,39 +472,85 @@ type Event struct {
// SetException appends the unwrapped errors to the event's exception list.
//
// maxErrorDepth is the maximum depth of the error chain we will look
// into while unwrapping the errors.
// into while unwrapping the errors. If maxErrorDepth is -1, we will
// unwrap all errors in the chain.
func (e *Event) SetException(exception error, maxErrorDepth int) {
err := exception
if err == nil {
if exception == nil {
return
}
for i := 0; i < maxErrorDepth && err != nil; i++ {
e.Exception = append(e.Exception, Exception{
Value: err.Error(),
Type: reflect.TypeOf(err).String(),
Stacktrace: ExtractStacktrace(err),
})
switch previous := err.(type) {
case interface{ Unwrap() error }:
err = previous.Unwrap()
case interface{ Cause() error }:
err = previous.Cause()
default:
err = nil
exceptions := convertErrorToExceptions(exception, maxErrorDepth)
if len(exceptions) == 0 {
return
}
e.Exception = exceptions
}
// ToEnvelopeItem converts the Event to a Sentry envelope item.
func (e *Event) ToEnvelopeItem() (*protocol.EnvelopeItem, error) {
eventBody, err := json.Marshal(e)
if err != nil {
// Try fallback: remove problematic fields and retry
e.Breadcrumbs = nil
e.Contexts = nil
e.Extra = map[string]interface{}{
"info": fmt.Sprintf("Could not encode original event as JSON. "+
"Succeeded by removing Breadcrumbs, Contexts and Extra. "+
"Please verify the data you attach to the scope. "+
"Error: %s", err),
}
eventBody, err = json.Marshal(e)
if err != nil {
return nil, fmt.Errorf("event could not be marshaled even with fallback: %w", err)
}
DebugLogger.Printf("Event marshaling succeeded with fallback after removing problematic fields")
}
// TODO: all event types should be abstracted to implement EnvelopeItemConvertible and convert themselves.
var item *protocol.EnvelopeItem
switch e.Type {
case transactionType:
item = protocol.NewEnvelopeItem(protocol.EnvelopeItemTypeTransaction, eventBody)
case checkInType:
item = protocol.NewEnvelopeItem(protocol.EnvelopeItemTypeCheckIn, eventBody)
case logEvent.Type:
item = protocol.NewLogItem(len(e.Logs), eventBody)
case traceMetricEvent.Type:
item = protocol.NewTraceMetricItem(len(e.Metrics), eventBody)
default:
item = protocol.NewEnvelopeItem(protocol.EnvelopeItemTypeEvent, eventBody)
}
return item, nil
}
// GetCategory returns the rate limit category for this event.
func (e *Event) GetCategory() ratelimit.Category {
return e.toCategory()
}
// GetEventID returns the event ID.
func (e *Event) GetEventID() string {
return string(e.EventID)
}
// GetSdkInfo returns SDK information for the envelope header.
func (e *Event) GetSdkInfo() *protocol.SdkInfo {
return &e.Sdk
}
// GetDynamicSamplingContext returns trace context for the envelope header.
func (e *Event) GetDynamicSamplingContext() map[string]string {
trace := make(map[string]string)
if dsc := e.sdkMetaData.dsc; dsc.HasEntries() {
for k, v := range dsc.Entries {
trace[k] = v
}
}
// Add a trace of the current stack to the most recent error in a chain if
// it doesn't have a stack trace yet.
// We only add to the most recent error to avoid duplication and because the
// current stack is most likely unrelated to errors deeper in the chain.
if e.Exception[0].Stacktrace == nil {
e.Exception[0].Stacktrace = NewStacktrace()
}
// event.Exception should be sorted such that the most recent error is last.
reverse(e.Exception)
return trace
}
// TODO: Event.Contexts map[string]interface{} => map[string]EventContext,
@@ -391,7 +570,9 @@ func (e *Event) MarshalJSON() ([]byte, error) {
// and a few type tricks.
if e.Type == transactionType {
return e.transactionMarshalJSON()
} else if e.Type == checkInType {
}
if e.Type == checkInType {
return e.checkInMarshalJSON()
}
return e.defaultMarshalJSON()
@@ -402,6 +583,33 @@ func (e *Event) defaultMarshalJSON() ([]byte, error) {
// loop. It preserves all fields while none of the attached methods.
type event Event
// metrics and logs should be serialized under the same `items` json field.
if e.Type == logEvent.Type {
type logEvent struct {
*event
Items []Log `json:"items,omitempty"`
Type json.RawMessage `json:"type,omitempty"`
Timestamp json.RawMessage `json:"timestamp,omitempty"`
StartTime json.RawMessage `json:"start_timestamp,omitempty"`
Spans json.RawMessage `json:"spans,omitempty"`
TransactionInfo json.RawMessage `json:"transaction_info,omitempty"`
}
return json.Marshal(logEvent{event: (*event)(e), Items: e.Logs})
}
if e.Type == traceMetricEvent.Type {
type metricEvent struct {
*event
Items []Metric `json:"items,omitempty"`
Type json.RawMessage `json:"type,omitempty"`
Timestamp json.RawMessage `json:"timestamp,omitempty"`
StartTime json.RawMessage `json:"start_timestamp,omitempty"`
Spans json.RawMessage `json:"spans,omitempty"`
TransactionInfo json.RawMessage `json:"transaction_info,omitempty"`
}
return json.Marshal(metricEvent{event: (*event)(e), Items: e.Metrics})
}
// errorEvent is like Event with shadowed fields for customizing JSON
// marshaling.
type errorEvent struct {
@@ -480,25 +688,43 @@ func (e *Event) checkInMarshalJSON() ([]byte, error) {
if e.MonitorConfig != nil {
checkIn.MonitorConfig = &MonitorConfig{
Schedule: e.MonitorConfig.Schedule,
CheckInMargin: e.MonitorConfig.CheckInMargin,
MaxRuntime: e.MonitorConfig.MaxRuntime,
Timezone: e.MonitorConfig.Timezone,
Schedule: e.MonitorConfig.Schedule,
CheckInMargin: e.MonitorConfig.CheckInMargin,
MaxRuntime: e.MonitorConfig.MaxRuntime,
Timezone: e.MonitorConfig.Timezone,
FailureIssueThreshold: e.MonitorConfig.FailureIssueThreshold,
RecoveryThreshold: e.MonitorConfig.RecoveryThreshold,
}
}
return json.Marshal(checkIn)
}
func (e *Event) toCategory() ratelimit.Category {
switch e.Type {
case errorType:
return ratelimit.CategoryError
case transactionType:
return ratelimit.CategoryTransaction
case logEvent.Type:
return ratelimit.CategoryLog
case checkInType:
return ratelimit.CategoryMonitor
case traceMetricEvent.Type:
return ratelimit.CategoryTraceMetric
default:
return ratelimit.CategoryUnknown
}
}
// NewEvent creates a new Event.
func NewEvent() *Event {
event := Event{
return &Event{
Contexts: make(map[string]Context),
Extra: make(map[string]interface{}),
Tags: make(map[string]string),
Modules: make(map[string]string),
}
return &event
}
// Thread specifies threads that were running at the time of an event.
@@ -520,3 +746,198 @@ type EventHint struct {
Request *http.Request
Response *http.Response
}
type Log struct {
Timestamp time.Time `json:"timestamp"`
TraceID TraceID `json:"trace_id"`
SpanID SpanID `json:"span_id,omitempty"`
Level LogLevel `json:"level"`
Severity int `json:"severity_number,omitempty"`
Body string `json:"body"`
Attributes map[string]Attribute `json:"attributes,omitempty"`
}
// GetCategory returns the rate limit category for logs.
func (l *Log) GetCategory() ratelimit.Category {
return ratelimit.CategoryLog
}
// GetEventID returns empty string (event ID set when batching).
func (l *Log) GetEventID() string {
return ""
}
// GetSdkInfo returns nil (SDK info set when batching).
func (l *Log) GetSdkInfo() *protocol.SdkInfo {
return nil
}
// GetDynamicSamplingContext returns nil (trace context set when batching).
func (l *Log) GetDynamicSamplingContext() map[string]string {
return nil
}
type AttrType string
const (
AttributeInvalid AttrType = ""
AttributeBool AttrType = "boolean"
AttributeInt AttrType = "integer"
AttributeFloat AttrType = "double"
AttributeString AttrType = "string"
)
type Attribute struct {
Value any `json:"value"`
Type AttrType `json:"type"`
}
// MarshalJSON converts a Log to JSON that skips SpanID and timestamp when zero.
func (l *Log) MarshalJSON() ([]byte, error) {
type log Log
var spanID string
if l.SpanID != zeroSpanID {
spanID = l.SpanID.String()
}
var ts json.RawMessage
if !l.Timestamp.IsZero() {
b, err := l.Timestamp.MarshalJSON()
if err != nil {
return nil, err
}
ts = b
}
return json.Marshal(struct {
*log
SpanID string `json:"span_id,omitempty"`
Timestamp json.RawMessage `json:"timestamp,omitempty"`
}{
log: (*log)(l),
SpanID: spanID,
Timestamp: ts,
})
}
type MetricType string
const (
MetricTypeInvalid MetricType = ""
MetricTypeCounter MetricType = "counter"
MetricTypeGauge MetricType = "gauge"
MetricTypeDistribution MetricType = "distribution"
)
type Metric struct {
Timestamp time.Time `json:"timestamp"`
TraceID TraceID `json:"trace_id"`
SpanID SpanID `json:"span_id,omitempty"`
Type MetricType `json:"type"`
Name string `json:"name"`
Value MetricValue `json:"value"`
Unit string `json:"unit,omitempty"`
Attributes map[string]Attribute `json:"attributes,omitempty"`
}
// MarshalJSON converts a Metric to JSON that skips SpanID and timestamp when zero.
func (m *Metric) MarshalJSON() ([]byte, error) {
type metric Metric
var spanID string
if m.SpanID != zeroSpanID {
spanID = m.SpanID.String()
}
var ts json.RawMessage
if !m.Timestamp.IsZero() {
b, err := m.Timestamp.MarshalJSON()
if err != nil {
return nil, err
}
ts = b
}
return json.Marshal(struct {
*metric
SpanID string `json:"span_id,omitempty"`
Timestamp json.RawMessage `json:"timestamp,omitempty"`
}{
metric: (*metric)(m),
SpanID: spanID,
Timestamp: ts,
})
}
// GetCategory returns the rate limit category for metrics.
func (m *Metric) GetCategory() ratelimit.Category {
return ratelimit.CategoryTraceMetric
}
// GetEventID returns empty string (event ID set when batching).
func (m *Metric) GetEventID() string {
return ""
}
// GetSdkInfo returns nil (SDK info set when batching).
func (m *Metric) GetSdkInfo() *protocol.SdkInfo {
return nil
}
// GetDynamicSamplingContext returns nil (trace context set when batching).
func (m *Metric) GetDynamicSamplingContext() map[string]string {
return nil
}
// MetricValue stores metric values with full precision.
// It supports int64 (for counters) and float64 (for gauges and distributions).
type MetricValue struct {
value attribute.Value
}
// Int64MetricValue creates a MetricValue from an int64.
// Used for counter metrics to preserve full int64 precision.
func Int64MetricValue(v int64) MetricValue {
return MetricValue{value: attribute.Int64Value(v)}
}
// Float64MetricValue creates a MetricValue from a float64.
// Used for gauge and distribution metrics.
func Float64MetricValue(v float64) MetricValue {
return MetricValue{value: attribute.Float64Value(v)}
}
// Type returns the type of the stored value (attribute.INT64 or attribute.FLOAT64).
func (v MetricValue) Type() attribute.Type {
return v.value.Type()
}
// Int64 returns the value as int64 if it holds an int64.
// The second return value indicates whether the type matched.
func (v MetricValue) Int64() (int64, bool) {
if v.value.Type() == attribute.INT64 {
return v.value.AsInt64(), true
}
return 0, false
}
// Float64 returns the value as float64 if it holds a float64.
// The second return value indicates whether the type matched.
func (v MetricValue) Float64() (float64, bool) {
if v.value.Type() == attribute.FLOAT64 {
return v.value.AsFloat64(), true
}
return 0, false
}
// AsInterface returns the value as int64 or float64.
// Use type assertion or type switch to handle the result.
func (v MetricValue) AsInterface() any {
return v.value.AsInterface()
}
// MarshalJSON serializes the value as a bare number.
func (v MetricValue) MarshalJSON() ([]byte, error) {
return json.Marshal(v.value.AsInterface())
}

View File

@@ -0,0 +1,35 @@
package debuglog
import (
"io"
"log"
)
// logger is the global debug logger instance.
var logger = log.New(io.Discard, "[Sentry] ", log.LstdFlags)
// SetOutput changes the output destination of the logger.
func SetOutput(w io.Writer) {
logger.SetOutput(w)
}
// GetLogger returns the current logger instance.
// This function is thread-safe and can be called concurrently.
func GetLogger() *log.Logger {
return logger
}
// Printf calls Printf on the underlying logger.
func Printf(format string, args ...interface{}) {
logger.Printf(format, args...)
}
// Println calls Println on the underlying logger.
func Println(args ...interface{}) {
logger.Println(args...)
}
// Print calls Print on the underlying logger.
func Print(args ...interface{}) {
logger.Print(args...)
}

View File

@@ -0,0 +1,572 @@
package http
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"sync"
"sync/atomic"
"time"
"github.com/getsentry/sentry-go/internal/debuglog"
"github.com/getsentry/sentry-go/internal/protocol"
"github.com/getsentry/sentry-go/internal/ratelimit"
)
const (
apiVersion = 7
defaultTimeout = time.Second * 30
defaultQueueSize = 1000
// maxDrainResponseBytes is the maximum number of bytes that transport
// implementations will read from response bodies when draining them.
maxDrainResponseBytes = 16 << 10
)
var (
ErrTransportQueueFull = errors.New("transport queue full")
ErrTransportClosed = errors.New("transport is closed")
ErrEmptyEnvelope = errors.New("empty envelope provided")
)
type TransportOptions struct {
Dsn string
HTTPClient *http.Client
HTTPTransport http.RoundTripper
HTTPProxy string
HTTPSProxy string
CaCerts *x509.CertPool
}
func getProxyConfig(options TransportOptions) func(*http.Request) (*url.URL, error) {
if len(options.HTTPSProxy) > 0 {
return func(*http.Request) (*url.URL, error) {
return url.Parse(options.HTTPSProxy)
}
}
if len(options.HTTPProxy) > 0 {
return func(*http.Request) (*url.URL, error) {
return url.Parse(options.HTTPProxy)
}
}
return http.ProxyFromEnvironment
}
func getTLSConfig(options TransportOptions) *tls.Config {
if options.CaCerts != nil {
return &tls.Config{
RootCAs: options.CaCerts,
MinVersion: tls.VersionTLS12,
}
}
return nil
}
func getSentryRequestFromEnvelope(ctx context.Context, dsn *protocol.Dsn, envelope *protocol.Envelope) (r *http.Request, err error) {
defer func() {
if r != nil {
sdkName := envelope.Header.Sdk.Name
sdkVersion := envelope.Header.Sdk.Version
r.Header.Set("User-Agent", fmt.Sprintf("%s/%s", sdkName, sdkVersion))
r.Header.Set("Content-Type", "application/x-sentry-envelope")
auth := fmt.Sprintf("Sentry sentry_version=%d, "+
"sentry_client=%s/%s, sentry_key=%s", apiVersion, sdkName, sdkVersion, dsn.GetPublicKey())
if dsn.GetSecretKey() != "" {
auth = fmt.Sprintf("%s, sentry_secret=%s", auth, dsn.GetSecretKey())
}
r.Header.Set("X-Sentry-Auth", auth)
}
}()
var buf bytes.Buffer
_, err = envelope.WriteTo(&buf)
if err != nil {
return nil, err
}
return http.NewRequestWithContext(
ctx,
http.MethodPost,
dsn.GetAPIURL().String(),
&buf,
)
}
func categoryFromEnvelope(envelope *protocol.Envelope) ratelimit.Category {
if envelope == nil || len(envelope.Items) == 0 {
return ratelimit.CategoryAll
}
for _, item := range envelope.Items {
if item == nil || item.Header == nil {
continue
}
switch item.Header.Type {
case protocol.EnvelopeItemTypeEvent:
return ratelimit.CategoryError
case protocol.EnvelopeItemTypeTransaction:
return ratelimit.CategoryTransaction
case protocol.EnvelopeItemTypeCheckIn:
return ratelimit.CategoryMonitor
case protocol.EnvelopeItemTypeLog:
return ratelimit.CategoryLog
case protocol.EnvelopeItemTypeAttachment:
continue
default:
return ratelimit.CategoryAll
}
}
return ratelimit.CategoryAll
}
// SyncTransport is a blocking implementation of Transport.
//
// Clients using this transport will send requests to Sentry sequentially and
// block until a response is returned.
//
// The blocking behavior is useful in a limited set of use cases. For example,
// use it when deploying code to a Function as a Service ("Serverless")
// platform, where any work happening in a background goroutine is not
// guaranteed to execute.
//
// For most cases, prefer AsyncTransport.
type SyncTransport struct {
dsn *protocol.Dsn
client *http.Client
transport http.RoundTripper
mu sync.Mutex
limits ratelimit.Map
Timeout time.Duration
}
func NewSyncTransport(options TransportOptions) protocol.TelemetryTransport {
dsn, err := protocol.NewDsn(options.Dsn)
if err != nil || dsn == nil {
debuglog.Printf("Transport is disabled: invalid dsn: %v\n", err)
return NewNoopTransport()
}
transport := &SyncTransport{
Timeout: defaultTimeout,
limits: make(ratelimit.Map),
dsn: dsn,
}
if options.HTTPTransport != nil {
transport.transport = options.HTTPTransport
} else {
transport.transport = &http.Transport{
Proxy: getProxyConfig(options),
TLSClientConfig: getTLSConfig(options),
}
}
if options.HTTPClient != nil {
transport.client = options.HTTPClient
} else {
transport.client = &http.Client{
Transport: transport.transport,
Timeout: transport.Timeout,
}
}
return transport
}
func (t *SyncTransport) SendEnvelope(envelope *protocol.Envelope) error {
return t.SendEnvelopeWithContext(context.Background(), envelope)
}
func (t *SyncTransport) Close() {}
func (t *SyncTransport) IsRateLimited(category ratelimit.Category) bool {
return t.disabled(category)
}
func (t *SyncTransport) HasCapacity() bool { return true }
func (t *SyncTransport) SendEnvelopeWithContext(ctx context.Context, envelope *protocol.Envelope) error {
if envelope == nil || len(envelope.Items) == 0 {
return ErrEmptyEnvelope
}
category := categoryFromEnvelope(envelope)
if t.disabled(category) {
return nil
}
request, err := getSentryRequestFromEnvelope(ctx, t.dsn, envelope)
if err != nil {
debuglog.Printf("There was an issue creating the request: %v", err)
return err
}
debuglog.Printf(
"Sending %s [%s] to %s project: %s",
envelope.Items[0].Header.Type,
envelope.Header.EventID,
t.dsn.GetHost(),
t.dsn.GetProjectID(),
)
response, err := t.client.Do(request)
if err != nil {
debuglog.Printf("There was an issue with sending an event: %v", err)
return err
}
if response.StatusCode >= 400 && response.StatusCode <= 599 {
b, err := io.ReadAll(response.Body)
if err != nil {
debuglog.Printf("Error while reading response body: %v", err)
}
debuglog.Printf("Sending %s failed with the following error: %s", envelope.Header.EventID, string(b))
}
t.mu.Lock()
if t.limits == nil {
t.limits = make(ratelimit.Map)
}
t.limits.Merge(ratelimit.FromResponse(response))
t.mu.Unlock()
_, _ = io.CopyN(io.Discard, response.Body, maxDrainResponseBytes)
return response.Body.Close()
}
func (t *SyncTransport) Flush(_ time.Duration) bool {
return true
}
func (t *SyncTransport) FlushWithContext(_ context.Context) bool {
return true
}
func (t *SyncTransport) disabled(c ratelimit.Category) bool {
t.mu.Lock()
defer t.mu.Unlock()
disabled := t.limits.IsRateLimited(c)
if disabled {
debuglog.Printf("Too many requests for %q, backing off till: %v", c, t.limits.Deadline(c))
}
return disabled
}
// AsyncTransport is the default, non-blocking, implementation of Transport.
//
// Clients using this transport will enqueue requests in a queue and return to
// the caller before any network communication has happened. Requests are sent
// to Sentry sequentially from a background goroutine.
type AsyncTransport struct {
dsn *protocol.Dsn
client *http.Client
transport http.RoundTripper
queue chan *protocol.Envelope
mu sync.RWMutex
limits ratelimit.Map
done chan struct{}
wg sync.WaitGroup
flushRequest chan chan struct{}
sentCount int64
droppedCount int64
errorCount int64
QueueSize int
Timeout time.Duration
startOnce sync.Once
closeOnce sync.Once
}
func NewAsyncTransport(options TransportOptions) protocol.TelemetryTransport {
dsn, err := protocol.NewDsn(options.Dsn)
if err != nil || dsn == nil {
debuglog.Printf("Transport is disabled: invalid dsn: %v", err)
return NewNoopTransport()
}
transport := &AsyncTransport{
QueueSize: defaultQueueSize,
Timeout: defaultTimeout,
done: make(chan struct{}),
limits: make(ratelimit.Map),
dsn: dsn,
}
transport.queue = make(chan *protocol.Envelope, transport.QueueSize)
transport.flushRequest = make(chan chan struct{})
if options.HTTPTransport != nil {
transport.transport = options.HTTPTransport
} else {
transport.transport = &http.Transport{
Proxy: getProxyConfig(options),
TLSClientConfig: getTLSConfig(options),
}
}
if options.HTTPClient != nil {
transport.client = options.HTTPClient
} else {
transport.client = &http.Client{
Transport: transport.transport,
Timeout: transport.Timeout,
}
}
transport.start()
return transport
}
func (t *AsyncTransport) start() {
t.startOnce.Do(func() {
t.wg.Add(1)
go t.worker()
})
}
// HasCapacity reports whether the async transport queue appears to have space
// for at least one more envelope. This is a best-effort, non-blocking check.
func (t *AsyncTransport) HasCapacity() bool {
t.mu.RLock()
defer t.mu.RUnlock()
select {
case <-t.done:
return false
default:
}
return len(t.queue) < cap(t.queue)
}
func (t *AsyncTransport) SendEnvelope(envelope *protocol.Envelope) error {
select {
case <-t.done:
return ErrTransportClosed
default:
}
if envelope == nil || len(envelope.Items) == 0 {
return ErrEmptyEnvelope
}
category := categoryFromEnvelope(envelope)
if t.isRateLimited(category) {
return nil
}
select {
case t.queue <- envelope:
debuglog.Printf(
"Sending %s [%s] to %s project: %s",
envelope.Items[0].Header.Type,
envelope.Header.EventID,
t.dsn.GetHost(),
t.dsn.GetProjectID(),
)
return nil
default:
atomic.AddInt64(&t.droppedCount, 1)
return ErrTransportQueueFull
}
}
func (t *AsyncTransport) Flush(timeout time.Duration) bool {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
return t.FlushWithContext(ctx)
}
func (t *AsyncTransport) FlushWithContext(ctx context.Context) bool {
flushResponse := make(chan struct{})
select {
case t.flushRequest <- flushResponse:
select {
case <-flushResponse:
debuglog.Println("Buffer flushed successfully.")
return true
case <-ctx.Done():
debuglog.Println("Failed to flush, buffer timed out.")
return false
}
case <-ctx.Done():
debuglog.Println("Failed to flush, buffer timed out.")
return false
}
}
func (t *AsyncTransport) Close() {
t.closeOnce.Do(func() {
close(t.done)
close(t.queue)
close(t.flushRequest)
t.wg.Wait()
})
}
func (t *AsyncTransport) IsRateLimited(category ratelimit.Category) bool {
return t.isRateLimited(category)
}
func (t *AsyncTransport) worker() {
defer t.wg.Done()
for {
select {
case <-t.done:
return
case envelope, open := <-t.queue:
if !open {
return
}
t.processEnvelope(envelope)
case flushResponse, open := <-t.flushRequest:
if !open {
return
}
t.drainQueue()
close(flushResponse)
}
}
}
func (t *AsyncTransport) drainQueue() {
for {
select {
case envelope, open := <-t.queue:
if !open {
return
}
t.processEnvelope(envelope)
default:
return
}
}
}
func (t *AsyncTransport) processEnvelope(envelope *protocol.Envelope) {
if t.sendEnvelopeHTTP(envelope) {
atomic.AddInt64(&t.sentCount, 1)
} else {
atomic.AddInt64(&t.errorCount, 1)
}
}
func (t *AsyncTransport) sendEnvelopeHTTP(envelope *protocol.Envelope) bool {
category := categoryFromEnvelope(envelope)
if t.isRateLimited(category) {
return false
}
ctx, cancel := context.WithTimeout(context.Background(), defaultTimeout)
defer cancel()
request, err := getSentryRequestFromEnvelope(ctx, t.dsn, envelope)
if err != nil {
debuglog.Printf("Failed to create request from envelope: %v", err)
return false
}
response, err := t.client.Do(request)
if err != nil {
debuglog.Printf("HTTP request failed: %v", err)
return false
}
defer response.Body.Close()
success := t.handleResponse(response)
t.mu.Lock()
if t.limits == nil {
t.limits = make(ratelimit.Map)
}
t.limits.Merge(ratelimit.FromResponse(response))
t.mu.Unlock()
_, _ = io.CopyN(io.Discard, response.Body, maxDrainResponseBytes)
return success
}
func (t *AsyncTransport) handleResponse(response *http.Response) bool {
if response.StatusCode >= 200 && response.StatusCode < 300 {
return true
}
if response.StatusCode >= 400 && response.StatusCode < 500 {
if body, err := io.ReadAll(io.LimitReader(response.Body, maxDrainResponseBytes)); err == nil {
debuglog.Printf("Client error %d: %s", response.StatusCode, string(body))
}
return false
}
if response.StatusCode >= 500 {
debuglog.Printf("Server error %d", response.StatusCode)
return false
}
debuglog.Printf("Unexpected status code %d", response.StatusCode)
return false
}
func (t *AsyncTransport) isRateLimited(category ratelimit.Category) bool {
t.mu.RLock()
defer t.mu.RUnlock()
limited := t.limits.IsRateLimited(category)
if limited {
debuglog.Printf("Rate limited for category %q until %v", category, t.limits.Deadline(category))
}
return limited
}
// NoopTransport is a transport implementation that drops all events.
// Used internally when an empty or invalid DSN is provided.
type NoopTransport struct{}
func NewNoopTransport() *NoopTransport {
debuglog.Println("Transport initialized with invalid DSN. Using NoopTransport. No events will be delivered.")
return &NoopTransport{}
}
func (t *NoopTransport) SendEnvelope(_ *protocol.Envelope) error {
debuglog.Println("Envelope dropped due to NoopTransport usage.")
return nil
}
func (t *NoopTransport) IsRateLimited(_ ratelimit.Category) bool {
return false
}
func (t *NoopTransport) Flush(_ time.Duration) bool {
return true
}
func (t *NoopTransport) FlushWithContext(_ context.Context) bool {
return true
}
func (t *NoopTransport) Close() {
// Nothing to close
}
func (t *NoopTransport) HasCapacity() bool { return true }

View File

@@ -0,0 +1,236 @@
package protocol
import (
"encoding/json"
"fmt"
"net/url"
"strconv"
"strings"
"time"
)
// apiVersion is the version of the Sentry API.
const apiVersion = "7"
type scheme string
const (
SchemeHTTP scheme = "http"
SchemeHTTPS scheme = "https"
)
func (scheme scheme) defaultPort() int {
switch scheme {
case SchemeHTTPS:
return 443
case SchemeHTTP:
return 80
default:
return 80
}
}
// DsnParseError represents an error that occurs if a Sentry
// DSN cannot be parsed.
type DsnParseError struct {
Message string
}
func (e DsnParseError) Error() string {
return "[Sentry] DsnParseError: " + e.Message
}
// Dsn is used as the remote address source to client transport.
type Dsn struct {
scheme scheme
publicKey string
secretKey string
host string
port int
path string
projectID string
}
// NewDsn creates a Dsn by parsing rawURL. Most users will never call this
// function directly. It is provided for use in custom Transport
// implementations.
func NewDsn(rawURL string) (*Dsn, error) {
// Parse
parsedURL, err := url.Parse(rawURL)
if err != nil {
return nil, &DsnParseError{fmt.Sprintf("invalid url: %v", err)}
}
// Scheme
var scheme scheme
switch parsedURL.Scheme {
case "http":
scheme = SchemeHTTP
case "https":
scheme = SchemeHTTPS
default:
return nil, &DsnParseError{"invalid scheme"}
}
// PublicKey
publicKey := parsedURL.User.Username()
if publicKey == "" {
return nil, &DsnParseError{"empty username"}
}
// SecretKey
var secretKey string
if parsedSecretKey, ok := parsedURL.User.Password(); ok {
secretKey = parsedSecretKey
}
// Host
host := parsedURL.Hostname()
if host == "" {
return nil, &DsnParseError{"empty host"}
}
// Port
var port int
if p := parsedURL.Port(); p != "" {
port, err = strconv.Atoi(p)
if err != nil {
return nil, &DsnParseError{"invalid port"}
}
} else {
port = scheme.defaultPort()
}
// ProjectID
if parsedURL.Path == "" || parsedURL.Path == "/" {
return nil, &DsnParseError{"empty project id"}
}
pathSegments := strings.Split(parsedURL.Path[1:], "/")
projectID := pathSegments[len(pathSegments)-1]
if projectID == "" {
return nil, &DsnParseError{"empty project id"}
}
// Path
var path string
if len(pathSegments) > 1 {
path = "/" + strings.Join(pathSegments[0:len(pathSegments)-1], "/")
}
return &Dsn{
scheme: scheme,
publicKey: publicKey,
secretKey: secretKey,
host: host,
port: port,
path: path,
projectID: projectID,
}, nil
}
// String formats Dsn struct into a valid string url.
func (dsn Dsn) String() string {
var url string
url += fmt.Sprintf("%s://%s", dsn.scheme, dsn.publicKey)
if dsn.secretKey != "" {
url += fmt.Sprintf(":%s", dsn.secretKey)
}
url += fmt.Sprintf("@%s", dsn.host)
if dsn.port != dsn.scheme.defaultPort() {
url += fmt.Sprintf(":%d", dsn.port)
}
if dsn.path != "" {
url += dsn.path
}
url += fmt.Sprintf("/%s", dsn.projectID)
return url
}
// Get the scheme of the DSN.
func (dsn Dsn) GetScheme() string {
return string(dsn.scheme)
}
// Get the public key of the DSN.
func (dsn Dsn) GetPublicKey() string {
return dsn.publicKey
}
// Get the secret key of the DSN.
func (dsn Dsn) GetSecretKey() string {
return dsn.secretKey
}
// Get the host of the DSN.
func (dsn Dsn) GetHost() string {
return dsn.host
}
// Get the port of the DSN.
func (dsn Dsn) GetPort() int {
return dsn.port
}
// Get the path of the DSN.
func (dsn Dsn) GetPath() string {
return dsn.path
}
// Get the project ID of the DSN.
func (dsn Dsn) GetProjectID() string {
return dsn.projectID
}
// GetAPIURL returns the URL of the envelope endpoint of the project
// associated with the DSN.
func (dsn Dsn) GetAPIURL() *url.URL {
var rawURL string
rawURL += fmt.Sprintf("%s://%s", dsn.scheme, dsn.host)
if dsn.port != dsn.scheme.defaultPort() {
rawURL += fmt.Sprintf(":%d", dsn.port)
}
if dsn.path != "" {
rawURL += dsn.path
}
rawURL += fmt.Sprintf("/api/%s/%s/", dsn.projectID, "envelope")
parsedURL, _ := url.Parse(rawURL)
return parsedURL
}
// RequestHeaders returns all the necessary headers that have to be used in the transport when sending events
// to the /store endpoint.
//
// Deprecated: This method shall only be used if you want to implement your own transport that sends events to
// the /store endpoint. If you're using the transport provided by the SDK, all necessary headers to authenticate
// against the /envelope endpoint are added automatically.
func (dsn Dsn) RequestHeaders(sdkVersion string) map[string]string {
auth := fmt.Sprintf("Sentry sentry_version=%s, sentry_timestamp=%d, "+
"sentry_client=sentry.go/%s, sentry_key=%s", apiVersion, time.Now().Unix(), sdkVersion, dsn.publicKey)
if dsn.secretKey != "" {
auth = fmt.Sprintf("%s, sentry_secret=%s", auth, dsn.secretKey)
}
return map[string]string{
"Content-Type": "application/json",
"X-Sentry-Auth": auth,
}
}
// MarshalJSON converts the Dsn struct to JSON.
func (dsn Dsn) MarshalJSON() ([]byte, error) {
return json.Marshal(dsn.String())
}
// UnmarshalJSON converts JSON data to the Dsn struct.
func (dsn *Dsn) UnmarshalJSON(data []byte) error {
var str string
_ = json.Unmarshal(data, &str)
newDsn, err := NewDsn(str)
if err != nil {
return err
}
*dsn = *newDsn
return nil
}

View File

@@ -0,0 +1,231 @@
package protocol
import (
"bytes"
"encoding/json"
"fmt"
"io"
"time"
)
// Envelope represents a Sentry envelope containing headers and items.
type Envelope struct {
Header *EnvelopeHeader `json:"-"`
Items []*EnvelopeItem `json:"-"`
}
// EnvelopeHeader represents the header of a Sentry envelope.
type EnvelopeHeader struct {
// EventID is the unique identifier for this event
EventID string `json:"event_id"`
// SentAt is the timestamp when the event was sent from the SDK as string in RFC 3339 format.
// Used for clock drift correction of the event timestamp. The time zone must be UTC.
SentAt time.Time `json:"sent_at,omitempty"`
// Dsn can be used for self-authenticated envelopes.
// This means that the envelope has all the information necessary to be sent to sentry.
// In this case the full DSN must be stored in this key.
Dsn string `json:"dsn,omitempty"`
// Sdk carries the same payload as the sdk interface in the event payload but can be carried for all events.
// This means that SDK information can be carried for minidumps, session data and other submissions.
Sdk *SdkInfo `json:"sdk,omitempty"`
// Trace contains the [Dynamic Sampling Context](https://develop.sentry.dev/sdk/telemetry/traces/dynamic-sampling-context/)
Trace map[string]string `json:"trace,omitempty"`
}
// EnvelopeItemType represents the type of envelope item.
type EnvelopeItemType string
// Constants for envelope item types as defined in the Sentry documentation.
const (
EnvelopeItemTypeEvent EnvelopeItemType = "event"
EnvelopeItemTypeTransaction EnvelopeItemType = "transaction"
EnvelopeItemTypeCheckIn EnvelopeItemType = "check_in"
EnvelopeItemTypeAttachment EnvelopeItemType = "attachment"
EnvelopeItemTypeLog EnvelopeItemType = "log"
EnvelopeItemTypeTraceMetric EnvelopeItemType = "trace_metric"
)
// EnvelopeItemHeader represents the header of an envelope item.
type EnvelopeItemHeader struct {
// Type specifies the type of this Item and its contents.
// Based on the Item type, more headers may be required.
Type EnvelopeItemType `json:"type"`
// Length is the length of the payload in bytes.
// If no length is specified, the payload implicitly goes to the next newline.
// For payloads containing newline characters, the length must be specified.
Length *int `json:"length,omitempty"`
// Filename is the name of the attachment file (used for attachments)
Filename string `json:"filename,omitempty"`
// ContentType is the MIME type of the item payload (used for attachments and some other item types)
ContentType string `json:"content_type,omitempty"`
// ItemCount is the number of items in a batch (used for logs)
ItemCount *int `json:"item_count,omitempty"`
}
// EnvelopeItem represents a single item within an envelope.
type EnvelopeItem struct {
Header *EnvelopeItemHeader `json:"-"`
Payload []byte `json:"-"`
}
// NewEnvelope creates a new envelope with the given header.
func NewEnvelope(header *EnvelopeHeader) *Envelope {
return &Envelope{
Header: header,
Items: make([]*EnvelopeItem, 0),
}
}
// AddItem adds an item to the envelope.
func (e *Envelope) AddItem(item *EnvelopeItem) {
if item == nil {
return
}
e.Items = append(e.Items, item)
}
// Serialize serializes the envelope to the Sentry envelope format.
//
// Format: Headers "\n" { Item } [ "\n" ]
// Item: Headers "\n" Payload "\n".
func (e *Envelope) Serialize() ([]byte, error) {
var buf bytes.Buffer
headerBytes, err := json.Marshal(e.Header)
if err != nil {
return nil, fmt.Errorf("failed to marshal envelope header: %w", err)
}
if _, err := buf.Write(headerBytes); err != nil {
return nil, fmt.Errorf("failed to write envelope header: %w", err)
}
if _, err := buf.WriteString("\n"); err != nil {
return nil, fmt.Errorf("failed to write newline after envelope header: %w", err)
}
for _, item := range e.Items {
if err := e.writeItem(&buf, item); err != nil {
return nil, fmt.Errorf("failed to write envelope item: %w", err)
}
}
return buf.Bytes(), nil
}
// WriteTo writes the envelope to the given writer in the Sentry envelope format.
func (e *Envelope) WriteTo(w io.Writer) (int64, error) {
data, err := e.Serialize()
if err != nil {
return 0, err
}
n, err := w.Write(data)
return int64(n), err
}
// writeItem writes a single envelope item to the buffer.
func (e *Envelope) writeItem(buf *bytes.Buffer, item *EnvelopeItem) error {
headerBytes, err := json.Marshal(item.Header)
if err != nil {
return fmt.Errorf("failed to marshal item header: %w", err)
}
if _, err := buf.Write(headerBytes); err != nil {
return fmt.Errorf("failed to write item header: %w", err)
}
if _, err := buf.WriteString("\n"); err != nil {
return fmt.Errorf("failed to write newline after item header: %w", err)
}
if len(item.Payload) > 0 {
if _, err := buf.Write(item.Payload); err != nil {
return fmt.Errorf("failed to write item payload: %w", err)
}
}
if _, err := buf.WriteString("\n"); err != nil {
return fmt.Errorf("failed to write newline after item payload: %w", err)
}
return nil
}
// Size returns the total size of the envelope when serialized.
func (e *Envelope) Size() (int, error) {
data, err := e.Serialize()
if err != nil {
return 0, err
}
return len(data), nil
}
// MarshalJSON converts the EnvelopeHeader to JSON.
func (h *EnvelopeHeader) MarshalJSON() ([]byte, error) {
type header EnvelopeHeader
return json.Marshal((*header)(h))
}
// NewEnvelopeItem creates a new envelope item with the specified type and payload.
func NewEnvelopeItem(itemType EnvelopeItemType, payload []byte) *EnvelopeItem {
length := len(payload)
return &EnvelopeItem{
Header: &EnvelopeItemHeader{
Type: itemType,
Length: &length,
},
Payload: payload,
}
}
// NewAttachmentItem creates a new envelope item for an attachment.
// Parameters: filename, contentType, payload.
func NewAttachmentItem(filename, contentType string, payload []byte) *EnvelopeItem {
length := len(payload)
return &EnvelopeItem{
Header: &EnvelopeItemHeader{
Type: EnvelopeItemTypeAttachment,
Length: &length,
ContentType: contentType,
Filename: filename,
},
Payload: payload,
}
}
// NewLogItem creates a new envelope item for logs.
func NewLogItem(itemCount int, payload []byte) *EnvelopeItem {
length := len(payload)
return &EnvelopeItem{
Header: &EnvelopeItemHeader{
Type: EnvelopeItemTypeLog,
Length: &length,
ItemCount: &itemCount,
ContentType: "application/vnd.sentry.items.log+json",
},
Payload: payload,
}
}
// NewTraceMetricItem creates a new envelope item for trace metrics.
func NewTraceMetricItem(itemCount int, payload []byte) *EnvelopeItem {
length := len(payload)
return &EnvelopeItem{
Header: &EnvelopeItemHeader{
Type: EnvelopeItemTypeTraceMetric,
Length: &length,
ItemCount: &itemCount,
ContentType: "application/vnd.sentry.items.trace-metric+json",
},
Payload: payload,
}
}

View File

@@ -0,0 +1,56 @@
package protocol
import (
"context"
"time"
"github.com/getsentry/sentry-go/internal/ratelimit"
)
// TelemetryItem represents any telemetry data that can be stored in buffers and sent to Sentry.
// This is the base interface that all telemetry items must implement.
type TelemetryItem interface {
// GetCategory returns the rate limit category for this item.
GetCategory() ratelimit.Category
// GetEventID returns the event ID for this item.
GetEventID() string
// GetSdkInfo returns SDK information for the envelope header.
GetSdkInfo() *SdkInfo
// GetDynamicSamplingContext returns trace context for the envelope header.
GetDynamicSamplingContext() map[string]string
}
// EnvelopeItemConvertible represents items that can be converted directly to envelope items.
type EnvelopeItemConvertible interface {
TelemetryItem
// ToEnvelopeItem converts the item to a Sentry envelope item.
ToEnvelopeItem() (*EnvelopeItem, error)
}
// TelemetryTransport represents the envelope-first transport interface.
// This interface is designed for the telemetry buffer system and provides
// non-blocking sends with backpressure signals.
type TelemetryTransport interface {
// SendEnvelope sends an envelope to Sentry. Returns immediately with
// backpressure error if the queue is full.
SendEnvelope(envelope *Envelope) error
// HasCapacity reports whether the transport has capacity to accept at least one more envelope.
HasCapacity() bool
// IsRateLimited checks if a specific category is currently rate limited
IsRateLimited(category ratelimit.Category) bool
// Flush waits for all pending envelopes to be sent, with timeout
Flush(timeout time.Duration) bool
// FlushWithContext waits for all pending envelopes to be sent
FlushWithContext(ctx context.Context) bool
// Close shuts down the transport gracefully
Close()
}

View File

@@ -0,0 +1,48 @@
package protocol
import (
"encoding/json"
"github.com/getsentry/sentry-go/internal/ratelimit"
)
// LogAttribute is the JSON representation for a single log attribute value.
type LogAttribute struct {
Value any `json:"value"`
Type string `json:"type"`
}
// Logs is a container for multiple log items which knows how to convert
// itself into a single batched log envelope item.
type Logs []TelemetryItem
func (ls Logs) ToEnvelopeItem() (*EnvelopeItem, error) {
// Convert each log to its JSON representation
items := make([]json.RawMessage, 0, len(ls))
for _, log := range ls {
logPayload, err := json.Marshal(log)
if err != nil {
continue
}
items = append(items, logPayload)
}
if len(items) == 0 {
return nil, nil
}
wrapper := struct {
Items []json.RawMessage `json:"items"`
}{Items: items}
payload, err := json.Marshal(wrapper)
if err != nil {
return nil, err
}
return NewLogItem(len(ls), payload), nil
}
func (Logs) GetCategory() ratelimit.Category { return ratelimit.CategoryLog }
func (Logs) GetEventID() string { return "" }
func (Logs) GetSdkInfo() *SdkInfo { return nil }
func (Logs) GetDynamicSamplingContext() map[string]string { return nil }

View File

@@ -0,0 +1,41 @@
package protocol
import (
"encoding/json"
"github.com/getsentry/sentry-go/internal/ratelimit"
)
type Metrics []TelemetryItem
func (ms Metrics) ToEnvelopeItem() (*EnvelopeItem, error) {
// Convert each metric to its JSON representation
items := make([]json.RawMessage, 0, len(ms))
for _, metric := range ms {
metricPayload, err := json.Marshal(metric)
if err != nil {
continue
}
items = append(items, metricPayload)
}
if len(items) == 0 {
return nil, nil
}
wrapper := struct {
Items []json.RawMessage `json:"items"`
}{Items: items}
payload, err := json.Marshal(wrapper)
if err != nil {
return nil, err
}
return NewTraceMetricItem(len(items), payload), nil
}
func (Metrics) GetCategory() ratelimit.Category { return ratelimit.CategoryTraceMetric }
func (Metrics) GetEventID() string { return "" }
func (Metrics) GetSdkInfo() *SdkInfo { return nil }
func (Metrics) GetDynamicSamplingContext() map[string]string { return nil }

View File

@@ -0,0 +1,15 @@
package protocol
// SdkInfo contains SDK metadata.
type SdkInfo struct {
Name string `json:"name,omitempty"`
Version string `json:"version,omitempty"`
Integrations []string `json:"integrations,omitempty"`
Packages []SdkPackage `json:"packages,omitempty"`
}
// SdkPackage describes a package that was installed.
type SdkPackage struct {
Name string `json:"name,omitempty"`
Version string `json:"version,omitempty"`
}

View File

@@ -0,0 +1,18 @@
package protocol
import (
"crypto/rand"
"encoding/hex"
)
// GenerateEventID generates a random UUID v4 for use as a Sentry event ID.
func GenerateEventID() string {
id := make([]byte, 16)
// Prefer rand.Read over rand.Reader, see https://go-review.googlesource.com/c/go/+/272326/.
_, _ = rand.Read(id)
id[6] &= 0x0F // clear version
id[6] |= 0x40 // set version to 4 (random uuid)
id[8] &= 0x3F // clear variant
id[8] |= 0x80 // set to IETF variant
return hex.EncodeToString(id)
}

View File

@@ -8,18 +8,21 @@ import (
)
// Reference:
// https://github.com/getsentry/relay/blob/0424a2e017d193a93918053c90cdae9472d164bf/relay-common/src/constants.rs#L116-L127
// https://github.com/getsentry/relay/blob/46dfaa850b8717a6e22c3e9a275ba17fe673b9da/relay-base-schema/src/data_category.rs#L231-L271
// Category classifies supported payload types that can be ingested by Sentry
// and, therefore, rate limited.
type Category string
// Known rate limit categories. As a special case, the CategoryAll applies to
// all known payload types.
// Known rate limit categories that are specified in rate limit headers.
const (
CategoryAll Category = ""
CategoryUnknown Category = "unknown" // Unknown category should not get rate limited
CategoryAll Category = "" // Special category for empty categories (applies to all)
CategoryError Category = "error"
CategoryTransaction Category = "transaction"
CategoryLog Category = "log_item"
CategoryMonitor Category = "monitor"
CategoryTraceMetric Category = "trace_metric"
)
// knownCategories is the set of currently known categories. Other categories
@@ -28,14 +31,28 @@ var knownCategories = map[Category]struct{}{
CategoryAll: {},
CategoryError: {},
CategoryTransaction: {},
CategoryLog: {},
CategoryMonitor: {},
CategoryTraceMetric: {},
}
// String returns the category formatted for debugging.
func (c Category) String() string {
switch c {
case "":
case CategoryAll:
return "CategoryAll"
case CategoryError:
return "CategoryError"
case CategoryTransaction:
return "CategoryTransaction"
case CategoryLog:
return "CategoryLog"
case CategoryMonitor:
return "CategoryMonitor"
case CategoryTraceMetric:
return "CategoryTraceMetric"
default:
// For unknown categories, use the original formatting logic
caser := cases.Title(language.English)
rv := "Category"
for _, w := range strings.Fields(string(c)) {
@@ -44,3 +61,49 @@ func (c Category) String() string {
return rv
}
}
// Priority represents the importance level of a category for buffer management.
type Priority int
const (
PriorityCritical Priority = iota + 1
PriorityHigh
PriorityMedium
PriorityLow
PriorityLowest
)
func (p Priority) String() string {
switch p {
case PriorityCritical:
return "critical"
case PriorityHigh:
return "high"
case PriorityMedium:
return "medium"
case PriorityLow:
return "low"
case PriorityLowest:
return "lowest"
default:
return "unknown"
}
}
// GetPriority returns the priority level for this category.
func (c Category) GetPriority() Priority {
switch c {
case CategoryError:
return PriorityCritical
case CategoryMonitor:
return PriorityHigh
case CategoryLog:
return PriorityLow
case CategoryTransaction:
return PriorityMedium
case CategoryTraceMetric:
return PriorityLow
default:
return PriorityMedium
}
}

View File

@@ -0,0 +1,398 @@
package telemetry
import (
"sync"
"sync/atomic"
"time"
"github.com/getsentry/sentry-go/internal/ratelimit"
)
const (
defaultBucketedCapacity = 100
perBucketItemLimit = 100
)
type Bucket[T any] struct {
traceID string
items []T
createdAt time.Time
lastUpdatedAt time.Time
}
// BucketedBuffer groups items by trace id, flushing per bucket.
type BucketedBuffer[T any] struct {
mu sync.RWMutex
buckets []*Bucket[T]
traceIndex map[string]int
head int
tail int
itemCapacity int
bucketCapacity int
totalItems int
bucketCount int
category ratelimit.Category
priority ratelimit.Priority
overflowPolicy OverflowPolicy
batchSize int
timeout time.Duration
lastFlushTime time.Time
offered int64
dropped int64
onDropped func(item T, reason string)
}
func NewBucketedBuffer[T any](
category ratelimit.Category,
capacity int,
overflowPolicy OverflowPolicy,
batchSize int,
timeout time.Duration,
) *BucketedBuffer[T] {
if capacity <= 0 {
capacity = defaultBucketedCapacity
}
if batchSize <= 0 {
batchSize = 1
}
if timeout < 0 {
timeout = 0
}
bucketCapacity := capacity / 10
if bucketCapacity < 10 {
bucketCapacity = 10
}
return &BucketedBuffer[T]{
buckets: make([]*Bucket[T], bucketCapacity),
traceIndex: make(map[string]int),
itemCapacity: capacity,
bucketCapacity: bucketCapacity,
category: category,
priority: category.GetPriority(),
overflowPolicy: overflowPolicy,
batchSize: batchSize,
timeout: timeout,
lastFlushTime: time.Now(),
}
}
func (b *BucketedBuffer[T]) Offer(item T) bool {
atomic.AddInt64(&b.offered, 1)
traceID := ""
if ta, ok := any(item).(TraceAware); ok {
if tid, hasTrace := ta.GetTraceID(); hasTrace {
traceID = tid
}
}
b.mu.Lock()
defer b.mu.Unlock()
return b.offerToBucket(item, traceID)
}
func (b *BucketedBuffer[T]) offerToBucket(item T, traceID string) bool {
if traceID != "" {
if idx, exists := b.traceIndex[traceID]; exists {
bucket := b.buckets[idx]
if len(bucket.items) >= perBucketItemLimit {
delete(b.traceIndex, traceID)
} else {
bucket.items = append(bucket.items, item)
bucket.lastUpdatedAt = time.Now()
b.totalItems++
return true
}
}
}
if b.totalItems >= b.itemCapacity {
return b.handleOverflow(item, traceID)
}
if b.bucketCount >= b.bucketCapacity {
return b.handleOverflow(item, traceID)
}
bucket := &Bucket[T]{
traceID: traceID,
items: []T{item},
createdAt: time.Now(),
lastUpdatedAt: time.Now(),
}
b.buckets[b.tail] = bucket
if traceID != "" {
b.traceIndex[traceID] = b.tail
}
b.tail = (b.tail + 1) % b.bucketCapacity
b.bucketCount++
b.totalItems++
return true
}
func (b *BucketedBuffer[T]) handleOverflow(item T, traceID string) bool {
switch b.overflowPolicy {
case OverflowPolicyDropOldest:
oldestBucket := b.buckets[b.head]
if oldestBucket == nil {
atomic.AddInt64(&b.dropped, 1)
if b.onDropped != nil {
b.onDropped(item, "buffer_full_invalid_state")
}
return false
}
if oldestBucket.traceID != "" {
delete(b.traceIndex, oldestBucket.traceID)
}
droppedCount := len(oldestBucket.items)
atomic.AddInt64(&b.dropped, int64(droppedCount))
if b.onDropped != nil {
for _, di := range oldestBucket.items {
b.onDropped(di, "buffer_full_drop_oldest_bucket")
}
}
b.totalItems -= droppedCount
b.bucketCount--
b.head = (b.head + 1) % b.bucketCapacity
// add new bucket
bucket := &Bucket[T]{traceID: traceID, items: []T{item}, createdAt: time.Now(), lastUpdatedAt: time.Now()}
b.buckets[b.tail] = bucket
if traceID != "" {
b.traceIndex[traceID] = b.tail
}
b.tail = (b.tail + 1) % b.bucketCapacity
b.bucketCount++
b.totalItems++
return true
case OverflowPolicyDropNewest:
atomic.AddInt64(&b.dropped, 1)
if b.onDropped != nil {
b.onDropped(item, "buffer_full_drop_newest")
}
return false
default:
atomic.AddInt64(&b.dropped, 1)
if b.onDropped != nil {
b.onDropped(item, "unknown_overflow_policy")
}
return false
}
}
func (b *BucketedBuffer[T]) Poll() (T, bool) {
b.mu.Lock()
defer b.mu.Unlock()
var zero T
if b.bucketCount == 0 {
return zero, false
}
bucket := b.buckets[b.head]
if bucket == nil || len(bucket.items) == 0 {
return zero, false
}
item := bucket.items[0]
bucket.items = bucket.items[1:]
b.totalItems--
if len(bucket.items) == 0 {
if bucket.traceID != "" {
delete(b.traceIndex, bucket.traceID)
}
b.buckets[b.head] = nil
b.head = (b.head + 1) % b.bucketCapacity
b.bucketCount--
}
return item, true
}
func (b *BucketedBuffer[T]) PollBatch(maxItems int) []T {
if maxItems <= 0 {
return nil
}
b.mu.Lock()
defer b.mu.Unlock()
if b.bucketCount == 0 {
return nil
}
res := make([]T, 0, maxItems)
for len(res) < maxItems && b.bucketCount > 0 {
bucket := b.buckets[b.head]
if bucket == nil {
break
}
n := maxItems - len(res)
if n > len(bucket.items) {
n = len(bucket.items)
}
res = append(res, bucket.items[:n]...)
bucket.items = bucket.items[n:]
b.totalItems -= n
if len(bucket.items) == 0 {
if bucket.traceID != "" {
delete(b.traceIndex, bucket.traceID)
}
b.buckets[b.head] = nil
b.head = (b.head + 1) % b.bucketCapacity
b.bucketCount--
}
}
return res
}
func (b *BucketedBuffer[T]) PollIfReady() []T {
b.mu.Lock()
defer b.mu.Unlock()
if b.bucketCount == 0 {
return nil
}
ready := b.totalItems >= b.batchSize || (b.timeout > 0 && time.Since(b.lastFlushTime) >= b.timeout)
if !ready {
return nil
}
oldest := b.buckets[b.head]
if oldest == nil {
return nil
}
items := oldest.items
if oldest.traceID != "" {
delete(b.traceIndex, oldest.traceID)
}
b.buckets[b.head] = nil
b.head = (b.head + 1) % b.bucketCapacity
b.totalItems -= len(items)
b.bucketCount--
b.lastFlushTime = time.Now()
return items
}
func (b *BucketedBuffer[T]) Drain() []T {
b.mu.Lock()
defer b.mu.Unlock()
if b.bucketCount == 0 {
return nil
}
res := make([]T, 0, b.totalItems)
for i := 0; i < b.bucketCount; i++ {
idx := (b.head + i) % b.bucketCapacity
bucket := b.buckets[idx]
if bucket != nil {
res = append(res, bucket.items...)
b.buckets[idx] = nil
}
}
b.traceIndex = make(map[string]int)
b.head = 0
b.tail = 0
b.totalItems = 0
b.bucketCount = 0
return res
}
func (b *BucketedBuffer[T]) Peek() (T, bool) {
b.mu.RLock()
defer b.mu.RUnlock()
var zero T
if b.bucketCount == 0 {
return zero, false
}
bucket := b.buckets[b.head]
if bucket == nil || len(bucket.items) == 0 {
return zero, false
}
return bucket.items[0], true
}
func (b *BucketedBuffer[T]) Size() int { b.mu.RLock(); defer b.mu.RUnlock(); return b.totalItems }
func (b *BucketedBuffer[T]) Capacity() int { b.mu.RLock(); defer b.mu.RUnlock(); return b.itemCapacity }
func (b *BucketedBuffer[T]) Category() ratelimit.Category {
b.mu.RLock()
defer b.mu.RUnlock()
return b.category
}
func (b *BucketedBuffer[T]) Priority() ratelimit.Priority {
b.mu.RLock()
defer b.mu.RUnlock()
return b.priority
}
func (b *BucketedBuffer[T]) IsEmpty() bool {
b.mu.RLock()
defer b.mu.RUnlock()
return b.bucketCount == 0
}
func (b *BucketedBuffer[T]) IsFull() bool {
b.mu.RLock()
defer b.mu.RUnlock()
return b.totalItems >= b.itemCapacity
}
func (b *BucketedBuffer[T]) Utilization() float64 {
b.mu.RLock()
defer b.mu.RUnlock()
if b.itemCapacity == 0 {
return 0
}
return float64(b.totalItems) / float64(b.itemCapacity)
}
func (b *BucketedBuffer[T]) OfferedCount() int64 { return atomic.LoadInt64(&b.offered) }
func (b *BucketedBuffer[T]) DroppedCount() int64 { return atomic.LoadInt64(&b.dropped) }
func (b *BucketedBuffer[T]) AcceptedCount() int64 { return b.OfferedCount() - b.DroppedCount() }
func (b *BucketedBuffer[T]) DropRate() float64 {
off := b.OfferedCount()
if off == 0 {
return 0
}
return float64(b.DroppedCount()) / float64(off)
}
func (b *BucketedBuffer[T]) GetMetrics() BufferMetrics {
b.mu.RLock()
size := b.totalItems
util := 0.0
if b.itemCapacity > 0 {
util = float64(b.totalItems) / float64(b.itemCapacity)
}
b.mu.RUnlock()
return BufferMetrics{Category: b.category, Priority: b.priority, Capacity: b.itemCapacity, Size: size, Utilization: util, OfferedCount: b.OfferedCount(), DroppedCount: b.DroppedCount(), AcceptedCount: b.AcceptedCount(), DropRate: b.DropRate(), LastUpdated: time.Now()}
}
func (b *BucketedBuffer[T]) SetDroppedCallback(callback func(item T, reason string)) {
b.mu.Lock()
defer b.mu.Unlock()
b.onDropped = callback
}
func (b *BucketedBuffer[T]) Clear() {
b.mu.Lock()
defer b.mu.Unlock()
for i := 0; i < b.bucketCapacity; i++ {
b.buckets[i] = nil
}
b.traceIndex = make(map[string]int)
b.head = 0
b.tail = 0
b.totalItems = 0
b.bucketCount = 0
}
func (b *BucketedBuffer[T]) IsReadyToFlush() bool {
b.mu.RLock()
defer b.mu.RUnlock()
if b.bucketCount == 0 {
return false
}
if b.totalItems >= b.batchSize {
return true
}
if b.timeout > 0 && time.Since(b.lastFlushTime) >= b.timeout {
return true
}
return false
}
func (b *BucketedBuffer[T]) MarkFlushed() {
b.mu.Lock()
defer b.mu.Unlock()
b.lastFlushTime = time.Now()
}

View File

@@ -0,0 +1,378 @@
package telemetry
import (
"sync"
"sync/atomic"
"time"
"github.com/getsentry/sentry-go/internal/ratelimit"
)
const defaultCapacity = 100
// RingBuffer is a thread-safe ring buffer with overflow policies.
type RingBuffer[T any] struct {
mu sync.RWMutex
items []T
head int
tail int
size int
capacity int
category ratelimit.Category
priority ratelimit.Priority
overflowPolicy OverflowPolicy
batchSize int
timeout time.Duration
lastFlushTime time.Time
offered int64
dropped int64
onDropped func(item T, reason string)
}
func NewRingBuffer[T any](category ratelimit.Category, capacity int, overflowPolicy OverflowPolicy, batchSize int, timeout time.Duration) *RingBuffer[T] {
if capacity <= 0 {
capacity = defaultCapacity
}
if batchSize <= 0 {
batchSize = 1
}
if timeout < 0 {
timeout = 0
}
return &RingBuffer[T]{
items: make([]T, capacity),
capacity: capacity,
category: category,
priority: category.GetPriority(),
overflowPolicy: overflowPolicy,
batchSize: batchSize,
timeout: timeout,
lastFlushTime: time.Now(),
}
}
func (b *RingBuffer[T]) SetDroppedCallback(callback func(item T, reason string)) {
b.mu.Lock()
defer b.mu.Unlock()
b.onDropped = callback
}
func (b *RingBuffer[T]) Offer(item T) bool {
atomic.AddInt64(&b.offered, 1)
b.mu.Lock()
defer b.mu.Unlock()
if b.size < b.capacity {
b.items[b.tail] = item
b.tail = (b.tail + 1) % b.capacity
b.size++
return true
}
switch b.overflowPolicy {
case OverflowPolicyDropOldest:
oldItem := b.items[b.head]
b.items[b.head] = item
b.head = (b.head + 1) % b.capacity
b.tail = (b.tail + 1) % b.capacity
atomic.AddInt64(&b.dropped, 1)
if b.onDropped != nil {
b.onDropped(oldItem, "buffer_full_drop_oldest")
}
return true
case OverflowPolicyDropNewest:
atomic.AddInt64(&b.dropped, 1)
if b.onDropped != nil {
b.onDropped(item, "buffer_full_drop_newest")
}
return false
default:
atomic.AddInt64(&b.dropped, 1)
if b.onDropped != nil {
b.onDropped(item, "unknown_overflow_policy")
}
return false
}
}
func (b *RingBuffer[T]) Poll() (T, bool) {
b.mu.Lock()
defer b.mu.Unlock()
var zero T
if b.size == 0 {
return zero, false
}
item := b.items[b.head]
b.items[b.head] = zero
b.head = (b.head + 1) % b.capacity
b.size--
return item, true
}
func (b *RingBuffer[T]) PollBatch(maxItems int) []T {
if maxItems <= 0 {
return nil
}
b.mu.Lock()
defer b.mu.Unlock()
if b.size == 0 {
return nil
}
itemCount := maxItems
if itemCount > b.size {
itemCount = b.size
}
result := make([]T, itemCount)
var zero T
for i := 0; i < itemCount; i++ {
result[i] = b.items[b.head]
b.items[b.head] = zero
b.head = (b.head + 1) % b.capacity
b.size--
}
return result
}
func (b *RingBuffer[T]) Drain() []T {
b.mu.Lock()
defer b.mu.Unlock()
if b.size == 0 {
return nil
}
result := make([]T, b.size)
index := 0
var zero T
for i := 0; i < b.size; i++ {
pos := (b.head + i) % b.capacity
result[index] = b.items[pos]
b.items[pos] = zero
index++
}
b.head = 0
b.tail = 0
b.size = 0
return result
}
func (b *RingBuffer[T]) Peek() (T, bool) {
b.mu.RLock()
defer b.mu.RUnlock()
var zero T
if b.size == 0 {
return zero, false
}
return b.items[b.head], true
}
func (b *RingBuffer[T]) Size() int {
b.mu.RLock()
defer b.mu.RUnlock()
return b.size
}
func (b *RingBuffer[T]) Capacity() int {
b.mu.RLock()
defer b.mu.RUnlock()
return b.capacity
}
func (b *RingBuffer[T]) Category() ratelimit.Category {
b.mu.RLock()
defer b.mu.RUnlock()
return b.category
}
func (b *RingBuffer[T]) Priority() ratelimit.Priority {
b.mu.RLock()
defer b.mu.RUnlock()
return b.priority
}
func (b *RingBuffer[T]) IsEmpty() bool {
b.mu.RLock()
defer b.mu.RUnlock()
return b.size == 0
}
func (b *RingBuffer[T]) IsFull() bool {
b.mu.RLock()
defer b.mu.RUnlock()
return b.size == b.capacity
}
func (b *RingBuffer[T]) Utilization() float64 {
b.mu.RLock()
defer b.mu.RUnlock()
return float64(b.size) / float64(b.capacity)
}
func (b *RingBuffer[T]) OfferedCount() int64 {
return atomic.LoadInt64(&b.offered)
}
func (b *RingBuffer[T]) DroppedCount() int64 {
return atomic.LoadInt64(&b.dropped)
}
func (b *RingBuffer[T]) AcceptedCount() int64 {
return b.OfferedCount() - b.DroppedCount()
}
func (b *RingBuffer[T]) DropRate() float64 {
offered := b.OfferedCount()
if offered == 0 {
return 0.0
}
return float64(b.DroppedCount()) / float64(offered)
}
func (b *RingBuffer[T]) Clear() {
b.mu.Lock()
defer b.mu.Unlock()
var zero T
for i := 0; i < b.capacity; i++ {
b.items[i] = zero
}
b.head = 0
b.tail = 0
b.size = 0
}
func (b *RingBuffer[T]) GetMetrics() BufferMetrics {
b.mu.RLock()
size := b.size
util := float64(b.size) / float64(b.capacity)
b.mu.RUnlock()
return BufferMetrics{
Category: b.category,
Priority: b.priority,
Capacity: b.capacity,
Size: size,
Utilization: util,
OfferedCount: b.OfferedCount(),
DroppedCount: b.DroppedCount(),
AcceptedCount: b.AcceptedCount(),
DropRate: b.DropRate(),
LastUpdated: time.Now(),
}
}
func (b *RingBuffer[T]) IsReadyToFlush() bool {
b.mu.RLock()
defer b.mu.RUnlock()
if b.size == 0 {
return false
}
if b.size >= b.batchSize {
return true
}
if b.timeout > 0 && time.Since(b.lastFlushTime) >= b.timeout {
return true
}
return false
}
func (b *RingBuffer[T]) MarkFlushed() {
b.mu.Lock()
defer b.mu.Unlock()
b.lastFlushTime = time.Now()
}
func (b *RingBuffer[T]) PollIfReady() []T {
b.mu.Lock()
defer b.mu.Unlock()
if b.size == 0 {
return nil
}
ready := b.size >= b.batchSize ||
(b.timeout > 0 && time.Since(b.lastFlushTime) >= b.timeout)
if !ready {
return nil
}
itemCount := b.batchSize
if itemCount > b.size {
itemCount = b.size
}
result := make([]T, itemCount)
var zero T
for i := 0; i < itemCount; i++ {
result[i] = b.items[b.head]
b.items[b.head] = zero
b.head = (b.head + 1) % b.capacity
b.size--
}
b.lastFlushTime = time.Now()
return result
}
type BufferMetrics struct {
Category ratelimit.Category `json:"category"`
Priority ratelimit.Priority `json:"priority"`
Capacity int `json:"capacity"`
Size int `json:"size"`
Utilization float64 `json:"utilization"`
OfferedCount int64 `json:"offered_count"`
DroppedCount int64 `json:"dropped_count"`
AcceptedCount int64 `json:"accepted_count"`
DropRate float64 `json:"drop_rate"`
LastUpdated time.Time `json:"last_updated"`
}
// OverflowPolicy defines how the ring buffer handles overflow.
type OverflowPolicy int
const (
OverflowPolicyDropOldest OverflowPolicy = iota
OverflowPolicyDropNewest
)
func (op OverflowPolicy) String() string {
switch op {
case OverflowPolicyDropOldest:
return "drop_oldest"
case OverflowPolicyDropNewest:
return "drop_newest"
default:
return "unknown"
}
}

View File

@@ -0,0 +1,49 @@
package telemetry
import (
"context"
"time"
"github.com/getsentry/sentry-go/internal/protocol"
"github.com/getsentry/sentry-go/internal/ratelimit"
)
// Processor is the top-level object that wraps the scheduler and buffers.
type Processor struct {
scheduler *Scheduler
}
// NewProcessor creates a new Processor with the given configuration.
func NewProcessor(
buffers map[ratelimit.Category]Buffer[protocol.TelemetryItem],
transport protocol.TelemetryTransport,
dsn *protocol.Dsn,
sdkInfo *protocol.SdkInfo,
) *Processor {
scheduler := NewScheduler(buffers, transport, dsn, sdkInfo)
scheduler.Start()
return &Processor{
scheduler: scheduler,
}
}
// Add adds a TelemetryItem to the appropriate buffer based on its category.
func (b *Processor) Add(item protocol.TelemetryItem) bool {
return b.scheduler.Add(item)
}
// Flush forces all buffers to flush within the given timeout.
func (b *Processor) Flush(timeout time.Duration) bool {
return b.scheduler.Flush(timeout)
}
// FlushWithContext flushes with a custom context for cancellation.
func (b *Processor) FlushWithContext(ctx context.Context) bool {
return b.scheduler.FlushWithContext(ctx)
}
// Close stops the buffer, flushes remaining data, and releases resources.
func (b *Processor) Close(timeout time.Duration) {
b.scheduler.Stop(timeout)
}

View File

@@ -0,0 +1,301 @@
package telemetry
import (
"context"
"sync"
"time"
"github.com/getsentry/sentry-go/internal/debuglog"
"github.com/getsentry/sentry-go/internal/protocol"
"github.com/getsentry/sentry-go/internal/ratelimit"
)
// Scheduler implements a weighted round-robin scheduler for processing buffered events.
type Scheduler struct {
buffers map[ratelimit.Category]Buffer[protocol.TelemetryItem]
transport protocol.TelemetryTransport
dsn *protocol.Dsn
sdkInfo *protocol.SdkInfo
currentCycle []ratelimit.Priority
cyclePos int
ctx context.Context
cancel context.CancelFunc
processingWg sync.WaitGroup
mu sync.Mutex
cond *sync.Cond
startOnce sync.Once
finishOnce sync.Once
}
func NewScheduler(
buffers map[ratelimit.Category]Buffer[protocol.TelemetryItem],
transport protocol.TelemetryTransport,
dsn *protocol.Dsn,
sdkInfo *protocol.SdkInfo,
) *Scheduler {
ctx, cancel := context.WithCancel(context.Background())
priorityWeights := map[ratelimit.Priority]int{
ratelimit.PriorityCritical: 5,
ratelimit.PriorityHigh: 4,
ratelimit.PriorityMedium: 3,
ratelimit.PriorityLow: 2,
ratelimit.PriorityLowest: 1,
}
var currentCycle []ratelimit.Priority
for priority, weight := range priorityWeights {
hasBuffers := false
for _, buffer := range buffers {
if buffer.Priority() == priority {
hasBuffers = true
break
}
}
if hasBuffers {
for i := 0; i < weight; i++ {
currentCycle = append(currentCycle, priority)
}
}
}
s := &Scheduler{
buffers: buffers,
transport: transport,
dsn: dsn,
sdkInfo: sdkInfo,
currentCycle: currentCycle,
ctx: ctx,
cancel: cancel,
}
s.cond = sync.NewCond(&s.mu)
return s
}
func (s *Scheduler) Start() {
s.startOnce.Do(func() {
s.processingWg.Add(1)
go s.run()
})
}
func (s *Scheduler) Stop(timeout time.Duration) {
s.finishOnce.Do(func() {
s.Flush(timeout)
s.cancel()
s.cond.Broadcast()
done := make(chan struct{})
go func() {
defer close(done)
s.processingWg.Wait()
}()
select {
case <-done:
case <-time.After(timeout):
debuglog.Printf("scheduler stop timed out after %v", timeout)
}
})
}
func (s *Scheduler) Signal() {
s.cond.Signal()
}
func (s *Scheduler) Add(item protocol.TelemetryItem) bool {
category := item.GetCategory()
buffer, exists := s.buffers[category]
if !exists {
return false
}
accepted := buffer.Offer(item)
if accepted {
s.Signal()
}
return accepted
}
func (s *Scheduler) Flush(timeout time.Duration) bool {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
return s.FlushWithContext(ctx)
}
func (s *Scheduler) FlushWithContext(ctx context.Context) bool {
s.flushBuffers()
return s.transport.FlushWithContext(ctx)
}
func (s *Scheduler) run() {
defer s.processingWg.Done()
go func() {
ticker := time.NewTicker(100 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-ticker.C:
s.cond.Broadcast()
case <-s.ctx.Done():
return
}
}
}()
for {
s.mu.Lock()
for !s.hasWork() && s.ctx.Err() == nil {
s.cond.Wait()
}
if s.ctx.Err() != nil {
s.mu.Unlock()
return
}
s.mu.Unlock()
s.processNextBatch()
}
}
func (s *Scheduler) hasWork() bool {
for _, buffer := range s.buffers {
if buffer.IsReadyToFlush() {
return true
}
}
return false
}
func (s *Scheduler) processNextBatch() {
if len(s.currentCycle) == 0 {
return
}
priority := s.currentCycle[s.cyclePos]
s.cyclePos = (s.cyclePos + 1) % len(s.currentCycle)
var bufferToProcess Buffer[protocol.TelemetryItem]
var categoryToProcess ratelimit.Category
for category, buffer := range s.buffers {
if buffer.Priority() == priority && buffer.IsReadyToFlush() {
bufferToProcess = buffer
categoryToProcess = category
break
}
}
if bufferToProcess != nil {
s.processItems(bufferToProcess, categoryToProcess, false)
}
}
func (s *Scheduler) processItems(buffer Buffer[protocol.TelemetryItem], category ratelimit.Category, force bool) {
var items []protocol.TelemetryItem
if force {
items = buffer.Drain()
} else {
items = buffer.PollIfReady()
}
// drop the current batch if rate-limited or if transport is full
if len(items) == 0 || s.isRateLimited(category) || !s.transport.HasCapacity() {
return
}
switch category {
case ratelimit.CategoryLog:
logs := protocol.Logs(items)
header := &protocol.EnvelopeHeader{EventID: protocol.GenerateEventID(), SentAt: time.Now(), Sdk: s.sdkInfo}
if s.dsn != nil {
header.Dsn = s.dsn.String()
}
envelope := protocol.NewEnvelope(header)
item, err := logs.ToEnvelopeItem()
if err != nil {
debuglog.Printf("error creating log batch envelope item: %v", err)
return
}
envelope.AddItem(item)
if err := s.transport.SendEnvelope(envelope); err != nil {
debuglog.Printf("error sending envelope: %v", err)
}
return
case ratelimit.CategoryTraceMetric:
metrics := protocol.Metrics(items)
header := &protocol.EnvelopeHeader{EventID: protocol.GenerateEventID(), SentAt: time.Now(), Sdk: s.sdkInfo}
if s.dsn != nil {
header.Dsn = s.dsn.String()
}
envelope := protocol.NewEnvelope(header)
item, err := metrics.ToEnvelopeItem()
if err != nil {
debuglog.Printf("error creating trace metric batch envelope item: %v", err)
return
}
envelope.AddItem(item)
if err := s.transport.SendEnvelope(envelope); err != nil {
debuglog.Printf("error sending envelope: %v", err)
}
return
default:
// if the buffers are properly configured, buffer.PollIfReady should return a single item for every category
// other than logs. We still iterate over the items just in case, because we don't want to send broken envelopes.
for _, it := range items {
convertible, ok := it.(protocol.EnvelopeItemConvertible)
if !ok {
debuglog.Printf("item does not implement EnvelopeItemConvertible: %T", it)
continue
}
s.sendItem(convertible)
}
}
}
func (s *Scheduler) sendItem(item protocol.EnvelopeItemConvertible) {
header := &protocol.EnvelopeHeader{
EventID: item.GetEventID(),
SentAt: time.Now(),
Trace: item.GetDynamicSamplingContext(),
Sdk: s.sdkInfo,
}
if header.EventID == "" {
header.EventID = protocol.GenerateEventID()
}
if s.dsn != nil {
header.Dsn = s.dsn.String()
}
envelope := protocol.NewEnvelope(header)
envItem, err := item.ToEnvelopeItem()
if err != nil {
debuglog.Printf("error while converting to envelope item: %v", err)
return
}
envelope.AddItem(envItem)
if err := s.transport.SendEnvelope(envelope); err != nil {
debuglog.Printf("error sending envelope: %v", err)
}
}
func (s *Scheduler) flushBuffers() {
for category, buffer := range s.buffers {
if !buffer.IsEmpty() {
s.processItems(buffer, category, true)
}
}
}
func (s *Scheduler) isRateLimited(category ratelimit.Category) bool {
return s.transport.IsRateLimited(category)
}

View File

@@ -0,0 +1,42 @@
package telemetry
import (
"github.com/getsentry/sentry-go/internal/ratelimit"
)
// Buffer defines the common interface for all buffer implementations.
type Buffer[T any] interface {
// Core operations
Offer(item T) bool
Poll() (T, bool)
PollBatch(maxItems int) []T
PollIfReady() []T
Drain() []T
Peek() (T, bool)
// State queries
Size() int
Capacity() int
IsEmpty() bool
IsFull() bool
Utilization() float64
// Flush management
IsReadyToFlush() bool
MarkFlushed()
// Category/Priority
Category() ratelimit.Category
Priority() ratelimit.Priority
// Metrics
OfferedCount() int64
DroppedCount() int64
AcceptedCount() int64
DropRate() float64
GetMetrics() BufferMetrics
// Configuration
SetDroppedCallback(callback func(item T, reason string))
Clear()
}

View File

@@ -0,0 +1,7 @@
package telemetry
// TraceAware is implemented by items that can expose a trace ID.
// BucketedBuffer uses this to group items by trace.
type TraceAware interface {
GetTraceID() (string, bool)
}

View File

@@ -1,15 +0,0 @@
## Benchmark results
```
goos: windows
goarch: amd64
pkg: github.com/getsentry/sentry-go/internal/trace
cpu: 12th Gen Intel(R) Core(TM) i7-12700K
BenchmarkEqualBytes-20 44323621 26.08 ns/op
BenchmarkStringEqual-20 60980257 18.27 ns/op
BenchmarkEqualPrefix-20 41369181 31.12 ns/op
BenchmarkFullParse-20 702012 1507 ns/op 1353.42 MB/s 1024 B/op 6 allocs/op
BenchmarkFramesIterator-20 1229971 969.3 ns/op 896 B/op 5 allocs/op
BenchmarkFramesReversedIterator-20 1271061 944.5 ns/op 896 B/op 5 allocs/op
BenchmarkSplitOnly-20 2250800 534.0 ns/op 3818.23 MB/s 128 B/op 1 allocs/op
```

View File

@@ -1,217 +0,0 @@
package traceparser
import (
"bytes"
"strconv"
)
var blockSeparator = []byte("\n\n")
var lineSeparator = []byte("\n")
// Parses multi-stacktrace text dump produced by runtime.Stack([]byte, all=true).
// The parser prioritizes performance but requires the input to be well-formed in order to return correct data.
// See https://github.com/golang/go/blob/go1.20.4/src/runtime/mprof.go#L1191
func Parse(data []byte) TraceCollection {
var it = TraceCollection{}
if len(data) > 0 {
it.blocks = bytes.Split(data, blockSeparator)
}
return it
}
type TraceCollection struct {
blocks [][]byte
}
func (it TraceCollection) Length() int {
return len(it.blocks)
}
// Returns the stacktrace item at the given index.
func (it *TraceCollection) Item(i int) Trace {
// The first item may have a leading data separator and the last one may have a trailing one.
// Note: Trim() doesn't make a copy for single-character cutset under 0x80. It will just slice the original.
var data []byte
switch {
case i == 0:
data = bytes.TrimLeft(it.blocks[i], "\n")
case i == len(it.blocks)-1:
data = bytes.TrimRight(it.blocks[i], "\n")
default:
data = it.blocks[i]
}
var splitAt = bytes.IndexByte(data, '\n')
if splitAt < 0 {
return Trace{header: data}
}
return Trace{
header: data[:splitAt],
data: data[splitAt+1:],
}
}
// Trace represents a single stacktrace block, identified by a Goroutine ID and a sequence of Frames.
type Trace struct {
header []byte
data []byte
}
var goroutinePrefix = []byte("goroutine ")
// GoID parses the Goroutine ID from the header.
func (t *Trace) GoID() (id uint64) {
if bytes.HasPrefix(t.header, goroutinePrefix) {
var line = t.header[len(goroutinePrefix):]
var splitAt = bytes.IndexByte(line, ' ')
if splitAt >= 0 {
id, _ = strconv.ParseUint(string(line[:splitAt]), 10, 64)
}
}
return id
}
// UniqueIdentifier can be used as a map key to identify the trace.
func (t *Trace) UniqueIdentifier() []byte {
return t.data
}
func (t *Trace) Frames() FrameIterator {
var lines = bytes.Split(t.data, lineSeparator)
return FrameIterator{lines: lines, i: 0, len: len(lines)}
}
func (t *Trace) FramesReversed() ReverseFrameIterator {
var lines = bytes.Split(t.data, lineSeparator)
return ReverseFrameIterator{lines: lines, i: len(lines)}
}
const framesElided = "...additional frames elided..."
// FrameIterator iterates over stack frames.
type FrameIterator struct {
lines [][]byte
i int
len int
}
// Next returns the next frame, or nil if there are none.
func (it *FrameIterator) Next() Frame {
return Frame{it.popLine(), it.popLine()}
}
func (it *FrameIterator) popLine() []byte {
switch {
case it.i >= it.len:
return nil
case string(it.lines[it.i]) == framesElided:
it.i++
return it.popLine()
default:
it.i++
return it.lines[it.i-1]
}
}
// HasNext return true if there are values to be read.
func (it *FrameIterator) HasNext() bool {
return it.i < it.len
}
// LengthUpperBound returns the maximum number of elements this stacks may contain.
// The actual number may be lower because of elided frames. As such, the returned value
// cannot be used to iterate over the frames but may be used to reserve capacity.
func (it *FrameIterator) LengthUpperBound() int {
return it.len / 2
}
// ReverseFrameIterator iterates over stack frames in reverse order.
type ReverseFrameIterator struct {
lines [][]byte
i int
}
// Next returns the next frame, or nil if there are none.
func (it *ReverseFrameIterator) Next() Frame {
var line2 = it.popLine()
return Frame{it.popLine(), line2}
}
func (it *ReverseFrameIterator) popLine() []byte {
it.i--
switch {
case it.i < 0:
return nil
case string(it.lines[it.i]) == framesElided:
return it.popLine()
default:
return it.lines[it.i]
}
}
// HasNext return true if there are values to be read.
func (it *ReverseFrameIterator) HasNext() bool {
return it.i > 1
}
// LengthUpperBound returns the maximum number of elements this stacks may contain.
// The actual number may be lower because of elided frames. As such, the returned value
// cannot be used to iterate over the frames but may be used to reserve capacity.
func (it *ReverseFrameIterator) LengthUpperBound() int {
return len(it.lines) / 2
}
type Frame struct {
line1 []byte
line2 []byte
}
// UniqueIdentifier can be used as a map key to identify the frame.
func (f *Frame) UniqueIdentifier() []byte {
// line2 contains file path, line number and program-counter offset from the beginning of a function
// e.g. C:/Users/name/scoop/apps/go/current/src/testing/testing.go:1906 +0x63a
return f.line2
}
var createdByPrefix = []byte("created by ")
func (f *Frame) Func() []byte {
if bytes.HasPrefix(f.line1, createdByPrefix) {
// Since go1.21, the line ends with " in goroutine X", saying which goroutine created this one.
// We currently don't have use for that so just remove it.
var line = f.line1[len(createdByPrefix):]
var spaceAt = bytes.IndexByte(line, ' ')
if spaceAt < 0 {
return line
}
return line[:spaceAt]
}
var end = bytes.LastIndexByte(f.line1, '(')
if end >= 0 {
return f.line1[:end]
}
return f.line1
}
func (f *Frame) File() (path []byte, lineNumber int) {
var line = f.line2
if len(line) > 0 && line[0] == '\t' {
line = line[1:]
}
var splitAt = bytes.IndexByte(line, ' ')
if splitAt >= 0 {
line = line[:splitAt]
}
splitAt = bytes.LastIndexByte(line, ':')
if splitAt < 0 {
return line, 0
}
lineNumber, _ = strconv.Atoi(string(line[splitAt+1:]))
return line[:splitAt], lineNumber
}

316
vendor/github.com/getsentry/sentry-go/log.go generated vendored Normal file
View File

@@ -0,0 +1,316 @@
package sentry
import (
"context"
"fmt"
"maps"
"os"
"strings"
"sync"
"time"
"github.com/getsentry/sentry-go/attribute"
"github.com/getsentry/sentry-go/internal/debuglog"
)
type LogLevel string
const (
LogLevelTrace LogLevel = "trace"
LogLevelDebug LogLevel = "debug"
LogLevelInfo LogLevel = "info"
LogLevelWarn LogLevel = "warn"
LogLevelError LogLevel = "error"
LogLevelFatal LogLevel = "fatal"
)
const (
LogSeverityTrace int = 1
LogSeverityDebug int = 5
LogSeverityInfo int = 9
LogSeverityWarning int = 13
LogSeverityError int = 17
LogSeverityFatal int = 21
)
var mapTypesToStr = map[attribute.Type]AttrType{
attribute.INVALID: AttributeInvalid,
attribute.BOOL: AttributeBool,
attribute.INT64: AttributeInt,
attribute.FLOAT64: AttributeFloat,
attribute.STRING: AttributeString,
}
type sentryLogger struct {
ctx context.Context
client *Client
attributes map[string]Attribute
defaultAttributes map[string]Attribute
mu sync.RWMutex
}
type logEntry struct {
logger *sentryLogger
ctx context.Context
level LogLevel
severity int
attributes map[string]Attribute
shouldPanic bool
}
// NewLogger returns a Logger that emits logs to Sentry. If logging is turned off, all logs get discarded.
func NewLogger(ctx context.Context) Logger { // nolint: dupl
var hub *Hub
hub = GetHubFromContext(ctx)
if hub == nil {
hub = CurrentHub()
}
client := hub.Client()
if client != nil && client.options.EnableLogs {
// Build default attrs
serverAddr := client.options.ServerName
if serverAddr == "" {
serverAddr, _ = os.Hostname()
}
defaults := map[string]string{
"sentry.release": client.options.Release,
"sentry.environment": client.options.Environment,
"sentry.server.address": serverAddr,
"sentry.sdk.name": client.sdkIdentifier,
"sentry.sdk.version": client.sdkVersion,
}
defaultAttrs := make(map[string]Attribute)
for k, v := range defaults {
if v != "" {
defaultAttrs[k] = Attribute{Value: v, Type: AttributeString}
}
}
return &sentryLogger{
ctx: ctx,
client: client,
attributes: make(map[string]Attribute),
defaultAttributes: defaultAttrs,
mu: sync.RWMutex{},
}
}
debuglog.Println("fallback to noopLogger: enableLogs disabled")
return &noopLogger{}
}
func (l *sentryLogger) Write(p []byte) (int, error) {
msg := strings.TrimRight(string(p), "\n")
l.Info().Emit(msg)
return len(p), nil
}
func (l *sentryLogger) log(ctx context.Context, level LogLevel, severity int, message string, entryAttrs map[string]Attribute, args ...interface{}) {
if message == "" {
return
}
scope, traceID, spanID := resolveScopeAndTrace(ctx, l.ctx)
// Pre-allocate with capacity hint to avoid map growth reallocations
estimatedCap := len(l.defaultAttributes) + len(entryAttrs) + len(args) + 8 // scope ~3 + instance ~5
attrs := make(map[string]Attribute, estimatedCap)
// attribute precedence: default -> scope -> instance (from SetAttrs) -> entry-specific
for k, v := range l.defaultAttributes {
attrs[k] = v
}
scope.populateAttrs(attrs)
l.mu.RLock()
for k, v := range l.attributes {
attrs[k] = v
}
l.mu.RUnlock()
for k, v := range entryAttrs {
attrs[k] = v
}
if len(args) > 0 {
attrs["sentry.message.template"] = Attribute{
Value: message, Type: AttributeString,
}
for i, p := range args {
attrs[fmt.Sprintf("sentry.message.parameters.%d", i)] = Attribute{
Value: fmt.Sprintf("%+v", p), Type: AttributeString,
}
}
}
log := &Log{
Timestamp: time.Now(),
TraceID: traceID,
SpanID: spanID,
Level: level,
Severity: severity,
Body: fmt.Sprintf(message, args...),
Attributes: attrs,
}
l.client.captureLog(log, scope)
if l.client.options.Debug {
debuglog.Printf(message, args...)
}
}
func (l *sentryLogger) SetAttributes(attrs ...attribute.Builder) {
l.mu.Lock()
defer l.mu.Unlock()
for _, v := range attrs {
t, ok := mapTypesToStr[v.Value.Type()]
if !ok || t == "" {
debuglog.Printf("invalid attribute type set: %v", t)
continue
}
l.attributes[v.Key] = Attribute{
Value: v.Value.AsInterface(),
Type: t,
}
}
}
func (l *sentryLogger) Trace() LogEntry {
return &logEntry{
logger: l,
ctx: l.ctx,
level: LogLevelTrace,
severity: LogSeverityTrace,
attributes: make(map[string]Attribute),
}
}
func (l *sentryLogger) Debug() LogEntry {
return &logEntry{
logger: l,
ctx: l.ctx,
level: LogLevelDebug,
severity: LogSeverityDebug,
attributes: make(map[string]Attribute),
}
}
func (l *sentryLogger) Info() LogEntry {
return &logEntry{
logger: l,
ctx: l.ctx,
level: LogLevelInfo,
severity: LogSeverityInfo,
attributes: make(map[string]Attribute),
}
}
func (l *sentryLogger) Warn() LogEntry {
return &logEntry{
logger: l,
ctx: l.ctx,
level: LogLevelWarn,
severity: LogSeverityWarning,
attributes: make(map[string]Attribute),
}
}
func (l *sentryLogger) Error() LogEntry {
return &logEntry{
logger: l,
ctx: l.ctx,
level: LogLevelError,
severity: LogSeverityError,
attributes: make(map[string]Attribute),
}
}
func (l *sentryLogger) Fatal() LogEntry {
return &logEntry{
logger: l,
ctx: l.ctx,
level: LogLevelFatal,
severity: LogSeverityFatal,
attributes: make(map[string]Attribute),
}
}
func (l *sentryLogger) Panic() LogEntry {
return &logEntry{
logger: l,
ctx: l.ctx,
level: LogLevelFatal,
severity: LogSeverityFatal,
attributes: make(map[string]Attribute),
shouldPanic: true,
}
}
func (l *sentryLogger) GetCtx() context.Context {
return l.ctx
}
func (e *logEntry) WithCtx(ctx context.Context) LogEntry {
return &logEntry{
logger: e.logger,
ctx: ctx,
level: e.level,
severity: e.severity,
attributes: maps.Clone(e.attributes),
shouldPanic: e.shouldPanic,
}
}
func (e *logEntry) String(key, value string) LogEntry {
e.attributes[key] = Attribute{Value: value, Type: AttributeString}
return e
}
func (e *logEntry) Int(key string, value int) LogEntry {
e.attributes[key] = Attribute{Value: int64(value), Type: AttributeInt}
return e
}
func (e *logEntry) Int64(key string, value int64) LogEntry {
e.attributes[key] = Attribute{Value: value, Type: AttributeInt}
return e
}
func (e *logEntry) Float64(key string, value float64) LogEntry {
e.attributes[key] = Attribute{Value: value, Type: AttributeFloat}
return e
}
func (e *logEntry) Bool(key string, value bool) LogEntry {
e.attributes[key] = Attribute{Value: value, Type: AttributeBool}
return e
}
func (e *logEntry) Emit(args ...interface{}) {
e.logger.log(e.ctx, e.level, e.severity, fmt.Sprint(args...), e.attributes)
if e.level == LogLevelFatal {
if e.shouldPanic {
panic(fmt.Sprint(args...))
}
os.Exit(1)
}
}
func (e *logEntry) Emitf(format string, args ...interface{}) {
e.logger.log(e.ctx, e.level, e.severity, format, e.attributes, args...)
if e.level == LogLevelFatal {
if e.shouldPanic {
formattedMessage := fmt.Sprintf(format, args...)
panic(formattedMessage)
}
os.Exit(1)
}
}

View File

@@ -0,0 +1,32 @@
package sentry
import (
"time"
)
// logBatchProcessor batches logs and sends them to Sentry.
type logBatchProcessor struct {
*batchProcessor[Log]
}
func newLogBatchProcessor(client *Client) *logBatchProcessor {
return &logBatchProcessor{
batchProcessor: newBatchProcessor(func(items []Log) {
if len(items) == 0 {
return
}
event := NewEvent()
event.Timestamp = time.Now()
event.EventID = EventID(uuid())
event.Type = logEvent.Type
event.Logs = items
client.Transport.SendEvent(event)
}),
}
}
func (p *logBatchProcessor) Send(log *Log) bool {
return p.batchProcessor.Send(*log)
}

105
vendor/github.com/getsentry/sentry-go/log_fallback.go generated vendored Normal file
View File

@@ -0,0 +1,105 @@
package sentry
import (
"context"
"fmt"
"os"
"github.com/getsentry/sentry-go/attribute"
"github.com/getsentry/sentry-go/internal/debuglog"
)
// Fallback, no-op logger if logging is disabled.
type noopLogger struct{}
// noopLogEntry implements LogEntry for the no-op logger.
type noopLogEntry struct {
level LogLevel
shouldPanic bool
}
func (n *noopLogEntry) WithCtx(_ context.Context) LogEntry {
return n
}
func (n *noopLogEntry) String(_, _ string) LogEntry {
return n
}
func (n *noopLogEntry) Int(_ string, _ int) LogEntry {
return n
}
func (n *noopLogEntry) Int64(_ string, _ int64) LogEntry {
return n
}
func (n *noopLogEntry) Float64(_ string, _ float64) LogEntry {
return n
}
func (n *noopLogEntry) Bool(_ string, _ bool) LogEntry {
return n
}
func (n *noopLogEntry) Attributes(_ ...attribute.Builder) LogEntry {
return n
}
func (n *noopLogEntry) Emit(args ...interface{}) {
debuglog.Printf("Log with level=[%v] is being dropped. Turn on logging via EnableLogs", n.level)
if n.level == LogLevelFatal {
if n.shouldPanic {
panic(args)
}
os.Exit(1)
}
}
func (n *noopLogEntry) Emitf(message string, args ...interface{}) {
debuglog.Printf("Log with level=[%v] is being dropped. Turn on logging via EnableLogs", n.level)
if n.level == LogLevelFatal {
if n.shouldPanic {
panic(fmt.Sprintf(message, args...))
}
os.Exit(1)
}
}
func (n *noopLogger) GetCtx() context.Context { return context.Background() }
func (*noopLogger) Trace() LogEntry {
return &noopLogEntry{level: LogLevelTrace}
}
func (*noopLogger) Debug() LogEntry {
return &noopLogEntry{level: LogLevelDebug}
}
func (*noopLogger) Info() LogEntry {
return &noopLogEntry{level: LogLevelInfo}
}
func (*noopLogger) Warn() LogEntry {
return &noopLogEntry{level: LogLevelWarn}
}
func (*noopLogger) Error() LogEntry {
return &noopLogEntry{level: LogLevelError}
}
func (*noopLogger) Fatal() LogEntry {
return &noopLogEntry{level: LogLevelFatal}
}
func (*noopLogger) Panic() LogEntry {
return &noopLogEntry{level: LogLevelFatal, shouldPanic: true}
}
func (*noopLogger) SetAttributes(...attribute.Builder) {
debuglog.Printf("No attributes attached. Turn on logging via EnableLogs")
}
func (*noopLogger) Write(_ []byte) (n int, err error) {
return 0, fmt.Errorf("log with level=[%v] is being dropped. Turn on logging via EnableLogs", LogLevelInfo)
}

View File

@@ -0,0 +1,32 @@
package sentry
import (
"time"
)
// metricBatchProcessor batches metrics and sends them to Sentry.
type metricBatchProcessor struct {
*batchProcessor[Metric]
}
func newMetricBatchProcessor(client *Client) *metricBatchProcessor {
return &metricBatchProcessor{
batchProcessor: newBatchProcessor(func(items []Metric) {
if len(items) == 0 {
return
}
event := NewEvent()
event.Timestamp = time.Now()
event.EventID = EventID(uuid())
event.Type = traceMetricEvent.Type
event.Metrics = items
client.Transport.SendEvent(event)
}),
}
}
func (p *metricBatchProcessor) Send(metric *Metric) bool {
return p.batchProcessor.Send(*metric)
}

235
vendor/github.com/getsentry/sentry-go/metrics.go generated vendored Normal file
View File

@@ -0,0 +1,235 @@
package sentry
import (
"context"
"maps"
"os"
"sync"
"time"
"github.com/getsentry/sentry-go/attribute"
"github.com/getsentry/sentry-go/internal/debuglog"
)
// Duration Units.
const (
UnitNanosecond = "nanosecond"
UnitMicrosecond = "microsecond"
UnitMillisecond = "millisecond"
UnitSecond = "second"
UnitMinute = "minute"
UnitHour = "hour"
UnitDay = "day"
UnitWeek = "week"
)
// Information Units.
const (
UnitBit = "bit"
UnitByte = "byte"
UnitKilobyte = "kilobyte"
UnitKibibyte = "kibibyte"
UnitMegabyte = "megabyte"
UnitMebibyte = "mebibyte"
UnitGigabyte = "gigabyte"
UnitGibibyte = "gibibyte"
UnitTerabyte = "terabyte"
UnitTebibyte = "tebibyte"
UnitPetabyte = "petabyte"
UnitPebibyte = "pebibyte"
UnitExabyte = "exabyte"
UnitExbibyte = "exbibyte"
)
// Fraction Units.
const (
UnitRatio = "ratio"
UnitPercent = "percent"
)
// NewMeter returns a new Meter. If there is no Client bound to the current hub, or if metrics are disabled,
// it returns a no-op Meter that discards all metrics.
func NewMeter(ctx context.Context) Meter {
hub := GetHubFromContext(ctx)
if hub == nil {
hub = CurrentHub()
}
client := hub.Client()
if client != nil && !client.options.DisableMetrics {
// build default attrs
serverAddr := client.options.ServerName
if serverAddr == "" {
serverAddr, _ = os.Hostname()
}
defaults := map[string]string{
"sentry.release": client.options.Release,
"sentry.environment": client.options.Environment,
"sentry.server.address": serverAddr,
"sentry.sdk.name": client.sdkIdentifier,
"sentry.sdk.version": client.sdkVersion,
}
defaultAttrs := make(map[string]Attribute)
for k, v := range defaults {
if v != "" {
defaultAttrs[k] = Attribute{Value: v, Type: AttributeString}
}
}
return &sentryMeter{
ctx: ctx,
client: client,
attributes: make(map[string]Attribute),
defaultAttributes: defaultAttrs,
mu: sync.RWMutex{},
}
}
debuglog.Printf("fallback to noopMeter: metrics disabled")
return &noopMeter{}
}
type sentryMeter struct {
ctx context.Context
client *Client
attributes map[string]Attribute
defaultAttributes map[string]Attribute
mu sync.RWMutex
}
func (m *sentryMeter) emit(ctx context.Context, metricType MetricType, name string, value MetricValue, unit string, attributes map[string]Attribute, customScope *Scope) {
if name == "" {
debuglog.Println("empty name provided, dropping metric")
return
}
scope, traceID, spanID := resolveScopeAndTrace(ctx, m.ctx)
if customScope != nil {
scope = customScope
}
// Pre-allocate with capacity hint to avoid map growth reallocations
estimatedCap := len(m.defaultAttributes) + len(attributes) + 8 // scope ~3 + call-specific ~5
attrs := make(map[string]Attribute, estimatedCap)
// attribute precedence: default -> scope -> instance (from SetAttrs) -> entry-specific
for k, v := range m.defaultAttributes {
attrs[k] = v
}
scope.populateAttrs(attrs)
m.mu.RLock()
for k, v := range m.attributes {
attrs[k] = v
}
m.mu.RUnlock()
for k, v := range attributes {
attrs[k] = v
}
metric := &Metric{
Timestamp: time.Now(),
TraceID: traceID,
SpanID: spanID,
Type: metricType,
Name: name,
Value: value,
Unit: unit,
Attributes: attrs,
}
if m.client.captureMetric(metric, scope) && m.client.options.Debug {
debuglog.Printf("Metric %s [%s]: %v %s", metricType, name, value.AsInterface(), unit)
}
}
// WithCtx returns a new Meter that uses the given context for trace/span association.
func (m *sentryMeter) WithCtx(ctx context.Context) Meter {
m.mu.RLock()
attrsCopy := maps.Clone(m.attributes)
m.mu.RUnlock()
return &sentryMeter{
ctx: ctx,
client: m.client,
attributes: attrsCopy,
defaultAttributes: m.defaultAttributes,
mu: sync.RWMutex{},
}
}
func (m *sentryMeter) applyOptions(opts []MeterOption) *meterOptions {
o := &meterOptions{}
for _, opt := range opts {
opt(o)
}
return o
}
// Count implements Meter.
func (m *sentryMeter) Count(name string, count int64, opts ...MeterOption) {
o := m.applyOptions(opts)
m.emit(m.ctx, MetricTypeCounter, name, Int64MetricValue(count), o.unit, o.attributes, o.scope)
}
// Distribution implements Meter.
func (m *sentryMeter) Distribution(name string, sample float64, opts ...MeterOption) {
o := m.applyOptions(opts)
m.emit(m.ctx, MetricTypeDistribution, name, Float64MetricValue(sample), o.unit, o.attributes, o.scope)
}
// Gauge implements Meter.
func (m *sentryMeter) Gauge(name string, value float64, opts ...MeterOption) {
o := m.applyOptions(opts)
m.emit(m.ctx, MetricTypeGauge, name, Float64MetricValue(value), o.unit, o.attributes, o.scope)
}
// SetAttributes implements Meter.
func (m *sentryMeter) SetAttributes(attrs ...attribute.Builder) {
m.mu.Lock()
defer m.mu.Unlock()
for _, v := range attrs {
t, ok := mapTypesToStr[v.Value.Type()]
if !ok || t == "" {
debuglog.Printf("invalid attribute type set: %v", t)
continue
}
m.attributes[v.Key] = Attribute{
Value: v.Value.AsInterface(),
Type: t,
}
}
}
// noopMeter is a no-operation implementation of Meter.
// This is used when there is no client available in the context or when metrics are disabled.
type noopMeter struct{}
// WithCtx implements Meter.
func (n *noopMeter) WithCtx(_ context.Context) Meter {
return n
}
// Count implements Meter.
func (n *noopMeter) Count(name string, _ int64, _ ...MeterOption) {
debuglog.Printf("Metric %q is being dropped. Turn on metrics by setting DisableMetrics to false", name)
}
// Distribution implements Meter.
func (n *noopMeter) Distribution(name string, _ float64, _ ...MeterOption) {
debuglog.Printf("Metric %q is being dropped. Turn on metrics by setting DisableMetrics to false", name)
}
// Gauge implements Meter.
func (n *noopMeter) Gauge(name string, _ float64, _ ...MeterOption) {
debuglog.Printf("Metric %q is being dropped. Turn on metrics by setting DisableMetrics to false", name)
}
// SetAttributes implements Meter.
func (n *noopMeter) SetAttributes(_ ...attribute.Builder) {
debuglog.Printf("No attributes attached. Turn on metrics by setting DisableMetrics to false")
}

49
vendor/github.com/getsentry/sentry-go/mocks.go generated vendored Normal file
View File

@@ -0,0 +1,49 @@
package sentry
import (
"context"
"sync"
"time"
)
// MockScope implements [Scope] for use in tests.
type MockScope struct {
breadcrumb *Breadcrumb
shouldDropEvent bool
}
func (scope *MockScope) AddBreadcrumb(breadcrumb *Breadcrumb, _ int) {
scope.breadcrumb = breadcrumb
}
func (scope *MockScope) ApplyToEvent(event *Event, _ *EventHint, _ *Client) *Event {
if scope.shouldDropEvent {
return nil
}
return event
}
// MockTransport implements [Transport] for use in tests.
type MockTransport struct {
mu sync.Mutex
events []*Event
lastEvent *Event
}
func (t *MockTransport) Configure(_ ClientOptions) {}
func (t *MockTransport) SendEvent(event *Event) {
t.mu.Lock()
defer t.mu.Unlock()
t.events = append(t.events, event)
t.lastEvent = event
}
func (t *MockTransport) Flush(_ time.Duration) bool {
return true
}
func (t *MockTransport) FlushWithContext(_ context.Context) bool { return true }
func (t *MockTransport) Events() []*Event {
t.mu.Lock()
defer t.mu.Unlock()
return t.events
}
func (t *MockTransport) Close() {}

View File

@@ -1,73 +0,0 @@
package sentry
// Based on https://github.com/getsentry/vroom/blob/d11c26063e802d66b9a592c4010261746ca3dfa4/internal/sample/sample.go
import (
"time"
)
type (
profileDevice struct {
Architecture string `json:"architecture"`
Classification string `json:"classification"`
Locale string `json:"locale"`
Manufacturer string `json:"manufacturer"`
Model string `json:"model"`
}
profileOS struct {
BuildNumber string `json:"build_number"`
Name string `json:"name"`
Version string `json:"version"`
}
profileRuntime struct {
Name string `json:"name"`
Version string `json:"version"`
}
profileSample struct {
ElapsedSinceStartNS uint64 `json:"elapsed_since_start_ns"`
StackID int `json:"stack_id"`
ThreadID uint64 `json:"thread_id"`
}
profileThreadMetadata struct {
Name string `json:"name,omitempty"`
Priority int `json:"priority,omitempty"`
}
profileStack []int
profileTrace struct {
Frames []*Frame `json:"frames"`
Samples []profileSample `json:"samples"`
Stacks []profileStack `json:"stacks"`
ThreadMetadata map[uint64]*profileThreadMetadata `json:"thread_metadata"`
}
profileInfo struct {
DebugMeta *DebugMeta `json:"debug_meta,omitempty"`
Device profileDevice `json:"device"`
Environment string `json:"environment,omitempty"`
EventID string `json:"event_id"`
OS profileOS `json:"os"`
Platform string `json:"platform"`
Release string `json:"release"`
Dist string `json:"dist"`
Runtime profileRuntime `json:"runtime"`
Timestamp time.Time `json:"timestamp"`
Trace *profileTrace `json:"profile"`
Transaction profileTransaction `json:"transaction"`
Version string `json:"version"`
}
// see https://github.com/getsentry/vroom/blob/a91e39416723ec44fc54010257020eeaf9a77cbd/internal/transaction/transaction.go
profileTransaction struct {
ActiveThreadID uint64 `json:"active_thread_id"`
DurationNS uint64 `json:"duration_ns,omitempty"`
ID EventID `json:"id"`
Name string `json:"name"`
TraceID string `json:"trace_id"`
}
)

View File

@@ -1,451 +0,0 @@
package sentry
import (
"container/ring"
"strconv"
"runtime"
"sync"
"sync/atomic"
"time"
"github.com/getsentry/sentry-go/internal/traceparser"
)
// Start a profiler that collects samples continuously, with a buffer of up to 30 seconds.
// Later, you can collect a slice from this buffer, producing a Trace.
func startProfiling(startTime time.Time) profiler {
onProfilerStart()
p := newProfiler(startTime)
// Wait for the profiler to finish setting up before returning to the caller.
started := make(chan struct{})
go p.run(started)
if _, ok := <-started; ok {
return p
}
return nil
}
type profiler interface {
// GetSlice returns a slice of the profiled data between the given times.
GetSlice(startTime, endTime time.Time) *profilerResult
Stop(wait bool)
}
type profilerResult struct {
callerGoID uint64
trace *profileTrace
}
func getCurrentGoID() uint64 {
// We shouldn't panic but let's be super safe.
defer func() {
if err := recover(); err != nil {
Logger.Printf("Profiler panic in getCurrentGoID(): %v\n", err)
}
}()
// Buffer to read the stack trace into. We should be good with a small buffer because we only need the first line.
var stacksBuffer = make([]byte, 100)
var n = runtime.Stack(stacksBuffer, false)
if n > 0 {
var traces = traceparser.Parse(stacksBuffer[0:n])
if traces.Length() > 0 {
var trace = traces.Item(0)
return trace.GoID()
}
}
return 0
}
const profilerSamplingRateHz = 101 // 101 Hz; not 100 Hz because of the lockstep sampling (https://stackoverflow.com/a/45471031/1181370)
const profilerSamplingRate = time.Second / profilerSamplingRateHz
const stackBufferMaxGrowth = 512 * 1024
const stackBufferLimit = 10 * 1024 * 1024
const profilerRuntimeLimit = 30 // seconds
type profileRecorder struct {
startTime time.Time
stopSignal chan struct{}
stopped int64
mutex sync.RWMutex
testProfilerPanic int64
// Map from runtime.StackRecord.Stack0 to an index in stacks.
stackIndexes map[string]int
stacks []profileStack
newStacks []profileStack // New stacks created in the current interation.
stackKeyBuffer []byte
// Map from runtime.Frame.PC to an index in frames.
frameIndexes map[string]int
frames []*Frame
newFrames []*Frame // New frames created in the current interation.
// We keep a ring buffer of 30 seconds worth of samples, so that we can later slice it.
// Each bucket is a slice of samples all taken at the same time.
samplesBucketsHead *ring.Ring
// Buffer to read current stacks - will grow automatically up to stackBufferLimit.
stacksBuffer []byte
}
func newProfiler(startTime time.Time) *profileRecorder {
// Pre-allocate the profile trace for the currently active number of routines & 100 ms worth of samples.
// Other coefficients are just guesses of what might be a good starting point to avoid allocs on short runs.
return &profileRecorder{
startTime: startTime,
stopSignal: make(chan struct{}, 1),
stackIndexes: make(map[string]int, 32),
stacks: make([]profileStack, 0, 32),
newStacks: make([]profileStack, 0, 32),
frameIndexes: make(map[string]int, 128),
frames: make([]*Frame, 0, 128),
newFrames: make([]*Frame, 0, 128),
samplesBucketsHead: ring.New(profilerRuntimeLimit * profilerSamplingRateHz),
// A buffer of 2 KiB per goroutine stack looks like a good starting point (empirically determined).
stacksBuffer: make([]byte, runtime.NumGoroutine()*2048),
}
}
// This allows us to test whether panic during profiling are handled correctly and don't block execution.
// If the number is lower than 0, profilerGoroutine() will panic immedately.
// If the number is higher than 0, profiler.onTick() will panic when the given samples-set index is being collected.
var testProfilerPanic int64
var profilerRunning int64
func (p *profileRecorder) run(started chan struct{}) {
// Code backup for manual test debugging:
// if !atomic.CompareAndSwapInt64(&profilerRunning, 0, 1) {
// panic("Only one profiler can be running at a time")
// }
// We shouldn't panic but let's be super safe.
defer func() {
if err := recover(); err != nil {
Logger.Printf("Profiler panic in run(): %v\n", err)
}
atomic.StoreInt64(&testProfilerPanic, 0)
close(started)
p.stopSignal <- struct{}{}
atomic.StoreInt64(&p.stopped, 1)
atomic.StoreInt64(&profilerRunning, 0)
}()
p.testProfilerPanic = atomic.LoadInt64(&testProfilerPanic)
if p.testProfilerPanic < 0 {
Logger.Printf("Profiler panicking during startup because testProfilerPanic == %v\n", p.testProfilerPanic)
panic("This is an expected panic in profilerGoroutine() during tests")
}
// Collect the first sample immediately.
p.onTick()
// Periodically collect stacks, starting after profilerSamplingRate has passed.
collectTicker := profilerTickerFactory(profilerSamplingRate)
defer collectTicker.Stop()
var tickerChannel = collectTicker.TickSource()
started <- struct{}{}
for {
select {
case <-tickerChannel:
p.onTick()
collectTicker.Ticked()
case <-p.stopSignal:
return
}
}
}
func (p *profileRecorder) Stop(wait bool) {
if atomic.LoadInt64(&p.stopped) == 1 {
return
}
p.stopSignal <- struct{}{}
if wait {
<-p.stopSignal
}
}
func (p *profileRecorder) GetSlice(startTime, endTime time.Time) *profilerResult {
// Unlikely edge cases - profiler wasn't running at all or the given times are invalid in relation to each other.
if p.startTime.After(endTime) || startTime.After(endTime) {
return nil
}
var relativeStartNS = uint64(0)
if p.startTime.Before(startTime) {
relativeStartNS = uint64(startTime.Sub(p.startTime).Nanoseconds())
}
var relativeEndNS = uint64(endTime.Sub(p.startTime).Nanoseconds())
samplesCount, bucketsReversed, trace := p.getBuckets(relativeStartNS, relativeEndNS)
if samplesCount == 0 {
return nil
}
var result = &profilerResult{
callerGoID: getCurrentGoID(),
trace: trace,
}
trace.Samples = make([]profileSample, samplesCount)
trace.ThreadMetadata = make(map[uint64]*profileThreadMetadata, len(bucketsReversed[0].goIDs))
var s = samplesCount - 1
for _, bucket := range bucketsReversed {
var elapsedSinceStartNS = bucket.relativeTimeNS - relativeStartNS
for i, goID := range bucket.goIDs {
trace.Samples[s].ElapsedSinceStartNS = elapsedSinceStartNS
trace.Samples[s].ThreadID = goID
trace.Samples[s].StackID = bucket.stackIDs[i]
s--
if _, goroutineExists := trace.ThreadMetadata[goID]; !goroutineExists {
trace.ThreadMetadata[goID] = &profileThreadMetadata{
Name: "Goroutine " + strconv.FormatUint(goID, 10),
}
}
}
}
return result
}
// Collect all buckets of samples in the given time range while holding a read lock.
func (p *profileRecorder) getBuckets(relativeStartNS, relativeEndNS uint64) (samplesCount int, buckets []*profileSamplesBucket, trace *profileTrace) {
p.mutex.RLock()
defer p.mutex.RUnlock()
// sampleBucketsHead points at the last stored bucket so it's a good starting point to search backwards for the end.
var end = p.samplesBucketsHead
for end.Value != nil && end.Value.(*profileSamplesBucket).relativeTimeNS > relativeEndNS {
end = end.Prev()
}
// Edge case - no items stored before the given endTime.
if end.Value == nil {
return 0, nil, nil
}
{ // Find the first item after the given startTime.
var start = end
var prevBucket *profileSamplesBucket
samplesCount = 0
buckets = make([]*profileSamplesBucket, 0, int64((relativeEndNS-relativeStartNS)/uint64(profilerSamplingRate.Nanoseconds()))+1)
for start.Value != nil {
var bucket = start.Value.(*profileSamplesBucket)
// If this bucket's time is before the requests start time, don't collect it (and stop iterating further).
if bucket.relativeTimeNS < relativeStartNS {
break
}
// If this bucket time is greater than previous the bucket's time, we have exhausted the whole ring buffer
// before we were able to find the start time. That means the start time is not present and we must break.
// This happens if the slice duration exceeds the ring buffer capacity.
if prevBucket != nil && bucket.relativeTimeNS > prevBucket.relativeTimeNS {
break
}
samplesCount += len(bucket.goIDs)
buckets = append(buckets, bucket)
start = start.Prev()
prevBucket = bucket
}
}
// Edge case - if the period requested was too short and we haven't collected enough samples.
if len(buckets) < 2 {
return 0, nil, nil
}
trace = &profileTrace{
Frames: p.frames,
Stacks: p.stacks,
}
return samplesCount, buckets, trace
}
func (p *profileRecorder) onTick() {
elapsedNs := time.Since(p.startTime).Nanoseconds()
if p.testProfilerPanic > 0 {
Logger.Printf("Profiler testProfilerPanic == %v\n", p.testProfilerPanic)
if p.testProfilerPanic == 1 {
Logger.Println("Profiler panicking onTick()")
panic("This is an expected panic in Profiler.OnTick() during tests")
}
p.testProfilerPanic--
}
records := p.collectRecords()
p.processRecords(uint64(elapsedNs), records)
// Free up some memory if we don't need such a large buffer anymore.
if len(p.stacksBuffer) > len(records)*3 {
p.stacksBuffer = make([]byte, len(records)*3)
}
}
func (p *profileRecorder) collectRecords() []byte {
for {
// Capture stacks for all existing goroutines.
// Note: runtime.GoroutineProfile() would be better but we can't use it at the moment because
// it doesn't give us `gid` for each routine, see https://github.com/golang/go/issues/59663
n := runtime.Stack(p.stacksBuffer, true)
// If we couldn't read everything, increase the buffer and try again.
if n >= len(p.stacksBuffer) && n < stackBufferLimit {
var newSize = n * 2
if newSize > n+stackBufferMaxGrowth {
newSize = n + stackBufferMaxGrowth
}
if newSize > stackBufferLimit {
newSize = stackBufferLimit
}
p.stacksBuffer = make([]byte, newSize)
} else {
return p.stacksBuffer[0:n]
}
}
}
func (p *profileRecorder) processRecords(elapsedNs uint64, stacksBuffer []byte) {
var traces = traceparser.Parse(stacksBuffer)
var length = traces.Length()
// Shouldn't happen but let's be safe and don't store empty buckets.
if length == 0 {
return
}
var bucket = &profileSamplesBucket{
relativeTimeNS: elapsedNs,
stackIDs: make([]int, length),
goIDs: make([]uint64, length),
}
// reset buffers
p.newFrames = p.newFrames[:0]
p.newStacks = p.newStacks[:0]
for i := 0; i < length; i++ {
var stack = traces.Item(i)
bucket.stackIDs[i] = p.addStackTrace(stack)
bucket.goIDs[i] = stack.GoID()
}
p.mutex.Lock()
defer p.mutex.Unlock()
p.stacks = append(p.stacks, p.newStacks...)
p.frames = append(p.frames, p.newFrames...)
p.samplesBucketsHead = p.samplesBucketsHead.Next()
p.samplesBucketsHead.Value = bucket
}
func (p *profileRecorder) addStackTrace(capturedStack traceparser.Trace) int {
iter := capturedStack.Frames()
stack := make(profileStack, 0, iter.LengthUpperBound())
// Originally, we've used `capturedStack.UniqueIdentifier()` as a key but that was incorrect because it also
// contains function arguments and we want to group stacks by function name and file/line only.
// Instead, we need to parse frames and we use a list of their indexes as a key.
// We reuse the same buffer for each stack to avoid allocations; this is a hot spot.
var expectedBufferLen = cap(stack) * 5 // 4 bytes per frame + 1 byte for space
if cap(p.stackKeyBuffer) < expectedBufferLen {
p.stackKeyBuffer = make([]byte, 0, expectedBufferLen)
} else {
p.stackKeyBuffer = p.stackKeyBuffer[:0]
}
for iter.HasNext() {
var frame = iter.Next()
if frameIndex := p.addFrame(frame); frameIndex >= 0 {
stack = append(stack, frameIndex)
p.stackKeyBuffer = append(p.stackKeyBuffer, 0) // space
// The following code is just like binary.AppendUvarint() which isn't yet available in Go 1.18.
x := uint64(frameIndex) + 1
for x >= 0x80 {
p.stackKeyBuffer = append(p.stackKeyBuffer, byte(x)|0x80)
x >>= 7
}
p.stackKeyBuffer = append(p.stackKeyBuffer, byte(x))
}
}
stackIndex, exists := p.stackIndexes[string(p.stackKeyBuffer)]
if !exists {
stackIndex = len(p.stacks) + len(p.newStacks)
p.newStacks = append(p.newStacks, stack)
p.stackIndexes[string(p.stackKeyBuffer)] = stackIndex
}
return stackIndex
}
func (p *profileRecorder) addFrame(capturedFrame traceparser.Frame) int {
// NOTE: Don't convert to string yet, it's expensive and compiler can avoid it when
// indexing into a map (only needs a copy when adding a new key to the map).
var key = capturedFrame.UniqueIdentifier()
frameIndex, exists := p.frameIndexes[string(key)]
if !exists {
module, function := splitQualifiedFunctionName(string(capturedFrame.Func()))
file, line := capturedFrame.File()
frame := newFrame(module, function, string(file), line)
frameIndex = len(p.frames) + len(p.newFrames)
p.newFrames = append(p.newFrames, &frame)
p.frameIndexes[string(key)] = frameIndex
}
return frameIndex
}
type profileSamplesBucket struct {
relativeTimeNS uint64
stackIDs []int
goIDs []uint64
}
// A Ticker holds a channel that delivers “ticks” of a clock at intervals.
type profilerTicker interface {
// Stop turns off a ticker. After Stop, no more ticks will be sent.
Stop()
// TickSource returns a read-only channel of ticks.
TickSource() <-chan time.Time
// Ticked is called by the Profiler after a tick is processed to notify the ticker. Used for testing.
Ticked()
}
type timeTicker struct {
*time.Ticker
}
func (t *timeTicker) TickSource() <-chan time.Time {
return t.C
}
func (t *timeTicker) Ticked() {}
func profilerTickerFactoryDefault(d time.Duration) profilerTicker {
return &timeTicker{time.NewTicker(d)}
}
// We allow overriding the ticker for tests. CI is terribly flaky
// because the time.Ticker doesn't guarantee regular ticks - they may come (a lot) later than the given interval.
var profilerTickerFactory = profilerTickerFactoryDefault

View File

@@ -1,5 +0,0 @@
//go:build !windows
package sentry
func onProfilerStart() {}

View File

@@ -1,24 +0,0 @@
package sentry
import (
"sync"
"syscall"
)
// This works around the ticker resolution on Windows being ~15ms by default.
// See https://github.com/golang/go/issues/44343
func setTimeTickerResolution() {
var winmmDLL = syscall.NewLazyDLL("winmm.dll")
if winmmDLL != nil {
var timeBeginPeriod = winmmDLL.NewProc("timeBeginPeriod")
if timeBeginPeriod != nil {
timeBeginPeriod.Call(uintptr(1))
}
}
}
var setupTickerResolutionOnce sync.Once
func onProfilerStart() {
setupTickerResolutionOnce.Do(setTimeTickerResolution)
}

View File

@@ -0,0 +1,90 @@
package sentry
import (
"crypto/rand"
"encoding/json"
)
type PropagationContext struct {
TraceID TraceID `json:"trace_id"`
SpanID SpanID `json:"span_id"`
ParentSpanID SpanID `json:"parent_span_id"`
DynamicSamplingContext DynamicSamplingContext `json:"-"`
}
func (p PropagationContext) MarshalJSON() ([]byte, error) {
type propagationContext PropagationContext
var parentSpanID string
if p.ParentSpanID != zeroSpanID {
parentSpanID = p.ParentSpanID.String()
}
return json.Marshal(struct {
*propagationContext
ParentSpanID string `json:"parent_span_id,omitempty"`
}{
propagationContext: (*propagationContext)(&p),
ParentSpanID: parentSpanID,
})
}
func (p PropagationContext) Map() map[string]interface{} {
m := map[string]interface{}{
"trace_id": p.TraceID,
"span_id": p.SpanID,
}
if p.ParentSpanID != zeroSpanID {
m["parent_span_id"] = p.ParentSpanID
}
return m
}
func NewPropagationContext() PropagationContext {
p := PropagationContext{}
if _, err := rand.Read(p.TraceID[:]); err != nil {
panic(err)
}
if _, err := rand.Read(p.SpanID[:]); err != nil {
panic(err)
}
return p
}
func PropagationContextFromHeaders(trace, baggage string) (PropagationContext, error) {
p := NewPropagationContext()
if _, err := rand.Read(p.SpanID[:]); err != nil {
panic(err)
}
hasTrace := false
if trace != "" {
if tpc, valid := ParseTraceParentContext([]byte(trace)); valid {
hasTrace = true
p.TraceID = tpc.TraceID
p.ParentSpanID = tpc.ParentSpanID
}
}
if baggage != "" {
dsc, err := DynamicSamplingContextFromHeader([]byte(baggage))
if err != nil {
return PropagationContext{}, err
}
p.DynamicSamplingContext = dsc
}
// In case a sentry-trace header is present but there are no sentry-related
// values in the baggage, create an empty, frozen DynamicSamplingContext.
if hasTrace && !p.DynamicSamplingContext.HasEntries() {
p.DynamicSamplingContext = DynamicSamplingContext{
Frozen: true,
}
}
return p, nil
}

View File

@@ -2,10 +2,13 @@ package sentry
import (
"bytes"
"context"
"io"
"net/http"
"sync"
"time"
"github.com/getsentry/sentry-go/internal/debuglog"
)
// Scope holds contextual data for the current scope.
@@ -43,20 +46,22 @@ type Scope struct {
Overflow() bool
}
eventProcessors []EventProcessor
propagationContext PropagationContext
span *Span
}
// NewScope creates a new Scope.
func NewScope() *Scope {
scope := Scope{
breadcrumbs: make([]*Breadcrumb, 0),
attachments: make([]*Attachment, 0),
tags: make(map[string]string),
contexts: make(map[string]Context),
extra: make(map[string]interface{}),
fingerprint: make([]string, 0),
return &Scope{
breadcrumbs: make([]*Breadcrumb, 0),
attachments: make([]*Attachment, 0),
tags: make(map[string]string),
contexts: make(map[string]Context),
extra: make(map[string]interface{}),
fingerprint: make([]string, 0),
propagationContext: NewPropagationContext(),
}
return &scope
}
// AddBreadcrumb adds new breadcrumb to the current scope
@@ -292,6 +297,30 @@ func (scope *Scope) SetLevel(level Level) {
scope.level = level
}
// SetPropagationContext sets the propagation context for the current scope.
func (scope *Scope) SetPropagationContext(propagationContext PropagationContext) {
scope.mu.Lock()
defer scope.mu.Unlock()
scope.propagationContext = propagationContext
}
// GetSpan returns the span from the current scope.
func (scope *Scope) GetSpan() *Span {
scope.mu.RLock()
defer scope.mu.RUnlock()
return scope.span
}
// SetSpan sets a span for the current scope.
func (scope *Scope) SetSpan(span *Span) {
scope.mu.Lock()
defer scope.mu.Unlock()
scope.span = span
}
// Clone returns a copy of the current scope with all data copied over.
func (scope *Scope) Clone() *Scope {
scope.mu.RLock()
@@ -318,6 +347,8 @@ func (scope *Scope) Clone() *Scope {
clone.request = scope.request
clone.requestBody = scope.requestBody
clone.eventProcessors = scope.eventProcessors
clone.propagationContext = scope.propagationContext
clone.span = scope.span
return clone
}
@@ -335,7 +366,7 @@ func (scope *Scope) AddEventProcessor(processor EventProcessor) {
}
// ApplyToEvent takes the data from the current scope and attaches it to the event.
func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint) *Event {
func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint, client *Client) *Event {
scope.mu.RLock()
defer scope.mu.RUnlock()
@@ -379,6 +410,29 @@ func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint) *Event {
}
}
if event.Contexts == nil {
event.Contexts = make(map[string]Context)
}
if scope.span != nil {
if _, ok := event.Contexts["trace"]; !ok {
event.Contexts["trace"] = scope.span.traceContext().Map()
}
transaction := scope.span.GetTransaction()
if transaction != nil {
event.sdkMetaData.dsc = DynamicSamplingContextFromTransaction(transaction)
}
} else {
event.Contexts["trace"] = scope.propagationContext.Map()
dsc := scope.propagationContext.DynamicSamplingContext
if !dsc.HasEntries() && client != nil {
dsc = DynamicSamplingContextFromScope(scope, client)
}
event.sdkMetaData.dsc = dsc
}
if len(scope.extra) > 0 {
if event.Extra == nil {
event.Extra = make(map[string]interface{}, len(scope.extra))
@@ -421,7 +475,7 @@ func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint) *Event {
id := event.EventID
event = processor(event, hint)
if event == nil {
Logger.Printf("Event dropped by one of the Scope EventProcessors: %s\n", id)
debuglog.Printf("Event dropped by one of the Scope EventProcessors: %s\n", id)
return nil
}
}
@@ -435,9 +489,91 @@ func (scope *Scope) ApplyToEvent(event *Event, hint *EventHint) *Event {
// a proper deep copy: if some context values are pointer types (e.g. maps),
// they won't be properly copied.
func cloneContext(c Context) Context {
res := Context{}
res := make(Context, len(c))
for k, v := range c {
res[k] = v
}
return res
}
func (scope *Scope) populateAttrs(attrs map[string]Attribute) {
if scope == nil {
return
}
scope.mu.RLock()
defer scope.mu.RUnlock()
// Add user-related attributes
if !scope.user.IsEmpty() {
if scope.user.ID != "" {
attrs["user.id"] = Attribute{Value: scope.user.ID, Type: AttributeString}
}
if scope.user.Name != "" {
attrs["user.name"] = Attribute{Value: scope.user.Name, Type: AttributeString}
}
if scope.user.Email != "" {
attrs["user.email"] = Attribute{Value: scope.user.Email, Type: AttributeString}
}
}
// In the future, add scope.attributes here
// for k, v := range scope.attributes {
// attrs[k] = v
// }
}
// resolveScopeAndTrace resolves scope, trace ID, and span ID from the given contexts.
//
// The resolution order follows a most-specific-to-least-specific pattern:
// 1. Check for span directly in contexts (SpanFromContext) - this is the most specific
// source as it represents a span explicitly attached to the current operation's context
// 2. Check for hub in contexts (GetHubFromContext) - provides access to scope which may
// contain a span, but this is less specific than a directly attached span
// 3. Fall back to CurrentHub() - the global hub as a last resort
//
// This ordering ensures we always use the most contextually relevant tracing information.
// For example, if a specific span is active for an operation, we use that span's trace/span IDs
// rather than accidentally using a different span that might be set on the hub's scope.
func resolveScopeAndTrace(ctxs ...context.Context) (scope *Scope, traceID TraceID, spanID SpanID) {
var span *Span
var hub *Hub
for _, ctx := range ctxs {
if ctx == nil {
continue
}
if span = SpanFromContext(ctx); span != nil {
break
}
}
for _, ctx := range ctxs {
if ctx == nil {
continue
}
if hub = GetHubFromContext(ctx); hub != nil {
break
}
}
if hub == nil {
hub = CurrentHub()
}
scope = hub.Scope()
if scope != nil {
scope.mu.RLock()
if span == nil {
span = scope.span
}
if span != nil {
traceID = span.TraceID
spanID = span.SpanID
} else {
traceID = scope.propagationContext.TraceID
}
scope.mu.RUnlock()
}
return scope, traceID, spanID
}

View File

@@ -6,7 +6,7 @@ import (
)
// The version of the SDK.
const SDKVersion = "0.27.0"
const SDKVersion = "0.42.0"
// apiVersion is the minimum version of the Sentry API compatible with the
// sentry-go SDK.
@@ -72,18 +72,17 @@ func Recover() *EventID {
// RecoverWithContext captures a panic and passes relevant context object.
func RecoverWithContext(ctx context.Context) *EventID {
if err := recover(); err != nil {
var hub *Hub
if HasHubOnContext(ctx) {
hub = GetHubFromContext(ctx)
} else {
hub = CurrentHub()
}
return hub.RecoverWithContext(ctx, err)
err := recover()
if err == nil {
return nil
}
return nil
hub := GetHubFromContext(ctx)
if hub == nil {
hub = CurrentHub()
}
return hub.RecoverWithContext(ctx, err)
}
// WithScope is a shorthand for CurrentHub().WithScope.
@@ -126,6 +125,23 @@ func Flush(timeout time.Duration) bool {
return hub.Flush(timeout)
}
// FlushWithContext waits until the underlying Transport sends any buffered events
// to the Sentry server, blocking for at most the duration specified by the context.
// It returns false if the context is canceled before the events are sent. In such a case,
// some events may not be delivered.
//
// FlushWithContext should be called before terminating the program to ensure no
// events are unintentionally dropped.
//
// Avoid calling FlushWithContext indiscriminately after each call to CaptureEvent,
// CaptureException, or CaptureMessage. To send events synchronously over the network,
// configure the SDK to use HTTPSyncTransport during initialization with Init.
func FlushWithContext(ctx context.Context) bool {
hub := CurrentHub()
return hub.FlushWithContext(ctx)
}
// LastEventID returns an ID of last captured event.
func LastEventID() EventID {
hub := CurrentHub()

View File

@@ -2,6 +2,8 @@ package sentry
import (
"sync"
"github.com/getsentry/sentry-go/internal/debuglog"
)
// A spanRecorder stores a span tree that makes up a transaction. Safe for
@@ -24,7 +26,7 @@ func (r *spanRecorder) record(s *Span) {
if len(r.spans) >= maxSpans {
r.overflowOnce.Do(func() {
root := r.spans[0]
Logger.Printf("Too many spans: dropping spans from transaction with TraceID=%s SpanID=%s limit=%d",
debuglog.Printf("Too many spans: dropping spans from transaction with TraceID=%s SpanID=%s limit=%d",
root.TraceID, root.SpanID, maxSpans)
})
// TODO(tracing): mark the transaction event in some way to

View File

@@ -4,6 +4,7 @@ import (
"go/build"
"reflect"
"runtime"
"slices"
"strings"
)
@@ -277,12 +278,7 @@ func extractFrames(pcs []uintptr) []runtime.Frame {
}
}
// TODO don't append and reverse, put in the right place from the start.
// reverse
for i, j := 0, len(frames)-1; i < j; i, j = i+1, j-1 {
frames[i], frames[j] = frames[j], frames[i]
}
slices.Reverse(frames)
return frames
}
@@ -307,6 +303,9 @@ func createFrames(frames []runtime.Frame) []Frame {
}
}
// Fix issues grouping errors with the new fully qualified function names
// introduced from Go 1.21
result = cleanupFunctionNamePrefix(result)
return result
}
@@ -333,12 +332,10 @@ func shouldSkipFrame(module string) bool {
var goRoot = strings.ReplaceAll(build.Default.GOROOT, "\\", "/")
func setInAppFrame(frame *Frame) {
if strings.HasPrefix(frame.AbsPath, goRoot) ||
strings.Contains(frame.Module, "vendor") ||
frame.InApp = true
if strings.HasPrefix(frame.AbsPath, goRoot) || strings.Contains(frame.Module, "vendor") ||
strings.Contains(frame.Module, "third_party") {
frame.InApp = false
} else {
frame.InApp = true
}
}
@@ -379,3 +376,32 @@ func baseName(name string) string {
}
return name
}
func isCompilerGeneratedSymbol(name string) bool {
// In versions of Go 1.20 and above a prefix of "type:" and "go:" is a
// compiler-generated symbol that doesn't belong to any package.
// See variable reservedimports in cmd/compile/internal/gc/subr.go
if strings.HasPrefix(name, "go:") || strings.HasPrefix(name, "type:") {
return true
}
return false
}
// Walk backwards through the results and for the current function name
// remove it's parent function's prefix, leaving only it's actual name. This
// fixes issues grouping errors with the new fully qualified function names
// introduced from Go 1.21.
func cleanupFunctionNamePrefix(f []Frame) []Frame {
for i := len(f) - 1; i > 0; i-- {
name := f[i].Function
parentName := f[i-1].Function + "."
if !strings.HasPrefix(name, parentName) {
continue
}
f[i].Function = name[len(parentName):]
}
return f
}

View File

@@ -1,15 +0,0 @@
//go:build !go1.20
package sentry
import "strings"
func isCompilerGeneratedSymbol(name string) bool {
// In versions of Go below 1.20 a prefix of "type." and "go." is a
// compiler-generated symbol that doesn't belong to any package.
// See variable reservedimports in cmd/compile/internal/gc/subr.go
if strings.HasPrefix(name, "go.") || strings.HasPrefix(name, "type.") {
return true
}
return false
}

View File

@@ -1,15 +0,0 @@
//go:build go1.20
package sentry
import "strings"
func isCompilerGeneratedSymbol(name string) bool {
// In versions of Go 1.20 and above a prefix of "type:" and "go:" is a
// compiler-generated symbol that doesn't belong to any package.
// See variable reservedimports in cmd/compile/internal/gc/subr.go
if strings.HasPrefix(name, "go:") || strings.HasPrefix(name, "type:") {
return true
}
return false
}

View File

@@ -1,90 +0,0 @@
package sentry
import (
"sync"
"time"
)
// Checks whether the transaction should be profiled (according to ProfilesSampleRate)
// and starts a profiler if so.
func (span *Span) sampleTransactionProfile() {
var sampleRate = span.clientOptions().ProfilesSampleRate
switch {
case sampleRate < 0.0 || sampleRate > 1.0:
Logger.Printf("Skipping transaction profiling: ProfilesSampleRate out of range [0.0, 1.0]: %f\n", sampleRate)
case sampleRate == 0.0 || rng.Float64() >= sampleRate:
Logger.Printf("Skipping transaction profiling: ProfilesSampleRate is: %f\n", sampleRate)
default:
startProfilerOnce.Do(startGlobalProfiler)
if globalProfiler == nil {
Logger.Println("Skipping transaction profiling: the profiler couldn't be started")
} else {
span.collectProfile = collectTransactionProfile
}
}
}
// transactionProfiler collects a profile for a given span.
type transactionProfiler func(span *Span) *profileInfo
var startProfilerOnce sync.Once
var globalProfiler profiler
func startGlobalProfiler() {
globalProfiler = startProfiling(time.Now())
}
func collectTransactionProfile(span *Span) *profileInfo {
result := globalProfiler.GetSlice(span.StartTime, span.EndTime)
if result == nil || result.trace == nil {
return nil
}
info := &profileInfo{
Version: "1",
EventID: uuid(),
// See https://github.com/getsentry/sentry-go/pull/626#discussion_r1204870340 for explanation why we use the Transaction time.
Timestamp: span.StartTime,
Trace: result.trace,
Transaction: profileTransaction{
DurationNS: uint64(span.EndTime.Sub(span.StartTime).Nanoseconds()),
Name: span.Name,
TraceID: span.TraceID.String(),
},
}
if len(info.Transaction.Name) == 0 {
// Name is required by Relay so use the operation name if the span name is empty.
info.Transaction.Name = span.Op
}
if result.callerGoID > 0 {
info.Transaction.ActiveThreadID = result.callerGoID
}
return info
}
func (info *profileInfo) UpdateFromEvent(event *Event) {
info.Environment = event.Environment
info.Platform = event.Platform
info.Release = event.Release
info.Dist = event.Dist
info.Transaction.ID = event.EventID
if runtimeContext, ok := event.Contexts["runtime"]; ok {
if value, ok := runtimeContext["name"]; !ok {
info.Runtime.Name = value.(string)
}
if value, ok := runtimeContext["version"]; !ok {
info.Runtime.Version = value.(string)
}
}
if osContext, ok := event.Contexts["os"]; ok {
if value, ok := osContext["name"]; !ok {
info.OS.Name = value.(string)
}
}
if deviceContext, ok := event.Contexts["device"]; ok {
if value, ok := deviceContext["arch"]; !ok {
info.Device.Architecture = value.(string)
}
}
}

View File

@@ -8,14 +8,32 @@ import (
"fmt"
"net/http"
"regexp"
"strconv"
"strings"
"sync"
"time"
"github.com/getsentry/sentry-go/internal/debuglog"
)
const (
SentryTraceHeader = "sentry-trace"
SentryBaggageHeader = "baggage"
TraceparentHeader = "traceparent"
)
// SpanOrigin indicates what created a trace or a span. See: https://develop.sentry.dev/sdk/performance/trace-origin/
type SpanOrigin string
const (
SpanOriginManual = "manual"
SpanOriginEcho = "auto.http.echo"
SpanOriginFastHTTP = "auto.http.fasthttp"
SpanOriginFiber = "auto.http.fiber"
SpanOriginGin = "auto.http.gin"
SpanOriginStdLib = "auto.http.stdlib"
SpanOriginIris = "auto.http.iris"
SpanOriginNegroni = "auto.http.negroni"
)
// A Span is the building block of a Sentry transaction. Spans build up a tree
@@ -24,19 +42,22 @@ const (
//
// Spans must be started with either StartSpan or Span.StartChild.
type Span struct { //nolint: maligned // prefer readability over optimal memory layout (see note below *)
TraceID TraceID `json:"trace_id"`
SpanID SpanID `json:"span_id"`
ParentSpanID SpanID `json:"parent_span_id"`
Name string `json:"name,omitempty"`
Op string `json:"op,omitempty"`
Description string `json:"description,omitempty"`
Status SpanStatus `json:"status,omitempty"`
Tags map[string]string `json:"tags,omitempty"`
StartTime time.Time `json:"start_timestamp"`
EndTime time.Time `json:"timestamp"`
Data map[string]interface{} `json:"data,omitempty"`
Sampled Sampled `json:"-"`
Source TransactionSource `json:"-"`
TraceID TraceID `json:"trace_id"`
SpanID SpanID `json:"span_id"`
ParentSpanID SpanID `json:"parent_span_id"`
Name string `json:"name,omitempty"`
Op string `json:"op,omitempty"`
Description string `json:"description,omitempty"`
Status SpanStatus `json:"status,omitempty"`
Tags map[string]string `json:"tags,omitempty"`
StartTime time.Time `json:"start_timestamp"`
EndTime time.Time `json:"timestamp"`
// Deprecated: use Data instead. To be removed in 0.33.0
Extra map[string]interface{} `json:"-"`
Data map[string]interface{} `json:"data,omitempty"`
Sampled Sampled `json:"-"`
Source TransactionSource `json:"-"`
Origin SpanOrigin `json:"origin,omitempty"`
// mu protects concurrent writes to map fields
mu sync.RWMutex
@@ -53,10 +74,10 @@ type Span struct { //nolint: maligned // prefer readability over optimal memory
recorder *spanRecorder
// span context, can only be set on transactions
contexts map[string]Context
// collectProfile is a function that collects a profile of the current transaction. May be nil.
collectProfile transactionProfiler
// a Once instance to make sure that Finish() is only called once.
finishOnce sync.Once
// explicitSampled is a flag for configuring sampling by using `WithSpanSampled` option.
explicitSampled Sampled
}
// TraceParentContext describes the context of a (remote) parent span.
@@ -113,11 +134,19 @@ func StartSpan(ctx context.Context, operation string, options ...SpanOption) *Sp
parent: parent,
}
_, err := rand.Read(span.SpanID[:])
if err != nil {
panic(err)
}
if hasParent {
span.TraceID = parent.TraceID
span.ParentSpanID = parent.SpanID
span.Origin = parent.Origin
} else {
// Only set the Source if this is a transaction
span.Source = SourceCustom
span.Origin = SpanOriginManual
// Implementation note:
//
@@ -154,13 +183,6 @@ func StartSpan(ctx context.Context, operation string, options ...SpanOption) *Sp
panic(err)
}
}
_, err := rand.Read(span.SpanID[:])
if err != nil {
panic(err)
}
if hasParent {
span.ParentSpanID = parent.SpanID
}
// Apply options to override defaults.
for _, option := range options {
@@ -169,22 +191,17 @@ func StartSpan(ctx context.Context, operation string, options ...SpanOption) *Sp
span.Sampled = span.sample()
span.recorder = &spanRecorder{}
if hasParent {
span.recorder = parent.spanRecorder()
} else {
span.recorder = &spanRecorder{}
}
span.recorder.record(&span)
hub := hubFromContext(ctx)
// Update scope so that all events include a trace context, allowing
// Sentry to correlate errors to transactions/spans.
hub.Scope().SetContext("trace", span.traceContext().Map())
// Start profiling only if it's a sampled root transaction.
if span.IsTransaction() && span.Sampled.Bool() {
span.sampleTransactionProfile()
clientOptions := span.clientOptions()
if clientOptions.EnableTracing {
hub := hubFromContext(ctx)
hub.Scope().SetSpan(&span)
}
return &span
@@ -226,7 +243,11 @@ func (s *Span) SetTag(name, value string) {
// SetData sets a data on the span. It is recommended to use SetData instead of
// accessing the data map directly as SetData takes care of initializing the map
// when necessary.
func (s *Span) SetData(name, value string) {
func (s *Span) SetData(name string, value interface{}) {
if value == nil {
return
}
s.mu.Lock()
defer s.mu.Unlock()
@@ -283,7 +304,7 @@ func (s *Span) GetTransaction() *Span {
// func (s *Span) TransactionName() string
// func (s *Span) SetTransactionName(name string)
// ToSentryTrace returns the seralized TraceParentContext from a transaction/span.
// ToSentryTrace returns the serialized TraceParentContext from a transaction/span.
// Use this function to propagate the TraceParentContext to a downstream SDK,
// either as the value of the "sentry-trace" HTTP header, or as an html "sentry-trace" meta tag.
func (s *Span) ToSentryTrace() string {
@@ -300,21 +321,34 @@ func (s *Span) ToSentryTrace() string {
return b.String()
}
// ToTraceparent returns the W3C traceparent header value for the span.
func (s *Span) ToTraceparent() string {
traceFlags := "00"
if s.Sampled == SampledTrue {
traceFlags = "01"
}
return fmt.Sprintf("00-%s-%s-%s", s.TraceID.String(), s.SpanID.String(), traceFlags)
}
// ToBaggage returns the serialized DynamicSamplingContext from a transaction.
// Use this function to propagate the DynamicSamplingContext to a downstream SDK,
// either as the value of the "baggage" HTTP header, or as an html "baggage" meta tag.
func (s *Span) ToBaggage() string {
if containingTransaction := s.GetTransaction(); containingTransaction != nil {
// In case there is currently no frozen DynamicSamplingContext attached to the transaction,
// create one from the properties of the transaction.
if !s.dynamicSamplingContext.IsFrozen() {
// This will return a frozen DynamicSamplingContext.
s.dynamicSamplingContext = DynamicSamplingContextFromTransaction(containingTransaction)
}
return containingTransaction.dynamicSamplingContext.String()
t := s.GetTransaction()
if t == nil {
return ""
}
return ""
// In case there is currently no frozen DynamicSamplingContext attached to the transaction,
// create one from the properties of the transaction.
if !s.dynamicSamplingContext.IsFrozen() {
// This will return a frozen DynamicSamplingContext.
if dsc := DynamicSamplingContextFromTransaction(t); dsc.HasEntries() {
t.dynamicSamplingContext = dsc
}
}
return t.dynamicSamplingContext.String()
}
// SetDynamicSamplingContext sets the given dynamic sampling context on the
@@ -325,12 +359,75 @@ func (s *Span) SetDynamicSamplingContext(dsc DynamicSamplingContext) {
}
}
// shouldIgnoreStatusCode checks if the transaction should be ignored based on HTTP status code.
func (s *Span) shouldIgnoreStatusCode() bool {
if !s.IsTransaction() {
return false
}
ignoreStatusCodes := s.clientOptions().TraceIgnoreStatusCodes
if len(ignoreStatusCodes) == 0 {
return false
}
s.mu.Lock()
statusCodeData, exists := s.Data["http.response.status_code"]
s.mu.Unlock()
if !exists {
return false
}
statusCode, ok := statusCodeData.(int)
if !ok {
return false
}
for _, ignoredRange := range ignoreStatusCodes {
switch len(ignoredRange) {
case 1:
// Single status code
if statusCode == ignoredRange[0] {
s.mu.Lock()
s.Sampled = SampledFalse
s.mu.Unlock()
debuglog.Printf("dropping transaction with status code %v: found in TraceIgnoreStatusCodes", statusCode)
return true
}
case 2:
// Range of status codes [min, max]
if ignoredRange[0] <= statusCode && statusCode <= ignoredRange[1] {
s.mu.Lock()
s.Sampled = SampledFalse
s.mu.Unlock()
debuglog.Printf("dropping transaction with status code %v: found in TraceIgnoreStatusCodes range [%d, %d]", statusCode, ignoredRange[0], ignoredRange[1])
return true
}
default:
debuglog.Printf("incorrect TraceIgnoreStatusCodes format: %v", ignoredRange)
}
}
return false
}
// doFinish runs the actual Span.Finish() logic.
func (s *Span) doFinish() {
if s.EndTime.IsZero() {
s.EndTime = monotonicTimeSince(s.StartTime)
}
hub := hubFromContext(s.ctx)
if !s.IsTransaction() {
if s.parent != nil {
hub.Scope().SetSpan(s.parent)
}
}
if s.shouldIgnoreStatusCode() {
return
}
if !s.Sampled.Bool() {
return
}
@@ -339,14 +436,9 @@ func (s *Span) doFinish() {
return
}
if s.collectProfile != nil {
event.sdkMetaData.transactionProfile = s.collectProfile(s)
}
// TODO(tracing): add breadcrumbs
// (see https://github.com/getsentry/sentry-python/blob/f6f3525f8812f609/sentry_sdk/tracing.py#L372)
hub := hubFromContext(s.ctx)
hub.CaptureEvent(event)
}
@@ -425,21 +517,21 @@ func (s *Span) sample() Sampled {
// https://develop.sentry.dev/sdk/performance/#sampling
// #1 tracing is not enabled.
if !clientOptions.EnableTracing {
Logger.Printf("Dropping transaction: EnableTracing is set to %t", clientOptions.EnableTracing)
debuglog.Printf("Dropping transaction: EnableTracing is set to %t", clientOptions.EnableTracing)
s.sampleRate = 0.0
return SampledFalse
}
// #2 explicit sampling decision via StartSpan/StartTransaction options.
if s.Sampled != SampledUndefined {
Logger.Printf("Using explicit sampling decision from StartSpan/StartTransaction: %v", s.Sampled)
switch s.Sampled {
if s.explicitSampled != SampledUndefined {
debuglog.Printf("Using explicit sampling decision from StartSpan/StartTransaction: %v", s.explicitSampled)
switch s.explicitSampled {
case SampledTrue:
s.sampleRate = 1.0
case SampledFalse:
s.sampleRate = 0.0
}
return s.Sampled
return s.explicitSampled
}
// Variant for non-transaction spans: they inherit the parent decision.
@@ -460,42 +552,52 @@ func (s *Span) sample() Sampled {
if sampler != nil {
tracesSamplerSampleRate := sampler.Sample(samplingContext)
s.sampleRate = tracesSamplerSampleRate
// tracesSampler can update the sample_rate on frozen DSC
if s.dynamicSamplingContext.HasEntries() {
s.dynamicSamplingContext.Entries["sample_rate"] = strconv.FormatFloat(tracesSamplerSampleRate, 'f', -1, 64)
}
if tracesSamplerSampleRate < 0.0 || tracesSamplerSampleRate > 1.0 {
Logger.Printf("Dropping transaction: Returned TracesSampler rate is out of range [0.0, 1.0]: %f", tracesSamplerSampleRate)
debuglog.Printf("Dropping transaction: Returned TracesSampler rate is out of range [0.0, 1.0]: %f", tracesSamplerSampleRate)
return SampledFalse
}
if tracesSamplerSampleRate == 0 {
Logger.Printf("Dropping transaction: Returned TracesSampler rate is: %f", tracesSamplerSampleRate)
if tracesSamplerSampleRate == 0.0 {
debuglog.Printf("Dropping transaction: Returned TracesSampler rate is: %f", tracesSamplerSampleRate)
return SampledFalse
}
if rng.Float64() < tracesSamplerSampleRate {
return SampledTrue
}
Logger.Printf("Dropping transaction: TracesSampler returned rate: %f", tracesSamplerSampleRate)
debuglog.Printf("Dropping transaction: TracesSampler returned rate: %f", tracesSamplerSampleRate)
return SampledFalse
}
// #4 inherit parent decision.
if s.parent != nil {
Logger.Printf("Using sampling decision from parent: %v", s.parent.Sampled)
switch s.parent.Sampled {
if s.Sampled != SampledUndefined {
debuglog.Printf("Using sampling decision from parent: %v", s.Sampled)
switch s.Sampled {
case SampledTrue:
s.sampleRate = 1.0
case SampledFalse:
s.sampleRate = 0.0
}
return s.parent.Sampled
return s.Sampled
}
// #5 use TracesSampleRate from ClientOptions.
sampleRate := clientOptions.TracesSampleRate
s.sampleRate = sampleRate
// tracesSampleRate can update the sample_rate on frozen DSC
if s.dynamicSamplingContext.HasEntries() {
s.dynamicSamplingContext.Entries["sample_rate"] = strconv.FormatFloat(sampleRate, 'f', -1, 64)
}
if sampleRate < 0.0 || sampleRate > 1.0 {
Logger.Printf("Dropping transaction: TracesSamplerRate out of range [0.0, 1.0]: %f", sampleRate)
debuglog.Printf("Dropping transaction: TracesSampleRate out of range [0.0, 1.0]: %f", sampleRate)
return SampledFalse
}
if sampleRate == 0.0 {
Logger.Printf("Dropping transaction: TracesSampleRate rate is: %f", sampleRate)
debuglog.Printf("Dropping transaction: TracesSampleRate rate is: %f", sampleRate)
return SampledFalse
}
@@ -518,7 +620,7 @@ func (s *Span) toEvent() *Event {
finished := make([]*Span, 0, len(children))
for _, child := range children {
if child.EndTime.IsZero() {
Logger.Printf("Dropped unfinished span: Op=%q TraceID=%s SpanID=%s", child.Op, child.TraceID, child.SpanID)
debuglog.Printf("Dropped unfinished span: Op=%q TraceID=%s SpanID=%s", child.Op, child.TraceID, child.SpanID)
continue
}
finished = append(finished, child)
@@ -530,7 +632,7 @@ func (s *Span) toEvent() *Event {
s.dynamicSamplingContext = DynamicSamplingContextFromTransaction(s)
}
contexts := map[string]Context{}
contexts := make(map[string]Context, len(s.contexts)+1)
for k, v := range s.contexts {
contexts[k] = cloneContext(v)
}
@@ -547,7 +649,6 @@ func (s *Span) toEvent() *Event {
Transaction: s.Name,
Contexts: contexts,
Tags: s.Tags,
Extra: s.Data,
Timestamp: s.EndTime,
StartTime: s.StartTime,
Spans: finished,
@@ -566,6 +667,7 @@ func (s *Span) traceContext() *TraceContext {
SpanID: s.SpanID,
ParentSpanID: s.ParentSpanID,
Op: s.Op,
Data: s.Data,
Description: s.Description,
Status: s.Status,
}
@@ -702,31 +804,32 @@ const (
maxSpanStatus
)
var spanStatuses = [maxSpanStatus]string{
"",
"ok",
"cancelled", // [sic]
"unknown",
"invalid_argument",
"deadline_exceeded",
"not_found",
"already_exists",
"permission_denied",
"resource_exhausted",
"failed_precondition",
"aborted",
"out_of_range",
"unimplemented",
"internal_error",
"unavailable",
"data_loss",
"unauthenticated",
}
func (ss SpanStatus) String() string {
if ss >= maxSpanStatus {
return ""
}
m := [maxSpanStatus]string{
"",
"ok",
"cancelled", // [sic]
"unknown",
"invalid_argument",
"deadline_exceeded",
"not_found",
"already_exists",
"permission_denied",
"resource_exhausted",
"failed_precondition",
"aborted",
"out_of_range",
"unimplemented",
"internal_error",
"unavailable",
"data_loss",
"unauthenticated",
}
return m[ss]
return spanStatuses[ss]
}
func (ss SpanStatus) MarshalJSON() ([]byte, error) {
@@ -740,12 +843,13 @@ func (ss SpanStatus) MarshalJSON() ([]byte, error) {
// A TraceContext carries information about an ongoing trace and is meant to be
// stored in Event.Contexts (as *TraceContext).
type TraceContext struct {
TraceID TraceID `json:"trace_id"`
SpanID SpanID `json:"span_id"`
ParentSpanID SpanID `json:"parent_span_id"`
Op string `json:"op,omitempty"`
Description string `json:"description,omitempty"`
Status SpanStatus `json:"status,omitempty"`
TraceID TraceID `json:"trace_id"`
SpanID SpanID `json:"span_id"`
ParentSpanID SpanID `json:"parent_span_id"`
Op string `json:"op,omitempty"`
Description string `json:"description,omitempty"`
Status SpanStatus `json:"status,omitempty"`
Data map[string]interface{} `json:"data,omitempty"`
}
func (tc *TraceContext) MarshalJSON() ([]byte, error) {
@@ -788,6 +892,10 @@ func (tc TraceContext) Map() map[string]interface{} {
m["status"] = tc.Status
}
if len(tc.Data) > 0 {
m["data"] = tc.Data
}
return m
}
@@ -862,10 +970,29 @@ func WithTransactionSource(source TransactionSource) SpanOption {
// WithSpanSampled updates the sampling flag for a given span.
func WithSpanSampled(sampled Sampled) SpanOption {
return func(s *Span) {
s.Sampled = sampled
s.explicitSampled = sampled
}
}
// WithSpanOrigin sets the origin of the span.
func WithSpanOrigin(origin SpanOrigin) SpanOption {
return func(s *Span) {
s.Origin = origin
}
}
// ContinueTrace continues a trace based on traceparent and baggage values.
// If the SDK is configured with tracing enabled,
// this function returns populated SpanOption.
// In any other cases, it populates the propagation context on the scope.
func ContinueTrace(hub *Hub, traceparent, baggage string) SpanOption {
scope := hub.Scope()
propagationContext, _ := PropagationContextFromHeaders(traceparent, baggage)
scope.SetPropagationContext(propagationContext)
return ContinueFromHeaders(traceparent, baggage)
}
// ContinueFromRequest returns a span option that updates the span to continue
// an existing trace. If it cannot detect an existing trace in the request, the
// span will be left unchanged.
@@ -883,16 +1010,17 @@ func ContinueFromHeaders(trace, baggage string) SpanOption {
return func(s *Span) {
if trace != "" {
s.updateFromSentryTrace([]byte(trace))
}
if baggage != "" {
s.updateFromBaggage([]byte(baggage))
}
// In case a sentry-trace header is present but there are no sentry-related
// values in the baggage, create an empty, frozen DynamicSamplingContext.
if trace != "" && !s.dynamicSamplingContext.HasEntries() {
s.dynamicSamplingContext = DynamicSamplingContext{
Frozen: true,
if baggage != "" {
s.updateFromBaggage([]byte(baggage))
}
// In case a sentry-trace header is present but there are no sentry-related
// values in the baggage, create an empty, frozen DynamicSamplingContext.
if !s.dynamicSamplingContext.HasEntries() {
s.dynamicSamplingContext = DynamicSamplingContext{
Frozen: true,
}
}
}
}
@@ -935,6 +1063,7 @@ func SpanFromContext(ctx context.Context) *Span {
func StartTransaction(ctx context.Context, name string, options ...SpanOption) *Span {
currentTransaction, exists := ctx.Value(spanContextKey{}).(*Span)
if exists {
currentTransaction.ctx = ctx
return currentTransaction
}

View File

@@ -2,6 +2,7 @@ package sentry
import (
"bytes"
"context"
"crypto/tls"
"encoding/json"
"errors"
@@ -12,11 +13,16 @@ import (
"sync"
"time"
"github.com/getsentry/sentry-go/internal/debuglog"
httpinternal "github.com/getsentry/sentry-go/internal/http"
"github.com/getsentry/sentry-go/internal/protocol"
"github.com/getsentry/sentry-go/internal/ratelimit"
)
const defaultBufferSize = 30
const defaultTimeout = time.Second * 30
const (
defaultBufferSize = 1000
defaultTimeout = time.Second * 30
)
// maxDrainResponseBytes is the maximum number of bytes that transport
// implementations will read from response bodies when draining them.
@@ -32,8 +38,10 @@ const maxDrainResponseBytes = 16 << 10
// Transport is used by the Client to deliver events to remote server.
type Transport interface {
Flush(timeout time.Duration) bool
FlushWithContext(ctx context.Context) bool
Configure(options ClientOptions)
SendEvent(event *Event)
Close()
}
func getProxyConfig(options ClientOptions) func(*http.Request) (*url.URL, error) {
@@ -82,14 +90,14 @@ func getRequestBodyFromEvent(event *Event) []byte {
}
body, err = json.Marshal(event)
if err == nil {
Logger.Println(msg)
debuglog.Println(msg)
return body
}
// This should _only_ happen when Event.Exception[0].Stacktrace.Frames[0].Vars is unserializable
// Which won't ever happen, as we don't use it now (although it's the part of public interface accepted by Sentry)
// Juuust in case something, somehow goes utterly wrong.
Logger.Println("Event couldn't be marshaled, even with stripped contextual data. Skipping delivery. " +
debuglog.Println("Event couldn't be marshaled, even with stripped contextual data. Skipping delivery. " +
"Please notify the SDK owners with possibly broken payload.")
return nil
}
@@ -142,6 +150,40 @@ func encodeEnvelopeItem(enc *json.Encoder, itemType string, body json.RawMessage
return err
}
func encodeEnvelopeLogs(enc *json.Encoder, count int, body json.RawMessage) error {
err := enc.Encode(
struct {
Type string `json:"type"`
ItemCount int `json:"item_count"`
ContentType string `json:"content_type"`
}{
Type: logEvent.Type,
ItemCount: count,
ContentType: logEvent.ContentType,
})
if err == nil {
err = enc.Encode(body)
}
return err
}
func encodeEnvelopeMetrics(enc *json.Encoder, count int, body json.RawMessage) error {
err := enc.Encode(
struct {
Type string `json:"type"`
ItemCount int `json:"item_count"`
ContentType string `json:"content_type"`
}{
Type: traceMetricEvent.Type,
ItemCount: count,
ContentType: traceMetricEvent.ContentType,
})
if err == nil {
err = enc.Encode(body)
}
return err
}
func envelopeFromBody(event *Event, dsn *Dsn, sentAt time.Time, body json.RawMessage) (*bytes.Buffer, error) {
var b bytes.Buffer
enc := json.NewEncoder(&b)
@@ -175,11 +217,17 @@ func envelopeFromBody(event *Event, dsn *Dsn, sentAt time.Time, body json.RawMes
return nil, err
}
if event.Type == transactionType || event.Type == checkInType {
switch event.Type {
case transactionType, checkInType:
err = encodeEnvelopeItem(enc, event.Type, body)
} else {
case logEvent.Type:
err = encodeEnvelopeLogs(enc, len(event.Logs), body)
case traceMetricEvent.Type:
err = encodeEnvelopeMetrics(enc, len(event.Metrics), body)
default:
err = encodeEnvelopeItem(enc, eventType, body)
}
if err != nil {
return nil, err
}
@@ -191,66 +239,51 @@ func envelopeFromBody(event *Event, dsn *Dsn, sentAt time.Time, body json.RawMes
}
}
// Profile data
if event.sdkMetaData.transactionProfile != nil {
body, err = json.Marshal(event.sdkMetaData.transactionProfile)
if err != nil {
return nil, err
}
err = encodeEnvelopeItem(enc, profileType, body)
if err != nil {
return nil, err
}
}
return &b, nil
}
func getRequestFromEvent(event *Event, dsn *Dsn) (r *http.Request, err error) {
func getRequestFromEvent(ctx context.Context, event *Event, dsn *Dsn) (r *http.Request, err error) {
defer func() {
if r != nil {
r.Header.Set("User-Agent", fmt.Sprintf("%s/%s", event.Sdk.Name, event.Sdk.Version))
r.Header.Set("Content-Type", "application/x-sentry-envelope")
auth := fmt.Sprintf("Sentry sentry_version=%s, "+
"sentry_client=%s/%s, sentry_key=%s", apiVersion, event.Sdk.Name, event.Sdk.Version, dsn.publicKey)
"sentry_client=%s/%s, sentry_key=%s", apiVersion, event.Sdk.Name, event.Sdk.Version, dsn.GetPublicKey())
// The key sentry_secret is effectively deprecated and no longer needs to be set.
// However, since it was required in older self-hosted versions,
// it should still passed through to Sentry if set.
if dsn.secretKey != "" {
auth = fmt.Sprintf("%s, sentry_secret=%s", auth, dsn.secretKey)
if dsn.GetSecretKey() != "" {
auth = fmt.Sprintf("%s, sentry_secret=%s", auth, dsn.GetSecretKey())
}
r.Header.Set("X-Sentry-Auth", auth)
}
}()
body := getRequestBodyFromEvent(event)
if body == nil {
return nil, errors.New("event could not be marshaled")
}
envelope, err := envelopeFromBody(event, dsn, time.Now(), body)
if err != nil {
return nil, err
}
return http.NewRequest(
if ctx == nil {
ctx = context.Background()
}
return http.NewRequestWithContext(
ctx,
http.MethodPost,
dsn.GetAPIURL().String(),
envelope,
)
}
func categoryFor(eventType string) ratelimit.Category {
switch eventType {
case "":
return ratelimit.CategoryError
case transactionType:
return ratelimit.CategoryTransaction
default:
return ratelimit.Category(eventType)
}
}
// ================================
// HTTPTransport
// ================================
@@ -281,7 +314,8 @@ type HTTPTransport struct {
// current in-flight items and starts a new batch for subsequent events.
buffer chan batch
start sync.Once
startOnce sync.Once
closeOnce sync.Once
// Size of the transport buffer. Defaults to 30.
BufferSize int
@@ -290,6 +324,9 @@ type HTTPTransport struct {
mu sync.RWMutex
limits ratelimit.Map
// receiving signal will terminate worker.
done chan struct{}
}
// NewHTTPTransport returns a new pre-configured instance of HTTPTransport.
@@ -297,7 +334,7 @@ func NewHTTPTransport() *HTTPTransport {
transport := HTTPTransport{
BufferSize: defaultBufferSize,
Timeout: defaultTimeout,
limits: make(ratelimit.Map),
done: make(chan struct{}),
}
return &transport
}
@@ -306,7 +343,7 @@ func NewHTTPTransport() *HTTPTransport {
func (t *HTTPTransport) Configure(options ClientOptions) {
dsn, err := NewDsn(options.Dsn)
if err != nil {
Logger.Printf("%v\n", err)
debuglog.Printf("%v\n", err)
return
}
t.dsn = dsn
@@ -339,24 +376,29 @@ func (t *HTTPTransport) Configure(options ClientOptions) {
}
}
t.start.Do(func() {
t.startOnce.Do(func() {
go t.worker()
})
}
// SendEvent assembles a new packet out of Event and sends it to remote server.
// SendEvent assembles a new packet out of Event and sends it to the remote server.
func (t *HTTPTransport) SendEvent(event *Event) {
t.SendEventWithContext(context.Background(), event)
}
// SendEventWithContext assembles a new packet out of Event and sends it to the remote server.
func (t *HTTPTransport) SendEventWithContext(ctx context.Context, event *Event) {
if t.dsn == nil {
return
}
category := categoryFor(event.Type)
category := event.toCategory()
if t.disabled(category) {
return
}
request, err := getRequestFromEvent(event, t.dsn)
request, err := getRequestFromEvent(ctx, event, t.dsn)
if err != nil {
return
}
@@ -383,17 +425,17 @@ func (t *HTTPTransport) SendEvent(event *Event) {
if event.Type == transactionType {
eventType = "transaction"
} else {
eventType = fmt.Sprintf("%s event", event.Level)
eventType = fmt.Sprintf("%s event", event.Type)
}
Logger.Printf(
debuglog.Printf(
"Sending %s [%s] to %s project: %s",
eventType,
event.EventID,
t.dsn.host,
t.dsn.projectID,
t.dsn.GetHost(),
t.dsn.GetProjectID(),
)
default:
Logger.Println("Event dropped due to transport buffer being full.")
debuglog.Println("Event dropped due to transport buffer being full.")
}
t.buffer <- b
@@ -410,8 +452,17 @@ func (t *HTTPTransport) SendEvent(event *Event) {
// have the SDK send events over the network synchronously, configure it to use
// the HTTPSyncTransport in the call to Init.
func (t *HTTPTransport) Flush(timeout time.Duration) bool {
toolate := time.After(timeout)
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
return t.FlushWithContext(ctx)
}
// FlushWithContext works like Flush, but it accepts a context.Context instead of a timeout.
func (t *HTTPTransport) FlushWithContext(ctx context.Context) bool {
return t.flushInternal(ctx.Done())
}
func (t *HTTPTransport) flushInternal(timeout <-chan struct{}) bool {
// Wait until processing the current batch has started or the timeout.
//
// We must wait until the worker has seen the current batch, because it is
@@ -419,6 +470,7 @@ func (t *HTTPTransport) Flush(timeout time.Duration) bool {
// possible execution flow in which b.done is never closed, and the only way
// out of Flush would be waiting for the timeout, which is undesired.
var b batch
for {
select {
case b = <-t.buffer:
@@ -428,7 +480,7 @@ func (t *HTTPTransport) Flush(timeout time.Duration) bool {
default:
t.buffer <- b
}
case <-toolate:
case <-timeout:
goto fail
}
}
@@ -447,17 +499,28 @@ started:
// Wait until the current batch is done or the timeout.
select {
case <-b.done:
Logger.Println("Buffer flushed successfully.")
debuglog.Println("Buffer flushed successfully.")
return true
case <-toolate:
case <-timeout:
goto fail
}
fail:
Logger.Println("Buffer flushing reached the timeout.")
debuglog.Println("Buffer flushing was canceled or timed out.")
return false
}
// Close will terminate events sending loop.
// It useful to prevent goroutines leak in case of multiple HTTPTransport instances initiated.
//
// Close should be called after Flush and before terminating the program
// otherwise some events may be lost.
func (t *HTTPTransport) Close() {
t.closeOnce.Do(func() {
close(t.done)
})
}
func (t *HTTPTransport) worker() {
for b := range t.buffer {
// Signal that processing of the current batch has started.
@@ -468,23 +531,44 @@ func (t *HTTPTransport) worker() {
t.buffer <- b
// Process all batch items.
for item := range b.items {
if t.disabled(item.category) {
continue
}
loop:
for {
select {
case <-t.done:
return
case item, open := <-b.items:
if !open {
break loop
}
if t.disabled(item.category) {
continue
}
response, err := t.client.Do(item.request)
if err != nil {
Logger.Printf("There was an issue with sending an event: %v", err)
continue
response, err := t.client.Do(item.request)
if err != nil {
debuglog.Printf("There was an issue with sending an event: %v", err)
continue
}
if response.StatusCode >= 400 && response.StatusCode <= 599 {
b, err := io.ReadAll(response.Body)
if err != nil {
debuglog.Printf("Error while reading response code: %v", err)
}
debuglog.Printf("Sending %s failed with the following error: %s", eventType, string(b))
}
t.mu.Lock()
if t.limits == nil {
t.limits = make(ratelimit.Map)
}
t.limits.Merge(ratelimit.FromResponse(response))
t.mu.Unlock()
// Drain body up to a limit and close it, allowing the
// transport to reuse TCP connections.
_, _ = io.CopyN(io.Discard, response.Body, maxDrainResponseBytes)
response.Body.Close()
}
t.mu.Lock()
t.limits.Merge(ratelimit.FromResponse(response))
t.mu.Unlock()
// Drain body up to a limit and close it, allowing the
// transport to reuse TCP connections.
_, _ = io.CopyN(io.Discard, response.Body, maxDrainResponseBytes)
response.Body.Close()
}
// Signal that processing of the batch is done.
@@ -497,7 +581,7 @@ func (t *HTTPTransport) disabled(c ratelimit.Category) bool {
defer t.mu.RUnlock()
disabled := t.limits.IsRateLimited(c)
if disabled {
Logger.Printf("Too many requests for %q, backing off till: %v", c, t.limits.Deadline(c))
debuglog.Printf("Too many requests for %q, backing off till: %v", c, t.limits.Deadline(c))
}
return disabled
}
@@ -543,7 +627,7 @@ func NewHTTPSyncTransport() *HTTPSyncTransport {
func (t *HTTPSyncTransport) Configure(options ClientOptions) {
dsn, err := NewDsn(options.Dsn)
if err != nil {
Logger.Printf("%v\n", err)
debuglog.Printf("%v\n", err)
return
}
t.dsn = dsn
@@ -567,41 +651,67 @@ func (t *HTTPSyncTransport) Configure(options ClientOptions) {
}
}
// SendEvent assembles a new packet out of Event and sends it to remote server.
// SendEvent assembles a new packet out of Event and sends it to the remote server.
func (t *HTTPSyncTransport) SendEvent(event *Event) {
t.SendEventWithContext(context.Background(), event)
}
func (t *HTTPSyncTransport) Close() {}
// SendEventWithContext assembles a new packet out of Event and sends it to the remote server.
func (t *HTTPSyncTransport) SendEventWithContext(ctx context.Context, event *Event) {
if t.dsn == nil {
return
}
if t.disabled(categoryFor(event.Type)) {
if t.disabled(event.toCategory()) {
return
}
request, err := getRequestFromEvent(event, t.dsn)
request, err := getRequestFromEvent(ctx, event, t.dsn)
if err != nil {
return
}
var eventType string
if event.Type == transactionType {
eventType = "transaction"
} else {
eventType = fmt.Sprintf("%s event", event.Level)
var eventIdentifier string
switch event.Type {
case errorType:
eventIdentifier = "error"
case transactionType:
eventIdentifier = "transaction"
case logEvent.Type:
eventIdentifier = fmt.Sprintf("%d log events", len(event.Logs))
case traceMetricEvent.Type:
eventIdentifier = fmt.Sprintf("%d metric events", len(event.Metrics))
default:
eventIdentifier = fmt.Sprintf("%s event", event.Type)
}
Logger.Printf(
debuglog.Printf(
"Sending %s [%s] to %s project: %s",
eventType,
eventIdentifier,
event.EventID,
t.dsn.host,
t.dsn.projectID,
t.dsn.GetHost(),
t.dsn.GetProjectID(),
)
response, err := t.client.Do(request)
if err != nil {
Logger.Printf("There was an issue with sending an event: %v", err)
debuglog.Printf("There was an issue with sending an event: %v", err)
return
}
if response.StatusCode >= 400 && response.StatusCode <= 599 {
b, err := io.ReadAll(response.Body)
if err != nil {
debuglog.Printf("Error while reading response code: %v", err)
}
debuglog.Printf("Sending %s failed with the following error: %s", eventIdentifier, string(b))
}
t.mu.Lock()
if t.limits == nil {
t.limits = make(ratelimit.Map)
}
t.limits.Merge(ratelimit.FromResponse(response))
t.mu.Unlock()
@@ -616,12 +726,17 @@ func (t *HTTPSyncTransport) Flush(_ time.Duration) bool {
return true
}
// FlushWithContext is a no-op for HTTPSyncTransport. It always returns true immediately.
func (t *HTTPSyncTransport) FlushWithContext(_ context.Context) bool {
return true
}
func (t *HTTPSyncTransport) disabled(c ratelimit.Category) bool {
t.mu.Lock()
defer t.mu.Unlock()
disabled := t.limits.IsRateLimited(c)
if disabled {
Logger.Printf("Too many requests for %q, backing off till: %v", c, t.limits.Deadline(c))
debuglog.Printf("Too many requests for %q, backing off till: %v", c, t.limits.Deadline(c))
}
return disabled
}
@@ -637,13 +752,98 @@ type noopTransport struct{}
var _ Transport = noopTransport{}
func (noopTransport) Configure(ClientOptions) {
Logger.Println("Sentry client initialized with an empty DSN. Using noopTransport. No events will be delivered.")
debuglog.Println("Sentry client initialized with an empty DSN. Using noopTransport. No events will be delivered.")
}
func (noopTransport) SendEvent(*Event) {
Logger.Println("Event dropped due to noopTransport usage.")
debuglog.Println("Event dropped due to noopTransport usage.")
}
func (noopTransport) Flush(time.Duration) bool {
return true
}
func (noopTransport) FlushWithContext(context.Context) bool {
return true
}
func (noopTransport) Close() {}
// ================================
// Internal Transport Adapters
// ================================
// newInternalAsyncTransport creates a new AsyncTransport from internal/http
// wrapped to satisfy the Transport interface.
//
// This is not yet exposed in the public API and is for internal experimentation.
func newInternalAsyncTransport() Transport {
return &internalAsyncTransportAdapter{}
}
// internalAsyncTransportAdapter wraps the internal AsyncTransport to implement
// the root-level Transport interface.
type internalAsyncTransportAdapter struct {
transport protocol.TelemetryTransport
dsn *protocol.Dsn
}
func (a *internalAsyncTransportAdapter) Configure(options ClientOptions) {
transportOptions := httpinternal.TransportOptions{
Dsn: options.Dsn,
HTTPClient: options.HTTPClient,
HTTPTransport: options.HTTPTransport,
HTTPProxy: options.HTTPProxy,
HTTPSProxy: options.HTTPSProxy,
CaCerts: options.CaCerts,
}
a.transport = httpinternal.NewAsyncTransport(transportOptions)
if options.Dsn != "" {
dsn, err := protocol.NewDsn(options.Dsn)
if err != nil {
debuglog.Printf("Failed to parse DSN in adapter: %v\n", err)
} else {
a.dsn = dsn
}
}
}
func (a *internalAsyncTransportAdapter) SendEvent(event *Event) {
header := &protocol.EnvelopeHeader{EventID: string(event.EventID), SentAt: time.Now(), Sdk: &protocol.SdkInfo{Name: event.Sdk.Name, Version: event.Sdk.Version}}
if a.dsn != nil {
header.Dsn = a.dsn.String()
}
if header.EventID == "" {
header.EventID = protocol.GenerateEventID()
}
envelope := protocol.NewEnvelope(header)
item, err := event.ToEnvelopeItem()
if err != nil {
debuglog.Printf("Failed to convert event to envelope item: %v", err)
return
}
envelope.AddItem(item)
for _, attachment := range event.Attachments {
attachmentItem := protocol.NewAttachmentItem(attachment.Filename, attachment.ContentType, attachment.Payload)
envelope.AddItem(attachmentItem)
}
if err := a.transport.SendEnvelope(envelope); err != nil {
debuglog.Printf("Error sending envelope: %v", err)
}
}
func (a *internalAsyncTransportAdapter) Flush(timeout time.Duration) bool {
return a.transport.Flush(timeout)
}
func (a *internalAsyncTransportAdapter) FlushWithContext(ctx context.Context) bool {
return a.transport.FlushWithContext(ctx)
}
func (a *internalAsyncTransportAdapter) Close() {
a.transport.Close()
}

View File

@@ -1,8 +1,6 @@
package sentry
import (
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"os"
@@ -10,18 +8,13 @@ import (
"strings"
"time"
"github.com/getsentry/sentry-go/internal/debuglog"
"github.com/getsentry/sentry-go/internal/protocol"
exec "golang.org/x/sys/execabs"
)
func uuid() string {
id := make([]byte, 16)
// Prefer rand.Read over rand.Reader, see https://go-review.googlesource.com/c/go/+/272326/.
_, _ = rand.Read(id)
id[6] &= 0x0F // clear version
id[6] |= 0x40 // set version to 4 (random uuid)
id[8] &= 0x3F // clear variant
id[8] |= 0x80 // set to IETF variant
return hex.EncodeToString(id)
return protocol.GenerateEventID()
}
func fileExists(fileName string) bool {
@@ -36,7 +29,7 @@ func monotonicTimeSince(start time.Time) (end time.Time) {
return start.Add(time.Since(start))
}
// nolint: deadcode, unused
// nolint: unused
func prettyPrint(data interface{}) {
dbg, _ := json.MarshalIndent(data, "", " ")
fmt.Println(string(dbg))
@@ -62,7 +55,7 @@ func defaultRelease() (release string) {
}
for _, e := range envs {
if release = os.Getenv(e); release != "" {
Logger.Printf("Using release from environment variable %s: %s", e, release)
debuglog.Printf("Using release from environment variable %s: %s", e, release)
return release
}
}
@@ -89,26 +82,30 @@ func defaultRelease() (release string) {
if err, ok := err.(*exec.ExitError); ok && len(err.Stderr) > 0 {
fmt.Fprintf(&s, ": %s", err.Stderr)
}
Logger.Print(s.String())
debuglog.Print(s.String())
} else {
release = strings.TrimSpace(string(b))
Logger.Printf("Using release from Git: %s", release)
debuglog.Printf("Using release from Git: %s", release)
return release
}
}
Logger.Print("Some Sentry features will not be available. See https://docs.sentry.io/product/releases/.")
Logger.Print("To stop seeing this message, pass a Release to sentry.Init or set the SENTRY_RELEASE environment variable.")
debuglog.Print("Some Sentry features will not be available. See https://docs.sentry.io/product/releases/.")
debuglog.Print("To stop seeing this message, pass a Release to sentry.Init or set the SENTRY_RELEASE environment variable.")
return ""
}
func revisionFromBuildInfo(info *debug.BuildInfo) string {
for _, setting := range info.Settings {
if setting.Key == "vcs.revision" && setting.Value != "" {
Logger.Printf("Using release from debug info: %s", setting.Value)
debuglog.Printf("Using release from debug info: %s", setting.Value)
return setting.Value
}
}
return ""
}
func Pointer[T any](v T) *T {
return &v
}