aws-sdk-http-async 0.1.0 → 0.1.1

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.
@@ -1,5 +1,7 @@
1
1
  require 'async/http'
2
+ require 'async/condition'
2
3
  require 'async/http/proxy'
4
+ require 'async/semaphore'
3
5
  require 'async/aws/errors'
4
6
  require 'base64'
5
7
  require 'digest'
@@ -26,15 +28,244 @@ module Async
26
28
  end
27
29
  end
28
30
 
29
- Entry = Struct.new(:client, :reactor_ref, :inflight)
31
+ @default_mutex = Mutex.new
32
+ @default = nil
33
+
34
+ # Process-wide cache used by every handler that has no explicit cache
35
+ # (`async_http_client_cache` or `Handler.new(client_cache:)`). Seahorse
36
+ # builds a new handler per API call, so only a shared cache lets calls
37
+ # reuse an `Async::HTTP::Client` (and its connections).
38
+ #
39
+ # @return [Async::Aws::ClientCache]
40
+ def self.default
41
+ return @default if @default
42
+
43
+ @default_mutex.synchronize { @default ||= new }
44
+ end
45
+
46
+ Entry = Struct.new(:client, :reactor_ref, :inflight, :limiter, :unused)
47
+
48
+ # WebMock's `Async::HTTP::Client` wrapper refuses to hand out its pool
49
+ # while real connections are disabled, with an error that is not a
50
+ # `StandardError`.
51
+ #
52
+ # @api private
53
+ # @param error [Exception]
54
+ # @return [Boolean]
55
+ def self.pool_refused?(error)
56
+ error.class.name == 'WebMock::NetConnectNotAllowedError'
57
+ end
58
+
59
+ # The deadline of `clear!(timeout:)`, kept apart from a caller's own timeout.
60
+ CloseDeadline = Class.new(Async::TimeoutError)
61
+ private_constant :CloseDeadline
62
+
63
+ # Retires pooled connections that went unused for `timeout` seconds, like
64
+ # the SDK's Net::HTTP pool does for `http_idle_timeout`. async-pool expires
65
+ # nothing by itself, and its checkout probe only notices connections the
66
+ # peer closed, not flows a NAT gateway or firewall dropped silently.
67
+ #
68
+ # Runs in the pool's transient gardener task. A connection is retired
69
+ # after it was seen unused, with the same request count, on two
70
+ # consecutive checks, so after `timeout` to `2 * timeout` seconds idle.
71
+ class IdlePolicy
72
+ # @param timeout [Numeric] seconds
73
+ # @return [void]
74
+ def initialize(timeout)
75
+ @timeout = timeout
76
+ end
77
+
78
+ # @param pool [Async::Pool::Controller]
79
+ # @return [void] once the pool is empty; the gardener calls again after the next release
80
+ def call(pool)
81
+ idle = {}.compare_by_identity
82
+ until pool.resources.empty?
83
+ sleep(@timeout)
84
+ previous = idle
85
+ idle = {}.compare_by_identity
86
+ pool.resources.each { |connection, usage| idle[connection] = connection.count if usage.zero? }
87
+ idle.each_key do |connection|
88
+ # Checked right before retiring: closing a connection may switch
89
+ # fibers, and another one may serve a request meanwhile.
90
+ pool.retire(connection) if previous[connection] == connection.count && pool.resources[connection]&.zero?
91
+ end
92
+ end
93
+ end
94
+ end
95
+
96
+ # The target endpoint of a proxied client. Every CONNECT tunnel runs in a
97
+ # task of its own below a transient task at the root of the reactor, not
98
+ # below the request that happened to open it: stopping that request leaves
99
+ # the pooled tunnel intact, and an open tunnel does not keep the reactor
100
+ # alive once its other tasks are done.
101
+ class TunnelEndpoint < Async::HTTP::Endpoint
102
+ # An endpoint that is already connected: lets
103
+ # `Async::HTTP::Endpoint#build_endpoint` put TLS on top of an open tunnel.
104
+ Tunnel = Struct.new(:connect)
105
+
106
+ # @param endpoint [Async::HTTP::Endpoint] the target
107
+ # @param proxy [Async::HTTP::Proxy]
108
+ # @return [void]
109
+ def initialize(endpoint, proxy)
110
+ super(endpoint.url, **endpoint.options)
111
+ @proxy = proxy
112
+ @tunnels = nil
113
+ @closed = false
114
+ @pool = nil
115
+ @connecting = 0
116
+ @connected = Async::Condition.new
117
+ @cut = 0
118
+ end
119
+
120
+ # @return [#call, nil] returns the pool of the client on top of this
121
+ # endpoint, or nil while that pool cannot be inspected
122
+ attr_writer :pool
123
+
124
+ # @return [Integer] how many tunnels were stopped while the connection
125
+ # on top of them was open, and so possibly under a request
126
+ attr_reader :cut
127
+
128
+ # Opens a tunnel to the target, including the TLS handshake for an
129
+ # https target. A caller that is stopped or times out while waiting
130
+ # takes its unfinished tunnel down with it.
131
+ #
132
+ # @return [IO] the socket to the target
133
+ # @raise [IOError] if the endpoint is closed
134
+ def connect
135
+ parent = tunnels
136
+ # Checked last: starting the parent task lets other tasks run.
137
+ raise IOError, 'proxy client is closed' if @closed
138
+
139
+ opened = Async::Promise.new
140
+ tunnel = nil
141
+ @connecting += 1
142
+ # Assigned inside the block: `async` runs the tunnel until it first
143
+ # waits, and the caller can be cancelled before `async` returns.
144
+ parent.async(annotation: 'aws-sdk-http-async proxy tunnel') do |task|
145
+ tunnel = task
146
+ run_tunnel(opened, task)
147
+ end
148
+ socket = opened.wait
149
+ ensure
150
+ if opened
151
+ @connecting -= 1
152
+ @connected.signal
153
+ end
154
+ tunnel&.cancel unless socket
155
+ end
156
+
157
+ # Closes every tunnel, also those under a request in flight, and
158
+ # refuses new ones.
159
+ #
160
+ # @return [void]
161
+ def close
162
+ @closed = true
163
+ # A task can only be stopped from inside its reactor. Elsewhere the
164
+ # tunnels end once the connections on top of them are closed.
165
+ @tunnels.cancel if @tunnels && Async::Task.current?&.reactor.equal?(@tunnels.reactor)
166
+ end
167
+
168
+ private
169
+
170
+ # Started with the first tunnel rather than with the endpoint, because
171
+ # starting a task lets other tasks run and the cache builds clients
172
+ # between two lookups.
173
+ def tunnels
174
+ # Not only `#close` ends the parent task: `Scheduler#stop` (SIGINT)
175
+ # cancels it too, and calls made during shutdown need a new one. A
176
+ # cancelled task still runs while it stops its tunnels, and would
177
+ # stop a new one with them.
178
+ return @tunnels if @closed || (@tunnels&.running? && !@tunnels.cancelled?)
179
+
180
+ Async::Task.run(
181
+ Async::Task.current.reactor,
182
+ transient: true,
183
+ annotation: 'aws-sdk-http-async proxy tunnels',
184
+ ) do |task|
185
+ @tunnels = task
186
+ sleep
187
+ ensure
188
+ # `Scheduler#stop` cancels this task at once, but not the requests
189
+ # that defer their cancel (a request a server is still answering)
190
+ # or that an `ensure` makes while it is stopped.
191
+ drain unless @closed
192
+ end
193
+ end
194
+
195
+ # Ends the tunnels the way a pool's gardener ends direct connections
196
+ # when it is stopped: an idle one at once, one in use after its
197
+ # request. A second cancel ends the wait, and so all tunnels.
198
+ def drain
199
+ pool = @pool&.call
200
+ loop do
201
+ # A tunnel that is being opened is in no pool yet.
202
+ @connected.wait while @connecting.positive?
203
+ pool&.drain
204
+ break if @connecting.zero?
205
+ end
206
+ rescue StandardError
207
+ # The tunnels are then stopped with this task, as by `#close`.
208
+ nil
209
+ end
210
+
211
+ def run_tunnel(opened, task)
212
+ @proxy.connect do |socket|
213
+ # Like a direct connection, so that a tunnel that went dead does not
214
+ # leave its request waiting for good.
215
+ socket.timeout = timeout if timeout
216
+ shutdown_on_close(socket)
217
+ opened.resolve(build_endpoint(Tunnel.new(socket)).connect)
218
+ # The tunnel's writer ends when the connection on top of it is
219
+ # closed. Returning then closes the pipe, which releases the proxy
220
+ # connection without waiting for the proxy to close it.
221
+ task.wait_all
222
+ ensure
223
+ # Stopped by `#close` or with the reactor while its connection is
224
+ # open: async-http closes the socket next, in this task.
225
+ @cut += 1 if opened.completed? && !socket.closed?
226
+ end
227
+ rescue StandardError => error
228
+ # Once the tunnel is open nobody waits for it any more; the
229
+ # connection on top of it then fails on the closed socket.
230
+ opened.reject(error)
231
+ ensure
232
+ # Stopped before it opened, by `#close` or for a caller that gave up.
233
+ opened.reject(IOError.new('proxy tunnel closed before it was established'))
234
+ # A cancel that lands while async-http sets up the tunnel's pipe leaves
235
+ # the pipe's transient tasks behind, holding the proxy connection.
236
+ # The proxy pool's gardener is a child of whichever tunnel opened a
237
+ # connection while the pool had none, and outlives it: cancelled, it
238
+ # would wait for the pool to drain and keep this task in the tree.
239
+ task.children&.each { it.cancel unless it.annotation.to_s.end_with?(' Gardener') }
240
+ end
241
+
242
+ # A process forked while the tunnel is open inherits the pipe's socket
243
+ # pair. A plain close of this end then no longer reaches the pipe's
244
+ # writer for as long as that process lives, and the tunnel would keep
245
+ # its proxy connection. A shutdown reaches it whoever else holds the
246
+ # socket. Only the process that opened the tunnel shuts it down.
247
+ def shutdown_on_close(socket)
248
+ owner = Process.pid
249
+ socket.define_singleton_method(:close) do
250
+ begin
251
+ shutdown if !closed? && Process.pid == owner
252
+ rescue SystemCallError, IOError
253
+ # Already disconnected by the other end.
254
+ end
255
+ super()
256
+ end
257
+ end
258
+ end
30
259
 
