connectrpc 0.2.1 → 0.3.0

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.
Files changed (44) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +57 -21
  3. data/docs/design.md +245 -52
  4. data/docs/development.md +102 -14
  5. data/docs/grpc-web.md +30 -13
  6. data/docs/grpc.md +98 -5
  7. data/docs/rbs.md +56 -19
  8. data/docs/streaming.md +80 -34
  9. data/docs/unary.md +269 -45
  10. data/lib/connectrpc/bindings/google_protobuf.rb +20 -7
  11. data/lib/connectrpc/client.rb +47 -22
  12. data/lib/connectrpc/deadline.rb +27 -6
  13. data/lib/connectrpc/error.rb +2 -2
  14. data/lib/connectrpc/generator/names.rb +17 -0
  15. data/lib/connectrpc/generator/rbs_renderer.rb +4 -3
  16. data/lib/connectrpc/generator/renderer.rb +35 -3
  17. data/lib/connectrpc/generator/runtime_names.rb +23 -5
  18. data/lib/connectrpc/generator/schema.rb +14 -7
  19. data/lib/connectrpc/grpc.rb +7 -4
  20. data/lib/connectrpc/grpc_client.rb +2 -2
  21. data/lib/connectrpc/grpc_server.rb +14 -14
  22. data/lib/connectrpc/grpc_web_cors.rb +12 -4
  23. data/lib/connectrpc/grpc_web_server.rb +19 -13
  24. data/lib/connectrpc/instrumentation.rb +47 -7
  25. data/lib/connectrpc/keepalive.rb +40 -0
  26. data/lib/connectrpc/method.rb +8 -8
  27. data/lib/connectrpc/metrics/connection_observer.rb +46 -17
  28. data/lib/connectrpc/metrics/definitions.rb +6 -2
  29. data/lib/connectrpc/protocol.rb +64 -11
  30. data/lib/connectrpc/proxy.rb +425 -0
  31. data/lib/connectrpc/server.rb +97 -13
  32. data/lib/connectrpc/streaming/client.rb +22 -25
  33. data/lib/connectrpc/streaming/client_execution.rb +2 -1
  34. data/lib/connectrpc/streaming/client_scope.rb +14 -7
  35. data/lib/connectrpc/streaming/server.rb +1 -0
  36. data/lib/connectrpc/streaming/server_terminal.rb +57 -14
  37. data/lib/connectrpc/streaming/session_messages.rb +12 -5
  38. data/lib/connectrpc/streaming/streams.rb +17 -6
  39. data/lib/connectrpc/streaming/terminal.rb +3 -5
  40. data/lib/connectrpc/transports/net_http.rb +512 -52
  41. data/lib/connectrpc/version.rb +1 -1
  42. data/lib/connectrpc.rb +1 -0
  43. data/sig/connectrpc.rbs +63 -17
  44. metadata +6 -2
data/docs/unary.md CHANGED
@@ -24,7 +24,7 @@ compatible core and Rack dependencies. Add it to your Gemfile and keep
24
24
  `require "connectrpc/rack"`:
25
25
 
26
26
  ```ruby
27
- gem "connectrpc-rack", "~> 0.2.0"
27
+ gem "connectrpc-rack", "~> 0.3.0"
28
28
  ```
29
29
 
30
30
  Core installed alone has no middleware file, so requiring `connectrpc/rack`
@@ -52,11 +52,12 @@ including typed deliberate error details.
52
52
 
53
53
  To use the installed gem's plugin in your own project, put
54
54
  `protoc-gen-connectrpc-ruby` on PATH (for example by running protoc through
55
- `bundle exec`) and generate official messages and Connect glue together:
55
+ `bundle exec`) and generate official messages and Connect glue together. With
56
+ the schema at `proto/greeting.proto`:
56
57
 
57
58
  ```sh
58
59
  mkdir -p generated
59
- protoc -I examples/proto --ruby_out=generated --connectrpc-ruby_out=generated greeting.proto
60
+ bundle exec protoc -I proto --ruby_out=generated --connectrpc-ruby_out=generated greeting.proto
60
61
  ```
61
62
 
62
63
  This creates official `greeting_pb.rb` and `greeting_connect.rb`. Add
@@ -66,30 +67,59 @@ This creates official `greeting_pb.rb` and `greeting_connect.rb`. Add
66
67
 
