connectrpc-hyper 0.3.0-aarch64-mingw-ucrt

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.
@@ -0,0 +1,79 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ConnectRPC
4
+ module Hyper
5
+ module Native
6
+ # Raised by the extension. `kind` classifies the failure; `reset_code` is
7
+ # the HTTP/2 error code, if any, of a stream reset or connection error,
8
+ # the peer's or h2's own; `errno` is the OS error, if any. Messages never
9
+ # carry paths or key material.
10
+ class Failure < StandardError
11
+ attr_reader :kind, :reset_code, :errno
12
+
13
+ def initialize(message, kind, reset_code, errno)
14
+ super(message)
15
+ @kind = kind
16
+ @reset_code = reset_code
17
+ @errno = errno
18
+ end
19
+ end
20
+ end
21
+
22
+ # Fixed, non-secret phrases naming what failed (core's transport phrases).
23
+ # Local failures keep the native failure as their cause.
24
+ module Errors
25
+ CLOSED = "HTTP transport admission is closed"
26
+ PHRASES = {
27
+ dns: "name resolution failed", refused: "connection refused", unreachable: "host unreachable",
28
+ connect: "connection failed", connect_timeout: "timed out", timeout: "timed out",
29
+ tls_verify: "TLS verification failed", tls: "TLS error", closed: "connection closed",
30
+ goaway: "connection closed", shutdown: "connection closed", protocol: "malformed response",
31
+ alpn: "ALPN negotiation failed", reset: "stream reset",
32
+ # Core NetHTTP's proxy phrases. Proxy reply bytes never reach them.
33
+ proxy_auth: "proxy authentication failed", proxy_refused: "proxy tunnel refused",
34
+ proxy_failed: "proxy tunnel failed", proxy_timeout: "proxy tunnel timed out",
35
+ proxy_scheme: "unsupported proxy scheme", proxy_address: "invalid proxy address",
36
+ proxy_cgi: "proxy refused in CGI environment"
37
+ }.freeze
38
+ # The Async transport's mapping of server RST_STREAM codes for gRPC.
39
+ GRPC_RESET = { 3 => :resource_exhausted, 7 => :unavailable, 8 => :canceled, 11 => :resource_exhausted,
40
+ 12 => :permission_denied }.freeze
41
+
42
+ # A proxy the call must not use, raised before any socket opens.
43
+ def self.proxy(kind) = Native::Failure.new(PHRASES.fetch(kind), kind, nil, nil)
44
+
45
+ def self.transport(kind)
46
+ reason = PHRASES[kind]
47
+ Error.new(:unavailable, reason ? "HTTP transport failed: #{reason}" : "HTTP transport failed")
48
+ end
49
+
50
+ # Maps a native failure; deadline and cancellation are the caller's
51
+ # arbiter's to raise first.
52
+ def self.translate(failure, grpc:)
53
+ case failure.kind
54
+ when :admission then raise Error.new(:unavailable, CLOSED), cause: nil
55
+ when :response_limit then raise Error.new(:resource_exhausted, "Response exceeds byte limit"), cause: nil
56
+ when :field_limit then raise Error.new(:resource_exhausted, "gRPC field block exceeds byte limit"), cause: nil
57
+ when :reset
58
+ if grpc
59
+ raise Error.new(GRPC_RESET.fetch(failure.reset_code, :internal), "HTTP/2 stream reset"), cause: failure
60
+ end
61
+ end
62
+ raise transport(failure.kind), cause: failure
63
+ end
64
+
65
+ # Runs one native operation for a request: cancellation and deadline
66
+ # first, then lifecycle failure recording (a per-wait timeout included,
67
+ # as the Async transport records it), then the fixed phrase.
68
+ def self.native(request, grpc:)
69
+ yield
70
+ rescue Native::Failure => e
71
+ request.cancellation ? request.cancellation.check! : request.deadline&.check!
72
+ request.lifecycle&.record_failure(e)
73
+ raise Error.new(:unavailable, "HTTP transport failed: timed out"), cause: nil if e.kind == :timeout
74
+
75
+ translate(e, grpc: grpc)
76
+ end
77
+ end
78
+ end
79
+ end
@@ -0,0 +1,89 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ConnectRPC
4
+ module Hyper
5
+ # One streaming call for core's exchange SPI. Operations run on the
6
+ # calling thread and block in Rust with the GVL released; each wait is
7
+ # bounded by the call deadline and the per-wait timeout.
8
+ class Exchange
9
+ def initialize(native, request, grpc:)
10
+ @native = native
11
+ @request = request
12
+ @grpc = grpc
13
+ @head = nil
14
+ @trailers = nil
15
+ @read_eof = false
16
+ end
17
+
18
+ def response_head(timeout: nil)
19
+ @response_head ||= begin
20
+ status, headers, end_stream = wait(timeout) { |limit| @native.head(limit) }
21
+ if @grpc
22
+ # h2 accepts blocks up to 16 MiB; core's field limit applies here.
23
+ GRPCProtocol.check_fields!(headers)
24
+ GRPCHead.new(status: status, headers: headers, end_stream: end_stream)
25
+ else
26
+ StreamHead.new(status: status, headers: headers)
27
+ end
28
+ end
29
+ end
30
+
31
+ def read(length, timeout: nil)
32
+ bytes = wait(timeout) { |limit| @native.read(length, limit) }
33
+ receive_trailers if bytes.nil? && @grpc
34
+ bytes
35
+ end
36
+
37
+ def write(bytes)
38
+ wait(nil) { |limit| @native.write(bytes, limit) }
39
+ nil
40
+ end
41
+
42
+ def close_send
43
+ @native.close_send
44
+ nil
45
+ end
46
+
47
+ def response_trailers
48
+ raise StreamStateError, "Trailers require response EOF" unless @read_eof
49
+
50
+ @trailers
51
+ end
52
+
53
+ def finish(timeout: nil)
54
+ wait(timeout) { |limit| @native.finish(limit) }
55
+ return unless @grpc
56
+
57
+ receive_trailers
58
+ head = @response_head
59
+ raise Error.new(:internal, "Missing final gRPC HEADERS"), cause: nil unless head&.end_stream || @trailers
60
+
61
+ nil
62
+ end
63
+
64
+ def abort
65
+ @native.abort
66
+ nil
67
+ end
68
+
69
+ private
70
+
71
+ def receive_trailers
72
+ return if @read_eof
73
+
74
+ trailers = @native.trailers
75
+ GRPCProtocol.check_fields!(trailers) if trailers
76
+ @trailers = trailers
77
+ @read_eof = true
78
+ end
79
+
80
+ def wait(timeout)
81
+ Errors.native(@request, grpc: @grpc) do
82
+ @request.cancellation ? @request.cancellation.check! : @request.deadline&.check!
83
+ remaining = @request.deadline&.remaining
84
+ yield [timeout, remaining].compact.min
85
+ end
86
+ end
87
+ end
88
+ end
89
+ end
@@ -0,0 +1,110 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "openssl"
4
+ require "securerandom"
5
+
6
+ module ConnectRPC
7
+ module Hyper
8
+ # Validates TLS client inputs as core NetHTTP's private ClientTLS does:
9
+ # an appended `ca_file`, a `certificate_chain` Array of PEM strings (leaf
10
+ # first) and a `private_key` PEM string. Rust receives DER.
11
+ module TLS
12
+ CERTIFICATE = %r{\A-----BEGIN CERTIFICATE-----\s+[A-Za-z0-9+/=\s]+-----END CERTIFICATE-----\z}
13
+ PRIVATE_KEY = %r{
14
+ \A-----BEGIN\ (RSA\ PRIVATE\ KEY|EC\ PRIVATE\ KEY|PRIVATE\ KEY)-----
15
+ \s+[A-Za-z0-9+/=\s]+-----END\ \1-----\z
16
+ }x
17
+ CERTIFICATE_BLOCK = /
18
+ -----BEGIN\ (?:X509\ |TRUSTED\ )?CERTIFICATE-----.*?-----END\ (?:X509\ |TRUSTED\ )?CERTIFICATE-----
19
+ /mx
20
+
21
+ # Names the input that failed validation, never its value.
22
+ class InvalidInput < ArgumentError
23
+ attr_reader :input
24
+
25
+ def initialize(input)
26
+ @input = input
27
+ super("Invalid #{input}")
28
+ end
29
+ end
30
+
31
+ def self.certificate(pem)
32
+ raise ArgumentError unless pem.is_a?(String) && CERTIFICATE.match?(pem.strip)
33
+
34
+ certificates = OpenSSL::X509::Certificate.load(pem.dup)
35
+ raise ArgumentError unless certificates.size == 1
36
+
37
+ certificate = certificates.first
38
+ raise ArgumentError unless certificate.not_before <= Time.now && certificate.not_after > Time.now
39
+
40
+ certificate
41
+ end
42
+
43
+ def self.input(name)
44
+ yield
45
+ rescue InvalidInput
46
+ raise
47
+ rescue StandardError
48
+ raise InvalidInput.new(name), cause: nil
49
+ end
50
+
51
+ def self.identity(chain, pem) # rubocop:disable Metrics/MethodLength, Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
52
+ certificates = input(:certificate_chain) do
53
+ raise ArgumentError unless chain.is_a?(Array) && !chain.empty?
54
+
55
+ chain.map { |element| certificate(element) }
56
+ end
57
+ key = input(:private_key) do
58
+ raise ArgumentError unless pem.is_a?(String) && PRIVATE_KEY.match?(pem.strip)
59
+
60
+ OpenSSL::PKey.read(pem.dup) { nil }
61
+ end
62
+ input(:private_key) do
63
+ digest = %w[ED25519 ED448].include?(key.oid) ? nil : "SHA256"
64
+ challenge = SecureRandom.random_bytes(32)
65
+ signature = key.sign(digest, challenge)
66
+ raise ArgumentError unless certificates.first.public_key.verify(digest, signature, challenge)
67
+ end
68
+ input(:certificate_chain) do
69
+ certificates.each_cons(2) do |child, issuer|
70
+ raise ArgumentError unless child.issuer == issuer.subject && child.verify(issuer.public_key)
71
+ end
72
+ end
73
+ [certificates, key]
74
+ end
75
+
76
+ # NetHTTP's check: the file must load into an OpenSSL store. The
77
+ # certificates OpenSSL would trust are appended (trust settings of a
78
+ # TRUSTED CERTIFICATE block are not kept); CRLs and keys are skipped.
79
+ def self.ca_file(path)
80
+ input(:ca_file) do
81
+ OpenSSL::X509::Store.new.add_file(path)
82
+ File.binread(path).scan(CERTIFICATE_BLOCK).map do |block|
83
+ OpenSSL::X509::Certificate.new(block.gsub(/(BEGIN|END) (?:X509 |TRUSTED )/, '\1 ')).to_der
84
+ end
85
+ end
86
+ end
87
+
88
+ # [chain DERs, key PKCS#8 DER], or [nil, nil] without an identity. As in
89
+ # NetHTTP, a false option counts as given but adds nothing.
90
+ def self.client_identity(chain, pem)
91
+ return [nil, nil] unless chain || pem
92
+
93
+ certificates, key = identity(chain, pem)
94
+ [certificates.map(&:to_der), key.private_to_der]
95
+ end
96
+
97
+ # [ca_file DERs, chain DERs, key PKCS#8 DER], or nil without TLS options.
98
+ # Errors name only the input: never paths or key material, and no cause.
99
+ def self.inputs(ca_file:, certificate_chain:, private_key:)
100
+ return if [ca_file, certificate_chain, private_key].all?(&:nil?)
101
+
102
+ [ca_file ? self.ca_file(ca_file) : [], *client_identity(certificate_chain, private_key)]
103
+ rescue InvalidInput => e
104
+ raise ArgumentError, "Invalid TLS client configuration: #{e.input}", cause: nil
105
+ rescue StandardError
106
+ raise ArgumentError, "Invalid TLS client configuration", cause: nil
107
+ end
108
+ end
109
+ end
110
+ end
@@ -0,0 +1,369 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ConnectRPC
4
+ module Hyper
5
+ # Connect and native gRPC calls of every shape from any Ruby thread,
6
+ # without an Async reactor. One shared HTTP/2 connection per origin serves
7
+ # every thread, answers PINGs and GOAWAY while idle and is replaced after a
8
+ # server restart. Construction validates options and starts no thread or
9
+ # socket; a forked child builds its own native driver on first use.
10
+ class Transport # rubocop:disable Metrics/ClassLength
11
+ STREAMING = %i[server_stream client_stream bidi_stream].freeze
12
+ HTTP1_STREAMING = %i[server_stream client_stream].freeze
13
+ GRPC = %i[unary server_stream client_stream bidi_stream].freeze
14
+ NO_GRPC = [].freeze
15
+ CONNECTIONS = %i[pooled per_call].freeze
16
+ # Go net/http bounds a proxy CONNECT exchange by one minute and its
17
+ # response head by MaxResponseHeaderBytes' default, as core NetHTTP does.
18
+ TUNNEL_TIMEOUT = 60
19
+ MAX_TUNNEL_HEAD = 10 * 1024 * 1024
20
+ UNUSABLE_PROXY = { cgi: :proxy_cgi, invalid_address: :proxy_address }.freeze
21
+ private_constant :STREAMING, :HTTP1_STREAMING, :GRPC, :NO_GRPC, :CONNECTIONS, :TUNNEL_TIMEOUT,
22
+ :MAX_TUNNEL_HEAD, :UNUSABLE_PROXY
23
+
24
+ # proxy: :environment snapshots HTTP_PROXY, HTTPS_PROXY and NO_PROXY now
25
+ # (Go net/http rules, through core's ConnectRPC::Proxy). A String or URI
26
+ # proxies every request; nil connects directly. Only http:// proxies.
27
+ # rubocop:disable-next Metrics/MethodLength
28
+ def initialize(connections: :pooled, idle_timeout: 1800, keepalive: nil, http2: true, connect_timeout: 10,
29
+ ca_file: nil, certificate_chain: nil, private_key: nil, proxy: :environment)
30
+ raise ArgumentError, "connections must be :pooled or :per_call" unless CONNECTIONS.include?(connections)
31
+ raise ArgumentError, "keepalive must be a Keepalive or nil" unless keepalive.nil? || keepalive.is_a?(Keepalive)
32
+ raise ArgumentError, "http2 must be true or false" unless [true, false].include?(http2)
33
+
34
+ @connections = connections
35
+ @idle_timeout = optional_seconds(idle_timeout, "idle_timeout")
36
+ @connect_timeout = seconds(connect_timeout, "connect_timeout")
37
+ @keepalive = keepalive
38
+ @http2 = http2
39
+ @tls = TLS.inputs(ca_file: ca_file, certificate_chain: certificate_chain, private_key: private_key)
40
+ @proxy = proxy_resolver(proxy)
41
+ @lock = Mutex.new
42
+ @state = :open
43
+ # Building the driver imports the TLS identity into the provider, so
44
+ # an identity aws-lc-rs cannot use fails here. It starts nothing.
45
+ build_driver
46
+ end
47
+
48
+ # Never shows proxy URLs, credentials or TLS material.
49
+ def inspect
50
+ "#<#{self.class} connections=#{@connections} http2=#{@http2} tls=#{!@tls.nil?} proxy=#{proxy_mode} " \
51
+ "state=#{state}>"
52
+ end
53
+
54
+ def streaming_capabilities = @http2 ? STREAMING : HTTP1_STREAMING
55
+ def grpc_capabilities = @http2 ? GRPC : NO_GRPC
56
+
57
+ def call(request)
58
+ check_origin!(request.url)
59
+ CallCancellation.with_request(request) { |outgoing| perform_call(outgoing) }
60
+ end
61
+
62
+ def open_stream(request, &)
63
+ raise ArgumentError, "A streaming block is required" unless block_given?
64
+
65
+ check_origin!(request.url)
66
+ CallCancellation.with_request(request) { |outgoing| perform_stream(outgoing, grpc: false, &) }
67
+ end
68
+
69
+ def open_grpc_stream(request, &)
70
+ raise ArgumentError, "A gRPC block is required" unless block_given?
71
+
72
+ check_origin!(request.url)
73
+ CallCancellation.with_request(request) { |outgoing| perform_stream(outgoing, grpc: true, &) }
74
+ end
75
+
76
+ # Stops admission (later calls fail `unavailable` with the closed
77
+ # phrase), lets in-flight calls finish within `grace`, then aborts the
78
+ # rest and waits for every owned connection task. True when everything
79
+ # drained; false after forced teardown. Repeated and concurrent calls
80
+ # share the first call's grace and outcome.
81
+ def close(grace: 5)
82
+ unless grace.is_a?(Numeric) && grace.real? && grace.finite? && grace >= 0
83
+ raise ArgumentError, "grace must be finite nonnegative seconds"
84
+ end
85
+
86
+ return close_on_helper(grace.to_f) if Fiber.scheduler && !Fiber.current.blocking?
87
+
88
+ Thread.handle_interrupt(Object => :never) { close_here(grace.to_f) }
89
+ end
90
+
91
+ private
92
+
93
+ # Core NetHTTP's validation: an explicit proxy must be http://.
94
+ def proxy_resolver(option)
95
+ resolver = Proxy.resolver(option)
96
+ fixed = resolver.is_a?(Proxy::Static) ? resolver.endpoint : nil
97
+ raise ArgumentError, "Unsupported proxy scheme", cause: nil if fixed && fixed.scheme != "http"
98
+
99
+ resolver
100
+ end
101
+
102
+ def proxy_mode
103
+ return "environment" unless @proxy.is_a?(Proxy::Static)
104
+
105
+ @proxy.endpoint ? "explicit" : "direct"
106
+ end
107
+
108
+ def optional_seconds(value, name)
109
+ return if value.nil?
110
+
111
+ seconds(value, name, nil_allowed: true)
112
+ end
113
+
114
+ # connectrpc-async's rule (ConnectRPC::Async::Internal.seconds).
115
+ def seconds(value, name, nil_allowed: false)
116
+ return value if value.is_a?(Numeric) && value.real? && value.finite? && value.positive?
117
+
118
+ raise ArgumentError, "#{name} must be finite positive seconds#{' or nil' if nil_allowed}"
119
+ end
120
+
121
+ # Every closer in this process, concurrent ones included, waits for
122
+ # native close: it starts teardown once, with the grace the first
123
+ # closer reserved, gives every closer its published outcome and holds an
124
+ # interrupt or a fiber scheduler's cancellation until then. The lock
125
+ # covers only the state and the driver handoff.
126
+ #
127
+ # On a fiber scheduler's non-blocking fiber, native close runs on a
128
+ # helper thread joined with Thread#value, which yields to the
129
+ # scheduler: the wait takes neither the reactor thread nor a worker of
130
+ # the scheduler's pool, so sibling tasks keep running and can drain.
131
+ # The closer waits for the lock as a non-blocking fiber with no
132
+ # interrupt mask: Thread.new copies the caller's mask into threads that
133
+ # sibling fibers start, and Mutex#unlock wakes one waiter, which cannot
134
+ # run while a blocking wait sleeps the reactor thread. Under the lock,
135
+ # where nothing yields, interrupts are deferred across the reservation,
136
+ # Thread.new and storing the helper, so none separates them, and the
137
+ # helper starts with interrupts deferred. An exception raised into the
138
+ # closer outside that section (async's Task#stop, Thread#raise) is
139
+ # held, the first one winning, and the closer retries; once the
140
+ # transport is closing, reserving again returns the same driver and
141
+ # grace. The helper records the outcome itself, so a closer that is
142
+ # killed (Fiber#kill, Thread#kill) still leaves it recorded.
143
+ # rubocop:disable-next Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
144
+ def close_on_helper(grace) # rubocop:disable Metrics/MethodLength
145
+ helper = held = recorded = nil
146
+ failures = 0
147
+ begin
148
+ unless helper
149
+ recorded = reserve_close(grace) { |*reserved| helper = start_close_helper(*reserved) || reserved }
150
+ end
151
+ outcome, error =
152
+ case helper
153
+ when Thread then helper.value
154
+ # No thread could start: wait on this thread, outside the lock.
155
+ when Array then await_teardown(*helper)
156
+ else [recorded, nil]
157
+ end
158
+ rescue Exception => e # rubocop:disable Lint/RescueException
159
+ held ||= e
160
+ # Keep joining a running helper. Otherwise retry once: each
161
+ # interrupt is raised once, so a second failure with no helper
162
+ # running counts as deterministic and is raised instead of looping.
163
+ retry if helper.is_a?(Thread) ? helper.alive? : (failures += 1) < 2
164
+ end
165
+ raise held if held
166
+ raise error if error
167
+
168
+ # A helper that was killed, or is gone after fork, returns nothing.
169
+ outcome.nil? ? recorded_close : outcome
170
+ end
171
+
172
+ # The helper thread, or nil when no thread could start. Runs under the
173
+ # lock with interrupts deferred, so a ThreadError here is Thread.new's.
174
+ def start_close_helper(driver, grace)
175
+ Thread.new do
176
+ Thread.current.report_on_exception = false
177
+ Thread.handle_interrupt(Object => :never) { await_teardown(driver, grace) }
178
+ end
179
+ rescue ThreadError
180
+ nil
181
+ end
182
+
183
+ # Thread interrupts are deferred: native close holds the thread until
184
+ # teardown published its outcome.
185
+ def close_here(grace)
186
+ reserved = reserve_close(grace)
187
+ return reserved unless reserved.is_a?(Array)
188
+
189
+ outcome, error = await_teardown(*reserved)
190
+ raise error if error
191
+
192
+ outcome
193
+ end
194
+
195
+ # [driver, reserved grace] to wait on, or what the block returns given
196
+ # them, or the recorded outcome when there is nothing to wait for. The
197
+ # first closer reserves its grace, so a later one that reaches native
198
+ # close first starts teardown with it. Interrupts are deferred from the
199
+ # reservation through the block, which must neither yield nor wait.
200
+ def reserve_close(grace) # rubocop:disable Metrics/MethodLength
201
+ @lock.synchronize do
202
+ Thread.handle_interrupt(Object => :never) do
203
+ inherit_fork_state
204
+ next @close_outcome if @state == :closed
205
+ # A forked child that never built its own driver has nothing to drain.
206
+ next finish_close(true) unless @driver_pid == Process.pid
207
+
208
+ if @state == :open
209
+ @close_grace = grace
210
+ @close_pid = Process.pid
211
+ @state = :closing
212
+ end
213
+ block_given? ? yield(@driver, @close_grace) : [@driver, @close_grace]
214
+ end
215
+ end
216
+ end
217
+
218
+ # [outcome, nil] or [nil, the exception native close raised]. Native
219
+ # close raises only after teardown published its outcome.
220
+ def await_teardown(driver, grace)
221
+ outcome = nil
222
+ begin
223
+ outcome = driver.close(grace)
224
+ [outcome, nil]
225
+ rescue Exception => e # rubocop:disable Lint/RescueException
226
+ [nil, e]
227
+ ensure
228
+ record_close(outcome.nil? ? driver.close_outcome : outcome)
229
+ end
230
+ end
231
+
232
+ # Records a published outcome. A closer that leaves before publication
233
+ # records nothing and leaves the transport closing, so the next closer
234
+ # waits on the same teardown.
235
+ def record_close(outcome)
236
+ @lock.synchronize { finish_close(outcome) } unless outcome.nil?
237
+ end
238
+
239
+ # The published outcome, or nil while teardown has not published one.
240
+ def recorded_close
241
+ @lock.synchronize do
242
+ inherit_fork_state
243
+ @close_outcome if @state == :closed
244
+ end
245
+ end
246
+
247
+ def finish_close(outcome)
248
+ @state = :closed
249
+ @close_outcome = outcome
250
+ end
251
+
252
+ # A child that inherits another process's pending close has no driver
253
+ # to drain; a transport closed before fork stays closed.
254
+ def inherit_fork_state
255
+ finish_close(true) if @state == :closing && @close_pid != Process.pid
256
+ end
257
+
258
+ def state
259
+ @state == :closing && @close_pid != Process.pid ? :closed : @state
260
+ end
261
+
262
+ # The driver for this process: a forked child never touches its
263
+ # parent's native state.
264
+ def driver
265
+ @lock.synchronize do
266
+ raise Error.new(:unavailable, Errors::CLOSED), cause: nil unless state == :open
267
+
268
+ build_driver unless @driver_pid == Process.pid
269
+ @driver
270
+ end
271
+ end
272
+
273
+ def build_driver
274
+ roots, chain, key = @tls
275
+ @driver = Native::Driver.new(@connections == :pooled, @http2, @idle_timeout&.to_f, @connect_timeout.to_f,
276
+ native_keepalive, roots || [], chain, key, tunnel_limits)
277
+ @driver_pid = Process.pid
278
+ rescue Native::Failure => e
279
+ raise unless e.kind == :tls_config
280
+
281
+ raise ArgumentError, "Invalid TLS client configuration: #{e.message}", cause: nil
282
+ end
283
+
284
+ def native_keepalive
285
+ @keepalive && [@keepalive.time.to_f, @keepalive.timeout.to_f, @keepalive.permit_without_calls]
286
+ end
287
+
288
+ # [CONNECT exchange seconds, response head bytes].
289
+ def tunnel_limits = [TUNNEL_TIMEOUT.to_f, MAX_TUNNEL_HEAD]
290
+
291
+ def check_request!(request)
292
+ request.cancellation ? request.cancellation.check! : request.deadline&.check!
293
+ end
294
+
295
+ def check_origin!(url)
296
+ return if url.scheme == "https" || @tls.nil?
297
+
298
+ raise ArgumentError, "TLS options require an HTTPS origin"
299
+ end
300
+
301
+ # [host, port, Proxy-Authorization or nil] for the request's proxy, or
302
+ # nil for a direct connection. An unusable environment proxy fails the
303
+ # call before any socket opens; it never falls back to a direct one.
304
+ def proxy_route(url)
305
+ endpoint = begin
306
+ @proxy.for(url)
307
+ rescue Proxy::Unusable => e
308
+ raise Errors.proxy(UNUSABLE_PROXY.fetch(e.reason)), cause: nil
309
+ end
310
+ return unless endpoint
311
+ raise Errors.proxy(:proxy_scheme), cause: nil unless endpoint.scheme == "http"
312
+
313
+ credentials = "Basic #{["#{endpoint.user}:#{endpoint.password}"].pack('m0')}" if endpoint.user
314
+ [endpoint.host, endpoint.port, credentials]
315
+ end
316
+
317
+ def fields(headers)
318
+ headers.flat_map { |name, values| values.map { |value| [name, value.to_s] } }
319
+ end
320
+
321
+ # The registration exists before the first native wait, so a token
322
+ # cancels resolution, connect, TLS and waiting behind another dial.
323
+ def with_cancel(request)
324
+ cancel = Native::Cancel.new
325
+ registration = request.cancellation&.on_cancel { cancel.fire }
326
+ begin
327
+ yield cancel
328
+ ensure
329
+ registration&.unregister
330
+ end
331
+ end
332
+
333
+ def perform_call(request) # rubocop:disable Metrics/AbcSize, Metrics/MethodLength
334
+ check_request!(request)
335
+ native = driver
336
+ with_cancel(request) do |cancel|
337
+ status, headers, body = Errors.native(request, grpc: false) do
338
+ native.unary(request.http_method, request.url.to_s, fields(request.headers),
339
+ request.http_method == "GET" ? nil : request.body, request.response_limit,
340
+ request.deadline ? :connect : nil, request.deadline&.remaining, cancel,
341
+ proxy_route(request.url))
342
+ end
343
+ TransportResponse.new(status: status, headers: headers, body: body)
344
+ end
345
+ end
346
+
347
+ def perform_stream(request, grpc:) # rubocop:disable Metrics/AbcSize, Metrics/MethodLength
348
+ check_request!(request)
349
+ native = driver
350
+ with_cancel(request) do |cancel|
351
+ call = nil
352
+ begin
353
+ call = Errors.native(request, grpc: grpc) do
354
+ native.open(request.url.to_s, fields(request.headers), (if request.deadline
355
+ grpc ? :grpc : :connect
356
+ end),
357
+ request.deadline&.remaining, grpc, @http2, cancel, proxy_route(request.url))
358
+ end
359
+ yield Exchange.new(call, request, grpc: grpc)
360
+ ensure
361
+ # ensure, not rescue: Thread#kill runs ensure blocks only. abort
362
+ # never waits and does nothing after a finished exchange.
363
+ Thread.handle_interrupt(Object => :never) { call&.abort }
364
+ end
365
+ end
366
+ end
367
+ end
368
+ end
369
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module ConnectRPC
4
+ module Hyper
5
+ VERSION = "0.3.0" # x-release-please-version
6
+ end
7
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "connectrpc"
4
+ require "connectrpc/proxy"
5
+ require_relative "hyper/version"
6
+ begin
7
+ # Platform gems ship one extension per Ruby minor.
8
+ require_relative "hyper/#{RUBY_VERSION[/\A\d+\.\d+/]}/connectrpc_hyper"
9
+ rescue LoadError
10
+ # The source gem compiles one extension at install time.
11
+ require_relative "hyper/connectrpc_hyper"
12
+ end
13
+
14
+ module ConnectRPC
15
+ # Explicit, optional reactor-free client transport. A Rust extension (hyper,
16
+ # h2, rustls, tokio) owns connections, HTTP/2 streams and blocking waits;
17
+ # Ruby owns protocol logic, deadlines, cancellation and error phrases.
18
+ module Hyper
19
+ end
20
+ end
21
+
22
+ require_relative "hyper/errors"
23
+ require_relative "hyper/tls"
24
+ require_relative "hyper/exchange"
25
+ require_relative "hyper/transport"
26
+
27
+ ConnectRPC::Hyper.send(:private_constant, :Native, :Errors, :TLS, :Exchange)