31
260
  class ProxyClient
32
261
  # @param client [Async::HTTP::Client]
33
262
  # @param proxy_client [Async::HTTP::Client]
263
+ # @param tunnels [TunnelEndpoint] the endpoint of `client`
34
264
  # @return [void]
35
- def initialize(client, proxy_client)
265
+ def initialize(client, proxy_client, tunnels)
36
266
  @client = client
37
267
  @proxy_client = proxy_client
268
+ @tunnels = tunnels
38
269
  end
39
270
 
40
271
  # @param request [Protocol::HTTP::Request]
@@ -43,12 +274,41 @@ module Async
43
274
  @client.call(request, &)
44
275
  end
45
276
 
277
+ # Waits for the requests in flight, then closes all connections. If the
278
+ # wait is interrupted (timeout, stop), the requests still in flight fail.
279
+ #
46
280
  # @return [void]
47
281
  def close
48
282
  @client.close
49
283
  ensure
284
+ # A tunnel holds its proxy connection for as long as it is open, so
285
+ # the proxy pool only drains once the tunnels are gone. Whatever is
286
+ # left then is the remains of a tunnel: nothing to wait for.
287
+ @tunnels.close
288
+ retire_proxy_connections
50
289
  @proxy_client.close
51
290
  end
291
+
292
+ # @return [Array<Async::Pool::Controller>] the target pool, then the proxy pool
293
+ def pools
294
+ [@client, @proxy_client].filter_map { it.pool if it.respond_to?(:pool) }
295
+ end
296
+
297
+ # @return [Integer] changes when a tunnel is stopped under its connection
298
+ def tunnels_cut
299
+ @tunnels.cut
300
+ end
301
+
302
+ private
303
+
304
+ def retire_proxy_connections
305
+ return unless @proxy_client.respond_to?(:pool)
306
+
307
+ pool = @proxy_client.pool
308
+ pool.resources.keys.each { pool.retire(it) } until pool.empty?
309
+ rescue Exception => e # rubocop:disable Lint/RescueException
310
+ raise unless ClientCache.pool_refused?(e)
311
+ end
52
312
  end
