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
@@ -2,15 +2,145 @@
2
2
 
3
3
  require "net/http"
4
4
  require "openssl"
5
+ require "resolv"
6
+ require "securerandom"
7
+ require "socket"
5
8
  require_relative "../../connectrpc"
9
+ require_relative "../proxy"
6
10
 
7
11
  module ConnectRPC
8
12
  module Transports
9
13
  class NetHTTP # rubocop:disable Metrics/ClassLength
10
- # Net::HTTP uses the open timeout again for TLS. Recompute it from the
11
- # original deadline after TCP/DNS, rather than starting another budget.
12
- class Connection < Net::HTTP
13
- attr_accessor :deadline, :cancellation, :socket_lifecycle
14
+ # Go net/http bounds a proxy CONNECT exchange by one minute and its
15
+ # response head by MaxResponseHeaderBytes' default.
16
+ TUNNEL_TIMEOUT = 60
17
+ MAX_TUNNEL_HEAD = 10 * 1024 * 1024
18
+ UNUSABLE_PROXY = { cgi: "proxy refused in CGI environment", invalid_address: "invalid proxy address" }.freeze
19
+
20
+ # A proxy failure with a fixed message. Proxy-supplied bytes never reach
21
+ # it, so it is safe as an error cause and in lifecycle failures.
22
+ class ProxyFailure < StandardError; end
23
+
24
+ # Validates TLS client inputs exactly as ConnectRPC::Async's TLS client
25
+ # does. A transport with TLS options builds its own context; every other
26
+ # transport shares one default context, built on first HTTPS use.
27
+ module ClientTLS
28
+ DEFAULT_LOCK = Mutex.new
29
+ CERTIFICATE = %r{\A-----BEGIN CERTIFICATE-----\s+[A-Za-z0-9+/=\s]+-----END CERTIFICATE-----\z}
30
+ PRIVATE_KEY = %r{
31
+ \A-----BEGIN\ (RSA\ PRIVATE\ KEY|EC\ PRIVATE\ KEY|PRIVATE\ KEY)-----
32
+ \s+[A-Za-z0-9+/=\s]+-----END\ \1-----\z
33
+ }x
34
+
35
+ # Names the input that failed validation, never its value.
36
+ class InvalidInput < ArgumentError
37
+ attr_reader :input
38
+
39
+ def initialize(input)
40
+ @input = input
41
+ super("Invalid #{input}")
42
+ end
43
+ end
44
+
45
+ def self.certificate(pem)
46
+ raise ArgumentError unless pem.is_a?(String) && CERTIFICATE.match?(pem.strip)
47
+
48
+ certificates = OpenSSL::X509::Certificate.load(pem.dup)
49
+ raise ArgumentError unless certificates.size == 1
50
+
51
+ certificate = certificates.first
52
+ raise ArgumentError unless certificate.not_before <= Time.now && certificate.not_after > Time.now
53
+
54
+ certificate
55
+ end
56
+
57
+ def self.input(name)
58
+ yield
59
+ rescue InvalidInput
60
+ raise
61
+ rescue StandardError
62
+ raise InvalidInput.new(name), cause: nil
63
+ end
64
+
65
+ def self.identity(chain, pem) # rubocop:disable Metrics/MethodLength, Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
66
+ certificates = input(:certificate_chain) do
67
+ raise ArgumentError unless chain.is_a?(Array) && !chain.empty?
68
+
69
+ chain.map { |element| certificate(element) }
70
+ end
71
+ key = input(:private_key) do
72
+ raise ArgumentError unless pem.is_a?(String) && PRIVATE_KEY.match?(pem.strip)
73
+
74
+ OpenSSL::PKey.read(pem.dup) { nil }
75
+ end
76
+ input(:private_key) do
77
+ digest = %w[ED25519 ED448].include?(key.oid) ? nil : "SHA256"
78
+ challenge = SecureRandom.random_bytes(32)
79
+ signature = key.sign(digest, challenge)
80
+ raise ArgumentError unless certificates.first.public_key.verify(digest, signature, challenge)
81
+ end
82
+ input(:certificate_chain) do
83
+ certificates.each_cons(2) do |child, issuer|
84
+ raise ArgumentError unless child.issuer == issuer.subject && child.verify(issuer.public_key)
85
+ end
86
+ end
87
+ [certificates, key]
88
+ end
89
+
90
+ # RFC 6066 section 3 forbids a server name for an IP literal.
91
+ def self.server_name(host)
92
+ host unless Resolv::IPv4::Regex.match?(host) || Resolv::IPv6::Regex.match?(host)
93
+ end
94
+
95
+ # Nil without TLS options. Loading the system trust store costs
96
+ # milliseconds and hundreds of KiB, so it happens once per process.
97
+ def self.context(ca_file:, certificate_chain:, private_key:)
98
+ return if ca_file.nil? && certificate_chain.nil? && private_key.nil?
99
+
100
+ build(ca_file, certificate_chain, private_key)
101
+ rescue InvalidInput => e
102
+ # Errors name only the input: never paths or key material.
103
+ raise ArgumentError, "Invalid TLS client configuration: #{e.input}", cause: nil
104
+ rescue StandardError
105
+ raise ArgumentError, "Invalid TLS client configuration", cause: nil
106
+ end
107
+
108
+ # SSL_CERT_FILE and SSL_CERT_DIR apply as they are at first use.
109
+ def self.default
110
+ @default || DEFAULT_LOCK.synchronize { @default ||= build(nil, nil, nil) }
111
+ end
112
+
113
+ # Setup freezes the context, so calls share it read-only.
114
+ def self.build(ca_file, certificate_chain, private_key) # rubocop:disable Metrics/MethodLength, Metrics/AbcSize
115
+ context = OpenSSL::SSL::SSLContext.new
116
+ context.set_params(verify_mode: OpenSSL::SSL::VERIFY_PEER, verify_hostname: true)
117
+ context.min_version = OpenSSL::SSL::TLS1_2_VERSION
118
+ context.options |= OpenSSL::SSL::OP_NO_TICKET
119
+ context.session_cache_mode = OpenSSL::SSL::SSLContext::SESSION_CACHE_OFF
120
+ context.session_id_context = SecureRandom.random_bytes(16)
121
+ store = OpenSSL::X509::Store.new
122
+ store.set_default_paths
123
+ input(:ca_file) { store.add_file(ca_file) } if ca_file
124
+ context.cert_store = store
125
+ if certificate_chain || private_key
126
+ certificates, key = identity(certificate_chain, private_key)
127
+ context.add_certificate(certificates.first, key, certificates.drop(1))
128
+ end
129
+ context.alpn_protocols = ["http/1.1"]
130
+ context.setup
131
+ context
132
+ end
133
+ end
134
+ private_constant :ClientTLS
135
+
136
+ # Owns TCP, proxy CONNECT and TLS setup so every socket belongs to the
137
+ # call from creation. Net::HTTP keeps request writing and response parsing.
138
+ class Connection < Net::HTTP # rubocop:disable Metrics/ClassLength
139
+ TUNNEL_HEAD_END = /\r?\n\r?\n/n
140
+ TUNNEL_STATUS = %r{\AHTTP/1\.[01] ([0-9]{3})(?: [^\r\n]*)?\z}n
141
+ TUNNEL_FIELD = /\A[!#$%&'*+\-.^_`|~0-9A-Za-z]+:/n
142
+
143
+ attr_accessor :deadline, :cancellation, :socket_lifecycle, :tls_context, :tunnel
14
144
 
15
145
  private
16
146
 
@@ -18,13 +148,131 @@ module ConnectRPC
18
148
  cancellation ? cancellation.check! : deadline&.check!
19
149
  end
20
150
 
21
- def connect
151
+ def native_wait
152
+ deadline ? deadline.native_timeout : Deadline::MAX_NATIVE_WAIT
153
+ end
154
+
155
+ def connect # rubocop:disable Metrics/MethodLength, Metrics/AbcSize, Metrics/CyclomaticComplexity
22
156
  check_cancellation!
23
157
  # begin_transport can reconnect a closed socket even with retries
24
158
  # disabled. A second socket would escape the call's watchdog.
25
159
  raise IOError, "Owned connection is closed" if @socket
26
160
 
27
- super
161
+ connected = false
162
+ attempts = []
163
+ raw = Dialer.new(attempts, socket_lifecycle, deadline, method(:check_cancellation!))
164
+ .dial(Addrinfo.getaddrinfo(*dial_target, nil, :STREAM, nil, 0, timeout: native_wait))
165
+ establish_tunnel(raw) if tunnel
166
+ socket = use_ssl? ? start_tls(raw) : raw
167
+ @socket = Net::BufferedIO.new(socket, read_timeout: @read_timeout, write_timeout: @write_timeout,
168
+ continue_timeout: @continue_timeout, debug_output: @debug_output)
169
+ @last_communicated = nil
170
+ on_connect
171
+ connected = true
172
+ ensure
173
+ # Every attempt closes unless it became the connection, including
174
+ # when an outer interruption lands mid-dial.
175
+ attempts&.each { |attempt| close_quietly(attempt) unless connected && attempt.equal?(raw) }
176
+ end
177
+
178
+ def dial_target
179
+ endpoint = tunnel
180
+ return [endpoint.host, endpoint.port] if endpoint
181
+ return [proxy_address, proxy_port] if proxy?
182
+
183
+ [address, port]
184
+ end
185
+
186
+ def establish_tunnel(socket)
187
+ expires_at = Process.clock_gettime(Process::CLOCK_MONOTONIC) + TUNNEL_TIMEOUT
188
+ authority = address.include?(":") ? "[#{address}]:#{port}" : "#{address}:#{port}"
189
+ head = "CONNECT #{authority} HTTP/1.1\r\nHost: #{authority}\r\n"
190
+ if (endpoint = tunnel) && endpoint.user
191
+ head << "Proxy-Authorization: Basic #{["#{endpoint.user}:#{endpoint.password}"].pack('m0')}\r\n"
192
+ end
193
+ write_tunnel(socket, "#{head}\r\n", expires_at)
194
+ read_tunnel(socket, expires_at)
195
+ end
196
+
197
+ def write_tunnel(socket, data, expires_at)
198
+ until data.empty?
199
+ written = socket.write_nonblock(data, exception: false)
200
+ if written == :wait_writable
201
+ wait_tunnel(socket, expires_at, :wait_writable)
202
+ else
203
+ data = data.byteslice(written..).to_s
204
+ check_tunnel!(expires_at)
205
+ end
206
+ end
207
+ end
208
+
209
+ # A TLS server never speaks first, so bytes after a 200 head came from
210
+ # the proxy. Status text and fields never leave this method.
211
+ def read_tunnel(socket, expires_at) # rubocop:disable Metrics/MethodLength, Metrics/AbcSize
212
+ head = +"".b
213
+ loop do
214
+ room = MAX_TUNNEL_HEAD - head.bytesize
215
+ raise ProxyFailure, "proxy tunnel failed", cause: nil unless room.positive?
216
+
217
+ chunk = socket.read_nonblock([16_384, room].min, exception: false)
218
+ next wait_tunnel(socket, expires_at, :wait_readable) if chunk == :wait_readable
219
+ raise ProxyFailure, "proxy tunnel failed", cause: nil if chunk.nil?
220
+
221
+ head << chunk
222
+ check_tunnel!(expires_at)
223
+ ending = head.match(TUNNEL_HEAD_END, [head.bytesize - chunk.bytesize - 3, 0].max)
224
+ next unless ending
225
+
226
+ return tunnel_status(head.byteslice(0, ending.begin(0)).to_s, ending.end(0) == head.bytesize)
227
+ end
228
+ end
229
+
230
+ def tunnel_status(head, complete)
231
+ lines = head.split(/\r?\n/n)
232
+ status = TUNNEL_STATUS.match(lines.first.to_s)
233
+ fields = lines.drop(1).all? { |line| TUNNEL_FIELD.match?(line) }
234
+ raise ProxyFailure, "proxy tunnel failed", cause: nil unless status && fields
235
+
236
+ code = status[1].to_i
237
+ raise ProxyFailure, "proxy authentication failed", cause: nil if code == 407
238
+ raise ProxyFailure, "proxy tunnel refused", cause: nil unless code == 200
239
+ raise ProxyFailure, "proxy tunnel failed", cause: nil unless complete
240
+ end
241
+
242
+ def wait_tunnel(socket, expires_at, direction)
243
+ loop do
244
+ wait = [native_wait, expires_at - Process.clock_gettime(Process::CLOCK_MONOTONIC)].min
245
+ return if wait.positive? && socket.public_send(direction, wait)
246
+
247
+ check_tunnel!(expires_at)
248
+ end
249
+ end
250
+
251
+ # The CONNECT cap applies even without a call deadline, after every
252
+ # read or write as well as while waiting, so a reply that arrives
253
+ # late is never accepted. Call expiry and cancellation keep their own
254
+ # outcomes.
255
+ def check_tunnel!(expires_at)
256
+ check_cancellation!
257
+ return if Process.clock_gettime(Process::CLOCK_MONOTONIC) < expires_at
258
+
259
+ raise ProxyFailure, "proxy tunnel timed out", cause: nil
260
+ end
261
+
262
+ def start_tls(raw)
263
+ socket = OpenSSL::SSL::SSLSocket.new(raw, tls_context || ClientTLS.default)
264
+ socket.sync_close = true
265
+ name = ClientTLS.server_name(address)
266
+ socket.hostname = name if name
267
+ ssl_socket_connect(socket, native_wait)
268
+ socket.post_connection_check(address)
269
+ socket
270
+ end
271
+
272
+ def close_quietly(socket)
273
+ socket.close unless socket.closed?
274
+ rescue IOError, SystemCallError
275
+ nil
28
276
  end
29
277
 
30
278
  def begin_transport(request)
@@ -33,39 +281,182 @@ module ConnectRPC
33
281
  request["connect-timeout-ms"] = deadline.timeout_ms if deadline
34
282
  end
35
283
 
284
+ # Net::HTTP uses the open timeout again for TLS. Recompute it from the
285
+ # original deadline after TCP/DNS, rather than starting another budget.
36
286
  def ssl_socket_connect(socket, _timeout)
37
- socket_lifecycle&.attach(socket.to_io)
38
287
  check_cancellation!
39
- super(socket, deadline ? deadline.native_timeout : Deadline::MAX_NATIVE_WAIT)
288
+ super(socket, native_wait)
40
289
  check_cancellation!
41
290
  end
42
291
  end
43
292
 
44
- # Owns only this call's raw socket. Closing wakes Net::HTTP's blocking
45
- # read/write waits even when individual header/body reads keep progressing.
293
+ # Dials resolved addresses as Go's net.Dialer does. Addresses of the
294
+ # first address's family are tried in order. The other family starts
295
+ # FALLBACK_DELAY later, or as soon as the first family has failed, so at
296
+ # most two attempts are in flight. Each attempt gets an equal share of
297
+ # the remaining deadline, at least MIN_ATTEMPT. The first connection
298
+ # wins and every other attempt closes. Connects are nonblocking and run
299
+ # in the calling thread; every attempt is owned from creation, so
300
+ # cancellation and expiry close all of them.
301
+ class Dialer # rubocop:disable Metrics/ClassLength
302
+ FALLBACK_DELAY = 0.3
303
+ MIN_ATTEMPT = 2.0
304
+
305
+ # One family's remaining addresses and its attempt in flight.
306
+ Racer = Struct.new(:addresses, :socket, :address, :expires_at, :failure)
307
+
308
+ def initialize(attempts, sockets, deadline, check)
309
+ @attempts = attempts
310
+ @sockets = sockets
311
+ @deadline = deadline
312
+ @check = check
313
+ end
314
+
315
+ # Raises the first failure of the first family when every address fails.
316
+ def dial(addresses) # rubocop:disable Metrics/MethodLength, Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
317
+ family = addresses.first&.afamily
318
+ primaries, fallbacks = addresses.partition { |address| address.afamily == family }
319
+ racers = [Racer.new(primaries)]
320
+ pending = Racer.new(fallbacks) unless fallbacks.empty?
321
+ fallback_at = now + FALLBACK_DELAY
322
+ loop do
323
+ @check.call
324
+ if pending && (now >= fallback_at || exhausted?(racers.first))
325
+ racers << pending
326
+ pending = nil
327
+ end
328
+ racers.each do |racer|
329
+ socket = start(racer)
330
+ return won(socket, racers) if socket
331
+ end
332
+ live = racers.select(&:socket)
333
+ next if live.empty? && pending
334
+ break if live.empty?
335
+
336
+ ready = wait(live.map(&:socket), timeout(live, pending && fallback_at))
337
+ live.each do |racer|
338
+ socket = progress(racer, ready)
339
+ return won(socket, racers) if socket
340
+ end
341
+ end
342
+ @check.call
343
+ raise racers.first.failure || SocketError.new("No addresses")
344
+ end
345
+
346
+ private
347
+
348
+ def now = Process.clock_gettime(Process::CLOCK_MONOTONIC)
349
+ def exhausted?(racer) = racer.socket.nil? && racer.addresses.empty?
350
+
351
+ # Starts the racer's next addresses until one is in flight. Returns a
352
+ # socket that connected at once.
353
+ def start(racer) # rubocop:disable Metrics/MethodLength, Metrics/AbcSize
354
+ while racer.socket.nil? && (address = racer.addresses.shift)
355
+ # Read the clock after the deadline, so a delay between the two
356
+ # reads moves this expiry past the call deadline, never before it.
357
+ share = budget(racer.addresses.size + 1)
358
+ racer.expires_at = now + share
359
+ socket = own(address)
360
+ begin
361
+ return socket if socket.connect_nonblock(address, exception: false) == 0 # rubocop:disable Style/NumericPredicate
362
+
363
+ racer.socket = socket
364
+ racer.address = address
365
+ rescue IOError, SystemCallError => e
366
+ fail_attempt(racer, socket, e)
367
+ end
368
+ end
369
+ nil
370
+ end
371
+
372
+ # Go's partialDeadline: no per-attempt split without a deadline.
373
+ def budget(left)
374
+ return Deadline::MAX_NATIVE_WAIT unless @deadline
375
+
376
+ remaining = @deadline.remaining
377
+ share = remaining / left
378
+ share < MIN_ATTEMPT ? [remaining, MIN_ATTEMPT].min : share
379
+ end
380
+
381
+ # Creation and ownership cannot be split by an outer interruption.
382
+ def own(address)
383
+ Thread.handle_interrupt(Exception => :never) do
384
+ socket = Socket.new(address.afamily, Socket::SOCK_STREAM, 0)
385
+ @attempts << socket
386
+ @sockets.attach(socket)
387
+ socket
388
+ end
389
+ end
390
+
391
+ # A close from another thread wakes wait_writable but not IO.select.
392
+ # The owner shuts sockets down before closing them, which aborts a
393
+ # pending connect and wakes IO.select on Linux.
394
+ def wait(sockets, timeout)
395
+ return sockets.first.wait_writable(timeout) ? sockets : [] if sockets.size == 1
396
+
397
+ _, writable = IO.select(nil, sockets, nil, timeout)
398
+ writable || []
399
+ end
400
+
401
+ def timeout(live, fallback_at)
402
+ times = live.map(&:expires_at)
403
+ times << fallback_at if fallback_at
404
+ limit = @deadline ? @deadline.native_timeout : Deadline::MAX_NATIVE_WAIT
405
+ (times.min - now).clamp(0, limit)
406
+ end
407
+
408
+ # Returns the racer's socket once it has connected.
409
+ def progress(racer, ready)
410
+ socket = racer.socket
411
+ if ready.include?(socket)
412
+ begin
413
+ return socket if socket.connect_nonblock(racer.address, exception: false) == 0 # rubocop:disable Style/NumericPredicate
414
+ rescue IOError, SystemCallError => e
415
+ return fail_attempt(racer, socket, e)
416
+ end
417
+ end
418
+ fail_attempt(racer, socket, Net::OpenTimeout.new("TCP connect timed out")) if now >= racer.expires_at
419
+ nil
420
+ end
421
+
422
+ def fail_attempt(racer, socket, error)
423
+ racer.failure ||= error
424
+ racer.socket = nil
425
+ discard(socket)
426
+ end
427
+
428
+ def won(socket, racers)
429
+ racers.each { |racer| discard(racer.socket) unless racer.socket.nil? || racer.socket.equal?(socket) }
430
+ socket.setsockopt(Socket::IPPROTO_TCP, Socket::TCP_NODELAY, 1)
431
+ socket
432
+ end
433
+
434
+ def discard(socket)
435
+ @sockets.release(socket)
436
+ socket.close
437
+ nil
438
+ rescue IOError, SystemCallError
439
+ nil
440
+ end
441
+ end
442
+
443
+ # Closes whatever socket the call owns when its deadline expires. Closing
444
+ # wakes blocking waits even when individual reads keep progressing.
46
445
  class Watchdog
47
- def initialize(socket, deadline)
446
+ def initialize(owner, deadline)
48
447
  @mutex = Mutex.new
49
448
  @condition = ConditionVariable.new
50
449
  @done = false
51
- @thread = Thread.new { watch(socket, deadline) }
450
+ @thread = Thread.new { watch(owner, deadline) }
52
451
  end
53
452
 
54
- def watch(socket, deadline)
453
+ def watch(owner, deadline)
55
454
  @mutex.synchronize do
56
455
  @condition.wait(@mutex, deadline.native_timeout) until @done || deadline.expired?
57
- close_socket(socket) unless @done
456
+ owner.close unless @done
58
457
  end
59
458
  end
60
459
 
61
- def close_socket(socket)
62
- socket.shutdown(Socket::SHUT_RDWR)
63
- socket.close
64
- rescue IOError, SystemCallError
65
- # Net::HTTP may have closed the same owned socket first.
66
- nil
67
- end
68
-
69
460
  def stop
70
461
  @mutex.synchronize do
71
462
  @done = true
@@ -75,12 +466,15 @@ module ConnectRPC
75
466
  end
76
467
  end
77
468
 
78
- # Retirement and callback closure share this guard. Unregister alone
79
- # cannot prevent an already-running callback from touching a reused FD.
469
+ # Holds the call's sockets: every dial attempt from creation, then only
470
+ # the connection. Once closed by cancellation or the watchdog, a later
471
+ # attach closes its socket at once. Retirement and callback closure
472
+ # share this guard. Unregister alone cannot prevent an already-running
473
+ # callback from touching a reused FD.
80
474
  class SocketLifecycle
81
475
  def initialize(cancellation)
82
476
  @mutex = Mutex.new
83
- @socket = nil
477
+ @sockets = []
84
478
  @closed = false
85
479
  @retired = false
86
480
  @registration = cancellation&.on_cancel { close }
@@ -90,24 +484,30 @@ module ConnectRPC
90
484
  @mutex.synchronize do
91
485
  return if @retired
92
486
 
93
- @socket = socket
94
- close_socket if @closed
487
+ @sockets << socket
488
+ close_socket(socket) if @closed
95
489
  end
96
490
  end
97
491
 
492
+ # Drops an attempt the dialer has given up and closes itself.
493
+ def release(socket)
494
+ @mutex.synchronize { @sockets.delete(socket) }
495
+ nil
496
+ end
497
+
98
498
  def close
99
499
  @mutex.synchronize do
100
500
  return if @retired
101
501
 
102
502
  @closed = true
103
- close_socket
503
+ @sockets.each { |socket| close_socket(socket) }
104
504
  end
105
505
  end
106
506
 
107
507
  def retire
108
508
  @mutex.synchronize do
109
509
  @retired = true
110
- @socket = nil
510
+ @sockets = []
111
511
  end
112
512
  @registration&.unregister
113
513
  @registration = nil
@@ -115,32 +515,94 @@ module ConnectRPC
115
515
 
116
516
  private
117
517
 
118
- def close_socket
119
- @socket&.shutdown(Socket::SHUT_RDWR)
120
- @socket&.close
518
+ # Shutdown aborts a pending connect, waking the dialer's IO.select. A
519
+ # socket that never started connecting cannot shut down; it must
520
+ # still close.
521
+ def close_socket(socket)
522
+ begin
523
+ socket.shutdown(Socket::SHUT_RDWR)
524
+ rescue IOError, SystemCallError
525
+ nil
526
+ end
527
+ socket.close
121
528
  rescue IOError, SystemCallError
122
529
  nil
123
530
  end
124
531
  end
125
532
 
533
+ # proxy: :environment snapshots HTTP_PROXY, HTTPS_PROXY and NO_PROXY now.
534
+ # A String or URI proxies every request; nil connects directly.
535
+ def initialize(ca_file: nil, certificate_chain: nil, private_key: nil, proxy: :environment)
536
+ @tls_context = ClientTLS.context(ca_file: ca_file, certificate_chain: certificate_chain,
537
+ private_key: private_key)
538
+ @proxy_mode = { environment: "environment", nil => "direct" }.fetch(proxy, "explicit")
539
+ @proxy = Proxy.resolver(proxy)
540
+ fixed = @proxy.is_a?(Proxy::Static) ? @proxy.endpoint : nil
541
+ raise ArgumentError, "Unsupported proxy scheme", cause: nil if fixed && fixed.scheme != "http"
542
+ end
543
+
544
+ # Never shows proxy URLs, credentials or TLS material.
545
+ def inspect = "#<#{self.class} proxy=#{@proxy_mode}>"
546
+
126
547
  def call(request)
548
+ raise ArgumentError, "TLS options require an HTTPS origin" if @tls_context && request.url.scheme != "https"
549
+
127
550
  CallCancellation.with_request(request) { |outgoing| perform_call(outgoing) }
128
551
  end
129
552
 
130
553
  private
131
554
 
132
- def perform_call(request) # rubocop:disable Metrics/MethodLength
555
+ def perform_call(request) # rubocop:disable Metrics/MethodLength, Metrics/AbcSize
133
556
  deadline = request.deadline
134
557
  outgoing = prepare_request(request)
135
- http = connection(request.url, deadline)
558
+ proxy = proxy_for(request.url)
559
+ http = connection(request.url, deadline, proxy)
136
560
  http.cancellation = request.cancellation
137
561
  with_connection(http, deadline, request.cancellation) { exchange(http, request, outgoing) }
138
562
  rescue Net::OpenTimeout, Net::ReadTimeout, Net::WriteTimeout,
139
563
  SocketError, IOError, SystemCallError, Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError,
140
- OpenSSL::SSL::SSLError => e
564
+ OpenSSL::SSL::SSLError, ProxyFailure, Proxy::Unusable => e
565
+ e = forwarded_failure(e) if proxy && request.url.scheme == "http"
141
566
  request.lifecycle&.record_failure(e)
142
567
  check_request!(request)
143
- raise Error.new(:unavailable, "HTTP transport failed"), cause: nil
568
+ reason = failure_reason(e)
569
+ raise Error.new(:unavailable, reason ? "HTTP transport failed: #{reason}" : "HTTP transport failed"), cause: e
570
+ end
571
+
572
+ # A fixed, non-secret phrase naming what failed. These errors are local
573
+ # to the caller, so they keep the original exception as their cause.
574
+ def failure_reason(error) # rubocop:disable Metrics/MethodLength, Metrics/CyclomaticComplexity
575
+ case error
576
+ when ProxyFailure then error.message
577
+ when Proxy::Unusable then UNUSABLE_PROXY[error.reason]
578
+ when Errno::ECONNREFUSED then "connection refused"
579
+ when SocketError then "name resolution failed"
580
+ when Errno::EHOSTUNREACH, Errno::ENETUNREACH then "host unreachable"
581
+ when Net::OpenTimeout, Net::ReadTimeout, Net::WriteTimeout, Errno::ETIMEDOUT, IO::TimeoutError then "timed out"
582
+ when OpenSSL::SSL::SSLError
583
+ verification = ["certificate verify failed", "does not match the server certificate"]
584
+ verification.any? { |text| error.message.include?(text) } ? "TLS verification failed" : "TLS error"
585
+ when EOFError, Errno::ECONNRESET, Errno::EPIPE, Errno::ECONNABORTED then "connection closed"
586
+ when Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError then "malformed response"
587
+ end
588
+ end
589
+
590
+ # A forward proxy writes the response head of an http:// call, and the
591
+ # parser's messages quote it, so they may carry the proxy's URL or
592
+ # credentials.
593
+ def forwarded_failure(error)
594
+ case error
595
+ when Net::HTTPBadResponse, Net::HTTPHeaderSyntaxError then ProxyFailure.new("malformed response")
596
+ else error
597
+ end
598
+ end
599
+
600
+ # NetHTTP speaks only to http:// proxies; CONNECT carries https targets.
601
+ def proxy_for(url)
602
+ proxy = @proxy.for(url)
603
+ raise ProxyFailure, "unsupported proxy scheme", cause: nil if proxy && proxy.scheme != "http"
604
+
605
+ proxy
144
606
  end
145
607
 
146
608
  def check_request!(request)
@@ -154,17 +616,15 @@ module ConnectRPC
154
616
  outgoing
155
617
  end
156
618
 
157
- # Keep startup ownership and terminal retirement in one ensure.
158
- # rubocop:disable Metrics/MethodLength, Metrics/AbcSize, Metrics/CyclomaticComplexity
159
- def with_connection(http, deadline, cancellation = nil)
619
+ # Keep startup ownership and terminal retirement in one ensure. The
620
+ # watchdog starts before TCP so it also bounds proxy CONNECT and TLS.
621
+ def with_connection(http, deadline, cancellation = nil) # rubocop:disable Metrics/MethodLength, Metrics/CyclomaticComplexity
160
622
  sockets = SocketLifecycle.new(cancellation)
161
623
  http.socket_lifecycle = sockets
162
624
  cancellation&.check!
625
+ watchdog = Watchdog.new(sockets, deadline) if deadline
163
626
  http.start
164
- sockets.attach(http.instance_variable_get(:@socket).io.to_io)
165
627
  cancellation ? cancellation.check! : deadline&.check!
166
- # Pinned Net::HTTP exposes its BufferedIO; one call owns this raw socket.
167
- watchdog = Watchdog.new(http.instance_variable_get(:@socket).io.to_io, deadline) if deadline
168
628
  yield
169
629
  ensure
170
630
  watchdog&.stop
@@ -172,8 +632,6 @@ module ConnectRPC
172
632
  http.finish if http.started?
173
633
  end
174
634
 
175
- # rubocop:enable Metrics/MethodLength, Metrics/AbcSize, Metrics/CyclomaticComplexity
176
-
177
635
  def exchange(http, request, outgoing)
178
636
  result = nil
179
637
  http.request(outgoing) do |response|
@@ -191,12 +649,15 @@ module ConnectRPC
191
649
  raise Error.new(:resource_exhausted, "Response exceeds byte limit") if length && length > limit
192
650
  end
193
651
 
652
+ # The wire carries exactly the request's user-agent values, never
653
+ # Net::HTTP's default "Ruby".
194
654
  def outgoing_request(request) # rubocop:disable Metrics/MethodLength, Metrics/AbcSize
195
655
  headers = request.headers.merge("connection" => ["close"])
196
656
  accept = request.headers.fetch("accept-encoding", ["identity"]).join(", ")
197
657
  has_body = request.http_method != "GET"
198
658
  outgoing = Net::HTTPGenericRequest.new(request.http_method, has_body, true, request.url.request_uri,
199
659
  "accept-encoding" => accept)
660
+ outgoing.delete("user-agent")
200
661
  headers.each do |key, values|
201
662
  next if key == "accept-encoding"
202
663
 
@@ -219,13 +680,13 @@ module ConnectRPC
219
680
  body
220
681
  end
221
682
 
222
- def verify_tls!(http)
223
- http.verify_mode = OpenSSL::SSL::VERIFY_PEER
224
- http.verify_hostname = true
225
- end
226
-
227
- def connection(uri, deadline)
228
- http = Connection.new(uri.hostname, uri.port, nil)
683
+ # Net::HTTP sends absolute-form requests and Proxy-Authorization to an
684
+ # http:// target's proxy. An https:// target tunnels through CONNECT.
685
+ def connection(uri, deadline, proxy = nil) # rubocop:disable Metrics/AbcSize
686
+ forward = proxy if uri.scheme == "http"
687
+ http = Connection.new(uri.hostname, uri.port, forward&.host, forward&.port, forward&.user, forward&.password)
688
+ http.tunnel = proxy if uri.scheme == "https"
689
+ http.tls_context = @tls_context
229
690
  http.deadline = deadline
230
691
  http.use_ssl = uri.scheme == "https"
231
692
  configure_http(http, deadline)
@@ -233,7 +694,6 @@ module ConnectRPC
233
694
  end
234
695
 
235
696
  def configure_http(http, deadline)
236
- verify_tls!(http) if http.use_ssl?
237
697
  native_timeout = deadline ? deadline.native_timeout : Deadline::MAX_NATIVE_WAIT
238
698
  http.open_timeout = native_timeout
239
699
  http.read_timeout = native_timeout