67
68
  ```ruby
68
69
  require "greeting_connect"
69
- require "connectrpc/bindings/google_protobuf"
70
70
 
71
71
  service = Greeting::V1::GreetingService
72
- binding = ConnectRPC::Bindings::GoogleProtobuf.new
73
- core = ConnectRPC::Client.new(base_url: "http://127.0.0.1:8080", binding: binding, codec: :json)
72
+ core = ConnectRPC::Client.new(base_url: "http://127.0.0.1:8080", codec: :json)
74
73
  client = service::Client.new(client: core)
75
74
  response = client.greet(Greeting::V1::Greeting.new(name: "Ruby"), timeout: 2)
76
75
 
77
76
  # Supply application callables accepting (request, context).
78
77
  handlers = service.handlers(greet: greet_handler, fail: fail_handler)
79
- server = ConnectRPC::Server.new(services: [service::SERVICE], handlers: handlers, binding: binding)
78
+ server = ConnectRPC::Server.new(services: [service::SERVICE], handlers: handlers)
80
79
  ```
81
80
 
82
81
  `greet_handler` and `fail_handler` above are application-defined callables; the
83
82
  [runnable example](../examples/generated.rb) defines both and hosts the Rack app.
84
83
 
84
+ Since 0.3.0, a service object can supply the handlers instead. `handlers_for`
85
+ maps each RPC to the object's public method of the same snake-case name, which
86
+ takes the arguments the callable would, `(request, context)` for unary:
87
+
88
+ ```ruby
89
+ class Greeter
90
+ def greet(request, _context) = Greeting::V1::Greeting.new(name: "Hello, #{request.name}!")
91
+ def fail(_request, _context) = raise ConnectRPC::Error.new(:failed_precondition, "Not today")
92
+ end
93
+
94
+ server = ConnectRPC::Server.new(services: [service::SERVICE],
95
+ handlers: service.handlers_for(Greeter.new, strict: true))
96
+ ```
97
+
85
98
  - `GREET` and `FAIL` are frozen `ConnectRPC::Method` constants; `SERVICE` is
86
99
  reusable.
87
100
  - Wrapper calls return the existing `Response` and forward keyword options
88
101
  exactly, including omission of `timeout:` versus explicit `timeout: nil`.
89
102
  - Binding, transport, codec, URL and limits belong to the configured core
90
- client.
103
+ client. Since 0.3.0, the generated file requires
104
+ `connectrpc/bindings/google_protobuf`, so Client and Server use the Google
105
+ binding when `binding:` is omitted.
91
106
  - `handlers` requires all declared RPC keywords and validates callability. Use
92
107
  the existing Server handler map directly for partial/custom registration.
108
+ - Since 0.3.0, `handlers_for(impl, strict: false)` checks each RPC with
109
+ `impl.respond_to?(name)`, so private methods count as missing and
110
+ `respond_to_missing?` is honored. A method whose owner is in
111
+ `Class.ancestors` when `handlers_for` runs also counts as missing, so methods
112
+ `impl` only inherits from `Object` (or, for a class or module, from `Class`
113
+ or `Module`) are never bound, including methods that frameworks such as
114
+ ActiveSupport add there. A handler module that is also mixed into `Object`,
115
+ `Module` or `Class` counts as a core method and is not bound. Methods from
116
+ `impl`'s class, its other mixins and its singleton class, including a
117
+ module's own singleton methods (`def self.greet`), count. It omits
118
+ RPCs the object lacks, which the Server's default invoker answers with
119
+ `unimplemented`. `strict: true` raises `ArgumentError` naming every missing
120
+ method. It does not check arity. Server streaming methods take
121
+ `(request, writer, context)`, client streaming `(reader, context)` and bidi
122
+ `(duplex, context)`.
93
123
 
94
124
  ### Generate with Buf
95
125
 
@@ -115,7 +145,8 @@ Proto2 and proto3, including optional presence and mixed unary/streaming
115
145
  services, are supported. Editions and unsupported plugin parameters are rejected.
116
146
  Default output is `dir/foo_connect.rb` for service-bearing `dir/foo.proto`.
117
147
  Message generation remains official `--ruby_out`. Set `rbs=true` to also emit
118
- `dir/foo_connect.rbs`.
148
+ `dir/foo_connect.rbs`. Since 0.3.0, `rbs=false` is accepted and equals the
149
+ default.
119
150
 
120
151
  The gem ships optional core signatures; the [RBS guide](rbs.md) covers official
121
152
  message `--rbs_out`, explicit protobuf bridge selection and strict Steep
@@ -127,10 +158,23 @@ Leading-underscore RPCs, object hooks, implicit conversion methods, reserved
127
158
  runtime names and collisions visible in the request fail with diagnostics.
128
159
  Compatible `google.*` and `Google::...` Ruby package nesting is supported,
129
160
  including WKT imports; replacing `Google`, `ConnectRPC` or concrete protobuf