53
313
 
54
314
  # @return [void]
@@ -56,14 +316,26 @@ module Async
56
316
  @clients = {}
57
317
  @mutex = Mutex.new
58
318
  @access_count = 0
319
+ @over_limit = ObjectSpace::WeakKeyMap.new
320
+ @force_closed = ObjectSpace::WeakKeyMap.new
321
+ # Every client that is still referenced, also one that `clear!` took
322
+ # out of the cache and is still closing.
323
+ @built = ObjectSpace::WeakMap.new
324
+ @pid = Process.pid
59
325
  end
60
326
 
327
+ # Hands out the cached client itself. Unlike {#with_client} it does not
328
+ # count the caller as a user of the client: the client may be evicted and
329
+ # closed while in use, and concurrent first calls can briefly exceed
330
+ # `async_http_connection_limit`.
331
+ #
61
332
  # @param endpoint [URI::HTTP, URI::HTTPS]
62
333
  # @param config [Seahorse::Client::Configuration]
63
334
  # @return [Async::HTTP::Client]
64
335
  def client_for(endpoint, config)
65
336
  raise NoReactorError, 'Async reactor is required. Wrap calls in Sync { }.' unless Async::Task.current?
66
337
 
338
+ discard_inherited_entries
67
339
  reactor = Async::Task.current.reactor
68
340
  key = cache_key(endpoint, config, reactor)
69
341
  entry = nil
@@ -80,8 +352,7 @@ module Async
80
352
  end
81
353
  end
82
354
 
83
- close_entry(stale_entry) if stale_entry
84
- sweep_dead_entries_if_needed.each { |dead| close_entry(dead) }
355
+ close_entries([stale_entry, *sweep_dead_entries_if_needed])
85
356
  return entry.client if entry
86
357
 
87
358
  new_entry = nil
@@ -89,7 +360,7 @@ module Async
89
360
  used_entry = nil
90
361
  stale_existing = nil
91
362
 
92
- new_entry = Entry.new(build_client(endpoint, config), WeakRef.new(reactor), 0)
363
+ key, new_entry = build_for_key(endpoint, config, reactor, key)
93
364
 
94
365
  @mutex.synchronize do
95
366
  existing = @clients[key]
@@ -105,20 +376,24 @@ module Async
105
376
  end
106
377
  end
107
378
 
108
- close_entry(new_entry) if used_entry != new_entry
109
- close_entry(stale_existing) if stale_existing
110
- evicted.each { |entry_to_close| close_entry(entry_to_close) }
379
+ close_entries([(new_entry if used_entry != new_entry), stale_existing, *evicted])
111
380
 
112
381
  used_entry.client
113
382
  end
114
383
 
384
+ # Yields the cached client for the endpoint and counts the caller as using
385
+ # it until the block returns. At most `async_http_connection_limit` callers
386
+ # use a client at once; further callers wait their turn.
387
+ #
115
388
  # @param endpoint [URI::HTTP, URI::HTTPS]
116
389
  # @param config [Seahorse::Client::Configuration]
117
390
  # @yieldparam client [Async::HTTP::Client]
118
- # @return [Object]
391
+ # @return [Object] the value of the block
392
+ # @raise [Async::Aws::TransportTimeoutError] if `async_http_header_timeout` passes while waiting for a turn
119
393
  def with_client(endpoint, config)
120
394
  raise NoReactorError, 'Async reactor is required. Wrap calls in Sync { }.' unless Async::Task.current?
121
395
 
396
+ discard_inherited_entries
122
397
  reactor = Async::Task.current.reactor
123
398
  key = cache_key(endpoint, config, reactor)
124
399
  entry = nil
@@ -136,78 +411,106 @@ module Async
136
411
  end
137
412
  end
138
413
 
139
- close_entry(stale_entry) if stale_entry
140
- sweep_dead_entries_if_needed.each { |dead| close_entry(dead) }
414
+ close_entries([stale_entry, *sweep_dead_entries_if_needed])
141
415
 
142
416
  unless entry
143
- new_entry = Entry.new(build_client(endpoint, config), WeakRef.new(reactor), 0)
417
+ key, new_entry = build_for_key(endpoint, config, reactor, key)
144
418
  evicted = []
145
- used_entry = nil
146
419
  stale_existing = nil
147
420
 
421
+ # `entry` is assigned where it is counted as in-flight, so the `ensure`
422
+ # below releases it whatever happens after this point.
148
423
  @mutex.synchronize do
149
424
  existing = @clients[key]
150
425
  if entry_valid_for?(existing, reactor)
151
426
  touch_lru!(key, existing)
152
427
  existing.inflight = existing.inflight.to_i + 1
153
- used_entry = existing
428
+ entry = existing
154
429
  else
155
430
  stale_existing = existing
156
431
  @clients[key] = new_entry
157
432
  touch_lru!(key, new_entry)
