-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathadapter.rb
287 lines (241 loc) · 8.19 KB
/
adapter.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
# frozen_string_literal: true
# Released under the MIT License.
# Copyright, 2018-2025, by Samuel Williams.
# Copyright, 2018, by Andreas Garnaes.
# Copyright, 2019, by Denis Talakevich.
# Copyright, 2019-2020, by Igor Sidorov.
# Copyright, 2023, by Genki Takiuchi.
# Copyright, 2023, by Flavio Fernandes.
# Copyright, 2024, by Jacob Frautschi.
# Copyright, 2025, by Nikolaos Anastopoulos.
require "faraday"
require "faraday/adapter"
require "async/barrier"
require "kernel/sync"
require "async/http/client"
require "async/http/proxy"
require_relative "clients"
module Async
module HTTP
module Faraday
# This is a simple wrapper around Faraday's body that allows it to be read in chunks.
class BodyReadWrapper < ::Protocol::HTTP::Body::Readable
# Create a new wrapper around the given body.
#
# The body must respond to `#read` and `#close` and is often an instance of `IO` or `Faraday::Multipart::CompositeReadIO`.
#
# @parameter body [Interface(:read)] The input body to wrap.
# @parameter block_size [Integer] The size of the blocks to read from the body.
# @parameter length [Integer | Nil] The length of the body, if known.
def initialize(body, length = nil, block_size: 4096)
@body = body
@length = length
@block_size = block_size
end
# @attribute [Integer | Nil] The total length of the body, or `nil` if the length is unknown.
attr :length
# Close the body if possible.
def close(error = nil)
@body.close if @body.respond_to?(:close)
ensure
super
end
# Read from the body in chunks.
def read
@body.read(@block_size)
end
end
# Implement the Faraday parallel manager interface, using Async.
class ParallelManager
# Create a new parallel manager.
def initialize(options = {})
@options = options
@barrier = nil
end
# @deprecated Please update your Faraday version!
def run
if $VERBOSE
warn "Please update your Faraday version!", uplevel: 2
end
end
# Run the given block asynchronously, using the barrier if available.
def async(&block)
if @barrier
@barrier.async(&block)
else
Sync(&block)
end
end
# Execute the given block which can perform multiple concurrent requests, waiting for them all to complete.
def execute(&block)
Sync do
@barrier = Async::Barrier.new
yield
@barrier.wait
ensure
@barrier&.stop
end
end
end
# An adapter that allows Faraday to use Async::HTTP as the underlying HTTP client.
class Adapter < ::Faraday::Adapter
self.supports_parallel = true
# Create a new parallel manager, which is used to handle multiple concurrent requests.
def self.setup_parallel_manager(**options)
ParallelManager.new(options)
end
# The exceptions that are considered connection errors and result in a `Faraday::ConnectionFailed` exception.
CONNECTION_EXCEPTIONS = [
Errno::EADDRNOTAVAIL,
Errno::ECONNABORTED,
Errno::ECONNREFUSED,
Errno::ECONNRESET,
Errno::EHOSTUNREACH,
Errno::EINVAL,
Errno::ENETUNREACH,
Errno::EPIPE,
IOError,
SocketError
].freeze
# Create a Faraday compatible adapter.
#
# @parameter timeout [Integer] The timeout for requests.
# @parameter options [Hash] Additional options to pass to the underlying Async::HTTP::Client.
def initialize(...)
super
@timeout = @connection_options.delete(:timeout)
@read_timeout = @connection_options.delete(:read_timeout)
if clients = @connection_options.delete(:clients)
@clients = clients.call(**@connection_options, &@config_block)
else
@clients = PerThreadPersistentClients.new(**@connection_options, &@config_block)
end
end
# @attribute [Numeric | Nil] The maximum time to send a request and wait for a response.
attr :timeout
# @attribute [Numeric | Nil] The maximum time to wait for an individual IO operation.
attr :read_timeout
# Close all clients.
def close
# The order of operations here is to avoid a race condition between iterating over clients (#close may yield) and creating new clients.
@clients.close
end
# Make a request using the adapter.
#
# @parameter env [Faraday::Env] The environment to make the request in.
# @raises [Faraday::TimeoutError] If the request times out.
# @raises [Faraday::SSLError] If there is an SSL error.
# @raises [Faraday::ConnectionFailed] If there is a connection error.
def call(env)
super
# For compatibility with the default adapter:
env.url.path = "/" if env.url.path.empty?
if parallel_manager = env.parallel_manager
parallel_manager.async do
perform_request(env)
env.response.finish(env)
end
else
perform_request(env)
end
@app.call(env)
end
private
def perform_request(env)
with_client(env) do |endpoint, client|
if headers = env.request_headers
headers = ::Protocol::HTTP::Headers[headers]
# Use content-length to inform body length if given, but remove the header since it will be
# set for us later anyway, and not doing so could result in a duplicate content-length headers
# if capitalization differs
content_length = headers.delete("content-length")&.to_i
end
if body = env.body
# We need to ensure the body is wrapped in a Readable object so that it can be read in chunks:
# Faraday's body only responds to `#read`.
if body.is_a?(::Protocol::HTTP::Body::Readable)
# Good to go
elsif body.respond_to?(:read)
body = BodyReadWrapper.new(body, content_length)
else
body = ::Protocol::HTTP::Body::Buffered.wrap(body)
end
end
method = env.method.to_s.upcase
request = ::Protocol::HTTP::Request.new(endpoint.scheme, endpoint.authority, method, endpoint.path, nil, headers, body)
with_timeout(env.request.timeout || @timeout) do
if env.stream_response?
response = env.stream_response do |&on_data|
response = client.call(request)
save_response(env, response.status, nil, response.headers, finished: false)
response.each do |chunk|
on_data.call(chunk)
end
response
end
else
response = client.call(request)
end
save_response(env, response.status, encoded_body(response), response.headers)
end
end
return @app.call(env)
rescue Errno::ETIMEDOUT, Async::TimeoutError => error
raise ::Faraday::TimeoutError, error
rescue OpenSSL::SSL::SSLError => error
raise ::Faraday::SSLError, error
rescue *CONNECTION_EXCEPTIONS => error
raise ::Faraday::ConnectionFailed, error
end
def with_client(env)
Sync do
endpoint = Endpoint.new(env.url, timeout: @read_timeout)
if proxy = env.request.proxy
proxy_endpoint = Endpoint.new(proxy.uri)
@clients.with_proxied_client(proxy_endpoint, endpoint) do |client|
yield endpoint, client
end
else
@clients.with_client(endpoint) do |client|
yield endpoint, client
end
end
end
end
def with_timeout(timeout = @timeout, task: Async::Task.current)
if timeout
task.with_timeout(timeout, ::Faraday::TimeoutError) do
yield
end
else
yield
end
end
def encoded_body(response)
body = response.read
return "" if body.nil?
content_type = response.headers["content-type"]
return body unless content_type
params = extract_type_parameters(content_type)
if charset = params["charset"]
body = body.dup if body.frozen?
body.force_encoding(charset)
end
body
rescue ArgumentError
nil
end
def extract_type_parameters(content_type)
result = {}
list = content_type.split(";")
list.shift
list.each do |param|
key, value = *param.split("=", 2)
result[key.strip] = value.strip
end
result
end
end
end
end
end