130
- runtime constants is rejected. Cross-invocation namespace conflicts cannot all
161
+ runtime constants is rejected. Packages may nest under the builtin modules
162
+ `FileTest`, `GC`, `Marshal`, `Math`, `ObjectSpace`, `Process` and `Signal`
163
+ (`math.v1` becomes `Math::V1`), but not at or below their existing values and
164
+ classes, such as `Math::E` or `Process::Status`. Other reserved roots, such as
165
+ `File`, `Kernel`, `Errno` and the standard library roots core loads, fail with a
166
+ suggestion to set `ruby_package`. Cross-invocation namespace conflicts cannot all
131
167
  be discovered; generated code also guards its directly defined constants at
132
168
  load time. See [design](design.md).
133
169
 
170
+ Generated service modules use protoc's Ruby constant rule, which upcases the
171
+ first letter and keeps underscores, so service `kw_service` becomes
172
+ `Kw_service`. A name that does not start with a letter gets a `PB_` prefix, so
173
+ `_service` becomes `PB__service`. This matches the message constants in official `_pb.rb` files.
174
+ grpc-ruby's `_services_pb.rb` camelizes service names instead (`KwService`), so
175
+ code migrating from grpc-ruby may need different constants for services whose
176
+ names contain underscores.
177
+
134
178
  ## Declare a method without generation
135
179
 
136
180
  Generated code composes the same public objects you can build by hand. This
@@ -147,17 +191,14 @@ method = ConnectRPC::Method.new(
147
191
  service: "example.v1.EchoService", name: "Echo",
148
192
  request_type: type, response_type: type
149
193
  )
150
- service = ConnectRPC::Service.new(name: method.service, methods: [method])
151
- binding = ConnectRPC::Bindings::GoogleProtobuf.new
194
+ service = ConnectRPC::Service.new(name: method.service, rpcs: [method])
152
195
  handler = lambda do |request, context|
153
196
  context.check!
154
197
  context.response_metadata.add("x-worker", "ruby")
155
198
  context.response_trailers.add("x-finished", "yes")
156
199
  type.new(value: "Hello, #{request.value}!")
157
200
  end
158
- server = ConnectRPC::Server.new(
159
- services: [service], binding: binding, handlers: { method.path => handler }
160
- )
201
+ server = ConnectRPC::Server.new(services: [service], handlers: { method.path => handler })
161
202
  app = ConnectRPC::Rack.new(server: server) # Supply this to your Rack host.
162
203
  ```
163
204
 
@@ -173,9 +214,7 @@ Reusable handlers must synchronize any application state they share.
173
214
  With that app hosted at a base URL, a client call is:
174
215
 
175
216
  ```ruby
176
- client = ConnectRPC::Client.new(
177
- base_url: "http://127.0.0.1:8080", binding: binding, codec: :json
178
- )
217
+ client = ConnectRPC::Client.new(base_url: "http://127.0.0.1:8080", codec: :json)
179
218
  response = client.call(
180
219
  method, type.new(value: "Ruby"), metadata: { "x-request" => ["example"] }, timeout: 2
181
220
  )
@@ -190,14 +229,116 @@ ignores unknown JSON fields. The Google binding handles scalar wrapper roots
190
229
  through the native Any decoder because protobuf 4.36 cannot parse those roots
191
230
  directly. This does not change Connect error details: each `ErrorDetail` has a
192
231
  protobuf type name and binary bytes, with a base64 representation on the wire.
232
+ A zero-length JSON payload is rejected, as connect-go does. Send the message's
233
+ JSON form instead: `{}` for an empty ordinary message, or the well-known type's
234
+ own form, such as `""` for an empty `StringValue`.
193
235
 
194
236
  ### Binding and transport seams
195
237
 
196
238
  Bindings implement `encode(message, type:, codec:)` and
197
239
  `decode(bytes, type:, codec:)`, raising `ConnectRPC::CodecError` for codec