158
433
  new_entry.inflight = new_entry.inflight.to_i + 1
159
- used_entry = new_entry
434
+ entry = new_entry
160
435
  evicted = evict_entries_locked(config, reactor)
161
436
  end
162
437
  end
163
438
 
164
- close_entry(new_entry) if used_entry != new_entry
165
- close_entry(stale_existing) if stale_existing
166
- evicted.each { |entry_to_close| close_entry(entry_to_close) }
167
-
168
- entry = used_entry
439
+ close_entries([(new_entry if entry != new_entry), stale_existing, *evicted])
169
440
  end
170
441
 
442
+ client = extract_client(entry)
443
+ limiter = entry.limiter
444
+ wait_for_turn(limiter, config) if limiter
445
+ cut = tunnels_cut(client)
171
446
  begin
172
- yield extract_client(entry)
447
+ yield client
173
448
  ensure
174
- @mutex.synchronize do
175
- if entry
176
- entry.inflight = [entry.inflight.to_i - 1, 0].max
177
- end
449
+ begin
450
+ take_close_interrupt if force_closed?(client) || cut != tunnels_cut(client)
451
+ ensure
452
+ limiter&.release
178
453
  end
179
454
  end
455
+ ensure
456
+ release_entry(entry, key, config, reactor) if entry
180
457
  end
181
458
 
182
- # Closes all cached clients and clears the cache. Intended for shutdown only.
459
+ # Whether the connections of `client` were closed under its requests by
460
+ # `clear!(timeout:)`. Such requests fail in whatever way their torn-down
461
+ # connection raises; the handler reports that as a networking error.
462
+ #
463
+ # @api private
464
+ # @param client [Async::HTTP::Client]
465
+ # @return [Boolean]
466
+ def force_closed?(client)
467
+ @mutex.synchronize { @force_closed.key?(client) }
468
+ end
469
+
470
+ # @return [Integer] number of cached clients, across all reactors
471
+ def size
472
+ discard_inherited_entries
473
+ @mutex.synchronize { @clients.size }
474
+ end
475
+
476
+ # Closes the clients of the calling reactor and of finished reactors, and
477
+ # removes them from the cache. Intended for shutdown.
478
+ #
479
+ # A client is only closed by its own reactor: its sockets and its pool's
480
+ # tasks belong to that reactor's thread. Clients of other running reactors
481
+ # therefore stay cached until those reactors call `clear!` or finish.
183
482
  #
483
+ # Without a timeout it waits for the calling reactor's in-flight requests.
484
+ # Cancelling the caller, or a timeout of its own around the call, ends that
485
+ # wait; the remaining clients are then closed as soon as they are unused.
486
+ #
487
+ # @param timeout [Numeric, nil] seconds to wait, in total, for in-flight
488
+ # requests of the calling reactor; after that their connections are
489
+ # closed anyway
184
490
  # @return [void]
185
491
  def clear!(timeout: nil)
186
- clients = @mutex.synchronize do
187
- values = @clients.values
188
- @clients.clear
189
- values
492
+ discard_inherited_entries
493
+ reactor = current_reactor
494
+ pending = @mutex.synchronize do
495
+ keys = @clients.keys.reject { owned_by_other_reactor?(@clients[it], reactor) }
496
+ keys.map { @clients.delete(it) }
190
497
  end
498
+ deadline = monotonic_time + timeout if timeout
191
499
 
192
- clients.each do |client_entry|
193
- current_reactor = Async::Task.current? ? Async::Task.current.reactor : nil
194
- owner_reactor = entry_reactor(client_entry)
195
- if timeout && current_reactor && owner_reactor == current_reactor
196
- begin
197
- client = extract_client(client_entry)
198
- Async::Task.current.with_timeout(timeout, Async::TimeoutError) { client.close if client.respond_to?(:close) }
199
- rescue Async::TimeoutError
200
- logger = logger_for
201
- logger&.warn('[aws-sdk-http-async] force-closing client (timeout)')
202
- close_entry(client_entry, force: true)
203
- rescue StandardError => e
204
- logger = logger_for
205
- logger&.warn("[aws-sdk-http-async] failed to close client: #{e.message}")
206
- end
500
+ # An entry leaves `pending` only once it is closed.
501
+ until pending.empty?
502
+ entry = pending.first
503
+ if reactor && reactor.equal?(entry_reactor(entry))
504
+ deadline ? close_before(entry, deadline) : close_gracefully(entry)
207
505
  else
208
- close_entry(client_entry, force: true)
506
+ close_entry(entry)
209
507
  end
508
+ pending.shift
210
509
  end
510
+ ensure
511
+ # Interrupted while waiting: the entries are already out of the cache, so
512
+ # nothing else would close them.
513
+ close_entries(pending) { close_without_waiting(it) } if pending && !pending.empty?
211
514
  end
212
515
 
213
516
  # @return [void]
@@ -217,19 +520,161 @@ module Async
217
520
 
218
521
  private
219
522
 
