straddle 1.0.0 → 1.1.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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +65 -0
- data/README.md +84 -89
- data/SKILL.md +4 -2
- data/api.md +26 -26
- data/lib/straddle/client.rb +24 -7
- data/lib/straddle/errors.rb +40 -0
- data/lib/straddle/file_part.rb +13 -1
- data/lib/straddle/internal/transport/base_client.rb +186 -42
- data/lib/straddle/internal/transport/connection_pool.rb +160 -0
- data/lib/straddle/internal/transport/pooled_net_requester.rb +77 -10
- data/lib/straddle/internal/type/base_model.rb +69 -18
- data/lib/straddle/internal/type/base_page.rb +14 -0
- data/lib/straddle/internal/type/boolean.rb +3 -1
- data/lib/straddle/internal/type/converter.rb +13 -3
- data/lib/straddle/internal/type/enum.rb +9 -4
- data/lib/straddle/internal/type/file_input.rb +8 -2
- data/lib/straddle/internal/type/hash_of.rb +3 -1
- data/lib/straddle/internal/type/union.rb +21 -7
- data/lib/straddle/internal/type/unknown.rb +3 -1
- data/lib/straddle/internal/util.rb +273 -15
- data/lib/straddle/internal/webhook_verifier.rb +240 -0
- data/lib/straddle/internal.rb +5 -1
- data/lib/straddle/models/capability_request_create_params.rb +18 -18
- data/lib/straddle/models/paykey.rb +3 -2
- data/lib/straddle/models/paykey_created_v1_webhook_event.rb +7 -2
- data/lib/straddle/models/paykey_event_v1_webhook_event.rb +7 -2
- data/lib/straddle/models/payout.rb +14 -14
- data/lib/straddle/models/unmasked_payout.rb +14 -14
- data/lib/straddle/models/webhook_unwrap_params.rb +2 -0
- data/lib/straddle/models.rb +30 -31
- data/lib/straddle/request_options.rb +13 -5
- data/lib/straddle/resources/accounts.rb +11 -12
- data/lib/straddle/resources/bridge.rb +8 -4
- data/lib/straddle/resources/capability_requests.rb +4 -5
- data/lib/straddle/resources/charges.rb +18 -15
- data/lib/straddle/resources/customers/review.rb +5 -6
- data/lib/straddle/resources/customers.rb +34 -35
- data/lib/straddle/resources/funding_events.rb +20 -20
- data/lib/straddle/resources/linked_bank_accounts.rb +9 -11
- data/lib/straddle/resources/organizations.rb +6 -6
- data/lib/straddle/resources/paykeys/review.rb +5 -6
- data/lib/straddle/resources/paykeys.rb +34 -39
- data/lib/straddle/resources/payments.rb +8 -7
- data/lib/straddle/resources/payouts.rb +18 -15
- data/lib/straddle/resources/representatives.rb +7 -6
- data/lib/straddle/resources/webhooks.rb +63 -6
- data/lib/straddle/version.rb +1 -1
- data/lib/straddle.rb +5 -6
- data/rbi/straddle/client.rbi +13 -0
- data/rbi/straddle/errors.rbi +25 -27
- data/rbi/straddle/internal/transport/base_client.rbi +45 -54
- data/rbi/straddle/internal/transport/connection_pool.rbi +44 -0
- data/rbi/straddle/internal/transport/pooled_net_requester.rbi +15 -16
- data/rbi/straddle/internal/type/base_model.rbi +24 -38
- data/rbi/straddle/internal/type/base_page.rbi +5 -0
- data/rbi/straddle/internal/type/converter.rbi +9 -42
- data/rbi/straddle/internal/type/enum.rbi +1 -5
- data/rbi/straddle/internal/type/request_parameters.rbi +1 -3
- data/rbi/straddle/internal/type/union.rbi +2 -11
- data/rbi/straddle/internal/util.rbi +101 -115
- data/rbi/straddle/internal/webhook_verifier.rbi +86 -0
- data/rbi/straddle/internal.rbi +1 -2
- data/rbi/straddle/models/capability_request_create_params.rbi +18 -18
- data/rbi/straddle/models/paykey.rbi +4 -2
- data/rbi/straddle/models/paykey_created_v1_webhook_event.rbi +6 -2
- data/rbi/straddle/models/paykey_event_v1_webhook_event.rbi +6 -2
- data/rbi/straddle/models/payout.rbi +18 -18
- data/rbi/straddle/models/unmasked_payout.rbi +18 -18
- data/rbi/straddle/models/webhook_unwrap_params.rbi +2 -0
- data/rbi/straddle/models.rbi +2 -0
- data/rbi/straddle/request_options.rbi +4 -10
- data/rbi/straddle/resources/accounts.rbi +2 -1
- data/rbi/straddle/resources/bridge.rbi +8 -4
- data/rbi/straddle/resources/charges.rbi +4 -2
- data/rbi/straddle/resources/customers.rbi +7 -3
- data/rbi/straddle/resources/funding_events.rbi +5 -2
- data/rbi/straddle/resources/organizations.rbi +2 -1
- data/rbi/straddle/resources/paykeys.rbi +2 -1
- data/rbi/straddle/resources/payments.rbi +3 -1
- data/rbi/straddle/resources/payouts.rbi +4 -2
- data/rbi/straddle/resources/representatives.rbi +3 -1
- data/rbi/straddle/resources/webhooks.rbi +107 -2
- data/sig/straddle/client.rbs +4 -0
- data/sig/straddle/errors.rbs +13 -0
- data/sig/straddle/internal/transport/base_client.rbs +19 -1
- data/sig/straddle/internal/transport/connection_pool.rbs +19 -0
- data/sig/straddle/internal/transport/pooled_net_requester.rbs +11 -1
- data/sig/straddle/internal/type/base_model.rbs +4 -0
- data/sig/straddle/internal/type/base_page.rbs +2 -0
- data/sig/straddle/internal/util.rbs +29 -1
- data/sig/straddle/internal/webhook_verifier.rbs +53 -0
- data/sig/straddle/models/capability_request_create_params.rbs +24 -24
- data/sig/straddle/models/payout.rbs +12 -12
- data/sig/straddle/models/unmasked_payout.rbs +12 -12
- data/sig/straddle/models/webhook_unwrap_params.rbs +4 -0
- data/sig/straddle/models.rbs +2 -0
- data/sig/straddle/resources/webhooks.rbs +59 -1
- metadata +12 -60
data/lib/straddle/errors.rb
CHANGED
|
@@ -46,6 +46,28 @@ module Straddle
|
|
|
46
46
|
# @return [Object, nil]
|
|
47
47
|
attr_accessor :body
|
|
48
48
|
|
|
49
|
+
# Request identifier exposed by common API response headers, matched case-insensitively.
|
|
50
|
+
# @return [String, nil]
|
|
51
|
+
def request_id
|
|
52
|
+
response_header("x-request-id") || response_header("request-id") ||
|
|
53
|
+
response_header("x-correlation-id")
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
# Parsed RFC 7807 body for application/problem+json responses, preserving extension fields.
|
|
57
|
+
# Non-object bodies and other media types are not treated as Problem Details.
|
|
58
|
+
# @return [Hash{String, Symbol=>Object}, nil]
|
|
59
|
+
def problem_details
|
|
60
|
+
media_type = response_header("content-type").to_s.split(";", 2).first.to_s.strip.downcase
|
|
61
|
+
@body if media_type == "application/problem+json" && @body.is_a?(Hash)
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
# Header maps supplied directly by callers need not use the transport's lowercase spelling.
|
|
65
|
+
# @param name [String]
|
|
66
|
+
# @return [String, nil]
|
|
67
|
+
private def response_header(name)
|
|
68
|
+
@headers&.find { |key, _| key.to_s.downcase == name }&.last
|
|
69
|
+
end
|
|
70
|
+
|
|
49
71
|
# @api private
|
|
50
72
|
#
|
|
51
73
|
# @param url [URI::Generic]
|
|
@@ -223,5 +245,23 @@ module Straddle
|
|
|
223
245
|
class InternalServerError < Straddle::Errors::APIStatusError
|
|
224
246
|
HTTP_STATUS = (500..)
|
|
225
247
|
end
|
|
248
|
+
|
|
249
|
+
# Raised by SDKs that verify webhook signatures through the `standardwebhooks` gem when that gem
|
|
250
|
+
# is not installed. This SDK verifies them with the standard library and never raises it; the
|
|
251
|
+
# class is declared so code that rescues or names it keeps working.
|
|
252
|
+
class MissingDependencyError < Straddle::Errors::Error
|
|
253
|
+
# @api private
|
|
254
|
+
#
|
|
255
|
+
# @param gem_name [String]
|
|
256
|
+
# @param feature [String]
|
|
257
|
+
def initialize(gem_name:, feature:)
|
|
258
|
+
message = [
|
|
259
|
+
"The '#{gem_name}' gem is required to use #{feature}.",
|
|
260
|
+
"Install it with: gem install #{gem_name}",
|
|
261
|
+
"Or add it to your Gemfile: gem '#{gem_name}'"
|
|
262
|
+
].join("\n")
|
|
263
|
+
super(message)
|
|
264
|
+
end
|
|
265
|
+
end
|
|
226
266
|
end
|
|
227
267
|
end
|
data/lib/straddle/file_part.rb
CHANGED
|
@@ -37,10 +37,22 @@ module Straddle
|
|
|
37
37
|
# @return [String]
|
|
38
38
|
def to_yaml(*a) = read.to_yaml(*a)
|
|
39
39
|
|
|
40
|
+
# The filename sent for a part is only ever a basename: an open `File` knows the full local path
|
|
41
|
+
# it was opened from, which is the caller's business and not the server's.
|
|
42
|
+
#
|
|
43
|
+
# The content type is written into the part's headers as given, so one carrying a control
|
|
44
|
+
# character (a CR or LF would start a header line of its own) is refused here, before any request.
|
|
45
|
+
#
|
|
40
46
|
# @param content [Pathname, StringIO, IO, String]
|
|
41
47
|
# @param filename [Pathname, String, nil]
|
|
42
48
|
# @param content_type [String, nil]
|
|
49
|
+
#
|
|
50
|
+
# @raise [ArgumentError] when `content_type` contains a control character
|
|
43
51
|
def initialize(content, filename: nil, content_type: nil)
|
|
52
|
+
if content_type&.to_s&.match?(/[\x00-\x1F\x7F]/)
|
|
53
|
+
raise ArgumentError.new("The content type #{content_type.inspect} contains a control character.")
|
|
54
|
+
end
|
|
55
|
+
|
|
44
56
|
@content_type = content_type
|
|
45
57
|
@filename =
|
|
46
58
|
case [filename, (@content = content)]
|
|
@@ -49,7 +61,7 @@ module Straddle
|
|
|
49
61
|
in [nil, Pathname]
|
|
50
62
|
content.basename.to_path
|
|
51
63
|
in [nil, IO]
|
|
52
|
-
content.to_path
|
|
64
|
+
content.respond_to?(:to_path) ? ::File.basename(content.to_path) : nil
|
|
53
65
|
else
|
|
54
66
|
filename
|
|
55
67
|
end
|
|
@@ -12,7 +12,11 @@ module Straddle
|
|
|
12
12
|
# from whatwg fetch spec
|
|
13
13
|
MAX_REDIRECTS = 20
|
|
14
14
|
|
|
15
|
-
#
|
|
15
|
+
# Longest wait, in seconds, a `retry-after-ms` or `Retry-After` header may ask for before the
|
|
16
|
+
# client's own backoff is used instead.
|
|
17
|
+
MAX_RETRY_AFTER = 60
|
|
18
|
+
|
|
19
|
+
# rubocop:disable-next Style/MutableConstant
|
|
16
20
|
PLATFORM_HEADERS = {
|
|
17
21
|
"x-scalar-arch" => Straddle::Internal::Util.arch,
|
|
18
22
|
"x-scalar-lang" => "ruby",
|
|
@@ -21,7 +25,6 @@ module Straddle
|
|
|
21
25
|
"x-scalar-runtime" => ::RUBY_ENGINE,
|
|
22
26
|
"x-scalar-runtime-version" => ::RUBY_ENGINE_VERSION
|
|
23
27
|
}
|
|
24
|
-
# rubocop:enable Style/MutableConstant
|
|
25
28
|
|
|
26
29
|
class << self
|
|
27
30
|
# @api private
|
|
@@ -30,7 +33,7 @@ module Straddle
|
|
|
30
33
|
#
|
|
31
34
|
# @raise [ArgumentError]
|
|
32
35
|
def validate!(req)
|
|
33
|
-
keys = %i[method path query headers body unwrap page stream model options]
|
|
36
|
+
keys = %i[method path query headers body unwrap page stream model security options]
|
|
34
37
|
case req
|
|
35
38
|
in Hash
|
|
36
39
|
req.each_key do |k|
|
|
@@ -66,6 +69,61 @@ module Straddle
|
|
|
66
69
|
end
|
|
67
70
|
end
|
|
68
71
|
|
|
72
|
+
# @api private
|
|
73
|
+
#
|
|
74
|
+
# The wait in seconds a `retry-after-ms` or `Retry-After` header asks for, when it is a
|
|
75
|
+
# finite value over zero and at most {MAX_RETRY_AFTER}; otherwise `nil`, and the caller backs
|
|
76
|
+
# off on its own schedule.
|
|
77
|
+
#
|
|
78
|
+
# Both headers come from the server, so neither is trusted: a negative or past value would
|
|
79
|
+
# make `sleep` raise, and an hour or `1e400` would park the call. `Retry-After` is seconds
|
|
80
|
+
# or an HTTP date; a date that does not parse is ignored rather than raised.
|
|
81
|
+
#
|
|
82
|
+
# @param headers [Hash{String=>String}, Net::HTTPResponse]
|
|
83
|
+
#
|
|
84
|
+
# @return [Float, nil]
|
|
85
|
+
def retry_after(headers)
|
|
86
|
+
millis = Float(headers["retry-after-ms"], exception: false)
|
|
87
|
+
if millis&.finite? && millis.positive? && millis <= self::MAX_RETRY_AFTER * 1000
|
|
88
|
+
return millis / 1000
|
|
89
|
+
end
|
|
90
|
+
|
|
91
|
+
header = headers["retry-after"]
|
|
92
|
+
return nil if header.nil?
|
|
93
|
+
|
|
94
|
+
seconds = Float(header, exception: false)
|
|
95
|
+
seconds ||=
|
|
96
|
+
begin
|
|
97
|
+
Time.httpdate(header.to_s) - Time.now
|
|
98
|
+
rescue ArgumentError, RangeError
|
|
99
|
+
nil
|
|
100
|
+
end
|
|
101
|
+
seconds.to_f if seconds&.finite? && seconds.positive? && seconds <= self::MAX_RETRY_AFTER
|
|
102
|
+
end
|
|
103
|
+
|
|
104
|
+
# @api private
|
|
105
|
+
#
|
|
106
|
+
# Whether a response is a redirect the client follows: a 301, 302, 303, 307 or 308 that
|
|
107
|
+
# names a `location`, the statuses the fetch spec follows. A 300 only offers choices, a 304
|
|
108
|
+
# tells a conditional request its copy is current, and a redirect with no `location` names
|
|
109
|
+
# no target, so `send_request` treats each as the server's answer and raises it as a status
|
|
110
|
+
# error, as it does a 4xx.
|
|
111
|
+
#
|
|
112
|
+
# @param status [Integer]
|
|
113
|
+
# @param headers [Hash{String=>String}]
|
|
114
|
+
#
|
|
115
|
+
# @return [Boolean]
|
|
116
|
+
def redirect?(status, headers:)
|
|
117
|
+
case status
|
|
118
|
+
in 301 | 302 | 303 | 307 | 308
|
|
119
|
+
# Net::HTTP strips a blank `location` to "", which `URI.join` resolves to the request's
|
|
120
|
+
# own URL, so it would be re-requested until the redirect limit.
|
|
121
|
+
!headers["location"].to_s.strip.empty?
|
|
122
|
+
else
|
|
123
|
+
false
|
|
124
|
+
end
|
|
125
|
+
end
|
|
126
|
+
|
|
69
127
|
# @api private
|
|
70
128
|
#
|
|
71
129
|
# @param request [Hash{Symbol=>Object}] .
|
|
@@ -86,13 +144,23 @@ module Straddle
|
|
|
86
144
|
#
|
|
87
145
|
# @param response_headers [Hash{String=>String}]
|
|
88
146
|
#
|
|
147
|
+
# @param base_url [URI::Generic] the client's base URL, whose origin is the only one its
|
|
148
|
+
# credentials belong to
|
|
149
|
+
#
|
|
150
|
+
# @param credential_headers [Array<String>] lowercase names of the client's header
|
|
151
|
+
# credentials, its `auth_header_keys`
|
|
152
|
+
#
|
|
89
153
|
# @return [Hash{Symbol=>Object}]
|
|
90
|
-
def follow_redirect(request, status:, response_headers:)
|
|
154
|
+
def follow_redirect(request, status:, response_headers:, base_url:, credential_headers:)
|
|
91
155
|
method, url, headers = request.fetch_values(:method, :url, :headers)
|
|
156
|
+
# `send_request` only passes a response `redirect?` accepted. The rescue covers a call
|
|
157
|
+
# handed a 3xx with no `location` (`ArgumentError`), and a `location` that is not a valid
|
|
158
|
+
# URI reference (`URI::Error`), such as one with a space or a bad `%` escape, or two
|
|
159
|
+
# `Location` headers Net::HTTP joined into "/a, /b".
|
|
92
160
|
location =
|
|
93
161
|
Kernel.then do
|
|
94
162
|
URI.join(url, response_headers["location"])
|
|
95
|
-
rescue ArgumentError
|
|
163
|
+
rescue ArgumentError, URI::Error
|
|
96
164
|
message = "Server responded with status #{status} but no valid location header."
|
|
97
165
|
raise Straddle::Errors::APIConnectionError.new(
|
|
98
166
|
url: url,
|
|
@@ -129,11 +197,22 @@ module Straddle
|
|
|
129
197
|
end
|
|
130
198
|
|
|
131
199
|
# from undici
|
|
132
|
-
if Straddle::Internal::Util.uri_origin(url) !=
|
|
200
|
+
if Straddle::Internal::Util.uri_origin(url) !=
|
|
201
|
+
Straddle::Internal::Util.uri_origin(location)
|
|
133
202
|
drop = %w[authorization cookie host proxy-authorization]
|
|
134
203
|
request = {**request, headers: request.fetch(:headers).except(*drop)}
|
|
135
204
|
end
|
|
136
205
|
|
|
206
|
+
# The list above only knows the standard credential headers, so an API key sent in a
|
|
207
|
+
# header of its own (`x-api-key`) would otherwise follow any redirect to a foreign host,
|
|
208
|
+
# and a 307/308 would carry the method and body with it. The drop is sticky: nothing
|
|
209
|
+
# re-adds a header once it is gone, so a chain that returns to the client's origin after
|
|
210
|
+
# a foreign hop still arrives without it.
|
|
211
|
+
if Straddle::Internal::Util.uri_origin(base_url) !=
|
|
212
|
+
Straddle::Internal::Util.uri_origin(location)
|
|
213
|
+
request = {**request, headers: request.fetch(:headers).except(*credential_headers)}
|
|
214
|
+
end
|
|
215
|
+
|
|
137
216
|
request
|
|
138
217
|
end
|
|
139
218
|
|
|
@@ -222,8 +301,31 @@ module Straddle
|
|
|
222
301
|
|
|
223
302
|
# @api private
|
|
224
303
|
#
|
|
304
|
+
# The credential headers one request is sent with, given the security requirement groups its
|
|
305
|
+
# operation passes as `security:` (`nil` for the client's default). A client that scopes its
|
|
306
|
+
# credentials per operation overrides this; every other one sends all of `auth_headers`.
|
|
307
|
+
#
|
|
308
|
+
# @param _security [Array<Array<String>>, nil]
|
|
309
|
+
#
|
|
310
|
+
# @return [Hash{String=>String}]
|
|
311
|
+
private def auth_headers_for(_security) = auth_headers
|
|
312
|
+
|
|
313
|
+
# @api private
|
|
314
|
+
#
|
|
315
|
+
# Lowercased names of every header credential `auth_headers` can write, whether or not the
|
|
316
|
+
# client holds a value for it. A redirect that leaves the base URL's origin drops these, so a
|
|
317
|
+
# key passed per call through `extra_headers` is dropped the same as one the client holds.
|
|
318
|
+
#
|
|
319
|
+
# @return [Array<String>]
|
|
320
|
+
private def auth_header_keys = []
|
|
321
|
+
|
|
322
|
+
# @api private
|
|
323
|
+
#
|
|
324
|
+
# A literal rather than `self.class.name`: a class name is namespaced (`Acme::Client`), and
|
|
325
|
+
# `:` is not a token character (RFC 9110 §5.6.2).
|
|
326
|
+
#
|
|
225
327
|
# @return [String]
|
|
226
|
-
private def user_agent = "
|
|
328
|
+
private def user_agent = "Straddle/Ruby #{Straddle::VERSION}"
|
|
227
329
|
|
|
228
330
|
# @api private
|
|
229
331
|
#
|
|
@@ -252,6 +354,8 @@ module Straddle
|
|
|
252
354
|
#
|
|
253
355
|
# @option req [Straddle::Internal::Type::Converter, Class, nil] :model
|
|
254
356
|
#
|
|
357
|
+
# @option req [Array<Array<String>>, nil] :security
|
|
358
|
+
#
|
|
255
359
|
# @param opts [Hash{Symbol=>Object}] .
|
|
256
360
|
#
|
|
257
361
|
# @option opts [String, nil] :idempotency_key
|
|
@@ -272,18 +376,33 @@ module Straddle
|
|
|
272
376
|
|
|
273
377
|
path = Straddle::Internal::Util.interpolate_path(uninterpolated_path)
|
|
274
378
|
|
|
275
|
-
query = Straddle::Internal::Util.deep_merge(
|
|
276
|
-
|
|
379
|
+
query = Straddle::Internal::Util.deep_merge(
|
|
380
|
+
req[:query].to_h,
|
|
381
|
+
opts[:extra_query].to_h
|
|
382
|
+
)
|
|
383
|
+
|
|
384
|
+
# The client's defaults, its credentials and the operation's own headers each may carry a
|
|
385
|
+
# `cookie`, and a plain merge would let the operation's cookie parameters replace the
|
|
386
|
+
# credential cookie. Those three are merged by cookie name instead; `extra_headers` still
|
|
387
|
+
# replaces the whole header, as it replaces any other.
|
|
388
|
+
sources =
|
|
389
|
+
[@headers, auth_headers_for(req[:security]), req[:headers].to_h].map do
|
|
390
|
+
Straddle::Internal::Util.normalized_headers(_1)
|
|
391
|
+
end
|
|
392
|
+
merged = Straddle::Internal::Util.normalized_headers(*sources)
|
|
393
|
+
# A local rather than an inline block: under a long module name the inline form is broken
|
|
394
|
+
# inside its braces, and the multi-line `{ }` block that leaves is a `Style` offense.
|
|
395
|
+
cookies = sources.map { _1["cookie"] }
|
|
396
|
+
cookie = Straddle::Internal::Util.merge_cookies(*cookies)
|
|
397
|
+
merged["cookie"] = cookie unless cookie.nil?
|
|
277
398
|
headers =
|
|
278
|
-
Straddle::Internal::Util.normalized_headers(
|
|
279
|
-
@headers,
|
|
280
|
-
auth_headers,
|
|
281
|
-
req[:headers].to_h,
|
|
282
|
-
opts[:extra_headers].to_h
|
|
283
|
-
)
|
|
399
|
+
Straddle::Internal::Util.normalized_headers(merged, opts[:extra_headers].to_h)
|
|
284
400
|
|
|
401
|
+
# A generated key goes on every method but `GET`, the HTTP-idempotent ones included: that a
|
|
402
|
+
# method is idempotent by RFC does not make a server's side effects safe to replay. A
|
|
403
|
+
# caller's own key is sent on any method, `GET` too. Built once here, it is resent on retries.
|
|
285
404
|
if @idempotency_header && !headers.key?(@idempotency_header) &&
|
|
286
|
-
(
|
|
405
|
+
(method.to_s.downcase != "get" || opts.key?(:idempotency_key))
|
|
287
406
|
headers[@idempotency_header] = opts.fetch(:idempotency_key) { generate_idempotency_key }
|
|
288
407
|
end
|
|
289
408
|
|
|
@@ -330,20 +449,8 @@ module Straddle
|
|
|
330
449
|
#
|
|
331
450
|
# @return [Float]
|
|
332
451
|
private def retry_delay(headers, retry_count:)
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
return span if span
|
|
336
|
-
|
|
337
|
-
retry_header = headers["retry-after"]
|
|
338
|
-
return span if (span = Float(retry_header, exception: false))
|
|
339
|
-
|
|
340
|
-
span =
|
|
341
|
-
retry_header&.then do
|
|
342
|
-
Time.httpdate(_1) - Time.now
|
|
343
|
-
rescue ArgumentError
|
|
344
|
-
nil
|
|
345
|
-
end
|
|
346
|
-
return span if span
|
|
452
|
+
asked = self.class.retry_after(headers)
|
|
453
|
+
return asked if asked
|
|
347
454
|
|
|
348
455
|
scale = retry_count**2
|
|
349
456
|
jitter = 1 - (0.25 * rand)
|
|
@@ -376,7 +483,10 @@ module Straddle
|
|
|
376
483
|
# @return [Array(Integer, Net::HTTPResponse, Enumerable<String>)]
|
|
377
484
|
def send_request(request, redirect_count:, retry_count:, send_retry_header:)
|
|
378
485
|
url, headers, max_retries, timeout = request.fetch_values(:url, :headers, :max_retries, :timeout)
|
|
379
|
-
input = {
|
|
486
|
+
input = {
|
|
487
|
+
**request.except(:timeout),
|
|
488
|
+
deadline: Straddle::Internal::Util.monotonic_secs + timeout
|
|
489
|
+
}
|
|
380
490
|
|
|
381
491
|
headers["x-scalar-retry-count"] = retry_count.to_s if send_retry_header
|
|
382
492
|
|
|
@@ -387,18 +497,31 @@ module Straddle
|
|
|
387
497
|
end
|
|
388
498
|
headers = Straddle::Internal::Util.normalized_headers(response&.each_header&.to_h)
|
|
389
499
|
|
|
500
|
+
redirect = status.is_a?(Integer) && self.class.redirect?(status, headers: headers)
|
|
501
|
+
|
|
390
502
|
case status
|
|
391
503
|
in ..299
|
|
392
504
|
[status, response, stream]
|
|
393
|
-
in
|
|
505
|
+
in Integer if redirect && redirect_count >= self.class::MAX_REDIRECTS
|
|
394
506
|
self.class.reap_connection!(status, stream: stream)
|
|
395
507
|
|
|
396
508
|
message = "Failed to complete the request within #{self.class::MAX_REDIRECTS} redirects."
|
|
397
|
-
raise Straddle::Errors::APIConnectionError.new(
|
|
398
|
-
|
|
509
|
+
raise Straddle::Errors::APIConnectionError.new(
|
|
510
|
+
url: url,
|
|
511
|
+
response: response,
|
|
512
|
+
message: message
|
|
513
|
+
)
|
|
514
|
+
in Integer if redirect
|
|
399
515
|
self.class.reap_connection!(status, stream: stream)
|
|
400
516
|
|
|
401
|
-
request =
|
|
517
|
+
request =
|
|
518
|
+
self.class.follow_redirect(
|
|
519
|
+
request,
|
|
520
|
+
status: status,
|
|
521
|
+
response_headers: headers,
|
|
522
|
+
base_url: @base_url,
|
|
523
|
+
credential_headers: auth_header_keys
|
|
524
|
+
)
|
|
402
525
|
send_request(
|
|
403
526
|
request,
|
|
404
527
|
redirect_count: redirect_count + 1,
|
|
@@ -407,10 +530,19 @@ module Straddle
|
|
|
407
530
|
)
|
|
408
531
|
in Straddle::Errors::APIConnectionError if retry_count >= max_retries
|
|
409
532
|
raise status
|
|
410
|
-
|
|
533
|
+
# Any other 3xx — a 304 answering a conditional request, a 300, a redirect status without a
|
|
534
|
+
# `location` — is the server's answer rather than a hop, so it fails as a status error, like a 4xx.
|
|
535
|
+
in (300..) if retry_count >= max_retries || !self.class.should_retry?(status, headers: headers)
|
|
536
|
+
# Read only for the error's `body`, so only its first `MAX_ERROR_BODY_BYTES` are kept and
|
|
537
|
+
# the rest is never read: a server cannot make an error cost more than that in memory.
|
|
411
538
|
decoded =
|
|
412
539
|
Kernel.then do
|
|
413
|
-
Straddle::Internal::Util.decode_content(
|
|
540
|
+
Straddle::Internal::Util.decode_content(
|
|
541
|
+
headers,
|
|
542
|
+
stream: stream,
|
|
543
|
+
suppress_error: true,
|
|
544
|
+
truncate_at: Straddle::Internal::Util::MAX_ERROR_BODY_BYTES
|
|
545
|
+
)
|
|
414
546
|
ensure
|
|
415
547
|
self.class.reap_connection!(status, stream: stream)
|
|
416
548
|
end
|
|
@@ -423,7 +555,7 @@ module Straddle
|
|
|
423
555
|
request: nil,
|
|
424
556
|
response: response
|
|
425
557
|
)
|
|
426
|
-
in
|
|
558
|
+
in 300.. | Straddle::Errors::APIConnectionError
|
|
427
559
|
self.class.reap_connection!(status, stream: stream)
|
|
428
560
|
|
|
429
561
|
delay = retry_delay(response || {}, retry_count: retry_count)
|
|
@@ -492,7 +624,14 @@ module Straddle
|
|
|
492
624
|
send_request(request, redirect_count: 0, retry_count: 0, send_retry_header: send_retry_header)
|
|
493
625
|
|
|
494
626
|
headers = Straddle::Internal::Util.normalized_headers(response.each_header.to_h)
|
|
495
|
-
|
|
627
|
+
# Only an operation declared to return raw bytes reads its body whole; every other buffered
|
|
628
|
+
# body is capped, since the response's own content type cannot be trusted to say which it is.
|
|
629
|
+
decoded =
|
|
630
|
+
Straddle::Internal::Util.decode_content(
|
|
631
|
+
headers,
|
|
632
|
+
stream: stream,
|
|
633
|
+
download: model == StringIO
|
|
634
|
+
)
|
|
496
635
|
case req
|
|
497
636
|
in stream: Class => st
|
|
498
637
|
st.new(
|
|
@@ -516,9 +655,8 @@ module Straddle
|
|
|
516
655
|
#
|
|
517
656
|
# @return [String]
|
|
518
657
|
def inspect
|
|
519
|
-
# rubocop:disable Layout/LineLength
|
|
658
|
+
# rubocop:disable-next Layout/LineLength
|
|
520
659
|
"#<#{self.class.name}:0x#{object_id.to_s(16)} base_url=#{@base_url} max_retries=#{@max_retries} timeout=#{@timeout}>"
|
|
521
|
-
# rubocop:enable Layout/LineLength
|
|
522
660
|
end
|
|
523
661
|
|
|
524
662
|
define_sorbet_constant!(:RequestComponents) do
|
|
@@ -545,7 +683,13 @@ module Straddle
|
|
|
545
683
|
)
|
|
546
684
|
),
|
|
547
685
|
page:
|
|
548
|
-
T.nilable(
|
|
686
|
+
T.nilable(
|
|
687
|
+
T::Class[
|
|
688
|
+
Straddle::Internal::Type::BasePage[
|
|
689
|
+
Straddle::Internal::Type::BaseModel
|
|
690
|
+
]
|
|
691
|
+
]
|
|
692
|
+
),
|
|
549
693
|
stream: T.nilable(T::Class[T.anything]),
|
|
550
694
|
model: T.nilable(Straddle::Internal::Type::Converter::Input),
|
|
551
695
|
options: T.nilable(Straddle::RequestOptions::OrHash)
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Straddle
|
|
4
|
+
module Internal
|
|
5
|
+
module Transport
|
|
6
|
+
# @api private
|
|
7
|
+
#
|
|
8
|
+
# A fixed-size, thread-safe pool of lazily created connections. `PooledNetRequester` keeps one per
|
|
9
|
+
# origin, so `size` caps the concurrent requests to that origin.
|
|
10
|
+
class ConnectionPool
|
|
11
|
+
# @api private
|
|
12
|
+
#
|
|
13
|
+
# Checks a connection out for the duration of the block and back in afterwards, even when the
|
|
14
|
+
# block raises.
|
|
15
|
+
#
|
|
16
|
+
# @param timeout [Float] seconds to wait for a connection when every one is checked out
|
|
17
|
+
# @param blk [Proc]
|
|
18
|
+
#
|
|
19
|
+
# @raise [Timeout::Error] when no connection frees up within `timeout`
|
|
20
|
+
# @yieldparam [Object]
|
|
21
|
+
# @return [Object] the block's result
|
|
22
|
+
def with(timeout:, &blk)
|
|
23
|
+
# Interrupts (`Thread#raise`, `Timeout.timeout`) are held back while a connection changes
|
|
24
|
+
# hands, so none can land between the checkout and the `ensure` and leak the connection. The
|
|
25
|
+
# block itself runs with them enabled again.
|
|
26
|
+
::Thread.handle_interrupt(Object => :never) do
|
|
27
|
+
conn, pid = checkout(timeout)
|
|
28
|
+
begin
|
|
29
|
+
::Thread.handle_interrupt(Object => :immediate) { blk.call(conn) }
|
|
30
|
+
ensure
|
|
31
|
+
checkin(conn, pid)
|
|
32
|
+
end
|
|
33
|
+
end
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
# @api private
|
|
37
|
+
#
|
|
38
|
+
# @param timeout [Float]
|
|
39
|
+
#
|
|
40
|
+
# @raise [Timeout::Error]
|
|
41
|
+
# @return [Array(Object, Integer)] the connection, and the process it was checked out in
|
|
42
|
+
private def checkout(timeout)
|
|
43
|
+
# The deadline is on the monotonic clock, as the requester's own is, so a wall-clock jump can
|
|
44
|
+
# neither stretch nor cut the wait.
|
|
45
|
+
deadline = Straddle::Internal::Util.monotonic_secs + timeout
|
|
46
|
+
@mutex.synchronize do
|
|
47
|
+
reset_after_fork
|
|
48
|
+
loop do
|
|
49
|
+
# An idle connection or a free slot is handed out even once the deadline has passed: the
|
|
50
|
+
# timeout bounds the wait for one, and the requester raises its own timeout from there
|
|
51
|
+
# before it uses the connection. Most recently returned first, so the connection most
|
|
52
|
+
# likely to still be alive is the one reused.
|
|
53
|
+
return @idle.pop, @pid unless @idle.empty?
|
|
54
|
+
|
|
55
|
+
if @created < @size
|
|
56
|
+
# Created under the lock so two threads cannot both take the last slot. That is cheap:
|
|
57
|
+
# the block only builds the client object, and the requester connects it later.
|
|
58
|
+
conn = @create.call
|
|
59
|
+
@created += 1
|
|
60
|
+
return conn, @pid
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
remaining = deadline - Straddle::Internal::Util.monotonic_secs
|
|
64
|
+
unless remaining.positive?
|
|
65
|
+
raise Timeout::Error, "Waited #{timeout} seconds for one of #{@size} pooled connections"
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
# `wait` releases the mutex while it sleeps and takes it back before returning, whether a
|
|
69
|
+
# check-in, the timeout or a spurious wakeup woke it. So the loop looks at the pool again
|
|
70
|
+
# instead of trusting the reason, and only ever waits for what is left of the deadline.
|
|
71
|
+
@available.wait(@mutex, remaining)
|
|
72
|
+
end
|
|
73
|
+
end
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
# @api private
|
|
77
|
+
#
|
|
78
|
+
# @param conn [Object]
|
|
79
|
+
# @param pid [Integer]
|
|
80
|
+
private def checkin(conn, pid)
|
|
81
|
+
close = nil
|
|
82
|
+
@mutex.synchronize do
|
|
83
|
+
reset_after_fork
|
|
84
|
+
# A connection checked out before a fork is the parent's: `reset_after_fork` has already
|
|
85
|
+
# stopped counting it, so it is dropped rather than handed to the child's next request.
|
|
86
|
+
if pid == @pid && @close
|
|
87
|
+
close = @close
|
|
88
|
+
# Its slot is free again, so the next checkout can build a connection in its place.
|
|
89
|
+
@created -= 1
|
|
90
|
+
elsif pid == @pid
|
|
91
|
+
@idle.push(conn)
|
|
92
|
+
end
|
|
93
|
+
@available.signal
|
|
94
|
+
end
|
|
95
|
+
# A pool shut down while this connection was out keeps nothing; closed outside the lock.
|
|
96
|
+
begin
|
|
97
|
+
close&.call(conn)
|
|
98
|
+
rescue StandardError
|
|
99
|
+
nil
|
|
100
|
+
end
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
# @api private
|
|
104
|
+
#
|
|
105
|
+
# Closes every idle connection with `close` and every connection still checked out as it comes
|
|
106
|
+
# back, so a pool the owner has let go of holds no socket open. The pool still works after
|
|
107
|
+
# this, one connection per checkout, for a caller that looked it up just before.
|
|
108
|
+
#
|
|
109
|
+
# @param close [Proc] closes one connection
|
|
110
|
+
#
|
|
111
|
+
# @yieldparam [Object]
|
|
112
|
+
def shutdown(&close)
|
|
113
|
+
idle =
|
|
114
|
+
@mutex.synchronize do
|
|
115
|
+
@close = close
|
|
116
|
+
# A forked child does not own the parent's connections, so it closes none of them.
|
|
117
|
+
taken = @pid == Process.pid ? @idle.slice!(0..) : []
|
|
118
|
+
@created -= taken.size
|
|
119
|
+
taken
|
|
120
|
+
end
|
|
121
|
+
idle.each do |conn|
|
|
122
|
+
close.call(conn)
|
|
123
|
+
rescue StandardError
|
|
124
|
+
nil
|
|
125
|
+
end
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
# @api private
|
|
129
|
+
#
|
|
130
|
+
# A forked child inherits the parent's open sockets. Reusing one would interleave both
|
|
131
|
+
# processes' requests on a single connection, so the first checkout or check-in in a new
|
|
132
|
+
# process forgets every connection and lets the pool fill up again from empty. The forgotten
|
|
133
|
+
# ones are not closed either: closing a TLS connection writes to the socket the parent is still
|
|
134
|
+
# using.
|
|
135
|
+
private def reset_after_fork
|
|
136
|
+
return if @pid == Process.pid
|
|
137
|
+
|
|
138
|
+
@idle.clear
|
|
139
|
+
@created = 0
|
|
140
|
+
@pid = Process.pid
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
# @api private
|
|
144
|
+
#
|
|
145
|
+
# @param size [Integer]
|
|
146
|
+
# @param blk [Proc] builds one connection, called lazily as the pool fills up
|
|
147
|
+
def initialize(size:, &blk)
|
|
148
|
+
@size = size
|
|
149
|
+
@create = blk
|
|
150
|
+
@mutex = Mutex.new
|
|
151
|
+
@available = ConditionVariable.new
|
|
152
|
+
@idle = []
|
|
153
|
+
@created = 0
|
|
154
|
+
@pid = Process.pid
|
|
155
|
+
@close = nil
|
|
156
|
+
end
|
|
157
|
+
end
|
|
158
|
+
end
|
|
159
|
+
end
|
|
160
|
+
end
|