198
- failures. Transports implement `call(TransportRequest)` and return a
199
- `TransportResponse`. Their fields and responsibilities are documented in
200
- [design](design.md). Neither seam requires Google or Rack types.
240
+ failures. Since 0.3.0, `Client.new`, `Server.new` and `ErrorDetail#decode`
241
+ accept an omitted or nil `binding:` once `require
242
+ "connectrpc/bindings/google_protobuf"` has loaded the Google binding, and raise
243
+ `ArgumentError` naming that require otherwise. Core never loads it. Pass
244
+ `binding:` explicitly for a custom binding.
245
+
246
+ Transports implement `call(TransportRequest)` and return a `TransportResponse`.
247
+ Their fields and responsibilities are documented in [design](design.md). Neither seam requires Google or Rack types. Since 0.3.0,
248
+ an in-process transport can set `TransportResponse#cause` on an error response;
249
+ the client raises its decoded error with that exception as the `cause`.
250
+
251
+ ### NetHTTP TLS and proxies
252
+
253
+ Since 0.3.0, `ConnectRPC::Transports::NetHTTP.new` takes the TLS options of the
254
+ Async client transports, plus `proxy:`. NetHTTP stays a dependency-free client
255
+ that opens one connection per call; the Async transports are the pooled and
256
+ HTTP/2 options.
257
+
258
+ ```ruby
259
+ transport = ConnectRPC::Transports::NetHTTP.new(
260
+ ca_file: "/etc/ssl/private-ca.pem", # Added to the system trust store.
261
+ certificate_chain: [leaf_pem, intermediate_pem], # Client certificate, leaf first.
262
+ private_key: key_pem,
263
+ proxy: :environment # Default. Or a URL String or URI, or nil.
264
+ )
265
+ ```
266
+
267
+ - TLS always verifies the server certificate and hostname, requires TLS 1.2 or
268
+ later and offers ALPN `http/1.1`. `ca_file` adds a trust anchor file to the
269
+ system default store. `certificate_chain` and `private_key` must be given
270
+ together. An invalid input raises `ArgumentError` that names only the input,
271
+ such as `Invalid TLS client configuration: private_key`, with no `cause`. A
272
+ call to an `http://` URL on a transport with any TLS option raises
273
+ `ArgumentError` before it connects.
274
+ - `proxy: :environment` reads `HTTPS_PROXY` for `https://` URLs, `HTTP_PROXY`
275
+ for `http://` URLs and the `NO_PROXY` exceptions once, when the transport is
276
+ constructed. As in Go's `net/http`, uppercase names win over lowercase ones,
277
+ a value without a scheme is read as `http://value`, and `localhost` and
278
+ loopback addresses never use the environment proxy.
279
+ - Proxy values fail closed. Go ignores a few values it cannot parse and dials
280
+ some odd ones; here every non-empty value either names a proxy or fails the
281
+ calls that would use it with `invalid proxy address`, never connecting
282
+ directly. Spaces or control characters anywhere, percent escapes in the
283
+ host, an IPv6 zone, an invalid port and userinfo outside RFC 3986's
284
+ characters or escapes all fail this way. So does a numeric host that is not
285
+ a canonical IP address, such as `010.0.0.1`, `127.1` or `2130706433`: the C
286
+ resolver would read those as other addresses (`010.0.0.1` as `8.0.0.1`),
287
+ while Go refuses them. Anything after the host and port, such as a path, is
288
+ ignored. An explicit `URI` is used only when its text parses back to the
289
+ same scheme, host, port and userinfo.
290
+ - `NO_PROXY` takes comma-separated entries: `*`, a domain (`example.com`
291
+ matches the domain and its subdomains; `.example.com` and `*.example.com`
292
+ match only subdomains), an IP address or a CIDR range, each with an optional
293
+ `:port`. As in Go, non-ASCII domain entries and proxy hostnames are
294
+ NFKC-normalized, lowercased, given ASCII dots for ideographic full stops and
295
+ converted to Punycode, so a Unicode entry matches its `xn--` host name, and
296
+ an IPv4-mapped range such as `::ffff:10.0.0.0/120` also matches IPv4 hosts.
297
+ UTS #46's other validity checks and mappings are not applied, and a name in
298
+ which NFKC produces a dot (U+2024 ONE DOT LEADER, for example) is rejected
299
+ rather than read as another domain. A name with a character Go deletes or
300
+ checks but this mapping does not (a soft hyphen, a variation selector, a
301
+ zero-width joiner or any right-to-left script) or a label that starts or
302
+ ends with a hyphen is rejected the same way. These rejections are not a
303
+ complete UTS #46 implementation: some other names, such as ones with
304
+ unassigned code points, leading combining marks or characters whose case
305
+ folding differs, still map to a different `xn--` name than Go's. A name that
306
+ Go's IDNA would reject, because it has invalid bytes or maps to anything but
307
+ letters, digits, hyphens and dots (a fullwidth at sign, slash or colon, for
308
+ example), never matches as a `NO_PROXY` entry. As an environment proxy host
309
+ it fails the call rather than going direct; as an explicit proxy it raises
310
+ `ArgumentError`.
311
+ - Some `NO_PROXY` details differ from Go on purpose: the target's port is
312
+ compared as a number, so an entry for port `80` also matches a URL written
313
+ with `:080`, which Go compares as text; a CIDR prefix with leading zeros,
314
+ such as `/024`, is not recognized; entries are trimmed of ASCII whitespace
315
+ only; lowercasing uses Ruby's `downcase`, which differs from Go for the
316
+ Turkish dotted capital I; and `localhost` matches in any case, where Go
317
+ proxies `LOCALHOST`.
318
+ - A String or URI proxies every request, including loopback and `NO_PROXY`
319
+ hosts. A String without a scheme is read as `http://value`. A value that is
320
+ not a valid proxy raises `ArgumentError` (`Invalid proxy configuration`),
321
+ with no `cause`. `proxy: nil` always connects directly.
322
+ - Only `http://` proxies are supported. An `https://` URL tunnels through
323
+ `CONNECT`, and TLS verifies the target host, not the proxy. An `http://` URL
324
+ is sent to the proxy in absolute form. Proxy URL userinfo is percent-decoded
325
+ and sent as `Proxy-Authorization: Basic`; as in Go, it ends at the last `@`,
326
+ so `http://user:p@ss@proxy:8080` has the password `p@ss`. An explicit `https://` or
327
+ `socks5://` proxy raises `ArgumentError`; from the environment it fails the
328
+ call.
329
+ - In a CGI process, where `REQUEST_METHOD` is set, an `HTTP_PROXY` value fails
330
+ every `http://` call rather than trusting a client-controlled `Proxy` request
331
+ header, as Go does. Explicit proxies are unaffected.
332
+
333
+ Proxy failures are `unavailable`, with a fixed reason:
334
+ `proxy authentication failed` (status 407), `proxy tunnel refused` (any other
335
+ status but 200), `proxy tunnel failed` (a malformed, truncated or oversized
336
+ reply, or bytes after a 200 reply), `proxy tunnel timed out`,
337
+ `unsupported proxy scheme`, `invalid proxy address` and
338
+ `proxy refused in CGI environment`. A `CONNECT` exchange is capped at 60
339
+ seconds, as in Go, even with `timeout: nil`; an earlier deadline still ends the
340
+ call with `deadline_exceeded`. Error messages and `inspect` never include proxy
341
+ URLs, credentials, reply text or TLS material.
201
342
 