523
+ # A forked child inherits the parent's entries, but their sockets (and TLS
524
+ # sessions) still belong to the parent. Drop them without closing: a close
525
+ # would write TLS close_notify / HTTP/2 GOAWAY onto connections the parent
526
+ # is still using.
527
+ def discard_inherited_entries
528
+ return if @pid == Process.pid
529
+
530
+ @mutex.synchronize do
531
+ next if @pid == Process.pid
532
+
533
+ inherited = @built.keys
534
+ @clients = {}
535
+ @access_count = 0
536
+ @over_limit = ObjectSpace::WeakKeyMap.new
537
+ @force_closed = ObjectSpace::WeakKeyMap.new
538
+ @built = ObjectSpace::WeakMap.new
539
+ @pid = Process.pid
540
+ release_inherited_sockets(inherited)
541
+ end
542
+ end
543
+
544
+ # Closes this process's copies of the parent's sockets, which writes
545
+ # nothing to them. Kept open, they would hold the parent's connections
546
+ # open for the peer after the parent closed them.
547
+ def release_inherited_sockets(clients)
548
+ clients.each do |client|
549
+ pools_of(client)&.each { |pool| pool.resources.each_key { close_socket(it) } }
550
+ end
551
+ rescue StandardError
552
+ nil
553
+ end
554
+
555
+ def owned_by_other_reactor?(entry, reactor)
556
+ entry.is_a?(Entry) && !entry_dead?(entry) && !entry_valid_for?(entry, reactor)
557
+ end
558
+
559
+ def current_reactor
560
+ Async::Task.current? ? Async::Task.current.reactor : nil
561
+ end
562
+
563
+ def monotonic_time
564
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
565
+ end
566
+
567
+ # Runs the block to completion even if the task is cancelled meanwhile.
568
+ # Used where entries were already taken out of the cache, so nothing else
569
+ # would close them.
570
+ def uninterrupted(&)
571
+ task = Async::Task.current?
572
+ task ? task.defer_cancel(&) : yield
573
+ end
574
+
575
+ # Closes entries that are already out of the cache, so nothing else would
576
+ # close them. `defer_cancel` holds back only the first cancel (a task under
577
+ # an `Async::Barrier` can get two from one stop), so the closes run in a
578
+ # transient task, which a cancel of the caller does not reach. The caller
579
+ # waits for it; a second cancel ends only that wait.
580
+ #
581
+ # A client can be busy without a request that counts as using it: an
582
+ # upload that goes on after the server answered early. Its close waits
583
+ # for that upload, which must not hold up the caller (possibly a call to
584
+ # another endpoint that evicted it), so it is left to the transient task.
585
+ def close_entries(entries, &close)
586
+ entries = entries.compact
587
+ return if entries.empty?
588
+
589
+ task = Async::Task.current?
590
+ return entries.each(&close || method(:close_entry)) unless task
591
+
592
+ unless close
593
+ close = method(:close_entry)
594
+ busy, entries = entries.partition { busy?(it) }
595
+ task.async(transient: true) { busy.each(&close) } unless busy.empty?
596
+ return if entries.empty?
597
+ end
598
+
599
+ closer = task.async(transient: true) { entries.each(&close) }
600
+ uninterrupted { closer.wait }
601
+ end
602
+
603
+ def busy?(entry)
604
+ return false if entry_dead?(entry)
605
+
606
+ pools_of(extract_client(entry)).to_a.any?(&:busy?)
607
+ rescue StandardError
608
+ false
609
+ end
610
+
611
+ # Waits for the client's requests, then closes it. The wait is outside any
612
+ # rescue, so cancelling the caller or its own timeout ends it.
613
+ def close_gracefully(entry)
614
+ wait_until_unused(entry)
615
+ close_entry(entry)
616
+ end
617
+
618
+ # A request that is still opening its connection holds no connection of
619
+ # the pool yet, so the pool alone cannot tell whether the client is in use.
620
+ def wait_until_unused(entry)
621
+ if entry.is_a?(Entry)
622
+ (entry.unused ||= Async::Condition.new).wait while entry.inflight.to_i.positive?
623
+ end
624
+ pools_of(extract_client(entry))&.first&.wait_until_free
625
+ end
626
+
627
+ # Closes an entry without waiting for its requests. An entry that is in
628
+ # use is closed by its last request instead (see `release_entry`).
629
+ def close_without_waiting(entry)
630
+ return close_entry(entry) if entry_dead?(entry)
631
+ return if entry.is_a?(Entry) && entry.inflight.to_i.positive?
632
+
633
+ client = extract_client(entry)
634
+ pools_of(client).to_a.empty? ? safe_close(client) : force_close(client)
635
+ end
636
+
637
+ # Counts the entry as no longer in use, and closes what this request kept
638
+ # alive: clients evicted late (in-flight entries are never evicted, so a
639
+ # burst can leave the reactor over its LRU bound) and the entry itself if
640
+ # it was cleared or replaced while in use.
641
+ def release_entry(entry, key, config, reactor)
642
+ # Only the owning reactor's fibers change the counter, so it needs no
643
+ # lock, and a cancellation while waiting for the lock cannot leak it.
644
+ entry.inflight = [entry.inflight.to_i - 1, 0].max
645
+ entry.unused&.signal if entry.inflight.zero?
646
+
647
+ uninterrupted do
648
+ to_close = @mutex.synchronize do
649
+ unmet = @over_limit[reactor]
650
+ evicted = unmet ? evict_entries_locked(config, reactor, limit: unmet) : []
651
+ detached = entry.inflight.zero? && !@clients[key].equal?(entry)
652
+ detached ? evicted | [entry] : evicted
653
+ end
654
+ close_entries(to_close)
655
+ end
656
+ end
657
+
658
+ # An Array, so that no value can run into the next one and values of
659
+ # different types (`50`, `'50'`) stay apart. Strings are frozen copies: a
660
+ # caller that changes its string in place must not change the hash of a
661
+ # stored key, which would strand the entry.
220
662
  def cache_key(endpoint, config, reactor)
