redu-sandbox-sdk 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.
- checksums.yaml +7 -0
- data/LICENSE +202 -0
- data/README.md +82 -0
- data/docs/reference.md +865 -0
- data/lib/redu_sandbox/audit.rb +525 -0
- data/lib/redu_sandbox/client.rb +59 -0
- data/lib/redu_sandbox/errors.rb +230 -0
- data/lib/redu_sandbox/http.rb +326 -0
- data/lib/redu_sandbox/sandboxes.rb +1947 -0
- data/lib/redu_sandbox/types.rb +1154 -0
- data/lib/redu_sandbox/version.rb +5 -0
- data/lib/redu_sandbox.rb +23 -0
- data/redu-sandbox-sdk.gemspec +27 -0
- metadata +63 -0
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# The one error family this client raises for a refusal or a failure.
|
|
4
|
+
#
|
|
5
|
+
# redu answers every error of /v1 as {"error": {"code", "message", "hint"?}}, so +code+ is the stable thing to branch
|
|
6
|
+
# on; +message+ and +hint+ are sentences for a person or an agent to read. A few answers come from in front of that
|
|
7
|
+
# envelope and are not JSON (a signed-in session's refused token is a plain-text 403 "Access denied" from the auth
|
|
8
|
+
# layer, a proxy's 502 or 504 is an HTML page): those get a code from their status, with the words the error envelope
|
|
9
|
+
# gives a bare status.
|
|
10
|
+
#
|
|
11
|
+
# Every error is a ReduSandbox::Error. Its subclass says what kind of answer it was (by the client's own code first, then by
|
|
12
|
+
# HTTP status), so both `rescue ReduSandbox::NotFoundError` and `rescue ReduSandbox::Error => e; e.code == "sandbox_not_found"` work.
|
|
13
|
+
module ReduSandbox
|
|
14
|
+
# The codes this client gives an error that did not come from redu's envelope.
|
|
15
|
+
# - network_error: no HTTP answer at all (the connection failed, or the request was cut at the timeout).
|
|
16
|
+
# - wait_timeout: a request that answered 202 was still running when the client stopped waiting for it.
|
|
17
|
+
# - still_pending: a read, or a command, kept answering "pending" after every retry; or a session through the
|
|
18
|
+
# platform (open_ssh, a websocket terminal) was not ready after every open.
|
|
19
|
+
# - unexpected_answer: redu answered 2xx with a body this client does not recognise.
|
|
20
|
+
CLIENT_ERROR_CODES = %w[network_error wait_timeout still_pending unexpected_answer].freeze
|
|
21
|
+
|
|
22
|
+
# What the error envelope calls a bare status (its STATUS_CODE_NAMES), for an answer that has no envelope.
|
|
23
|
+
STATUS_CODE_NAMES = {
|
|
24
|
+
400 => "bad_request",
|
|
25
|
+
401 => "unauthorized",
|
|
26
|
+
402 => "payment_required",
|
|
27
|
+
403 => "forbidden",
|
|
28
|
+
404 => "not_found",
|
|
29
|
+
405 => "method_not_allowed",
|
|
30
|
+
409 => "conflict",
|
|
31
|
+
413 => "payload_too_large",
|
|
32
|
+
422 => "validation_error",
|
|
33
|
+
429 => "rate_limited",
|
|
34
|
+
500 => "internal_error",
|
|
35
|
+
502 => "bad_gateway",
|
|
36
|
+
503 => "service_unavailable",
|
|
37
|
+
504 => "gateway_timeout"
|
|
38
|
+
}.freeze
|
|
39
|
+
|
|
40
|
+
# The code of a bare status, as the API names it, or "error".
|
|
41
|
+
def self.code_for_status(status)
|
|
42
|
+
STATUS_CODE_NAMES.fetch(status, "error")
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
# A refusal or failure of a redu request.
|
|
46
|
+
#
|
|
47
|
+
# status:: the HTTP status, or 0 when no answer came back (code network_error).
|
|
48
|
+
# code:: redu's stable code (sandbox_not_found, quota_exceeded, ...), or one of CLIENT_ERROR_CODES.
|
|
49
|
+
# message, hint:: redu's own sentences, unchanged.
|
|
50
|
+
# details:: the rest of redu's error object (a validation error's issues, a scope error's required_scope).
|
|
51
|
+
# retry_after_s:: from Retry-After, in seconds.
|
|
52
|
+
# workflow_id:: set when the error is how a request that answered 202 ended, on a take_snapshot refused with
|
|
53
|
+
# snapshot_in_progress (the take already under way), on a resize refused with resize_busy, on a change_egress
|
|
54
|
+
# refused with egress_change_busy, on a set_lifecycle refused with lifecycle_busy, on a change of secrets refused
|
|
55
|
+
# with secrets_change_busy and on a change of SSH keys refused with ssh_keys_busy (the one under way):
|
|
56
|
+
# wait_for_request(workflow_id) waits for it. On a still_pending of open_ssh or a websocket terminal it is the last
|
|
57
|
+
# 202's id, which /v1/sandboxes/requests does not read: open it again instead.
|
|
58
|
+
# ran, idempotency_key:: set on errors of exec and start_command: :yes, :no or :unknown, and the key it was tried
|
|
59
|
+
# under, so a caller knows whether running it again is safe.
|
|
60
|
+
# http_method, path:: the request this error answers (not +method+: that name is Object#method).
|
|
61
|
+
class Error < StandardError
|
|
62
|
+
attr_reader :status, :code, :hint, :details, :retry_after_s, :workflow_id, :ran, :idempotency_key,
|
|
63
|
+
:http_method, :path
|
|
64
|
+
|
|
65
|
+
def initialize(status:, code:, message:, hint: nil, details: nil, retry_after_s: nil, workflow_id: nil, ran: nil,
|
|
66
|
+
idempotency_key: nil, http_method: nil, path: nil)
|
|
67
|
+
super(message)
|
|
68
|
+
@status = status
|
|
69
|
+
@code = code
|
|
70
|
+
@text = message
|
|
71
|
+
@hint = hint
|
|
72
|
+
@details = details
|
|
73
|
+
@retry_after_s = retry_after_s
|
|
74
|
+
@workflow_id = workflow_id
|
|
75
|
+
@ran = ran
|
|
76
|
+
@idempotency_key = idempotency_key
|
|
77
|
+
@http_method = http_method
|
|
78
|
+
@path = path
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
# redu's own sentence, unchanged.
|
|
82
|
+
def message
|
|
83
|
+
@text
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
# What an uncaught error prints: the code, the sentence, the status and the hint.
|
|
87
|
+
def detailed_message(highlight: false, **)
|
|
88
|
+
where = status.zero? ? "no answer" : "HTTP #{status}"
|
|
89
|
+
text = "[#{code}] #{message} (#{where})"
|
|
90
|
+
text += " Hint: #{hint}" if hint
|
|
91
|
+
highlight ? "\e[1m#{text}\e[m" : text
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
def inspect
|
|
95
|
+
"#<#{self.class.name} status=#{status.inspect} code=#{code.inspect} message=#{message.inspect}>"
|
|
96
|
+
end
|
|
97
|
+
|
|
98
|
+
# The same error, of the same class, with more of what the caller needs to know.
|
|
99
|
+
def with_context(workflow_id: nil, ran: nil, idempotency_key: nil)
|
|
100
|
+
e = self.class.new(
|
|
101
|
+
status: status, code: code, message: message, hint: hint, details: details, retry_after_s: retry_after_s,
|
|
102
|
+
http_method: http_method, path: path,
|
|
103
|
+
workflow_id: workflow_id.nil? ? self.workflow_id : workflow_id,
|
|
104
|
+
ran: ran.nil? ? self.ran : ran,
|
|
105
|
+
idempotency_key: idempotency_key.nil? ? self.idempotency_key : idempotency_key
|
|
106
|
+
)
|
|
107
|
+
e.set_backtrace(backtrace) if backtrace
|
|
108
|
+
e
|
|
109
|
+
end
|
|
110
|
+
|
|
111
|
+
# The fields a log needs (never a credential: redu's error bodies carry none).
|
|
112
|
+
def to_h(include_request: false)
|
|
113
|
+
out = { name: self.class.name, status: status, code: code, message: message }
|
|
114
|
+
%i[hint details retry_after_s workflow_id ran idempotency_key].each do |k|
|
|
115
|
+
v = public_send(k)
|
|
116
|
+
out[k] = v unless v.nil?
|
|
117
|
+
end
|
|
118
|
+
if include_request
|
|
119
|
+
out[:http_method] = http_method
|
|
120
|
+
out[:path] = path
|
|
121
|
+
end
|
|
122
|
+
out
|
|
123
|
+
end
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
# No HTTP answer came back (status 0, code network_error).
|
|
127
|
+
class NetworkError < Error; end
|
|
128
|
+
# A request that answered 202 was still running when the client stopped waiting (code wait_timeout).
|
|
129
|
+
class WaitTimeoutError < Error; end
|
|
130
|
+
# A read or a command kept answering "pending" after every retry, or a session through the platform was not ready
|
|
131
|
+
# after every open (code still_pending).
|
|
132
|
+
class StillPendingError < Error; end
|
|
133
|
+
# redu answered 2xx with a body this client does not recognise (code unexpected_answer).
|
|
134
|
+
class UnexpectedAnswerError < Error; end
|
|
135
|
+
# 400 or 422: the request was refused as written (validation_error, template_not_found, ...).
|
|
136
|
+
class BadRequestError < Error; end
|
|
137
|
+
# 401: no valid credential (unauthorized, key_expired).
|
|
138
|
+
class AuthenticationError < Error; end
|
|
139
|
+
# 402: a billing gate (billing_inactive, spend_cap_reached, max_spend_reached, ...).
|
|
140
|
+
class PaymentRequiredError < Error; end
|
|
141
|
+
# 403: insufficient_scope, sandboxes_not_available, the auth layer's forbidden, ...
|
|
142
|
+
class PermissionDeniedError < Error; end
|
|
143
|
+
# 404: sandbox_not_found, sandbox_request_not_found, file_not_found, command_not_found, snapshot_not_found, ...
|
|
144
|
+
class NotFoundError < Error; end
|
|
145
|
+
# 409: the sandbox's state refuses the request (sandbox_not_running, sandbox_suspended, fork_not_now,
|
|
146
|
+
# sandbox_busy_for_snapshot, snapshot_limit_reached, egress_change_busy, volume_in_use, ...).
|
|
147
|
+
class ConflictError < Error; end
|
|
148
|
+
# 429: rate_limited (redu's limiters), sandbox_busy (too many commands at once), or template_build_rate_limited (the
|
|
149
|
+
# account's template builds of the last 24 hours: never sent again by the client).
|
|
150
|
+
class RateLimitError < Error; end
|
|
151
|
+
# 5xx: redu's own failure codes, or a proxy's page in front of it.
|
|
152
|
+
class ServerError < Error; end
|
|
153
|
+
# 503 snapshot_not_taken: a take whose answer was lost, and whose snapshot was then not found. Nothing was kept, so
|
|
154
|
+
# taking it again is safe.
|
|
155
|
+
class SnapshotNotTakenError < ServerError; end
|
|
156
|
+
# 503 snapshot_outcome_unknown: a take whose answer was lost and could not be confirmed. The snapshot MAY have been
|
|
157
|
+
# taken: then it exists and counts against the account's snapshot limit without being listed (redu kept no record
|
|
158
|
+
# of it, so list_snapshots never shows it). Never "not taken": wait a few minutes before taking another, and if
|
|
159
|
+
# snapshot_limit_reached answers while fewer snapshots are listed, write to support@redu.cloud (redu's hint says so).
|
|
160
|
+
class SnapshotOutcomeUnknownError < ServerError; end
|
|
161
|
+
|
|
162
|
+
# 409 resize_not_available: the sandbox's template cannot be resized (or resizing is switched off), and nothing
|
|
163
|
+
# changed. Its size was set at its create: create a new sandbox at the size you need. A ConflictError.
|
|
164
|
+
class ResizeNotAvailableError < ConflictError; end
|
|
165
|
+
|
|
166
|
+
# 409 egress_change_unavailable: a running sandbox's egress rules cannot be changed on this platform yet, and nothing
|
|
167
|
+
# changed. The sandbox keeps the rules it was created with: create a sandbox with the rules you need. A ConflictError.
|
|
168
|
+
class EgressChangeUnavailableError < ConflictError; end
|
|
169
|
+
|
|
170
|
+
# 502 idle_pause_outcome_unknown: a lifecycle change whose idle pause may have been changed, but whose answer was
|
|
171
|
+
# lost; the rest of the change was not made. Sending the same change again is safe; get_lifecycle shows the idle
|
|
172
|
+
# pause the sandbox has. A part applied before it is in details["applied"]. A ServerError.
|
|
173
|
+
class IdlePauseOutcomeUnknownError < ServerError; end
|
|
174
|
+
|
|
175
|
+
# 502 secrets_outcome_unknown: a change of a sandbox's secrets whose answer was lost. They may have been changed:
|
|
176
|
+
# send the same list again (the same list twice is one change). A ServerError.
|
|
177
|
+
class SecretsOutcomeUnknownError < ServerError; end
|
|
178
|
+
|
|
179
|
+
# 502 ssh_outcome_unknown: a change of a sandbox's SSH keys whose answer was lost. get_ssh shows its keys; add or
|
|
180
|
+
# remove the key again (the same change twice is one change). A ServerError.
|
|
181
|
+
class SshOutcomeUnknownError < ServerError; end
|
|
182
|
+
|
|
183
|
+
ERROR_BY_CODE = {
|
|
184
|
+
"network_error" => NetworkError,
|
|
185
|
+
"wait_timeout" => WaitTimeoutError,
|
|
186
|
+
"still_pending" => StillPendingError,
|
|
187
|
+
"unexpected_answer" => UnexpectedAnswerError
|
|
188
|
+
}.freeze
|
|
189
|
+
|
|
190
|
+
# redu's codes that have a class of their own, a subclass of their status's class (so rescue
|
|
191
|
+
# ReduSandbox::ServerError still catches them): the two outcomes of a snapshot's take that must never be mistaken for
|
|
192
|
+
# each other, and the changes of an idle pause, of secrets and of SSH keys whose answer was lost.
|
|
193
|
+
ERROR_BY_REDU_CODE = {
|
|
194
|
+
"snapshot_not_taken" => SnapshotNotTakenError,
|
|
195
|
+
"snapshot_outcome_unknown" => SnapshotOutcomeUnknownError,
|
|
196
|
+
"idle_pause_outcome_unknown" => IdlePauseOutcomeUnknownError,
|
|
197
|
+
"secrets_outcome_unknown" => SecretsOutcomeUnknownError,
|
|
198
|
+
"ssh_outcome_unknown" => SshOutcomeUnknownError
|
|
199
|
+
}.freeze
|
|
200
|
+
|
|
201
|
+
ERROR_BY_STATUS = {
|
|
202
|
+
400 => BadRequestError,
|
|
203
|
+
401 => AuthenticationError,
|
|
204
|
+
402 => PaymentRequiredError,
|
|
205
|
+
403 => PermissionDeniedError,
|
|
206
|
+
404 => NotFoundError,
|
|
207
|
+
409 => ConflictError,
|
|
208
|
+
422 => BadRequestError,
|
|
209
|
+
429 => RateLimitError
|
|
210
|
+
}.freeze
|
|
211
|
+
|
|
212
|
+
# The ReduSandbox::Error subclass for an answer: by the client's own code first, then by redu's few codes with a
|
|
213
|
+
# class of their own (the two snapshot outcomes and the three outcome_unknown changes as 5xx, resize_not_available
|
|
214
|
+
# and egress_change_unavailable as 409, as redu answers them), then by HTTP status.
|
|
215
|
+
def self.error_class(status, code)
|
|
216
|
+
return ERROR_BY_CODE[code] if ERROR_BY_CODE.key?(code)
|
|
217
|
+
return ERROR_BY_REDU_CODE[code] if status >= 500 && ERROR_BY_REDU_CODE.key?(code)
|
|
218
|
+
return ResizeNotAvailableError if status == 409 && code == "resize_not_available"
|
|
219
|
+
return EgressChangeUnavailableError if status == 409 && code == "egress_change_unavailable"
|
|
220
|
+
return ERROR_BY_STATUS[status] if ERROR_BY_STATUS.key?(status)
|
|
221
|
+
return ServerError if status >= 500
|
|
222
|
+
|
|
223
|
+
Error
|
|
224
|
+
end
|
|
225
|
+
|
|
226
|
+
# A ReduSandbox::Error of the class its status and code call for.
|
|
227
|
+
def self.make_error(status:, code:, message:, **kw)
|
|
228
|
+
error_class(status, code).new(status: status, code: code, message: message, **kw)
|
|
229
|
+
end
|
|
230
|
+
end
|
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
require "net/http"
|
|
5
|
+
require "openssl"
|
|
6
|
+
require "time"
|
|
7
|
+
require "uri"
|
|
8
|
+
require "zlib"
|
|
9
|
+
|
|
10
|
+
module ReduSandbox
|
|
11
|
+
DEFAULT_BASE_URL = "https://console.redu.cloud"
|
|
12
|
+
|
|
13
|
+
# The longest Retry-After this client waits out by itself, in seconds; a longer one is raised to the caller.
|
|
14
|
+
MAX_RETRY_AFTER_S = 60.0
|
|
15
|
+
|
|
16
|
+
# The resolved options of a client (see ReduSandbox::Client for what each one means). +token+ is a String, or anything
|
|
17
|
+
# that answers #call with a fresh one (a session token expires).
|
|
18
|
+
Options = Data.define(:base_url, :timeout, :poll_interval, :max_rate_limit_retries, :user_agent, :token) do
|
|
19
|
+
def inspect
|
|
20
|
+
"#<ReduSandbox::Options base_url=#{base_url.inspect} timeout=#{timeout} poll_interval=#{poll_interval} " \
|
|
21
|
+
"max_rate_limit_retries=#{max_rate_limit_retries} user_agent=#{user_agent.inspect}>"
|
|
22
|
+
end
|
|
23
|
+
alias_method :to_s, :inspect
|
|
24
|
+
|
|
25
|
+
def pretty_print(q)
|
|
26
|
+
q.text(inspect)
|
|
27
|
+
end
|
|
28
|
+
end
|
|
29
|
+
|
|
30
|
+
# A 1xx to 3xx answer: its status, its parsed JSON body (nil for an empty one, a 204), its headers (names in lower
|
|
31
|
+
# case) and, for a request made with raw: true, its bytes (body is nil then).
|
|
32
|
+
Answer = Data.define(:status, :body, :headers, :content)
|
|
33
|
+
|
|
34
|
+
# The HTTP layer: one exchange with redu, how an answer becomes a ReduSandbox::Error, and the rate-limit retry.
|
|
35
|
+
class Transport
|
|
36
|
+
NOT_JSON = Object.new.freeze
|
|
37
|
+
|
|
38
|
+
NETWORK_ERRORS = [
|
|
39
|
+
SocketError, SystemCallError, IOError, EOFError, OpenSSL::SSL::SSLError, Net::HTTPBadResponse,
|
|
40
|
+
Net::ProtocolError, Zlib::Error, Timeout::Error
|
|
41
|
+
].freeze
|
|
42
|
+
|
|
43
|
+
attr_reader :options
|
|
44
|
+
|
|
45
|
+
def self.resolve_options(api_key:, token:, base_url:, timeout:, poll_interval:, max_rate_limit_retries:, user_agent:)
|
|
46
|
+
raise ArgumentError, "Give api_key or token, not both." if !api_key.nil? && !token.nil?
|
|
47
|
+
|
|
48
|
+
credential =
|
|
49
|
+
if !token.nil?
|
|
50
|
+
unless token.respond_to?(:call) || (token.is_a?(String) && !token.empty?)
|
|
51
|
+
raise ArgumentError, "token must be a non-empty string, or something that answers #call with one."
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
token
|
|
55
|
+
else
|
|
56
|
+
key = api_key.nil? ? env("REDU_API_KEY") : api_key
|
|
57
|
+
raise ArgumentError, "No credential: give api_key or token, or set REDU_API_KEY." unless key.is_a?(String) && !key.empty?
|
|
58
|
+
|
|
59
|
+
key
|
|
60
|
+
end
|
|
61
|
+
retries = non_negative(max_rate_limit_retries, 2, "max_rate_limit_retries")
|
|
62
|
+
Options.new(
|
|
63
|
+
base_url: (base_url || env("REDU_API_BASE") || DEFAULT_BASE_URL).sub(%r{/+\z}, ""),
|
|
64
|
+
timeout: non_negative(timeout, 120.0, "timeout"),
|
|
65
|
+
poll_interval: non_negative(poll_interval, 5.0, "poll_interval"),
|
|
66
|
+
max_rate_limit_retries: retries.to_i,
|
|
67
|
+
user_agent: user_agent || "redu-sandbox-sdk-ruby/#{VERSION}",
|
|
68
|
+
token: credential
|
|
69
|
+
)
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
def self.env(name)
|
|
73
|
+
v = ENV.fetch(name, nil)
|
|
74
|
+
v.nil? || v.empty? ? nil : v
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
def self.non_negative(value, default, what)
|
|
78
|
+
return default.to_f if value.nil?
|
|
79
|
+
unless value.is_a?(Numeric) && value.real? && value.finite? && value >= 0
|
|
80
|
+
raise ArgumentError, "#{what} must be a number of 0 or more."
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
value.to_f
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
# How long a kept connection may stay idle before it is opened again (Net::HTTP's keep_alive_timeout, 2 s by
|
|
87
|
+
# default): 55 s, below the idle timeout common in front of HTTP APIs. An agent's calls usually come further apart
|
|
88
|
+
# than 2 s, and a new connection costs a TCP and TLS handshake (measured 2 Dec 2026 from a client 28 ms from the API:
|
|
89
|
+
# about 88 ms for a call on a new connection against 27 ms on a kept one).
|
|
90
|
+
KEEP_ALIVE_S = 55
|
|
91
|
+
|
|
92
|
+
def initialize(options)
|
|
93
|
+
@options = options
|
|
94
|
+
@sessions_key = :"redu_sandbox_http_#{object_id}"
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
# This thread's kept connections dropped (closed); the next call opens one again.
|
|
98
|
+
def close
|
|
99
|
+
sessions = Thread.current[@sessions_key]
|
|
100
|
+
return if sessions.nil?
|
|
101
|
+
|
|
102
|
+
sessions.each_value { |http| finish_quietly(http) }
|
|
103
|
+
sessions.clear
|
|
104
|
+
end
|
|
105
|
+
|
|
106
|
+
# One request, sent again after a 429 rate_limited up to max_rate_limit_retries times.
|
|
107
|
+
#
|
|
108
|
+
# redu's rate limits answer before any route runs (the API mounts the per-IP and per-user limiters ahead of the
|
|
109
|
+
# routes), so nothing was done and the same request, with the same Idempotency-Key, is safe to send again. A 429
|
|
110
|
+
# with any other code (sandbox_busy is the sandbox service's) is not a rate limit and is raised.
|
|
111
|
+
#
|
|
112
|
+
# +read_timeout+, in seconds, replaces the client's timeout for the wait for this request's answer (a route that
|
|
113
|
+
# redu holds open on purpose); connecting and sending keep the client's timeout.
|
|
114
|
+
#
|
|
115
|
+
# +raw+ true answers the body's bytes (a file's, asked for as application/octet-stream); +raw+ :text answers the
|
|
116
|
+
# bytes of a JSON answer unparsed (the audit log, whose records are hashed as they were written). Either way an
|
|
117
|
+
# error answer is read as JSON.
|
|
118
|
+
def request(method, path, body: nil, headers: {}, content: nil, raw: false, read_timeout: nil)
|
|
119
|
+
attempt = 0
|
|
120
|
+
loop do
|
|
121
|
+
return exchange(method, path, body: body, headers: headers, content: content, raw: raw, read_timeout: read_timeout)
|
|
122
|
+
rescue Error => e
|
|
123
|
+
raise unless e.status == 429 && e.code == "rate_limited" && attempt < options.max_rate_limit_retries
|
|
124
|
+
|
|
125
|
+
wait = e.retry_after_s || options.poll_interval
|
|
126
|
+
raise if wait > MAX_RETRY_AFTER_S
|
|
127
|
+
|
|
128
|
+
attempt += 1
|
|
129
|
+
pause(wait)
|
|
130
|
+
end
|
|
131
|
+
end
|
|
132
|
+
|
|
133
|
+
def pause(seconds)
|
|
134
|
+
sleep(seconds) if seconds.positive?
|
|
135
|
+
end
|
|
136
|
+
|
|
137
|
+
# One HTTP exchange: an Answer for 1xx to 3xx, else the ReduSandbox::Error the answer (or its absence) says.
|
|
138
|
+
def exchange(method, path, body: nil, headers: {}, content: nil, raw: false, read_timeout: nil)
|
|
139
|
+
uri = URI.parse(options.base_url + path)
|
|
140
|
+
req = build(method, uri, body, headers, content, raw)
|
|
141
|
+
waited = read_timeout || options.timeout
|
|
142
|
+
res = begin
|
|
143
|
+
http = session(uri)
|
|
144
|
+
http.read_timeout = waited
|
|
145
|
+
http.request(req)
|
|
146
|
+
rescue *NETWORK_ERRORS => e
|
|
147
|
+
drop_session(uri)
|
|
148
|
+
raise network_error(e, method, path, waited)
|
|
149
|
+
end
|
|
150
|
+
answer_of(res, method, path, raw)
|
|
151
|
+
end
|
|
152
|
+
|
|
153
|
+
# This thread's started connection to the URI's host, kept between calls (Net::HTTP is not thread-safe, so one per
|
|
154
|
+
# thread and client). Net::HTTP opens it again by itself when it was idle longer than KEEP_ALIVE_S or the server
|
|
155
|
+
# closed it, before it sends anything.
|
|
156
|
+
def session(uri)
|
|
157
|
+
sessions = (Thread.current[@sessions_key] ||= {})
|
|
158
|
+
id = [uri.scheme, uri.host, uri.port]
|
|
159
|
+
kept = sessions[id]
|
|
160
|
+
return kept if kept&.started?
|
|
161
|
+
|
|
162
|
+
http = Net::HTTP.new(uri.host, uri.port)
|
|
163
|
+
http.use_ssl = uri.scheme == "https"
|
|
164
|
+
http.open_timeout = options.timeout
|
|
165
|
+
http.write_timeout = options.timeout
|
|
166
|
+
http.keep_alive_timeout = KEEP_ALIVE_S
|
|
167
|
+
# Net::HTTP sends an idempotent request again by itself after a lost answer: the client's own rules decide.
|
|
168
|
+
http.max_retries = 0
|
|
169
|
+
http.start
|
|
170
|
+
sessions[id] = http
|
|
171
|
+
end
|
|
172
|
+
|
|
173
|
+
# The connection a failed exchange used, closed: the next call opens a new one.
|
|
174
|
+
def drop_session(uri)
|
|
175
|
+
sessions = Thread.current[@sessions_key]
|
|
176
|
+
return if sessions.nil?
|
|
177
|
+
|
|
178
|
+
http = sessions.delete([uri.scheme, uri.host, uri.port])
|
|
179
|
+
finish_quietly(http) unless http.nil?
|
|
180
|
+
end
|
|
181
|
+
|
|
182
|
+
def finish_quietly(http)
|
|
183
|
+
http.finish if http.started?
|
|
184
|
+
rescue IOError, SystemCallError, OpenSSL::SSL::SSLError
|
|
185
|
+
nil
|
|
186
|
+
end
|
|
187
|
+
|
|
188
|
+
# Retry-After in seconds (redu's limiters send seconds), or nil.
|
|
189
|
+
def self.retry_after_of(headers)
|
|
190
|
+
v = headers["retry-after"]
|
|
191
|
+
return nil if v.nil?
|
|
192
|
+
|
|
193
|
+
begin
|
|
194
|
+
n = Float(v.strip)
|
|
195
|
+
return n if n >= 0 && n.finite?
|
|
196
|
+
rescue ArgumentError
|
|
197
|
+
nil
|
|
198
|
+
end
|
|
199
|
+
begin
|
|
200
|
+
at = Time.httpdate(v.strip)
|
|
201
|
+
[0.0, (at - Time.now).ceil.to_f].max
|
|
202
|
+
rescue ArgumentError
|
|
203
|
+
nil
|
|
204
|
+
end
|
|
205
|
+
end
|
|
206
|
+
|
|
207
|
+
# The parsed body, nil for an empty one, or NOT_JSON.
|
|
208
|
+
def self.parse_json(text)
|
|
209
|
+
return nil if text.nil? || text.empty?
|
|
210
|
+
|
|
211
|
+
JSON.parse(text)
|
|
212
|
+
rescue JSON::ParserError, EncodingError
|
|
213
|
+
NOT_JSON
|
|
214
|
+
end
|
|
215
|
+
|
|
216
|
+
# The error of a 4xx or 5xx answer.
|
|
217
|
+
#
|
|
218
|
+
# redu's envelope ({"error": {"code", "message", "hint"?}}) is read as it is; an error that is a bare string gets
|
|
219
|
+
# its code from the status; an answer that is not JSON (the auth layer's plain-text 403 "Access denied", a proxy's
|
|
220
|
+
# page) gets its code from the status and a sentence of ours, with a short plain text kept as the message.
|
|
221
|
+
def self.error_from_answer(status, text, headers, method, path)
|
|
222
|
+
base = { status: status, retry_after_s: retry_after_of(headers), http_method: method, path: path }
|
|
223
|
+
parsed = parse_json(text)
|
|
224
|
+
if parsed.is_a?(Hash) && parsed.key?("error")
|
|
225
|
+
err = parsed["error"]
|
|
226
|
+
return ReduSandbox.make_error(code: ReduSandbox.code_for_status(status), message: err, **base) if err.is_a?(String)
|
|
227
|
+
|
|
228
|
+
if err.is_a?(Hash)
|
|
229
|
+
rest = err.reject { |k, _| %w[code message hint details].include?(k) }
|
|
230
|
+
code = err["code"]
|
|
231
|
+
message = err["message"]
|
|
232
|
+
hint = err["hint"]
|
|
233
|
+
details = err.key?("details") ? err["details"] : (rest.empty? ? nil : rest)
|
|
234
|
+
return ReduSandbox.make_error(
|
|
235
|
+
code: code.is_a?(String) && !code.empty? ? code : ReduSandbox.code_for_status(status),
|
|
236
|
+
message: message.is_a?(String) ? message : "redu answered HTTP #{status}.",
|
|
237
|
+
hint: hint.is_a?(String) ? hint : nil,
|
|
238
|
+
details: details,
|
|
239
|
+
**base
|
|
240
|
+
)
|
|
241
|
+
end
|
|
242
|
+
end
|
|
243
|
+
plain = nil
|
|
244
|
+
if parsed.equal?(NOT_JSON) && (headers["content-type"] || "").match?(%r{\Atext/plain}i) && text.length.between?(1, 200)
|
|
245
|
+
plain = text.strip
|
|
246
|
+
end
|
|
247
|
+
ReduSandbox.make_error(
|
|
248
|
+
code: ReduSandbox.code_for_status(status),
|
|
249
|
+
message: plain || "redu answered HTTP #{status} without its own error body (for example a proxy's error page).",
|
|
250
|
+
**base
|
|
251
|
+
)
|
|
252
|
+
end
|
|
253
|
+
|
|
254
|
+
# Whether an error carries no answer of redu's: no HTTP answer at all, or a 5xx whose body was not redu's envelope.
|
|
255
|
+
def self.no_answer?(error, known_codes)
|
|
256
|
+
return true if error.status.zero?
|
|
257
|
+
|
|
258
|
+
error.status >= 500 && !known_codes.include?(error.code)
|
|
259
|
+
end
|
|
260
|
+
|
|
261
|
+
private
|
|
262
|
+
|
|
263
|
+
def token
|
|
264
|
+
t = options.token
|
|
265
|
+
t = t.call if t.respond_to?(:call)
|
|
266
|
+
raise ArgumentError, "The token function returned no token." unless t.is_a?(String) && !t.empty?
|
|
267
|
+
|
|
268
|
+
t
|
|
269
|
+
end
|
|
270
|
+
|
|
271
|
+
def build(method, uri, body, headers, content, raw)
|
|
272
|
+
klass = { "GET" => Net::HTTP::Get, "POST" => Net::HTTP::Post, "PUT" => Net::HTTP::Put,
|
|
273
|
+
"DELETE" => Net::HTTP::Delete }.fetch(method)
|
|
274
|
+
req = klass.new(uri.request_uri)
|
|
275
|
+
# An API key travels as Authorization: Bearer: the API takes a 64-hex bearer as a key, and lets the request past
|
|
276
|
+
# once the key is checked. A session token goes the same way.
|
|
277
|
+
req["accept"] = raw == true ? "application/octet-stream, application/json" : "application/json"
|
|
278
|
+
req["user-agent"] = options.user_agent
|
|
279
|
+
req["authorization"] = "Bearer #{token}"
|
|
280
|
+
headers.each { |k, v| req[k] = v }
|
|
281
|
+
if !content.nil?
|
|
282
|
+
req["content-type"] = "application/octet-stream"
|
|
283
|
+
req.body = content.b
|
|
284
|
+
elsif !body.nil?
|
|
285
|
+
req["content-type"] = "application/json"
|
|
286
|
+
req.body = JSON.generate(body)
|
|
287
|
+
elsif req.request_body_permitted?
|
|
288
|
+
# A POST with nothing to send (a pause, a terminal's open): Net::HTTP would send an empty form body with a
|
|
289
|
+
# warning. An empty JSON body reads as {} (body-parser's json special-cases it), which those routes take.
|
|
290
|
+
req["content-type"] = "application/json"
|
|
291
|
+
req.body = ""
|
|
292
|
+
end
|
|
293
|
+
req
|
|
294
|
+
end
|
|
295
|
+
|
|
296
|
+
def network_error(cause, method, path, waited = options.timeout)
|
|
297
|
+
message =
|
|
298
|
+
case cause
|
|
299
|
+
when Net::ReadTimeout then "No answer from redu within #{waited.round} s."
|
|
300
|
+
when Timeout::Error then "No answer from redu within #{options.timeout.round} s."
|
|
301
|
+
when Zlib::Error
|
|
302
|
+
"redu's answer could not be read: its body could not be decoded (for example a proxy's broken compression)."
|
|
303
|
+
else "The connection to redu failed before an answer came back."
|
|
304
|
+
end
|
|
305
|
+
ReduSandbox.make_error(status: 0, code: "network_error", http_method: method, path: path, message: message)
|
|
306
|
+
end
|
|
307
|
+
|
|
308
|
+
def answer_of(res, method, path, raw)
|
|
309
|
+
headers = {}
|
|
310
|
+
res.each_header { |k, v| headers[k.downcase] = v }
|
|
311
|
+
status = res.code.to_i
|
|
312
|
+
bytes = (res.body || "").b
|
|
313
|
+
if status >= 400
|
|
314
|
+
raise self.class.error_from_answer(status, bytes.dup.force_encoding(Encoding::UTF_8), headers, method, path)
|
|
315
|
+
end
|
|
316
|
+
return Answer.new(status: status, body: nil, headers: headers, content: bytes) if raw
|
|
317
|
+
|
|
318
|
+
parsed = self.class.parse_json(bytes.dup.force_encoding(Encoding::UTF_8))
|
|
319
|
+
if parsed.equal?(NOT_JSON)
|
|
320
|
+
raise ReduSandbox.make_error(status: status, code: "unexpected_answer", http_method: method, path: path,
|
|
321
|
+
message: "redu answered HTTP #{status} with a body that is not JSON.")
|
|
322
|
+
end
|
|
323
|
+
Answer.new(status: status, body: parsed, headers: headers, content: "".b)
|
|
324
|
+
end
|
|
325
|
+
end
|
|
326
|
+
end
|