202
343
  ## Use unary GET
203
344
 
@@ -215,8 +356,7 @@ Manual `Method.new` declarations accept the same three symbols.
215
356
  Enable GET on the core client; generated wrappers keep their existing API:
216
357
 
217
358
  ```ruby
218
- core = ConnectRPC::Client.new(base_url: "https://api.example.com", binding: binding,
219
- use_get: true, get_url_limit: 8192)
359
+ core = ConnectRPC::Client.new(base_url: "https://api.example.com", use_get: true, get_url_limit: 8192)
220
360
  ```
221
361
 
222
362
  Only `:no_side_effects` methods select GET. The default remains POST.
@@ -252,10 +392,8 @@ requests and advertise `gzip, identity` for responses. Configure it on the serve
252
392
  to accept gzip requests and negotiate gzip success responses in both codecs:
253
393
 
254
394
  ```ruby
255
- client = ConnectRPC::Client.new(base_url: "http://127.0.0.1:8080", binding: binding,
256
- encoding: :gzip)
257
- server = ConnectRPC::Server.new(services: [service], binding: binding,
258
- handlers: { method.path => handler }, encoding: :gzip)
395
+ client = ConnectRPC::Client.new(base_url: "http://127.0.0.1:8080", encoding: :gzip)
396
+ server = ConnectRPC::Server.new(services: [service], handlers: { method.path => handler }, encoding: :gzip)
259
397
  ```
260
398
 
261
399
  Client `accept_encoding:` independently controls accepted responses. Its default
@@ -269,8 +407,9 @@ For example:
269
407
 
270
408
  The server selects a supported compression coding from the ordered accept
271
409
  fields before identity. An absent field inherits the request coding; an
272
- explicitly empty field selects identity. Unknown tokens and quality values are
273
- ignored. Only one identity or gzip content coding is accepted.
410
+ explicitly empty field selects identity. Unknown tokens and parameters are
411
+ ignored, except that a zero quality value (`gzip;q=0`) refuses gzip. Only one
412
+ identity or gzip content coding is accepted.
274
413
 
275
414
  Empty serialized messages selected for gzip produce valid nonempty gzip members.
276
415
  Zero-length HTTP content is never inflated, after its coding header is validated.
@@ -296,6 +435,14 @@ metadata are omitted, including the entire field if any repeated value is
296
435
  invalid. Valid adjacent fields remain available in leading and trailing
297
436
  metadata. Outbound names and values are always validated strictly.