221
- reactor_id = reactor.object_id
222
- "#{reactor_id}|#{endpoint.scheme}://#{endpoint.host}:#{endpoint.port}|" \
223
- "limit=#{config.async_http_connection_limit}|" \
224
- "timeout=#{config.http_open_timeout}|" \
225
- "idle=#{config.async_http_idle_timeout}|" \
226
- "proxy=#{proxy_cache_value(config.http_proxy)}|" \
227
- "ssl=#{config.ssl_verify_peer}|" \
228
- "ca_store=#{ssl_cache_value(config.ssl_ca_store)}|" \
229
- "ca_bundle=#{config.ssl_ca_bundle}|" \
230
- "ca_dir=#{config.ssl_ca_directory}|" \
231
- "ssl_cert=#{ssl_cache_value(config.ssl_cert)}|" \
232
- "ssl_key=#{ssl_cache_value(config.ssl_key)}"
663
+ [
664
+ reactor.object_id, endpoint.scheme, endpoint.host, endpoint.port,
665
+ Async::HTTP::Client.object_id,
666
+ config.async_http_connection_limit,
667
+ config.http_open_timeout,
668
+ config.async_http_idle_timeout,
669
+ config.http_idle_timeout,
670
+ proxy_cache_value(config.http_proxy),
671
+ config.ssl_verify_peer,
672
+ ssl_cache_value(config.ssl_ca_store),
673
+ ssl_cache_value(config.ssl_ca_bundle),
674
+ ssl_cache_value(config.ssl_ca_directory),
675
+ ssl_cache_value(config.ssl_cert),
676
+ ssl_cache_value(config.ssl_key),
677
+ ].map! { it.is_a?(String) ? -it : it }.freeze
233
678
  end
234
679
 
235
680
  def entry_valid_for?(entry, reactor)
@@ -247,8 +692,7 @@ module Async
247
692
  @clients[key] = entry
248
693
  end
249
694
 
250
- def evict_entries_locked(config, reactor)
251
- limit = config.async_http_max_cached_clients
695
+ def evict_entries_locked(config, reactor, limit: config.async_http_max_cached_clients)
252
696
  return [] if limit.nil? || limit <= 0
253
697
 
254
698
  evicted = []
@@ -275,29 +719,35 @@ module Async
275
719
  evicted << entry if entry
276
720
  current_size -= 1
277
721
  end
722
+
723
+ # Still over a bound means in-flight entries blocked the eviction:
724
+ # remember the tightest such bound, so the next release of this reactor
725
+ # trims again. Clients with a larger (or no) bound share the cache and
726
+ # must not clear it.
727
+ unmet = [limit, @over_limit[reactor]].compact.min
728
+ if current_size > unmet
729
+ @over_limit[reactor] = unmet
730
+ else
731
+ @over_limit.delete(reactor)
732
+ end
278
733
  evicted
279
734
  end
280
735
 
281
- def close_entry(entry, force: false)
736
+ def close_entry(entry)
282
737
  client = extract_client(entry)
283
738
  return unless client.respond_to?(:close)
284
739
 
740
+ return close_orphaned(client) if entry_dead?(entry)
741
+
285
742
  reactor = entry_reactor(entry)
286
- current_reactor = Async::Task.current? ? Async::Task.current.reactor : nil
287
- if reactor && reactor != current_reactor && !force
288
- logger = logger_for
289
- logger&.debug('[aws-sdk-http-async] skipping close from different reactor')
743
+ if reactor && !reactor.equal?(current_reactor)
744
+ logger_for&.debug('[aws-sdk-http-async] skipping close from different reactor')
290
745
  return
291
746
  end
292
- if reactor && reactor != current_reactor && force
293
- logger = logger_for
294
- logger&.debug('[aws-sdk-http-async] force-closing client from different reactor')
295
- end
296
747
 
297
748
  safe_close(client)
298
749
  rescue StandardError => e
299
- logger = logger_for
300
- logger&.warn("[aws-sdk-http-async] failed to close client: #{e.message}")
750
+ close_failed(e)
301
751
  end
302
752
 
303
753
  def extract_client(entry)
@@ -317,13 +767,16 @@ module Async
317
767
  nil
318
768
  end
319
769
 
770
+ # An entry is dead once its reactor was collected or closed. A closed
771
+ # reactor stops its pools' gardener tasks, which close the connections.
320
772
  def entry_dead?(entry)
321
773
  return false unless entry.is_a?(Entry)
322
774
 
323
775
  ref = entry.reactor_ref
324
776
  return true unless ref&.weakref_alive?
325
777
 
326
- false
778
+ reactor = ref.__getobj__
779
+ reactor.respond_to?(:closed?) && reactor.closed?
327
780
  rescue WeakRef::RefError
328
781
  true
329
782
  end
@@ -357,32 +810,225 @@ module Async
357
810
  def safe_close(client)
358
811
  client.close
359
812
  rescue StandardError => e
