connectrpc-sentry 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 5a921b8eab5e8fbc260bd996774c3b6ebf623aeff05d6516539a8e46ab92144a
4
+ data.tar.gz: a38aa9d22479209568754421bec844567bb0af7e265e6644a5ea43ed805b4570
5
+ SHA512:
6
+ metadata.gz: 387c0b77882751f6e1b9c1ced43c7d4bd7ba1ef56b241937df11d43be66a1d7bed85cc3122807ad6d9a93a2c938aa82afabce13c67f60e75bb501e300b362878
7
+ data.tar.gz: cf3e1f674eb74af3b98a4048836e437d1718a2439e1ff53e13fbd5599fb4b44ad8cca8f3f0fe1fffbea9966243dea9e874f4e57c9cef0ecd0e74586f43898f3e
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Jim Myhrberg
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,299 @@
1
+ <div align="center">
2
+
3
+ <img height="128px" width="128px" src="../../img/connectrpc-ruby.svg" alt="connectrpc-ruby logo">
4
+
5
+ # connectrpc-sentry
6
+
7
+ **Native Sentry tracing and handler exception capture for ConnectRPC.**
8
+
9
+ [![RubyGems](https://img.shields.io/gem/v/connectrpc-sentry?logo=rubygems&logoColor=white&label=RubyGems)](https://rubygems.org/gems/connectrpc-sentry)
10
+ [![CI](https://img.shields.io/github/actions/workflow/status/jimeh/connectrpc-ruby/ci.yml?branch=main&logo=github&label=CI)](https://github.com/jimeh/connectrpc-ruby/actions/workflows/ci.yml)
11
+ [![Docs](https://img.shields.io/badge/Docs-guides-0969da?logo=markdown&logoColor=white)](https://github.com/jimeh/connectrpc-ruby/tree/main/docs)
12
+ [![License](https://img.shields.io/github/license/jimeh/connectrpc-ruby?label=License)](https://github.com/jimeh/connectrpc-ruby/blob/main/LICENSE)
13
+
14
+ </div>
15
+
16
+ `connectrpc-sentry` turns the core ConnectRPC per-call lifecycle into native
17
+ Sentry transactions and spans for Connect unary/streaming, native gRPC and server
18
+ gRPC-Web RPCs, and reports unexpected server handler exceptions. Use it when your
19
+ application already uses the Sentry Ruby SDK, with or without `sentry-rails`,
20
+ and you want one Sentry observation per RPC side, linked across services by
21
+ `sentry-trace` and `baggage`.
22
+
23
+ The package is experimental. See the [supported 0.x contract](../../docs/support.md)
24
+ for the target support profile, matched package versions, compatibility policy
25
+ and adoption gates.
26
+
27
+ ## Installation
28
+
29
+ ```ruby
30
+ gem "connectrpc-sentry", "~> 0.1.0"
31
+ ```
32
+
33
+ The only runtime dependencies are `connectrpc ~> 0.1.0` and
34
+ `sentry-ruby >= 6.7.0, < 8`. Core and the HTTP/framework packages do not depend
35
+ on Sentry. `sentry-rails` is optional; Rails RPCs work through the active-span
36
+ rule below.
37
+
38
+ ## Usage
39
+
40
+ Create a subscriber and pass the resulting instrumentation to both the client
41
+ and the server:
42
+
43
+ ```ruby
44
+ require "connectrpc/sentry"
45
+
46
+ subscriber = ConnectRPC::Sentry::Subscriber.new
47
+ instrumentation = ConnectRPC::Instrumentation.new(
48
+ subscribers: [subscriber], on_error: ->(error) { application_logger.warn(error.class.name) }
49
+ )
50
+ # Pass instrumentation: instrumentation to both ConnectRPC::Client.new and
51
+ # ConnectRPC::Server.new. Their other options and generated callers are unchanged.
52
+ ```
53
+
54
+ `capture_exceptions:` defaults to `true`; pass `false` to keep tracing without
55
+ reporting handler exceptions. For native Rails controllers, override the private
56
+ `connect_instrumentation` hook instead; see [host notes](#host-notes).
57
+
58
+ `mise run sentry:example` runs generated callers against the real SDK with an
59
+ in-memory transport from the repository root.
60
+
61
+ ### What the application owns
62
+
63
+ The application owns `Sentry.init`: DSN, sampling (`traces_sample_rate` or
64
+ `traces_sampler`), `before_send`, transports, `excluded_exceptions` and
65
+ `trace_ignore_status_codes`. Requiring `connectrpc/sentry` never initializes or
66
+ reconfigures the SDK, and the subscriber records nothing until
67
+ `Sentry.initialized?`.
68
+
69
+ Fiber hosts need fiber hub isolation. Applications that serve or call RPCs on
70
+ the native Async or Falcon hosts, `ConnectRPC::Async::Transport` or
71
+ `ConnectRPC::Async::ThreadedTransport` must set:
72
+
73
+ ```ruby
74
+ Sentry.init do |config|
75
+ config.hub_isolation_level = :fiber # sentry-ruby >= 6.7.0
76
+ end
77
+ ```
78
+
79
+ With the default `:thread` level, every fiber on a reactor thread shares one
80
+ Sentry scope, so interleaved RPCs would merge traces and swap spans. The
81
+ subscriber fails closed instead: when a fiber scheduler is active and isolation
82
+ is `:thread`, at RPC start or at any activation, it records no span, injects no
83
+ headers and leaves the scope untouched. It logs one warning per subscriber
84
+ through the SDK logger. Unexpected server exceptions are still reported, on a
85
+ cleared temporary scope that carries only the RPC tags. `ThreadedTransport`
86
+ callers on ordinary threads keep their client spans; only the activation inside
87
+ the transport's reactor thread is skipped.
88
+
89
+ ## Lifetime model
90
+
91
+ Each RPC side produces at most one observation, chosen when the RPC starts:
92
+
93
+ | Side | Current scope has an open span | No open span |
94
+ | --- | --- | --- |
95
+ | Server | Child span `rpc.server`, finished when processing finishes | Own `rpc.server` transaction continued from `sentry-trace`/`baggage`, finished at terminal delivery |
96
+ | Client | Child span `rpc.client`, finished at terminal completion | No span; outgoing propagation only, as Sentry's Net::HTTP integration does |
97
+
98
+ Rails, `sentry-rails` and `Sentry::Rack::CaptureExceptions` finish their
99
+ `http.server` transaction when the Rack call returns. ConnectRPC processing runs
100
+ inside that call, while response delivery comes after it. A nested `rpc.server`
101
+ span therefore ends at `processing_finished`, while its parent is still open, so
102
+ controller and ActiveRecord spans stay below it in the request transaction.
103
+ When the parent is Sentry's `http.server` transaction, its name becomes the RPC
104
+ route (`example.v1.EchoService/Echo`, source `route`); unknown methods keep the
105
+ host's name.
106
+
107
+ Native Async and Falcon servers have no request transaction, so each RPC owns
108
+ one. Owned transactions record delivery facts (`completed`, `aborted`,
109
+ `body_closed`, `response_finished` or `unobserved`). Admission rejections finish
110
+ an owned transaction without ever activating it.
111
+
112
+ A child is promoted to its own transaction, with the same trace id, span id,
113
+ parent span id, start time and sampling decision, when its parent transaction
114
+ has already finished by the time the child ends, or when the SDK's span recorder
115
+ (1,000 spans per transaction) rejected it at start. A typical case is a caller
116
+ that finishes its transaction inside a streaming block and keeps consuming. A
117
+ promoted child is never also sent as a child.
118
+
119
+ Documented limits:
120
+
121
+ - Rack and Rails delivery facts, including an abort after the response, are
122
+ recorded nowhere, because Sentry's middleware has already sent its
123
+ transaction.
124
+ - Spans nested under a promoted child stay in the original parent's recorder
125
+ and are orphaned or dropped.
126
+ - A parent finished concurrently on another thread between the check and its
127
+ serialization can still drop the child.
128
+ - Sentry's default `trace_ignore_status_codes` drops transactions whose
129
+ `http.response.status_code` is 301-303, 305-399 or 401-404. That includes
130
+ owned Connect RPCs that end `unauthenticated`, `permission_denied` or
131
+ `not_found`. Change the setting if you want those transactions.
132
+
133
+ ### Scopes
134
+
135
+ An owned server transaction activates on a pushed scope, which is popped only
136
+ if it is still current. That scope's propagation context comes from the
137
+ incoming headers, so errors-only applications (no tracing) still continue the
138
+ caller's trace. Nested and client spans save and restore the current span
139
+ without pushing, so `Sentry.set_user` and tags set in a Rails request stay on
140
+ the request. A child pushes its own scope only when it activates in a context
141
+ that has no span to restore; a nested server span seeds that scope from the
142
+ scope the RPC started on. A nested server span's error event and promoted
143
+ transaction use the scope its handler ran on, even when the RPC started in
144
+ another fiber or thread. When that context already holds its own unrelated
145
+ span, its scope is left as is, so start-scope request data is not added. If
146
+ seeding a pushed scope fails, the child pops it again before the handler runs.
147
+ Finishing an owned or promoted transaction runs in `Sentry.with_scope` on a
148
+ cleared copy of the RPC scope (tags, user, contexts,
149
+ `rack_env`, level and event processors), never on whatever scope the finishing
150
+ host fiber or thread holds. Error events use a copy too. Copies are
151
+ independent, so the RPC tags an error event adds never reach the request scope
152
+ or later events. Starting an RPC never mutates a scope.
153
+
154
+ An owned transaction often finishes on another fiber's or thread's hub than the
155
+ one that started it. Finishing releases the transaction's profiler registration
156
+ on the starting hub, so later RPCs started on that hub can still be profiled.
157
+
158
+ ## Data and privacy
159
+
160
+ Names are `fully.qualified.Service/Method`. Unknown methods use `connectrpc` or
161
+ `grpc` with `rpc.method=_OTHER`. Ops are `rpc.server` and `rpc.client`; origin
162
+ is `auto.rpc.connectrpc`.
163
+
164
+ Span data is bounded: `rpc.system.name` (`connectrpc` or `grpc`), `rpc.method`,
165
+ `connectrpc.protocol=grpc_web` for gRPC-Web, `rpc.response.status_code`
166
+ (lower-case Connect codes, upper-case gRPC codes including `CANCELLED`),
167
+ `http.response.status_code`, client `server.address`/`server.port`, measured
168
+ wire bytes (`connectrpc.request.wire_bytes`, `connectrpc.response.wire_bytes`),
169
+ `connectrpc.processing.duration`, `connectrpc.processing.state`,
170
+ `connectrpc.decision` and `connectrpc.delivery`. There are no payloads,
171
+ metadata, URLs, query strings or exception text on spans.
172
+
173
+ Span status maps the RPC code: `OK` to `ok`, `canceled` to `cancelled`,
174
+ `unknown` to `unknown_error`, `internal` to `internal_error`, and every other
175
+ code to the Sentry status of the same name. Bare HTTP rejections without a code
176
+ use Sentry's HTTP status mapping. A successful RPC whose delivery aborted ends
177
+ `unknown_error`.
178
+
179
+ ## Propagation
180
+
181
+ Owned server transactions read a single `sentry-trace` value and the joined
182
+ `baggage` values. They follow Sentry's continuation rules: inherited sampling
183
+ without a `traces_sampler`, deferred decisions from the propagated
184
+ `sentry-sample_rand`, and new traces for malformed headers or a mismatched
185
+ `org_id`. An application `traces_sampler` takes precedence over the parent's
186
+ decision and receives `parent_sampled` plus
187
+ `connectrpc: { role:, protocol:, method: }`; it receives no Rack `env`. Nested
188
+ spans inherit the host's continued trace.
189
+
190
+ Clients inject `sentry-trace` and Sentry `baggage` only when
191
+ `config.propagate_traces` is true and a `trace_propagation_targets` entry
192
+ matches. The call has no URL, so targets match the host (`api.internal`) and
193
+ `host:port` (`api.internal:8443`). Regular expressions anchored on a scheme
194
+ never match. With a client span, the headers carry that span and its sampling
195
+ decision; without one, they carry the scope's propagation context. W3C
196
+ `traceparent` is not injected.
197
+
198
+ Sentry baggage is prepended to `baggage` staged by earlier subscribers. Caller
199
+ `baggage` metadata passed to the RPC is still replaced by injected values; see
200
+ issue #73.
201
+
202
+ ## OpenTelemetry and OTLP
203
+
204
+ Pick one path into Sentry: native Sentry tracing (this package), or OpenTelemetry
205
+ with `connectrpc-otel` exporting to Sentry through `sentry-opentelemetry` or
206
+ OTLP. Never feed both into Sentry. When `config.instrumenter == :otel`, or when
207
+ `sentry-opentelemetry` is loaded and `config.otlp.enabled` is true, this
208
+ subscriber records and propagates nothing and only reports unexpected handler
209
+ exceptions on the current scope.
210
+
211
+ When both packages feed different backends, list `connectrpc-otel` first:
212
+
213
+ ```ruby
214
+ ConnectRPC::Instrumentation.new(subscribers: [otel_subscriber, sentry_subscriber])
215
+ ```
216
+
217
+ The OpenTelemetry subscriber writes `baggage` as one value and replaces what an
218
+ earlier subscriber staged, so Sentry's baggage survives only when Sentry runs
219
+ second. The two subscribers use different trace ids.
220
+
221
+ ## Exception capture
222
+
223
+ Server handler exceptions never escape `ConnectRPC::Server#call`, so Sentry's
224
+ Rack middleware never sees them. With `capture_exceptions: true` (the default)
225
+ the subscriber reports the original server exception when it is a
226
+ `StandardError`, not a `ConnectRPC::Error`, and the normalized code is
227
+ `internal` or `unknown`, or processing ended without one. Events use mechanism
228
+ `connectrpc` with `handled: false`, carry the RPC scope and link to the RPC span
229
+ or transaction. SDK `excluded_exceptions` and `before_send` apply.
230
+
231
+ Never reported:
232
+
233
+ - Client failures.
234
+ - Deliberate `ConnectRPC::Error`s.
235
+ - Codec, compression and metadata input failures, which normalize to
236
+ `invalid_argument`.
237
+ - Failures that cancellation or a deadline arbitrates to `canceled` or
238
+ `deadline_exceeded`.
239
+ - Admission and host rejections, and delivery failures.
240
+ - Rails `rescue_responses` errors, which map to other codes.
241
+
242
+ The SDK skips an exception object that was already captured, so an application
243
+ or `sentry-rails` report of the same exception is not duplicated. Native Rails
244
+ controllers report handler errors through
245
+ `Rails.error.report(handled: false, source: "connectrpc.rails")`, which
246
+ `sentry-rails` captures only with `config.rails.register_error_subscriber = true`;
247
+ either way the bug produces one event.
248
+
249
+ Limits: an internal error whose rendered body exceeds a very small error limit
250
+ becomes `resource_exhausted` and is not reported. The residual host
251
+ `$ERROR_INFO` attribution sites tracked in #26 can attach an unrelated exception
252
+ as the RPC's original error.
253
+
254
+ ## Host notes
255
+
256
+ - Rack consumers must close the body, or invoke the promised
257
+ `rack.response_finished` callbacks, before an owned transaction finishes.
258
+ - For native Rails controllers, override private `connect_instrumentation`. The
259
+ RPC nests under the `sentry-rails` request transaction when one is open.
260
+ - Native hosts and transports need `config.hub_isolation_level = :fiber`; see
261
+ [What the application owns](#what-the-application-owns).
262
+ - Connections and setup rejected before any RPC exists are outside per-RPC
263
+ observation.
264
+
265
+ ## Static signatures
266
+
267
+ This package owns `sig/` and its discovery manifest. Add
268
+ `library "connectrpc-sentry"` to a strict Steep target with this gem installed.
269
+ The supported API is `Subscriber.new(capture_exceptions: bool)` and
270
+ `Subscriber#start`; observers are private. The signatures do not describe the
271
+ Sentry SDK. See the [RBS guide](../../docs/rbs.md) for supported APIs and
272
+ extension contracts.
273
+
274
+ ## Development
275
+
276
+ From the repository root use `mise run sentry:setup`, `sentry:test`,
277
+ `sentry:check`, `sentry:build`, `sentry:package`, `sentry:example`, and
278
+ `sentry:verify`. The independent development bundle includes the real SDK,
279
+ `sentry-rails` with Rails and in-memory SQLite ActiveRecord,
280
+ `sentry-opentelemetry`, the OpenTelemetry SDK and local integration packages.
281
+ They float to their newest allowed releases; only tools stay pinned. Specs use
282
+ `Sentry::DummyTransport`, no background worker threads and a `.invalid` DSN, so
283
+ nothing leaves the process. Caches and archives are in `vendor/sentry`, and
284
+ coverage is in `coverage/sentry/<Ruby>/`. Both pinned Ruby 3.4.12 and 4.0.9 CI
285
+ leaves run `sentry:verify`.
286
+
287
+ `floors:sentry` repeats specs and package checks with `sentry-ruby` 6.7.0 and
288
+ every other local package's runtime dependency at its gemspec floor. That lane
289
+ constrains `json` to `< 3` for the Rails floor, as the OpenTelemetry lane does.
290
+
291
+ On Ruby 3.4, `require "connectrpc/sentry"` also loads `cgi/util` when nothing
292
+ else has: `sentry-ruby` parses incoming baggage with `CGI.unescape` after
293
+ requiring only `cgi/escape`, which lacks the default charset on that Ruby.
294
+
295
+ ## License
296
+
297
+ Original project work is [MIT licensed](LICENSE), copyright 2026 Jim Myhrberg.
298
+ All package archives pin `allowed_push_host=https://rubygems.org`; these checks
299
+ never publish or release a gem.
@@ -0,0 +1,502 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "version"
4
+
5
+ module ConnectRPC
6
+ module Sentry
7
+ # Inside this namespace the Sentry SDK is always ::Sentry.
8
+ class Subscriber
9
+ ORIGIN = "auto.rpc.connectrpc"
10
+ private_constant :ORIGIN
11
+
12
+ def initialize(capture_exceptions: true)
13
+ unless [true, false].include?(capture_exceptions)
14
+ raise ArgumentError, "capture_exceptions must be true or false"
15
+ end
16
+
17
+ @capture_exceptions = capture_exceptions
18
+ @guard = Guard.new
19
+ end
20
+
21
+ def start(call)
22
+ return unless ::Sentry.initialized?
23
+
24
+ rpc = RPC.build(call)
25
+ inert = Support.inert?(::Sentry.configuration)
26
+ # Fail closed: no span, no injection and no scope change; only capture remains.
27
+ return capture_only(call, rpc, clear: !inert) if inert || !@guard.safe?
28
+
29
+ call.role == :server ? server(call, rpc) : client(call, rpc)
30
+ end
31
+
32
+ private
33
+
34
+ def capture_only(call, rpc, clear:)
35
+ Capture.new(rpc, clear: clear) if call.role == :server && @capture_exceptions
36
+ end
37
+
38
+ def server(call, rpc)
39
+ scope = ::Sentry.get_current_scope
40
+ parent = scope&.get_span
41
+ if parent && parent.timestamp.nil?
42
+ span = Support.annotate(parent.start_child(op: "rpc.server", description: rpc.name, origin: ORIGIN), rpc)
43
+ return Child.new(rpc, span, scope, @guard, capture: @capture_exceptions, nested: true)
44
+ end
45
+
46
+ incoming = incoming(call.carrier)
47
+ hub = ::Sentry.get_current_hub
48
+ Owned.new(rpc, owned_transaction(hub, rpc, incoming), hub, incoming, @guard, capture: @capture_exceptions)
49
+ end
50
+
51
+ def owned_transaction(hub, rpc, incoming)
52
+ return unless ::Sentry.configuration.tracing_enabled?
53
+
54
+ context = ::Sentry::PropagationContext.new(nil, incoming)
55
+ transaction = ::Sentry::Transaction.new(
56
+ name: rpc.name, source: :route, op: "rpc.server", origin: ORIGIN,
57
+ trace_id: context.trace_id, parent_span_id: context.parent_span_id, parent_sampled: context.parent_sampled,
58
+ baggage: (context.baggage if context.incoming_trace), sample_rand: context.sample_rand
59
+ )
60
+ sampling = { connectrpc: { role: :server, protocol: rpc.protocol, method: rpc.method_name } }
61
+ hub.start_transaction(transaction: Support.annotate(transaction, rpc), custom_sampling_context: sampling)
62
+ end
63
+
64
+ def client(call, rpc)
65
+ scope = ::Sentry.get_current_scope
66
+ parent = scope&.get_span
67
+ if parent && parent.timestamp.nil?
68
+ span = Support.annotate(parent.start_child(op: "rpc.client", description: rpc.name, origin: ORIGIN), rpc)
69
+ end
70
+ inject(call, span) if propagate?(call)
71
+ span && Child.new(rpc, span, scope, @guard, capture: false, nested: false)
72
+ end
73
+
74
+ def incoming(carrier)
75
+ trace = carrier["sentry-trace"]
76
+ baggage = carrier["baggage"]
77
+ { "sentry-trace" => (trace.first if trace&.size == 1),
78
+ "baggage" => (baggage.join(",") if baggage && !baggage.empty?) }.compact
79
+ end
80
+
81
+ # Call has no URL, so targets match the host and host:port.
82
+ def propagate?(call)
83
+ configuration = ::Sentry.configuration
84
+ return false unless configuration.propagate_traces
85
+
86
+ host = call.server_address.to_s
87
+ candidates = [host, ("#{host}:#{call.server_port}" if call.server_address && call.server_port)].compact
88
+ configuration.trace_propagation_targets.any? do |target|
89
+ candidates.any? { |candidate| candidate.match?(target) }
90
+ end
91
+ end
92
+
93
+ # Earlier subscribers' staged baggage stays after Sentry's entries.
94
+ def inject(call, span)
95
+ headers = if span
96
+ { "sentry-trace" => span.to_sentry_trace, "baggage" => span.to_baggage }
97
+ else
98
+ ::Sentry.get_trace_propagation_headers || {}
99
+ end
100
+ carrier = call.carrier
101
+ trace = headers["sentry-trace"]
102
+ carrier["sentry-trace"] = [trace] if trace
103
+ baggage = headers["baggage"]
104
+ carrier["baggage"] = [baggage, *carrier["baggage"]] if baggage && !baggage.empty?
105
+ end
106
+
107
+ module Support
108
+ STATUS = { "OK" => "ok", "canceled" => "cancelled", "unknown" => "unknown_error",
109
+ "internal" => "internal_error" }.freeze
110
+ CAPTURED_CODES = %w[internal unknown].freeze
111
+
112
+ module_function
113
+
114
+ # Tracing and propagation stay off when another instrumenter feeds Sentry.
115
+ def inert?(configuration)
116
+ return true if configuration.instrumenter == :otel
117
+
118
+ configuration.respond_to?(:otlp) && configuration.otlp&.enabled ? true : false
119
+ end
120
+
121
+ def status(code) = STATUS.fetch(code, code)
122
+
123
+ def annotate(span, rpc)
124
+ rpc.data.each { |key, value| span.set_data(key, value) }
125
+ span
126
+ end
127
+
128
+ # Unexpected handler failures only; deliberate errors and client input arbitrate to other codes.
129
+ def unexpected?(outcome)
130
+ error = outcome.error
131
+ return false unless error.is_a?(StandardError) && !error.is_a?(ConnectRPC::Error)
132
+
133
+ normalized = outcome.normalized_error
134
+ code = normalized.is_a?(ConnectRPC::Error) ? normalized.code : outcome.code
135
+ code.nil? || CAPTURED_CODES.include?(code)
136
+ end
137
+
138
+ # Copies every scope attribute, including those update_from_scope omits.
139
+ # update_from_scope shares the source's containers, so it reads from a
140
+ # Scope#dup (deep copies) and changes to the copy never reach the source.
141
+ def copy_scope(target, source)
142
+ target.clear
143
+ target.update_from_scope(source.dup)
144
+ # Scope#dup also copies the span object; keep the source's own span.
145
+ span = source.get_span
146
+ target.set_span(span) if span
147
+ target.set_rack_env(source.rack_env)
148
+ target.set_level(source.level)
149
+ source.event_processors.each { |processor| target.add_event_processor(&processor) }
150
+ target
151
+ end
152
+
153
+ # Transaction#finish captures with the current scope, so finish on a copy of the RPC scope.
154
+ def finish_transaction(transaction, source, name: nil)
155
+ return transaction.finish unless ::Sentry.initialized?
156
+
157
+ ::Sentry.with_scope do |scope|
158
+ source ? copy_scope(scope, source) : scope.clear
159
+ scope.set_transaction_name(name, source: :route) if name
160
+ scope.set_span(transaction)
161
+ transaction.finish
162
+ end
163
+ end
164
+ end
165
+ private_constant :Support
166
+
167
+ # Fiber hosts share one thread hub unless the application isolates hubs per fiber.
168
+ class Guard
169
+ WARNING = "ConnectRPC::Sentry: a fiber scheduler is active and config.hub_isolation_level is :thread; " \
170
+ "RPC tracing and propagation are off. Set config.hub_isolation_level = :fiber."
171
+ private_constant :WARNING
172
+
173
+ def initialize
174
+ @lock = Mutex.new
175
+ @warned = false
176
+ end
177
+
178
+ def safe?
179
+ return true unless ::Fiber.scheduler
180
+ return true if ::Sentry.configuration.hub_isolation_level == :fiber
181
+
182
+ warn_once
183
+ false
184
+ end
185
+
186
+ def attachable? = ::Sentry.initialized? && safe?
187
+
188
+ private
189
+
190
+ def warn_once
191
+ first = @lock.synchronize { !@warned && (@warned = true) }
192
+ ::Sentry.sdk_logger&.warn(::Sentry::LOGGER_PROGNAME) { WARNING } if first
193
+ end
194
+ end
195
+ private_constant :Guard
196
+
197
+ RPC = Data.define(:name, :system, :method_name, :protocol, :data, :tags)
198
+ private_constant :RPC
199
+
200
+ class RPC
201
+ # Bounded names and attributes only: no payloads, metadata, URLs or exception text.
202
+ def self.build(call)
203
+ system = %i[grpc grpc_web].include?(call.protocol) ? "grpc" : "connectrpc"
204
+ declared = call.method
205
+ name = declared ? "#{declared.service}/#{declared.name}" : system
206
+ method_name = declared ? name : "_OTHER"
207
+ tags = { "rpc.system.name" => system, "rpc.method" => method_name }
208
+ tags["connectrpc.protocol"] = "grpc_web" if call.protocol == :grpc_web
209
+ new(name: name, system: system, method_name: method_name, protocol: call.protocol,
210
+ data: tags.merge(peer(call)).freeze, tags: tags.freeze)
211
+ end
212
+
213
+ def self.peer(call)
214
+ return {} unless call.role == :client
215
+
216
+ { "server.address" => call.server_address, "server.port" => call.server_port }.compact
217
+ end
218
+
219
+ def declared? = method_name != "_OTHER"
220
+
221
+ def code(value)
222
+ return value unless system == "grpc"
223
+
224
+ value == "canceled" ? "CANCELLED" : value.upcase
225
+ end
226
+ end
227
+
228
+ class Observer
229
+ MECHANISM = "connectrpc"
230
+ HTTP_STATUS = "http.response.status_code"
231
+ private_constant :MECHANISM, :HTTP_STATUS
232
+
233
+ def initialize(rpc, span, capture:)
234
+ @rpc = rpc
235
+ @span = span
236
+ @capture = capture
237
+ end
238
+
239
+ private
240
+
241
+ # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity
242
+ def record_outcome(outcome)
243
+ span = @span
244
+ return unless span
245
+
246
+ span.set_data("rpc.response.status_code", @rpc.code(outcome.code)) if outcome.code
247
+ span.set_data(HTTP_STATUS, outcome.http_status) if outcome.http_status
248
+ span.set_data("connectrpc.processing.duration", outcome.duration)
249
+ span.set_data("connectrpc.request.wire_bytes", outcome.request_bytes) if outcome.request_bytes
250
+ span.set_data("connectrpc.response.wire_bytes", outcome.response_bytes) if outcome.response_bytes
251
+ if outcome.code
252
+ span.set_status(Support.status(outcome.code))
253
+ elsif outcome.http_status
254
+ span.set_http_status(outcome.http_status)
255
+ elsif outcome.error
256
+ span.set_status("unknown_error")
257
+ end
258
+ end
259
+
260
+ def record_completion(completion)
261
+ span = @span
262
+ return unless span
263
+
264
+ span.set_data("connectrpc.processing.state", completion.processing_state.to_s)
265
+ span.set_data("connectrpc.decision", completion.decision.to_s)
266
+ span.set_data("connectrpc.delivery", completion.delivery.to_s)
267
+ span.set_data(HTTP_STATUS, completion.http_status) if completion.http_status
268
+ code = completion.outcome&.code
269
+ if completion.delivery == :aborted && (code.nil? || code == "OK")
270
+ span.set_status("unknown_error")
271
+ elsif code.nil? && completion.http_status
272
+ span.set_http_status(completion.http_status)
273
+ elsif span.status.nil?
274
+ span.set_status("unknown_error") unless completion.decision == :processed
275
+ end
276
+ end
277
+ # rubocop:enable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity
278
+
279
+ def capture(outcome)
280
+ return unless @capture && Support.unexpected?(outcome)
281
+
282
+ hint = { mechanism: ::Sentry::Mechanism.new(type: MECHANISM, handled: false) }
283
+ ::Sentry.capture_exception(outcome.error, hint: hint) do |scope|
284
+ prepare(scope)
285
+ scope.set_tags(@rpc.tags)
286
+ end
287
+ end
288
+
289
+ def prepare(scope) = scope
290
+ end
291
+ private_constant :Observer
292
+
293
+ # Records nothing; reports unexpected failures on the current or a cleared scope.
294
+ class Capture < Observer
295
+ def initialize(rpc, clear:)
296
+ super(rpc, nil, capture: true)
297
+ @clear = clear
298
+ end
299
+
300
+ def processing_finished(outcome) = capture(outcome)
301
+
302
+ private
303
+
304
+ def prepare(scope)
305
+ scope.clear if @clear
306
+ scope
307
+ end
308
+ end
309
+ private_constant :Capture
310
+
311
+ # A server transaction continued from the carrier, finished with delivery facts.
312
+ class Owned < Observer
313
+ def initialize(rpc, transaction, hub, incoming, guard, capture:)
314
+ super(rpc, transaction, capture: capture)
315
+ @hub = hub
316
+ @incoming = incoming
317
+ @guard = guard
318
+ end
319
+
320
+ def attach # rubocop:disable Metrics/MethodLength
321
+ return unless @guard.attachable?
322
+
323
+ hub = ::Sentry.get_current_hub
324
+ # Hosts nest activations; the inner one reuses the active RPC scope so handler changes reach the event.
325
+ return if @scope && hub.current_scope.equal?(@scope)
326
+
327
+ hub.push_scope
328
+ scope = hub.current_scope
329
+ begin
330
+ activate(scope)
331
+ rescue StandardError
332
+ hub.pop_scope if hub.current_scope.equal?(scope)
333
+ raise
334
+ end
335
+ [hub, scope]
336
+ end
337
+
338
+ def detach(token)
339
+ return unless token
340
+
341
+ hub, scope = token
342
+ hub.pop_scope if hub.current_scope.equal?(scope)
343
+ end
344
+
345
+ def processing_finished(outcome)
346
+ record_outcome(outcome)
347
+ capture(outcome)
348
+ end
349
+
350
+ def finished(completion)
351
+ record_completion(completion)
352
+ ensure
353
+ finish_transaction if @span
354
+ end
355
+
356
+ private
357
+
358
+ # Transaction#finish stops profiling only on the finishing context's hub,
359
+ # so first release the registration on the hub that started the transaction.
360
+ def finish_transaction
361
+ @hub.stop_profiler!(@span)
362
+ ensure
363
+ Support.finish_transaction(@span, @scope)
364
+ end
365
+
366
+ # The first activation becomes the RPC scope; later ones in other contexts copy it.
367
+ def activate(scope)
368
+ if (rpc_scope = @scope)
369
+ Support.copy_scope(scope, rpc_scope)
370
+ else
371
+ scope.generate_propagation_context(@incoming)
372
+ scope.set_transaction_name(@rpc.name, source: :route)
373
+ @scope = scope
374
+ end
375
+ scope.set_span(@span) if @span
376
+ end
377
+
378
+ def prepare(scope)
379
+ rpc_scope = @scope
380
+ rpc_scope ? Support.copy_scope(scope, rpc_scope) : scope.clear
381
+ scope.set_span(@span) if @span
382
+ scope
383
+ end
384
+ end
385
+ private_constant :Owned
386
+
387
+ # A child of the active span. Nested server spans end when processing ends,
388
+ # while their parent is still open; client spans end at terminal completion.
389
+ class Child < Observer
390
+ def initialize(rpc, span, scope, guard, capture:, nested:)
391
+ super(rpc, span, capture: capture)
392
+ @scope = scope
393
+ @guard = guard
394
+ @nested = nested
395
+ recorder = span.span_recorder
396
+ @rejected = recorder ? recorder.spans.rindex { |recorded| recorded.equal?(span) }.nil? : false
397
+ end
398
+
399
+ # Saves and restores the current span; pushes only when there is none to restore.
400
+ # A server child remembers the scope its handler runs on, wherever it started.
401
+ def attach
402
+ return unless @guard.attachable?
403
+
404
+ scope = ::Sentry.get_current_scope
405
+ previous = scope.get_span
406
+ if previous
407
+ scope.set_span(@span)
408
+ @handler_scope = scope if @nested
409
+ return [:span, scope, previous]
410
+ end
411
+
412
+ push(::Sentry.get_current_hub)
413
+ end
414
+
415
+ def detach(token)
416
+ kind, owner, value = token
417
+ if kind == :span
418
+ owner.set_span(value) if owner.get_span.equal?(@span)
419
+ elsif kind == :scope
420
+ owner.pop_scope if owner.current_scope.equal?(value)
421
+ end
422
+ end
423
+
424
+ def processing_finished(outcome)
425
+ record_outcome(outcome)
426
+ return unless @nested
427
+
428
+ @span.set_data("connectrpc.processing.state", "finished")
429
+ rename
430
+ capture(outcome)
431
+ ensure
432
+ close if @nested
433
+ end
434
+
435
+ # A finished child still serializes with its open parent, so late terminal facts land there.
436
+ def finished(completion)
437
+ record_completion(completion) unless @promoted || (@closed && @span.transaction.timestamp)
438
+ ensure
439
+ close
440
+ end
441
+
442
+ private
443
+
444
+ # A server child's pushed scope starts from the RPC's start scope, so request data survives.
445
+ # The pushed scope is popped again if seeding it fails, since no detach token exists then.
446
+ def push(hub) # rubocop:disable Metrics/MethodLength
447
+ hub.push_scope
448
+ scope = hub.current_scope
449
+ begin
450
+ Support.copy_scope(scope, @scope) if @nested
451
+ scope.set_span(@span)
452
+ rescue StandardError
453
+ hub.pop_scope if hub.current_scope.equal?(scope)
454
+ raise
455
+ end
456
+ @handler_scope = scope if @nested
457
+ [:scope, hub, scope]
458
+ end
459
+
460
+ # Names Sentry's HTTP server transaction after the RPC route.
461
+ def rename
462
+ host = @span.transaction
463
+ return unless @rpc.declared? && host.op == "http.server" && @scope.get_transaction.equal?(host)
464
+
465
+ @scope.set_transaction_name(@rpc.name, source: :route)
466
+ end
467
+
468
+ def prepare(scope)
469
+ Support.copy_scope(scope, @handler_scope || @scope)
470
+ scope.set_span(@span)
471
+ scope
472
+ end
473
+
474
+ def close
475
+ return if @closed
476
+
477
+ @closed = true
478
+ @promoted = @rejected || !@span.transaction.timestamp.nil?
479
+ @promoted ? promote : @span.finish
480
+ end
481
+
482
+ # A child its parent can no longer carry becomes its own transaction with
483
+ # the same identity, so it is sent exactly once.
484
+ def promote # rubocop:disable Metrics/AbcSize, Metrics/MethodLength
485
+ span = @span
486
+ parent = span.transaction
487
+ transaction = ::Sentry::Transaction.new(
488
+ name: @rpc.name, source: :route, op: span.op, origin: span.origin, description: span.description,
489
+ trace_id: span.trace_id, span_id: span.span_id, parent_span_id: span.parent_span_id,
490
+ sampled: span.sampled, start_timestamp: span.start_timestamp,
491
+ baggage: parent.get_baggage, sample_rand: parent.sample_rand
492
+ )
493
+ span.data.each { |key, value| transaction.set_data(key, value) }
494
+ span.tags.each { |key, value| transaction.set_tag(key, value) }
495
+ transaction.set_status(span.status)
496
+ Support.finish_transaction(transaction, @handler_scope || @scope, name: @rpc.name)
497
+ end
498
+ end
499
+ private_constant :Child
500
+ end
501
+ end
502
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ConnectRPC
4
+ module Sentry
5
+ VERSION = "0.1.2" # x-release-please-version
6
+ end
7
+ end
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "connectrpc"
4
+ require_relative "sentry/version"
5
+ require "sentry-ruby"
6
+ require "cgi/escape"
7
+ # sentry-ruby unescapes incoming baggage with CGI.unescape after requiring only
8
+ # cgi/escape. On Ruby 3.4 that default charset lives in cgi/util.
9
+ require "cgi/util" unless CGI.class_variable_defined?(:@@accept_charset)
10
+ require_relative "sentry/subscriber"
@@ -0,0 +1,10 @@
1
+ module ConnectRPC
2
+ module Sentry
3
+ VERSION: String
4
+ class Subscriber
5
+ def initialize: (?capture_exceptions: bool) -> void
6
+ # The adapter's observers are private and discovered by the neutral lifecycle.
7
+ def start: (Instrumentation::Call) -> Object?
8
+ end
9
+ end
10
+ end
data/sig/manifest.yaml ADDED
@@ -0,0 +1,2 @@
1
+ dependencies:
2
+ - name: connectrpc
metadata ADDED
@@ -0,0 +1,86 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: connectrpc-sentry
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.2
5
+ platform: ruby
6
+ authors:
7
+ - jimeh
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 2026-11-16 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: connectrpc
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: 0.1.0
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - "~>"
24
+ - !ruby/object:Gem::Version
25
+ version: 0.1.0
26
+ - !ruby/object:Gem::Dependency
27
+ name: sentry-ruby
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - ">="
31
+ - !ruby/object:Gem::Version
32
+ version: 6.7.0
33
+ - - "<"
34
+ - !ruby/object:Gem::Version
35
+ version: '8'
36
+ type: :runtime
37
+ prerelease: false
38
+ version_requirements: !ruby/object:Gem::Requirement
39
+ requirements:
40
+ - - ">="
41
+ - !ruby/object:Gem::Version
42
+ version: 6.7.0
43
+ - - "<"
44
+ - !ruby/object:Gem::Version
45
+ version: '8'
46
+ description: Records one native Sentry transaction or span per Connect, native gRPC
47
+ or gRPC-Web RPC side and reports unexpected server handler exceptions through the
48
+ connectrpc instrumentation lifecycle. The application owns the Sentry SDK configuration.
49
+ Part of the unofficial connectrpc-ruby project. Experimental and not production
50
+ ready.
51
+ executables: []
52
+ extensions: []
53
+ extra_rdoc_files: []
54
+ files:
55
+ - LICENSE
56
+ - README.md
57
+ - lib/connectrpc/sentry.rb
58
+ - lib/connectrpc/sentry/subscriber.rb
59
+ - lib/connectrpc/sentry/version.rb
60
+ - sig/connectrpc-sentry.rbs
61
+ - sig/manifest.yaml
62
+ homepage: https://github.com/jimeh/connectrpc-ruby
63
+ licenses:
64
+ - MIT
65
+ metadata:
66
+ allowed_push_host: https://rubygems.org
67
+ rubygems_mfa_required: 'true'
68
+ source_code_uri: https://github.com/jimeh/connectrpc-ruby
69
+ rdoc_options: []
70
+ require_paths:
71
+ - lib
72
+ required_ruby_version: !ruby/object:Gem::Requirement
73
+ requirements:
74
+ - - ">="
75
+ - !ruby/object:Gem::Version
76
+ version: '3.4'
77
+ required_rubygems_version: !ruby/object:Gem::Requirement
78
+ requirements:
79
+ - - ">="
80
+ - !ruby/object:Gem::Version
81
+ version: '0'
82
+ requirements: []
83
+ rubygems_version: 3.6.9
84
+ specification_version: 4
85
+ summary: Native Sentry tracing and handler exception capture for ConnectRPC
86
+ test_files: []