298
437
 
438
+ Since 0.3.0, Connect clients send
439
+ `User-Agent: connectrpc-ruby/<version> (ruby <RUBY_VERSION>)` and gRPC clients
440
+ send `grpc-ruby-connectrpc/<version> (ruby <RUBY_VERSION>)`, unless the call
441
+ metadata or an interceptor sets `user-agent`. `"user-agent" => []` sends no
442
+ User-Agent. The client adds the default after interceptors run, so interceptors
443
+ do not see it. NetHTTP sends exactly the request's `user-agent` values and
444
+ never adds Net::HTTP's `User-Agent: Ruby`.
445
+
299
446
  Rack responses preserve arrays. Net::HTTP preserves repeated raw response
300
447
  fields, but joins outgoing request arrays with `", "`. rackup/WEBrick also
301
448
  coalesces incoming and response fields. For example, `['a', 'b']` may arrive as
@@ -308,8 +455,50 @@ Raise a deliberate `ConnectRPC::Error.new(:invalid_argument, "safe message",
308
455
  details: [...], metadata: {...}, trailers: {...})` from a handler. Unexpected
309
456
  application exceptions become `internal` with `"Internal error"`. Clients raise
310
457
  `ConnectRPC::Error` with `code`, `details`, `metadata`, and `trailers`. Decode a