360
- logger = logger_for
361
- logger&.warn("[aws-sdk-http-async] failed to close client: #{e.message}")
813
+ close_failed(e)
814
+ end
815
+
816
+ # The owning reactor is gone, so no fiber is left to release a busy
817
+ # connection and `Async::HTTP::Client#close` would wait forever for the
818
+ # pool to drain. Close only idle clients; GC reclaims the rest.
819
+ def close_orphaned(client)
820
+ pools = pools_of(client)
821
+ if pools.nil? || pools.any?(&:busy?)
822
+ return logger_for&.debug('[aws-sdk-http-async] skipping close of busy client from a finished reactor')
823
+ end
824
+
825
+ safe_close(client)
826
+ rescue StandardError => e
827
+ close_failed(e)
828
+ end
829
+
830
+ # Waits until `deadline` for the client's requests to finish, then closes it
831
+ # either way.
832
+ def close_before(entry, deadline)
833
+ client = extract_client(entry)
834
+ return unless client.respond_to?(:close)
835
+
836
+ pools = pools_of(client).to_a
837
+ remaining = [deadline - monotonic_time, 0].max
838
+ Async::Task.current.with_timeout(remaining, CloseDeadline) do
839
+ wait_until_unused(entry)
840
+ # Nothing to retire: WebMock does not show its pool.
841
+ client.close if pools.empty?
842
+ end
843
+ force_close(client)
844
+ rescue CloseDeadline
845
+ logger_for&.warn('[aws-sdk-http-async] force-closing client (timeout)')
846
+ force_close(client)
847
+ rescue StandardError => e
848
+ close_failed(e)
849
+ end
850
+
851
+ # A close that fails must not keep the other clients from being closed.
852
+ # The caller's own timeout is not such a failure: it ends the caller.
853
+ def close_failed(error)
854
+ raise error if error.is_a?(Async::TimeoutError)
855
+
856
+ logger_for&.warn("[aws-sdk-http-async] failed to close client: #{error.message}")
857
+ end
858
+
859
+ # `Async::HTTP::Client#close` waits for the pool to drain. Close the
860
+ # connections under the in-flight requests instead; those requests fail
861
+ # with a network error.
862
+ def force_close(client)
863
+ pools = pools_of(client).to_a
864
+ return if pools.empty?
865
+
866
+ @mutex.synchronize { @force_closed[client] = true }
867
+ # Each retire frees a slot, so a request that was waiting for one may
868
+ # connect meanwhile: repeat until nothing is left.
869
+ pools.each do |pool|
870
+ until pool.empty?
871
+ pool.resources.to_a.each do |connection, usage|
872
+ close_socket(connection) if usage.positive?
873
+ pool.retire(connection)
874
+ end
875
+ end
876
+ end
877
+ # The client may hold more than its pools show (WebMock keeps a second
878
+ # pool for stubbed responses), so the final close is not waited for.
879
+ task = Async::Task.current?
880
+ task ? task.async(transient: true) { safe_close(client) } : safe_close(client)
881
+ rescue StandardError => e
882
+ close_failed(e)
883
+ end
884
+
885
+ # Closing a connection flushes its stream, under the stream's write lock,
886
+ # and TLS flushes once more. A request that is blocked writing its body
887
+ # holds that lock until the peer reads or the socket times out, so the
888
+ # close would wait as long (several socket timeouts under TLS). Closing
889
+ # the socket underneath fails the blocked write at once, and the stream
890
+ # then closes without flushing.
891
+ def close_socket(connection)
892
+ stream = connection.stream if connection.respond_to?(:stream)
893
+ io = stream.io if stream.respond_to?(:io)
894
+ # Under TLS: the TCP socket, because `SSLSocket#close` flushes too.
895
+ io = io.to_io if io.respond_to?(:to_io)
896
+ io.close if io.respond_to?(:close)
897
+ rescue StandardError
898
+ nil
899
+ end
900
+
901
+ # Closing a socket under a blocked request makes Ruby interrupt that fiber
902
+ # with an IOError, which the scheduler delivers on its next turn. A request
903
+ # that left its read before that (its own timeout fired in the same timer
904
+ # batch) would get the error at its next yield point instead, which may be
905
+ # the caller's own code. Take it here: the interrupt is queued ahead of
906
+ # this yield.
907
+ #
908
+ # A tunnel that is stopped under its request (a second stop of the
909
+ # reactor, its close) leaves the same interrupt behind: the end of the
910
+ # stream wakes the request first. A stop or a timeout that arrives during
911
+ # the yield is held until the interrupt is taken. `defer_cancel` cannot do
912
+ # that for a task whose own `defer_stop` already holds a cancel, and the
913
+ # interrupt would otherwise replace the stop, or reach the task while it
914
+ # stops its children, outside any `rescue`, and end the reactor.
915
+ def take_close_interrupt
916
+ held = nil
917
+ begin
918
+ Async::Task.current.yield
919
+ rescue IOError
920
+ nil
921
+ rescue Async::Stop, Async::TimeoutError => held
922
+ retry
923
+ end
924
+ raise held if held
925
+ end
926
+
927
+ # A tunnel that is stopped closes its socket under the request using it,
928
+ # like `clear!(timeout:)` does.
929
+ def tunnels_cut(client)
930
+ client.tunnels_cut if client.respond_to?(:tunnels_cut)
931
+ end
932
+
933
+ # @return [Array<Async::Pool::Controller>, nil] nil when the client does
934
+ # not let its pool be inspected
935
+ def pools_of(client)
936
+ return client.pools if client.respond_to?(:pools)
937
+
938
+ client.respond_to?(:pool) ? [client.pool] : []
939
+ rescue Exception => e # rubocop:disable Lint/RescueException
940
+ raise unless ClientCache.pool_refused?(e)
941
+
942
+ nil
943
+ end
944
+
945
+ # The key and the client both read the working directory (relative TLS
946
+ # paths) and the client class (WebMock swaps it), at different moments.
947
+ # If those changed in between, the client is built again: it must not be
948
+ # cached under a key that names other settings than its own.
949
+ #
950
+ # @return [Array(Array, Entry)] the key the entry was built for, and the entry
951
+ def build_for_key(endpoint, config, reactor, key)
952
+ loop do
953
+ entry = build_entry(endpoint, config, reactor)
954
+ current = cache_key(endpoint, config, reactor)
955
+ return [key, entry] if current == key
956
+
957
+ close_entries([entry])
958
+ key = current
959
+ end
960
+ end
961
+
962
+ def build_entry(endpoint, config, reactor)
963
+ client = build_client(endpoint, config)
964
+ @mutex.synchronize { @built[client] = true }
965
+ Entry.new(client, WeakRef.new(reactor), 0, limiter_for(config))
966
+ end
967
+
968
+ # Stands in for "no bound" where async-pool wants an Integer.
969
+ UNBOUNDED_CONNECTS = 1 << 30
970
+
971
+ # @return [Integer, nil] nil for no limit: nil, zero or less, infinity
972
+ def connection_limit(config)
973
+ limit = config.async_http_connection_limit
974
+ return if limit.nil?
975
+ raise ArgumentError, 'async_http_connection_limit must be a number or nil' unless limit.is_a?(Numeric)
976
+
977
+ limit.ceil if limit.positive? && limit.finite?
978
+ end
979
+
980
+ # Waits until fewer than `async_http_connection_limit` requests use the
981
+ # client, for at most `async_http_header_timeout`.
982
+ def wait_for_turn(limiter, config)
983
+ timeout = config.async_http_header_timeout
984
+ return limiter.acquire unless timeout && timeout > 0
985
+
986
+ Async::Task.current.with_timeout(timeout, TransportTimeoutError, 'timed out waiting for a free connection') do
987
+ limiter.acquire
988
+ end
989
+ end
990
+
991
+ # The pool may open connections concurrently (see `pool_options`), which
992
+ # keeps to its limit only while no more than `limit` requests use it at
993
+ # once. This semaphore guarantees that for requests made through
994
+ # `with_client`.
995
+ def limiter_for(config)
996
+ limit = connection_limit(config)
997
+ Async::Semaphore.new(limit) if limit
998
+ end
999
+
1000
+ # async-pool opens one connection at a time by default and holds that
1001
+ # guard even to hand out an idle connection, so one slow connect would
1002
+ # make every call to the endpoint wait. Without a limit the guard has
1003
+ # nothing to protect, so it must not serialize connects either.
1004
+ def pool_options(config, idle: config.http_idle_timeout)
1005
+ limit = connection_limit(config)
1006
+ options = { retries: 0, limit:, concurrency: limit || UNBOUNDED_CONNECTS }
1007
+ options[:policy] = IdlePolicy.new(idle) if idle && idle > 0
1008
+ options
362
1009
  end
