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
@@ -0,0 +1,425 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "uri"
4
+ require "ipaddr"
5
+ require "socket"
6
+
7
+ module ConnectRPC
8
+ # Chooses the HTTP proxy for one request URL, or none. Environment rules
9
+ # follow Go net/http (golang.org/x/net/http/httpproxy as vendored by Go 1.27).
10
+ # Internal: transports decide which proxy schemes they can use.
11
+ module Proxy # rubocop:disable Metrics/ModuleLength
12
+ # A proxy for one request. The user and password are percent-decoded.
13
+ Endpoint = Data.define(:scheme, :host, :port, :user, :password)
14
+
15
+ # Data#pretty_print ignores inspect, so pp would show the credentials.
16
+ class Endpoint
17
+ def inspect = "#<#{self.class} #{scheme} proxy>"
18
+ def to_s = inspect
19
+ def pretty_print(printer) = printer.text(inspect)
20
+ end
21
+
22
+ PROXY_PORTS = { "http" => 80, "https" => 443, "socks5" => 1080, "socks5h" => 1080 }.freeze
23
+ TARGET_PORTS = { "http" => 80, "https" => 443 }.freeze
24
+ LDH_HOST = /\A[a-z0-9.-]+\z/
25
+ SCHEME = /\A[A-Za-z][A-Za-z0-9+.-]*\z/
26
+ # RFC 3986 userinfo, plus the "@" that the last-"@" split leaves in it.
27
+ USERINFO = /\A(?:[A-Za-z0-9\-._~!$&'()*+,;=:@]|%\h\h)*\z/
28
+ ASCII_HOST = /\A[A-Za-z0-9._~-]+\z/
29
+ # ASCII control characters and whitespace, which a proxy value never needs.
30
+ CONTROL = /[\x00-\x20\x7F]/
31
+ # Go's IDNA maps these to "."; NFKC leaves U+3002 as it is.
32
+ FULL_STOPS = "\u3002\uFF0E\uFF61"
33
+ # Characters Go's IDNA deletes or rejects, which this mapping does not
34
+ # reproduce: default-ignorable code points (soft hyphen, variation
35
+ # selectors, ZWJ/ZWNJ) and right-to-left scripts, whose bidi rules are not
36
+ # checked. A host containing one fails closed.
37
+ RIGHT_TO_LEFT = "\u0590-\u08FF\uFB1D-\uFDFF\uFE70-\uFEFF\u{10800}-\u{10FFF}\u{1E800}-\u{1EFFF}"
38
+ UNMAPPED = /[\p{Default_Ignorable_Code_Point}#{RIGHT_TO_LEFT}]/
39
+
40
+ # A proxy that this call must not use. The reason is a fixed symbol and the
41
+ # message never includes the proxy value.
42
+ class Unusable < StandardError
43
+ attr_reader :reason
44
+
45
+ def initialize(reason)
46
+ @reason = reason
47
+ super("Proxy unusable: #{reason}")
48
+ end
49
+ end
50
+
51
+ # :environment snapshots the proxy environment once; a String or URI is
52
+ # used for every request; nil is always direct.
53
+ def self.resolver(option, env = ENV)
54
+ case option
55
+ when :environment then Environment.new(env)
56
+ when nil then Static.new(nil)
57
+ when String, URI::Generic then Static.new(explicit(option))
58
+ else raise ArgumentError, "Invalid proxy configuration", cause: nil
59
+ end
60
+ end
61
+
62
+ def self.explicit(option)
63
+ endpoint = option.is_a?(String) ? parse(option) : uri_endpoint(option)
64
+ raise ArgumentError, "Invalid proxy configuration", cause: nil unless endpoint
65
+
66
+ endpoint
67
+ end
68
+
69
+ # URI::HTTP.new skips component checks, so delimiters in a component
70
+ # could reshape the authority once serialized. A URI is accepted only when
71
+ # its text parses back to the same components; the host[:port] shorthand
72
+ # is for Strings only.
73
+ def self.uri_endpoint(uri)
74
+ value = uri.to_s
75
+ return unless value.include?("://")
76
+
77
+ reparsed = URI.parse(value)
78
+ same = reparsed.scheme.to_s.casecmp?(uri.scheme.to_s) &&
79
+ %i[host port userinfo].all? { |part| reparsed.public_send(part) == uri.public_send(part) }
80
+ parse(value) if same
81
+ rescue StandardError
82
+ nil
83
+ end
84
+ private_class_method :explicit, :uri_endpoint
85
+
86
+ # Parses scheme://userinfo@host:port[tail], or Go's host[:port] shorthand
87
+ # for http, into an Endpoint. Nil for anything else: unlike Go, which goes
88
+ # direct for some malformed values and dials odd ones, every value either
89
+ # names a valid endpoint or fails closed. The tail after the authority
90
+ # cannot change the endpoint and is ignored. Userinfo ends at the last "@"
91
+ # (go.dev/issue/22655) and the authority is split before a host is mapped.
92
+ def self.parse(value) # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity
93
+ value = utf8(value)
94
+ return if value.nil? || CONTROL.match?(value)
95
+
96
+ scheme, separator, rest = value.partition("://")
97
+ if separator.empty?
98
+ scheme = "http"
99
+ rest = value
100
+ end
101
+ return unless SCHEME.match?(scheme)
102
+
103
+ scheme = scheme.downcase.freeze
104
+ userinfo, at, authority = rest[%r{\A[^/?#]*}].to_s.rpartition("@")
105
+ user, password = credentials(userinfo) unless at.empty?
106
+ return if !at.empty? && user.nil?
107
+
108
+ host, port = host_port(authority, scheme)
109
+ Endpoint.new(scheme: scheme, host: host, port: port, user: user, password: password) if host
110
+ rescue StandardError
111
+ nil
112
+ end
113
+
114
+ # [user, password] percent-decoded, never form-decoded; the password is
115
+ # nil without a ":". Nil for characters outside RFC 3986 userinfo, a stray
116
+ # "%" or invalid UTF-8.
117
+ def self.credentials(userinfo)
118
+ return unless USERINFO.match?(userinfo)
119
+
120
+ user, colon, password = userinfo.partition(":")
121
+ user = decode(user)
122
+ return [user, nil] if user && colon.empty?
123
+
124
+ password = decode(password)
125
+ [user, password] if user && password
126
+ end
127
+
128
+ def self.decode(part)
129
+ decoded = part.b.gsub(/%\h\h/) { |escape| escape.delete_prefix("%").hex.chr }.force_encoding(Encoding::UTF_8)
130
+ decoded.freeze if decoded.valid_encoding?
131
+ end
132
+
133
+ # [host, port] for a bracketed IPv6 address without a zone or a name, and
134
+ # an optional port in 1..65535, else nil. A missing port takes the scheme's
135
+ # default; a scheme without one keeps nil and transports reject it.
136
+ def self.host_port(value, scheme) # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity
137
+ if value.start_with?("[")
138
+ address, close, port = value[1..].to_s.partition("]")
139
+ return unless !close.empty? && address.include?(":") && ip(address)
140
+ return unless port.empty? || port.start_with?(":")
141
+
142
+ host = address.downcase
143
+ port = port[1..].to_s
144
+ else
145
+ host, _, port = value.partition(":")
146
+ return if host.empty? || host.include?("%") || port.include?(":")
147
+
148
+ host = host.ascii_only? ? (host.downcase if ASCII_HOST.match?(host)) : ascii_host(host)
149
+ return if host.nil? || numeric_shorthand?(host)
150
+ end
151
+ return [host.freeze, PROXY_PORTS[scheme]] if port.empty?
152
+
153
+ [host.freeze, port.to_i] if /\A[0-9]+\z/.match?(port) && port.to_i.between?(1, 65_535)
154
+ end
155
+
156
+ # The C resolver reads old BSD forms such as "010.0.0.1" (octal, so
157
+ # 8.0.0.1), "127.1" and "2130706433" as IPv4 addresses; Go refuses them.
158
+ # Only canonical IP literals are dialled as addresses.
159
+ def self.numeric_shorthand?(host)
160
+ return false if ip(host)
161
+
162
+ !Socket.getaddrinfo(host, nil, nil, :STREAM, nil, Socket::AI_NUMERICHOST).empty?
163
+ rescue SocketError
164
+ false
165
+ end
166
+ private_class_method :credentials, :decode, :host_port, :numeric_shorthand?
167
+
168
+ # A valid UTF-8 copy of the value's bytes, or nil. Go handles bytes in any
169
+ # encoding, so an invalidly encoded value is unparseable, not an exception.
170
+ def self.utf8(value)
171
+ value = value.to_s.b.force_encoding(Encoding::UTF_8)
172
+ value if value.valid_encoding?
173
+ end
174
+
175
+ # Maps a non-ASCII host as Go's idna.Lookup.ToASCII does for ordinary
176
+ # names: ideographic full stops as dots, NFKC, lowercase, then Punycode
177
+ # for each non-ASCII label. Nil when NFKC adds a dot (U+2024 or U+2488,
178
+ # for example), which would name a different host, or when the result is
179
+ # not a letter, digit, hyphen and dot name, which Go's STD3 rules reject,
180
+ # so a mapping never yields a delimiter such as "@", "/" or ":". UTS #46's
181
+ # other validity checks and mappings are not applied.
182
+ def self.ascii_host(host) # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
183
+ return host if host.ascii_only?
184
+ return if UNMAPPED.match?(host)
185
+
186
+ dotted = host.tr(FULL_STOPS, ".")
187
+ normalized = dotted.unicode_normalize(:nfkc).downcase
188
+ return if normalized.count(".") > dotted.count(".")
189
+
190
+ labels = normalized.split(".", -1)
191
+ return if labels.any? { |label| label.start_with?("-") || label.end_with?("-") }
192
+
193
+ mapped = labels.map { |label| label.ascii_only? ? label : "xn--#{Punycode.encode(label)}" }.join(".")
194
+ mapped if LDH_HOST.match?(mapped)
195
+ end
196
+
197
+ # Go net.SplitHostPort, returning nil where Go returns an error.
198
+ def self.split_host_port(value) # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity
199
+ if value.start_with?("[")
200
+ close = value.index("]")
201
+ return unless close && value[close + 1] == ":"
202
+
203
+ host = value[1...close].to_s
204
+ port = value[(close + 2)..].to_s
205
+ else
206
+ index = value.rindex(":")
207
+ return unless index
208
+
209
+ host = value[0...index].to_s
210
+ port = value[(index + 1)..].to_s
211
+ return if host.include?(":")
212
+ end
213
+ return if [host, port].any? { |part| part.include?("[") || part.include?("]") }
214
+
215
+ [host, port]
216
+ end
217
+
218
+ # IPv4-mapped IPv6 addresses compare as IPv4, as Go net.IP does.
219
+ def self.ip(value)
220
+ return unless /\A[0-9A-Fa-f:.]+\z/.match?(value)
221
+
222
+ address = IPAddr.new(value)
223
+ address.ipv4_mapped? ? address.native : address
224
+ rescue IPAddr::Error
225
+ nil
226
+ end
227
+
228
+ # RFC 3492 Punycode encoding of one label, without the "xn--" prefix.
229
+ module Punycode
230
+ BASE = 36
231
+ T_MIN = 1
232
+ T_MAX = 26
233
+ SKEW = 38
234
+ DAMP = 700
235
+
236
+ def self.encode(label) # rubocop:disable Metrics/MethodLength, Metrics/AbcSize, Metrics/CyclomaticComplexity
237
+ points = label.codepoints
238
+ output = points.select { |point| point < 0x80 }.pack("U*")
239
+ basic = handled = output.length
240
+ output << "-" if basic.positive?
241
+ code = 0x80
242
+ delta = 0
243
+ bias = 72
244
+ while handled < points.length
245
+ following = points.select { |point| point >= code }.min.to_i
246
+ delta += (following - code) * (handled + 1)
247
+ code = following
248
+ points.each do |point|
249
+ delta += 1 if point < code
250
+ next unless point == code
251
+
252
+ output << digits(delta, bias)
253
+ bias = adapt(delta, handled + 1, handled == basic)
254
+ delta = 0
255
+ handled += 1
256
+ end
257
+ delta += 1
258
+ code += 1
259
+ end
260
+ output
261
+ end
262
+
263
+ # The generalized variable-length integer for one delta.
264
+ def self.digits(delta, bias)
265
+ output = +""
266
+ k = BASE
267
+ loop do
268
+ threshold = (k - bias).clamp(T_MIN, T_MAX)
269
+ return output << digit(delta) if delta < threshold
270
+
271
+ output << digit(threshold + ((delta - threshold) % (BASE - threshold)))
272
+ delta = (delta - threshold) / (BASE - threshold)
273
+ k += BASE
274
+ end
275
+ end
276
+
277
+ def self.digit(value) = (value < 26 ? value + 97 : value + 22).chr
278
+
279
+ def self.adapt(delta, points, first)
280
+ delta = first ? delta / DAMP : delta / 2
281
+ delta += delta / points
282
+ k = 0
283
+ while delta > ((BASE - T_MIN) * T_MAX) / 2
284
+ delta /= BASE - T_MIN
285
+ k += BASE
286
+ end
287
+ k + (((BASE - T_MIN + 1) * delta) / (delta + SKEW))
288
+ end
289
+ end
290
+
291
+ class Static
292
+ attr_reader :endpoint
293
+
294
+ def initialize(endpoint)
295
+ @endpoint = endpoint
296
+ freeze
297
+ end
298
+
299
+ def for(_url) = @endpoint
300
+ def inspect = "#<#{self.class} #{@endpoint ? 'explicit' : 'direct'}>"
301
+ end
302
+
303
+ class Environment
304
+ def initialize(env)
305
+ @http = proxy(value(env, "HTTP_PROXY", "http_proxy"))
306
+ @https = proxy(value(env, "HTTPS_PROXY", "https_proxy"))
307
+ @cgi = !env.fetch("REQUEST_METHOD", nil).to_s.empty?
308
+ @all = false
309
+ @ip_matchers = []
310
+ @domain_matchers = []
311
+ no_proxy(value(env, "NO_PROXY", "no_proxy"))
312
+ @ip_matchers.freeze
313
+ @domain_matchers.freeze
314
+ freeze
315
+ end
316
+
317
+ def inspect = "#<#{self.class}>"
318
+
319
+ # Order follows Go proxyForURL: select by target scheme, refuse an HTTP
320
+ # proxy in CGI, apply NO_PROXY, then require a usable address.
321
+ def for(url)
322
+ scheme = url.scheme.to_s.downcase
323
+ proxy = { "https" => @https, "http" => @http }[scheme]
324
+ return unless proxy
325
+ raise Unusable.new(:cgi), cause: nil if scheme == "http" && @cgi
326
+ return unless use_proxy?(url, scheme)
327
+ raise Unusable.new(:invalid_address), cause: nil unless proxy.is_a?(Endpoint)
328
+
329
+ proxy
330
+ end
331
+
332
+ private
333
+
334
+ # Parses a value once, as Go does: an Endpoint, :unusable for any value
335
+ # that is not a valid endpoint, or nil for none.
336
+ def proxy(value)
337
+ return unless value
338
+
339
+ Proxy.parse(value) || :unusable
340
+ end
341
+
342
+ def value(env, *names)
343
+ names.each do |name|
344
+ value = env.fetch(name, nil).to_s
345
+ return value.dup.freeze unless value.empty?
346
+ end
347
+ nil
348
+ end
349
+
350
+ def use_proxy?(url, scheme) # rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
351
+ host = url.hostname.to_s.strip.downcase
352
+ port = (url.port || TARGET_PORTS[scheme]).to_s
353
+ return false if host == "localhost"
354
+
355
+ address = Proxy.ip(host)
356
+ return false if address&.loopback? || @all
357
+ # Domain entries never match an IP host.
358
+ return @ip_matchers.none? { |matcher| ip_match?(matcher, address, port) } if address
359
+
360
+ @domain_matchers.none? { |matcher| domain_match?(matcher, host, port) }
361
+ end
362
+
363
+ def ip_match?(matcher, address, port)
364
+ network, wanted, cidr = matcher
365
+ if cidr
366
+ network.family == address.family && network.include?(address)
367
+ else
368
+ network == address && (wanted.empty? || wanted == port)
369
+ end
370
+ end
371
+
372
+ def domain_match?(matcher, host, port)
373
+ suffix, wanted, exact = matcher
374
+ (host.end_with?(suffix) || (exact && host == suffix[1..])) && (wanted.empty? || wanted == port)
375
+ end
376
+
377
+ def no_proxy(value) # rubocop:disable Metrics/MethodLength, Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
378
+ # Go keeps an entry with invalid bytes or an unmappable name as written,
379
+ # so it never matches an ASCII host; drop it and keep the others.
380
+ value.to_s.b.split(",").each do |raw|
381
+ entry = Proxy.utf8(raw)&.strip&.downcase
382
+ next if entry.nil? || entry.empty?
383
+
384
+ if entry == "*"
385
+ @all = true
386
+ break
387
+ end
388
+
389
+ network = cidr(entry)
390
+ next @ip_matchers << [network, "", true] if network
391
+
392
+ host, port = Proxy.split_host_port(entry)
393
+ if host
394
+ next if host.empty?
395
+ else
396
+ host = entry
397
+ port = ""
398
+ end
399
+ address = Proxy.ip(host)
400
+ next @ip_matchers << [address, port.to_s, false] if address
401
+ next if host.empty?
402
+
403
+ host = host[1..].to_s if host.start_with?("*.")
404
+ exact = !host.start_with?(".")
405
+ host = ".#{host}" if exact
406
+ host = Proxy.ascii_host(host)
407
+ @domain_matchers << [host.freeze, port.to_s.freeze, exact] if host
408
+ end
409
+ nil
410
+ end
411
+
412
+ # Go matches an IPv4-mapped network of /96 or longer against IPv4 hosts.
413
+ def cidr(entry)
414
+ address, prefix = entry.split("/", 2)
415
+ return unless address && prefix && /\A[0-9]{1,3}\z/.match?(prefix)
416
+ return unless Proxy.ip(address)
417
+
418
+ network = IPAddr.new(entry)
419
+ network.ipv4_mapped? ? network.native : network
420
+ rescue IPAddr::Error
421
+ nil
422
+ end
423
+ end
424
+ end
425
+ end
@@ -1,26 +1,35 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "ipaddr"
4
+
3
5
  module ConnectRPC
4
6
  class Server # rubocop:disable Metrics/ClassLength
5
7
  attr_reader :services
6
8
 
7
9
  # Public configuration keeps each validation next to its assignment.
8
10
  # rubocop:disable Metrics/MethodLength, Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
9
- def initialize(services:, binding:, handlers: {}, invoker: nil, request_limit: Protocol::DEFAULT_LIMIT,
11
+ def initialize(services:, binding: nil, handlers: {}, invoker: nil, request_limit: Protocol::DEFAULT_LIMIT,
10
12
  response_limit: Protocol::DEFAULT_LIMIT, request_wire_limit: request_limit,
11
13
  response_wire_limit: response_limit, protocol: :connect, mode: :unary, encoding: :identity,
12
14
  instrumentation: nil, get_query_limit: nil, terminal_wire_limit: 65_536, terminal_limit: 65_536,
13
15
  status_codec: nil, grpc_status_wire_limit: 65_536, grpc_status_limit: 65_536, cors: nil,
14
- interceptors: [])
16
+ interceptors: [], on_error: nil)
15
17
  Protocol.profile!(protocol, mode, encoding, server: true)
16
18
  @protocol = Protocol.server_protocols(protocol)
17
19
  unless cors.nil? || (cors.is_a?(GRPCWebCORS) && @protocol.include?(:grpc_web))
18
20
  raise ArgumentError, "cors requires a GRPCWebCORS policy and explicit gRPC-Web enablement"
19
21
  end
20
22
 
23
+ if on_error
24
+ probe = on_error #: (^(StandardError) -> void | _ServerErrorHandler) & _InterceptorProbe
25
+ raise ArgumentError, "on_error must be callable" unless probe.respond_to?(:call)
26
+ end
27
+
28
+ @on_error = on_error
21
29
  @cors = cors
22
30
  @grpc_status_wire_limit = Protocol.limit!(grpc_status_wire_limit)
23
31
  @grpc_status_limit = Protocol.limit!(grpc_status_limit)
32
+ binding = Protocol.binding!(binding)
24
33
  @status_codec = GRPCProtocol.status_codec!(binding, status_codec) if @protocol.intersect?(%i[grpc grpc_web])
25
34
  @terminal_wire_limit = Protocol.limit!(terminal_wire_limit)
26
35
  @terminal_limit = Protocol.limit!(terminal_limit)
@@ -53,24 +62,28 @@ module ConnectRPC
53
62
  instrumentation = @instrumentation
54
63
  return unless instrumentation
55
64
 
65
+ carrier = Instrumentation.carrier(headers)
66
+ address, port = request_authority(carrier["host"])
56
67
  instrumentation.start(owner: self, path: path.dup.freeze, role: :server, method: @methods[path],
57
- carrier: Instrumentation.carrier(headers),
68
+ carrier: carrier, server_address: address, server_port: port,
58
69
  protocol: request_protocol(headers, http_method))
59
70
  end
60
71
 
61
72
  # Keep processing and terminal ensures adjacent to their owner.
62
73
  # rubocop:disable Metrics/MethodLength, Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
63
- def call(path:, http_method:, headers:, input:, query: "", lifecycle: nil, cancellation: nil)
74
+ # on_error is the host's per-call reporter. It runs after the Server's own
75
+ # on_error for the same unexpected exception.
76
+ def call(path:, http_method:, headers:, input:, query: "", lifecycle: nil, cancellation: nil, on_error: nil)
64
77
  if @protocol.include?(:grpc_web)
65
78
  early = cors_response(path: path, http_method: http_method, headers: headers)
66
79
  return early if early
67
80
  if request_protocol(headers, http_method) == :grpc_web
68
- return call_grpc_web_unary(path, http_method, headers, input, lifecycle, cancellation)
81
+ return call_grpc_web_unary(path, http_method, headers, input, lifecycle, cancellation, on_error)
69
82
  end
70
83
  end
71
84
  unless lifecycle || @instrumentation
72
85
  return process_call(path: path, http_method: http_method, headers: headers, input: input, query: query,
73
- cancellation: cancellation)
86
+ cancellation: cancellation, on_error: on_error)
74
87
  end
75
88
 
76
89
  owned = lifecycle.nil?
@@ -83,7 +96,7 @@ module ConnectRPC
83
96
  record_request_metadata(active, Protocol.headers(headers))
84
97
  active.activate do
85
98
  process_call(path: path, http_method: http_method, headers: headers, input: input, query: query,
86
- lifecycle: active, cancellation: cancellation)
99
+ lifecycle: active, cancellation: cancellation, on_error: on_error)
87
100
  end
88
101
  rescue Exception => e # rubocop:disable Lint/RescueException -- include escapes from processing cleanup
89
102
  error = e
@@ -96,6 +109,42 @@ module ConnectRPC
96
109
 
97
110
  private
98
111
 
112
+ # Hostname labels start and end with a letter, digit or underscore; IPv4
113
+ # dotted quads are valid names. The bracketed part is checked by IPAddr.
114
+ AUTHORITY = /\A(?:\[(?<ipv6>[0-9A-Fa-f:.]+)\]|
115
+ (?<name>(?:[0-9A-Za-z_](?:[0-9A-Za-z_-]*[0-9A-Za-z_])?\.)*
116
+ [0-9A-Za-z_](?:[0-9A-Za-z_-]*[0-9A-Za-z_])?\.?))
117
+ (?::(?<port>[0-9]+))?\z/x
118
+ private_constant :AUTHORITY
119
+
120
+ # The address the client used, from a single host or :authority value:
121
+ # host, host:port, [v6] or [v6]:port. Anything else, including a value that
122
+ # is not valid ASCII text, yields neither fact. Observation never raises.
123
+ def request_authority(values)
124
+ return [nil, nil] unless values && values.size == 1
125
+
126
+ authority = values.fetch(0)
127
+ return [nil, nil] unless authority.is_a?(String) && authority.bytesize <= 255 &&
128
+ authority.valid_encoding? && authority.ascii_only?
129
+
130
+ match = AUTHORITY.match(authority)
131
+ return [nil, nil] unless match
132
+
133
+ port = match[:port]&.to_i
134
+ return [nil, nil] unless port.nil? || port.between?(1, 65_535)
135
+
136
+ ipv6 = match[:ipv6]
137
+ return [nil, nil] if ipv6 && !ipv6_address?(ipv6)
138
+
139
+ [(ipv6 || match[:name] || "").dup.freeze, port]
140
+ end
141
+
142
+ def ipv6_address?(text)
143
+ IPAddr.new(text).ipv6?
144
+ rescue ArgumentError
145
+ false
146
+ end
147
+
99
148
  def request_protocol(headers, http_method)
100
149
  # Query controls own Connect GET, including rejection before header work.
101
150
  return :connect if http_method == "GET" && @protocol.include?(:connect)
@@ -106,7 +155,7 @@ module ConnectRPC
106
155
  GRPCProtocol.intent?(headers) ? :grpc : :connect
107
156
  end
108
157
 
109
- def process_call(path:, http_method:, headers:, input:, query:, lifecycle: nil, cancellation: nil)
158
+ def process_call(path:, http_method:, headers:, input:, query:, lifecycle: nil, cancellation: nil, on_error: nil)
110
159
  # @type var response: TransportResponse?
111
160
  # @type var context: Context?
112
161
  context = nil
@@ -143,7 +192,10 @@ module ConnectRPC
143
192
  response = error_response(terminal_error(e, context, cancellation), context, lifecycle)
144
193
  rescue StandardError => e
145
194
  lifecycle&.record_failure(e)
146
- safe = terminal_error(Error.new(:internal, "Internal error"), context, cancellation)
195
+ internal = Error.new(:internal, "Internal error")
196
+ safe = terminal_error(internal, context, cancellation)
197
+ # A deadline or cancellation outcome that wins arbitration is not reported.
198
+ report_unexpected(e, on_error) if safe.equal?(internal)
147
199
  response = error_response(safe, context, lifecycle)
148
200
  ensure
149
201
  context&.close
@@ -155,11 +207,12 @@ module ConnectRPC
155
207
  raise
156
208
  ensure
157
209
  if lifecycle && !lifecycle.outcome
210
+ head, trailers = Instrumentation.unary_carriers(response ? response.headers : {})
158
211
  lifecycle.processing_finished(code: response&.status == 200 && cleaned && !error ? "OK" : lifecycle.code,
159
212
  error: error,
160
213
  normalized_error: lifecycle.normalized_error,
161
214
  http_status: response&.status, response_bytes: response&.body&.bytesize,
162
- response_metadata: response ? Instrumentation.carrier(response.headers) : {})
215
+ response_metadata: head, response_trailers: trailers)
163
216
  end
164
217
  end
165
218
 
@@ -248,7 +301,7 @@ module ConnectRPC
248
301
  raise ArgumentError, "Invalid service declarations" unless services.is_a?(Array) && services.all?(Service)
249
302
  raise ArgumentError, "Duplicate service" unless services.map(&:name).uniq.size == services.size
250
303
 
251
- services.flat_map(&:methods).to_h { |method| [method.path, method] }.freeze
304
+ services.flat_map(&:rpcs).to_h { |method| [method.path, method] }.freeze
252
305
  end
253
306
 
254
307
  def invoke_handler(method, request, context)
@@ -382,11 +435,42 @@ module ConnectRPC
382
435
  def response_headers(context, content_type)
383
436
  # @type var headers: headers
384
437
  headers = context ? context.response_metadata.to_h : {}
385
- context&.response_trailers&.each { |key, values| headers["trailer-#{key}"] = values }
438
+ append_trailer_fields(headers, context.response_trailers) if context
386
439
  headers["accept-encoding"] = ["gzip, identity"] if @encoding == :gzip
387
440
  headers.merge("content-type" => [content_type])
388
441
  end
389
442
 
443
+ # A trailer without values writes no field, as Go net/http does, whatever the host.
444
+ def append_trailer_fields(headers, trailers)
445
+ trailers.each do |key, values|
446
+ merged = (headers["trailer-#{key}"] || []) + values
447
+ headers["trailer-#{key}"] = merged unless merged.empty?
448
+ end
449
+ end
450
+
451
+ # Reporters run on the calling thread or fiber, inside the instrumented call
452
+ # scope, and never change the peer response.
453
+ def report_unexpected(error, host = nil)
454
+ [@on_error, host].each do |reporter|
455
+ next unless reporter
456
+
457
+ begin
458
+ reporter.call(error)
459
+ rescue StandardError
460
+ nil
461
+ end
462
+ end
463
+ nil
464
+ end
465
+
466
+ # Report only a converted exception whose generic internal error survived
467
+ # arbitration. Only the portable gRPC-Web unary path carries a host reporter.
468
+ def report_stream_error(error, safe, state)
469
+ return if error.equal?(safe) || !state.error.equal?(safe)
470
+
471
+ report_unexpected(error, state.is_a?(GRPCWeb::ServerState) ? state.on_error : nil)
472
+ end
473
+
390
474
  def terminal_error(error, context, cancellation)
391
475
  if context
392
476
  context.commit!
@@ -412,7 +496,7 @@ module ConnectRPC
412
496
  end
413
497
  headers = response_headers(context, "application/json")
414
498
  error.metadata.each { |key, values| headers[key] = (headers[key] || []) + values }
415
- error.trailers.each { |key, values| headers["trailer-#{key}"] = (headers["trailer-#{key}"] || []) + values }
499
+ append_trailer_fields(headers, error.trailers)
416
500
  response = TransportResponse.new(status: status, headers: headers, body: body)
417
501
  if lifecycle
418
502
  lifecycle.code = code