311
- detail with `detail.decode(binding: binding, type: message_class)` after choosing
312
- the class corresponding to `detail.type`.
458
+ detail with `detail.decode(type: message_class)` after choosing
459
+ the class corresponding to `detail.type`. `Error#code` is a frozen String such
460
+ as `"invalid_argument"`, even though `Error.new` accepts a Symbol, so compare it
461
+ with a String: `error.code == "invalid_argument"`.
462
+
463
+ The peer never sees an unexpected exception, so log or report it on the server.
464
+ Since 0.3.0, pass `on_error:` to the Server:
465
+
466
+ ```ruby
467
+ server = ConnectRPC::Server.new(
468
+ services: [service::SERVICE], handlers: handlers,
469
+ on_error: ->(error) { logger.error(error.full_message(highlight: false)) }
470
+ )
471
+ ```
472
+
473
+ Core calls `on_error` with the original exception when a `StandardError` that
474
+ is not a `ConnectRPC::Error` escapes a handler, an interceptor, a custom
475
+ invoker or unary response encoding, and the peer receives the generic
476
+ `internal` error. This covers Connect, gRPC and gRPC-Web, unary and streaming,
477
+ on every host. The callable runs on the request's thread or fiber, inside the
478
+ RPC's instrumentation scope, so request-scoped loggers and an active trace
479
+ still apply. Exceptions raised by `on_error` itself are ignored, and the peer
480
+ response is unchanged.
481
+
482
+ Some failures are not reported. When the deadline or a cancellation already
483
+ decides the outcome, the peer receives `deadline_exceeded` or `canceled`
484
+ instead. Failures that core maps to its own error first, such as a streaming
485
+ response message the binding cannot encode, reach
486
+ [instrumentation](#instrumentation) only.
487
+
488
+ Hosts add their own reporting:
489
+
490
+ - Since 0.3.0, [connectrpc-rack](../gems/connectrpc-rack/README.md) also writes
491
+ each unexpected exception with its backtrace to `env["rack.errors"]`.
492
+ - Since 0.3.0, [connectrpc-testing](../gems/connectrpc-testing/README.md)
493
+ records the original exception as `TransportResponse#cause`, and the client
494
+ raises its decoded `internal` error with that `cause`.
495
+ - [connectrpc-on-rails](../gems/connectrpc-on-rails/README.md) builds its own
496
+ Server per request. Handler exceptions follow Rails: `rescue_from`, the
497
+ controller logger and `Rails.error`. Unexpected exceptions outside the action,
498
+ such as from a server interceptor, go to `env["rack.errors"]` as on Rack.
499
+ - [connectrpc-sentry](../gems/connectrpc-sentry/README.md) already reports
500
+ unexpected handler exceptions, so do not also send them to Sentry from
501
+ `on_error`.
313
502
 
314
503
  ## Limits
315
504
 
@@ -333,9 +522,36 @@ HTTP input coalescing belong to the library and host.
333
522
 
334
523
  ## Deadlines
335
524
 
336
- Client `timeout:` accepts finite positive seconds, defaulting to 30. Explicit
337
- `timeout: nil` sends no timeout header and creates no logical deadline or expiry
338
- watchdog. Native TCP/TLS/read/write waits remain independently capped at
525
+ Client `timeout:` accepts finite real seconds, defaulting to 30. Since 0.3.0,
526
+ zero and negative timeouts are already expired, as in grpc-go: the call fails
527
+ locally with `deadline_exceeded` before the transport runs. Infinite, NaN and
528
+ non-numeric timeouts raise `ArgumentError`. Explicit `timeout: nil` removes
529
+ only the relative timeout budget. A call has no logical deadline, expiry
530
+ watchdog or timeout header only when it passes `timeout: nil` and no
531
+ `deadline:`.
532
+
533
+ Since 0.3.0, every call, including the streaming calls and generated wrappers,
534
+ also accepts `deadline:`, a `ConnectRPC::Deadline` or nil. The call uses the
535
+ earlier of `timeout:` and `deadline:`, chosen once at call setup, and reuses the
536
+ supplied object when it is strictly earlier; a tie keeps the `timeout:`
537
+ budget, which always runs on the default monotonic clock. A `deadline:` built
538
+ on a custom `clock:` is compared with the call's timeout by remaining time at
539
+ call setup, so the choice can be off by the time between those two clock
540
+ reads; deadlines on the default clock compare exactly. A handler passes its
541
+ own deadline to a downstream call so it ends no later than the request that
542
+ caused it:
543
+
544
+ ```ruby
545
+ def greet(request, context)
546
+ profile = profiles.lookup(ProfileRequest.new(id: request.name), deadline: context.deadline)
547
+ Greeting::V1::Greeting.new(name: "Hello, #{profile.message.display_name}!")
548
+ end
549
+ ```
550
+
551
+ The downstream call keeps the default 30 second cap when that is earlier;
552
+ pass `timeout: nil` to rely on `deadline:` alone. Nothing propagates
553
+ implicitly, and cancelling the upstream call does not cancel the downstream
554
+ one. Native TCP/TLS/read/write waits remain independently capped at
339
555
  `9_999_999.999` seconds; a native timeout returns `unavailable`. Sustained
340
556
  progress can outlast that per-operation cap.
341
557
 
@@ -347,14 +563,18 @@ the remaining budget.
347
563
  The default NetHTTP transport:
348
564
 
349
565
  - uses one connection per call and closes it on every outcome
566
+ - dials a dual-stack host as Go does: the second address family starts 300 ms
567
+ after the first, and each address gets a share of the remaining deadline
350
568
  - sends the configured `Accept-Encoding`
351
- - ignores proxy environment variables
569
+ - uses HTTP proxies from the environment by default (see
570
+ [NetHTTP TLS and proxies](#nethttp-tls-and-proxies))
352
571
  - disables retries and decompression
353
572
  - preserves TLS peer/hostname verification
354
573
  - does not follow redirects
355
574
 
356
- A transport-owned watchdog closes its socket at expiry, including during
357
- response-header trickle and blocked writes. Native DNS resolution may outlast
575
+ A transport-owned watchdog closes the call's socket at expiry, including during
576
+ TCP connect, a proxy `CONNECT` exchange, the TLS handshake, response-header
577
+ trickle and blocked writes. Native DNS resolution may outlast
358
578
  the budget; expiry is checked when control returns. Codec work and request
359
579
  preparation are synchronous and checked before/after; gzip work also checks
360
580
  each native input/output chunk and member boundary. They are not interrupted.
@@ -401,9 +621,10 @@ delayed. Cancellation never substitutes a timeout header for `timeout: nil`.
401
621
 
402
622
  ### Transport behavior
403
623
 
404
- NetHTTP closes only its call-owned socket to interrupt exposed TLS, writes,
405
- headers and body reads. Native DNS/TCP before socket exposure remains
406
- cooperative; cancellation is checked on return before any later dispatch.
624
+ NetHTTP owns each socket from its creation and closes only that socket to
625
+ interrupt TCP connect, a proxy `CONNECT` exchange, TLS, writes, headers and body
626
+ reads. Native DNS resolution remains cooperative; cancellation is checked on
627
+ return before any later dispatch.
407
628
  The optional Async transport wakes its owner reactor and resets its stream.
408
629
  Healthy multiplexed siblings survive; a stuck frame retains the documented
409
630
  connection-wide cleanup fallback. Neither backend retries or replays a cancelled call.
@@ -422,8 +643,10 @@ check, so a handler waiting past its deadline needs a wait bounded by
422
643
  transport accept explicit cancellation. Native HTTP/2 publishes peer
423
644
  `RST_STREAM(CANCEL)` before input teardown; normal END_STREAM/half-close, other
424
645
  reset codes, connection loss and host shutdown do not manufacture explicit
425
- cancellation. Rack/Rails and Falcon HTTP/1 add no peer detection or token env
426
- injection. Synchronous adapters cannot interrupt blocked application code.
646
+ cancellation. The [support contract](support.md#delivery-cancellation-and-metadata)
647
+ classifies this signal policy as provisional. Rack/Rails and Falcon HTTP/1 add
648
+ no peer detection or token env injection. Synchronous adapters cannot interrupt
649
+ blocked application code.
427
650
  See [design](design.md) for ownership and transport limits.
428
651
 
429
652
  ## Interceptors
@@ -453,9 +676,8 @@ class RequireTenant
453
676
  end
454
677
  end
455
678
 
456
- client = ConnectRPC::Client.new(base_url: url, binding: binding, interceptors: [BearerAuth.new(tokens)])
457
- server = ConnectRPC::Server.new(services: services, binding: binding, handlers: handlers,
458
- interceptors: [RequireTenant.new])
679
+ client = ConnectRPC::Client.new(base_url: url, interceptors: [BearerAuth.new(tokens)])
680
+ server = ConnectRPC::Server.new(services: services, handlers: handlers, interceptors: [RequireTenant.new])
459
681
  ```
460
682
 
461
683
  `interceptors:` defaults to an empty Array. Core discovers each element's
@@ -523,6 +745,8 @@ innermost continuation starts dispatch, `request=` replaces the message and
523
745
  - Instrumentation injects its propagation headers after the chain, merging them
524
746
  with interceptor-added metadata as caller metadata. The lifecycle records the
525
747
  caller metadata before the chain and the metadata actually sent at dispatch.
748
+ Since 0.3.0, the client's default User-Agent is added after that point, so
749
+ it is not part of the recorded request metadata.
526
750
  - Every client unary `Response` is frozen, with or without interceptors: the
527
751
  struct, its `metadata` and its `trailers`. Core freezes a short-circuit or
528
752
  replacement `Response` before the next outer layer receives it. The message is
@@ -19,6 +19,23 @@ module ConnectRPC
19
19
  google.protobuf.Int32Value google.protobuf.UInt32Value google.protobuf.BoolValue google.protobuf.StringValue
20
20
  google.protobuf.BytesValue
21
21
  ].freeze
22
+ STATUS_LOCK = Mutex.new
23
+ private_constant :STATUS_LOCK
24
+
25
+ # Built once per process. The pool is intentionally detached from
26
+ # generated_pool and public constants.
27
+ def self.status_types
28
+ @status_types || STATUS_LOCK.synchronize do
29
+ @status_types ||= begin
30
+ pool = Google::Protobuf::DescriptorPool.new
31
+ path = File.join(__dir__, "descriptors/status.bin")
32
+ set = Google::Protobuf::FileDescriptorSet.decode(File.binread(path))
33
+ set.file.each { |file| pool.add_serialized_file(Google::Protobuf::FileDescriptorProto.encode(file)) }
34
+ [pool.lookup("google.rpc.Status").msgclass, pool.lookup("google.protobuf.Any").msgclass].freeze
35
+ end
36
+ end
37
+ end
38
+ private_class_method :status_types
22
39
 
23
40
  def encode(message, type:, codec:)
24
41
  Protocol.codec!(codec)
@@ -32,6 +49,8 @@ module ConnectRPC
32
49
  def decode(bytes, type:, codec:)
33
50
  Protocol.codec!(codec)
34
51
  return type.decode(bytes) if codec == :proto
52
+ # connect-go rejects this too: an empty body is not a JSON object.
53
+ raise CodecError, "Zero-length payload is not valid JSON" if bytes.empty?
35
54
  return decode_wrapper(bytes, type) if WRAPPERS.include?(type.descriptor.name)
36
55
 
37
56
  type.decode_json(bytes, ignore_unknown_fields: true)
@@ -71,13 +90,7 @@ module ConnectRPC
71
90
 
72
91
  private
73
92
 
74
- def status_types
75
- # This pool is intentionally detached from generated_pool and public constants.
76
- pool = Google::Protobuf::DescriptorPool.new
77
- set = Google::Protobuf::FileDescriptorSet.decode(File.binread(File.join(__dir__, "descriptors/status.bin")))
78
- set.file.each { |file| pool.add_serialized_file(Google::Protobuf::FileDescriptorProto.encode(file)) }
79
- [pool.lookup("google.rpc.Status").msgclass, pool.lookup("google.protobuf.Any").msgclass]
80
- end
93
+ def status_types = GoogleProtobuf.send(:status_types)
81
94
 
82
95
  def decode_wrapper(bytes, type)
83
96
  # Native protobuf 4.36 cannot parse a scalar wrapper at the JSON root.