363
1010
 
364
1011
  def build_client(endpoint, config)
365
1012
  target_endpoint = build_endpoint(endpoint, config)
366
- return Async::HTTP::Client.new(
367
- target_endpoint,
368
- retries: 0,
369
- limit: config.async_http_connection_limit,
370
- ) unless config.http_proxy
1013
+ return Async::HTTP::Client.new(target_endpoint, **pool_options(config)) unless config.http_proxy
371
1014
 
372
1015
  proxy_endpoint = build_proxy_endpoint(config)
373
- proxy_client = Async::HTTP::Client.new(
374
- proxy_endpoint,
375
- retries: 0,
376
- limit: config.async_http_connection_limit,
377
- )
378
- headers = proxy_headers(proxy_endpoint.url)
379
- proxied_endpoint = proxy_client.proxied_endpoint(target_endpoint, headers)
380
- client = Async::HTTP::Client.new(
381
- proxied_endpoint,
382
- retries: 0,
383
- limit: config.async_http_connection_limit,
384
- )
385
- ProxyClient.new(client, proxy_client)
1016
+ proxy_client = Async::HTTP::Client.new(proxy_endpoint, **pool_options(config))
1017
+ proxy = proxy_client.proxy(target_endpoint, proxy_headers(proxy_endpoint.url))
1018
+ tunnels = TunnelEndpoint.new(target_endpoint, proxy)
1019
+ client = Async::HTTP::Client.new(tunnels, **pool_options(config, idle: tunnel_idle_timeout(config)))
1020
+ tunnels.pool = -> { pools_of(client)&.first }
1021
+ ProxyClient.new(client, proxy_client, tunnels)
1022
+ end
1023
+
1024
+ # The proxy socket's I/O timeout (see `build_timeout`) ends an idle
1025
+ # tunnel inside async-http without closing the connection on top of it,
1026
+ # and the next call would wait for an answer that cannot come. Idle
1027
+ # tunnels are therefore retired well before that: the policy retires
1028
+ # after one to two times its timeout.
1029
+ def tunnel_idle_timeout(config)
1030
+ io_timeout = build_timeout(config)
1031
+ [config.http_idle_timeout, (io_timeout / 3.0 if io_timeout)].compact.select(&:positive?).min
386
1032
  end
387
1033
 
388
1034
  def build_endpoint(endpoint, config)
@@ -424,8 +1070,8 @@ module Async
424
1070
  if config.ssl_ca_store
425
1071
  context.cert_store = config.ssl_ca_store
426
1072
  else
427
- context.ca_file = config.ssl_ca_bundle if config.ssl_ca_bundle
428
- context.ca_path = config.ssl_ca_directory if config.ssl_ca_directory
1073
+ context.ca_file = absolute_path(config.ssl_ca_bundle) if config.ssl_ca_bundle
1074
+ context.ca_path = absolute_path(config.ssl_ca_directory) if config.ssl_ca_directory
429
1075
  unless config.ssl_ca_bundle || config.ssl_ca_directory
430
1076
  context.cert_store = self.class.default_cert_store
431
1077
  end
@@ -481,10 +1127,25 @@ module Async
481
1127
 
482
1128
  def ssl_cache_value(value)
483
1129
  return nil if value.nil?
484
- return value if value.is_a?(String)
485
- return value.to_path if value.respond_to?(:to_path)
486
1130
 
487
- value.object_id.to_s
1131
+ path = value.respond_to?(:to_path) ? value.to_path : value
1132
+ return value.object_id.to_s unless path.is_a?(String)
1133
+ # Keeps '' apart from nil, so an invalid empty value is not served a
1134
+ # client that was cached for nil.
1135
+ return '""' if path.empty?
1136
+
1137
+ absolute_path(path)
1138
+ end
1139
+
1140
+ # Files are read relative to the working directory at build time. OpenSSL
1141
+ # reads the CA bundle and directory only when the context is first used,
1142
+ # so they are handed over as absolute paths. The path is not normalized:
1143
+ # `..` after a symlink names another file than its lexical parent.
1144
+ def absolute_path(path)
1145
+ path = path.to_path if path.respond_to?(:to_path)
1146
+ return path unless path.is_a?(String) && !path.empty?
1147
+
1148
+ File.absolute_path?(path) ? path : File.join(Dir.pwd, path)
488
1149
  end
489
1150
 
490
1151
  def proxy_headers(proxy_url)