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.
@@ -0,0 +1,1947 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+ require "set"
5
+
6
+ module ReduSandbox
7
+ # Every /v1/sandboxes route, answered as
8
+ # answers them, with the same rules for a 202, a lost answer and a
9
+ # failure as the Python, TypeScript and Go SDKs.
10
+ #
11
+ # An account that sandboxes are not open to gets 403 sandboxes_not_available on every route
12
+ # (Client#sandboxes_enabled? tells whether they are open to it).
13
+ class Sandboxes
14
+ # The codes the sandbox routes answer a failure of their own with (the terminal's included, and the bind layer's
15
+ # refusals of a name). A 5xx with one of these is
16
+ # redu's answer about the request. A 5xx without one (a proxy's page, a gateway timeout) says nothing about it.
17
+ SANDBOX_ANSWER_CODES = Set[
18
+ "sandboxes_not_available", "sandbox_not_found", "template_not_found", "template_unavailable",
19
+ "sandbox_not_running", "sandbox_deleting", "quota_exceeded", "sandbox_busy", "invalid_request",
20
+ "sandboxes_unavailable", "exec_outcome_unknown", "exec_not_started", "exec_result_lost", "sandbox_not_public",
21
+ "address_quota_exceeded", "sandbox_ending", "name_in_use", "sandbox_request_failed", "DOMAIN_TAKEN",
22
+ "DOMAIN_UNVERIFIED", "TARGET_NOT_ALLOWED", "domain_check_failed", "terminal_download_failed",
23
+ "terminal_checksum_mismatch", "terminal_port_in_use", "terminal_unsupported", "terminal_not_started",
24
+ "terminal_busy",
25
+ # pause, suspend, resume, extend, files and background commands
26
+ "sandbox_suspended", "sandbox_cannot_suspend", "sandbox_resume_unavailable", "sandbox_state_busy",
27
+ "max_spend_reached", "file_not_found", "file_too_large", "range_not_satisfiable", "command_not_found",
28
+ # snapshots, a create from a snapshot, and forks
29
+ "snapshot_not_found", "snapshot_limit_reached", "sandbox_busy_for_snapshot", "snapshot_not_possible",
30
+ "snapshot_not_taken", "snapshot_outcome_unknown", "snapshot_unavailable", "snapshot_server_unavailable",
31
+ "snapshot_deleting", "snapshot_in_progress", "fork_not_now", "fork_unsupported", "fork_no_room",
32
+ # a create's size and network, a resize, the event logs (connections and audit), and the refusals redu has for
33
+ # volumes and for groups
34
+ "size_unsupported", "network_not_found", "network_unusable", "resize_not_available", "resize_out_of_range",
35
+ "resize_refused", "resize_failed", "resize_incomplete", "resize_outcome_unknown", "resize_limit_reached",
36
+ "resize_busy", "event_log_unreadable", "too_many_log_reads", "volume_not_found", "volume_in_use",
37
+ "volume_not_available", "volume_unsupported", "too_many_volumes", "volumes_unavailable", "sandbox_has_volumes",
38
+ "security_group_quota_exceeded", "command_stop_unconfirmed", "volume_attach_failed",
39
+ # a change of a running sandbox's egress rules
40
+ "egress_change_unavailable", "egress_change_unsupported", "egress_change_busy", "egress_change_outcome_unknown",
41
+ "egress_not_filtered", "egress_rules_refused", "sandbox_changing",
42
+ # a sandbox's lifecycle and the account's limits: idle_pause_outcome_unknown is a 502 and usage_not_current a 503,
43
+ # so without them here they would be read again as a lost answer
44
+ "lifecycle_busy", "idle_pause_not_changeable", "idle_pause_change_unsupported", "idle_pause_outcome_unknown",
45
+ "max_spend_below_spend", "usage_not_current", "spend_cap_reached",
46
+ # templates built from container images
47
+ "template_build_in_progress", "template_build_not_found", "template_build_rate_limited", "template_build_refused",
48
+ "template_builds_unavailable", "template_in_use", "template_limit_reached", "template_name_taken",
49
+ # secrets bound to hosts: two of them are 502s
50
+ "secrets_change_busy", "secrets_unavailable", "secrets_unsupported", "secrets_refused",
51
+ "secrets_need_egress_filtering", "secrets_failed", "secrets_outcome_unknown",
52
+ # SSH and the terminals through the platform: two are 502s
53
+ "ssh_keys_busy", "ssh_unavailable", "ssh_unsupported", "ssh_keys_revoked", "ssh_key_refused", "ssh_failed",
54
+ "ssh_outcome_unknown", "denied_by_sandbox_rules", "terminal_unavailable", "sessions_not_closable",
55
+ # a sandbox with no end (timeout_s 0 at a create or an extend): no_end_unavailable is a
56
+ # 503, so without it here a request that ended with it would be read again as a lost answer
57
+ "no_end_needs_card", "no_end_unavailable",
58
+ # the account's free sandbox
59
+ "free_sandbox_options", "free_sandbox_mcp_only", "free_sandbox_exists", "free_sandbox_creating",
60
+ "free_sandbox_hours_used", "free_sandbox_size", "free_sandbox_unavailable"
61
+ ].freeze
62
+
63
+ # The codes a sandbox with no end (timeout_s 0 at a create or an extend) is refused with, beside a 400
64
+ # validation_error on timeout_s that says why (not offered, volumes attached): 403 no_end_needs_card (the account
65
+ # has no card) and 503 no_end_unavailable (it cannot be given right now; nothing was made or changed).
66
+ NO_END_CODES = Set["no_end_needs_card", "no_end_unavailable"].freeze
67
+
68
+ # The codes the account's free sandbox is refused with. At its create (create(..., free: true)):
69
+ # 403 free_sandbox_options, free_sandbox_mcp_only and free_sandbox_exists, 409 free_sandbox_creating, 402
70
+ # free_sandbox_hours_used. At a resize of it: 403 free_sandbox_size (it keeps its size). And 403
71
+ # free_sandbox_unavailable when the account cannot have a free sandbox now (its setup is not complete). Each is
72
+ # redu's own answer, never sent again by the client.
73
+ FREE_SANDBOX_CODES = Set[
74
+ "free_sandbox_options", "free_sandbox_mcp_only", "free_sandbox_exists", "free_sandbox_creating",
75
+ "free_sandbox_hours_used", "free_sandbox_size", "free_sandbox_unavailable"
76
+ ].freeze
77
+
78
+ # The codes a lifecycle change (set_lifecycle) is refused or ends with, beside the general ones (sandbox_not_found,
79
+ # sandbox_deleting, max_spend_reached).
80
+ LIFECYCLE_CODES = Set[
81
+ "lifecycle_busy", "idle_pause_not_changeable", "idle_pause_change_unsupported", "idle_pause_outcome_unknown",
82
+ "max_spend_below_spend", "usage_not_current", "spend_cap_reached"
83
+ ].freeze
84
+
85
+ # The codes a template build, its cancel and a built template's delete are refused or end with.
86
+ TEMPLATE_BUILD_CODES = Set[
87
+ "template_build_in_progress", "template_build_not_found", "template_build_rate_limited", "template_build_refused",
88
+ "template_builds_unavailable", "template_in_use", "template_limit_reached", "template_name_taken",
89
+ "template_not_found", "spend_cap_reached"
90
+ ].freeze
91
+
92
+ # The codes a change of secrets is refused or ends with, beside the general ones.
93
+ SECRETS_CODES = Set[
94
+ "secrets_change_busy", "secrets_unavailable", "secrets_unsupported", "secrets_refused",
95
+ "secrets_need_egress_filtering", "secrets_failed", "secrets_outcome_unknown", "sandbox_not_running"
96
+ ].freeze
97
+
98
+ # The codes SSH (its keys and its sessions) and the terminals through the platform are refused or end with, beside
99
+ # the general ones.
100
+ SSH_CODES = Set[
101
+ "ssh_keys_busy", "ssh_unavailable", "ssh_unsupported", "ssh_keys_revoked", "ssh_key_refused", "ssh_failed",
102
+ "ssh_outcome_unknown", "denied_by_sandbox_rules", "terminal_unavailable", "sessions_not_closable",
103
+ "sandbox_not_running"
104
+ ].freeze
105
+
106
+ # The codes a change of egress rules (change_egress) is refused or ends with, beside the general ones
107
+ # (sandbox_not_found, sandbox_ending, sandbox_not_running, sandbox_suspended).
108
+ EGRESS_CHANGE_CODES = Set[
109
+ "egress_change_unavailable", "egress_change_unsupported", "egress_change_busy", "egress_change_outcome_unknown",
110
+ "egress_not_filtered", "egress_rules_refused", "sandbox_changing"
111
+ ].freeze
112
+
113
+ # The codes a create with volumes can answer, beside the general ones.
114
+ VOLUME_CODES = Set[
115
+ "volume_not_found", "volume_in_use", "volume_not_available", "volume_unsupported", "too_many_volumes",
116
+ "volumes_unavailable", "volume_attach_failed", "sandbox_has_volumes"
117
+ ].freeze
118
+
119
+ # How long each kind of request can run at most, in seconds: its workflow's execution timeout in (create 40m, delete
120
+ # 30m, a name's add 20m, its removal 15m, a terminal's open 30m and its close 15m on one id, an extend 10m, a pause
121
+ # 10m and a suspend or resume 35m on one id, a fork 45m, a snapshot's take 40m and its delete 30m, a resize 20m, a
122
+ # change of egress rules 15m; from the API of 27 Nov 2026 a lifecycle change 25m, a change of secrets 55m, a change
123
+ # of SSH keys 55m and a removal of every key 170m under one kind, a template build's start 12m, a template's delete
124
+ # 10m). Waiting longer cannot help.
125
+ REQUEST_LIMIT_S = {
126
+ create: 40 * 60.0,
127
+ delete: 30 * 60.0,
128
+ add_public_name: 20 * 60.0,
129
+ remove_public_name: 15 * 60.0,
130
+ terminal: 30 * 60.0,
131
+ extend: 10 * 60.0,
132
+ state: 35 * 60.0,
133
+ fork: 45 * 60.0,
134
+ take_snapshot: 40 * 60.0,
135
+ delete_snapshot: 30 * 60.0,
136
+ resize: 20 * 60.0,
137
+ change_egress: 15 * 60.0,
138
+ lifecycle: 25 * 60.0,
139
+ secrets: 55 * 60.0,
140
+ ssh_keys: 170 * 60.0,
141
+ template_build: 12 * 60.0,
142
+ delete_template: 10 * 60.0
143
+ }.freeze
144
+
145
+ # The least time one read of GET /v1/sandboxes/requests/:workflow_id waits for its answer, in seconds, whatever the
146
+ # client's timeout: redu holds that read open while the request runs, up to 10 s (SANDBOX_REQUEST_WAIT_MS, never more
147
+ # than the 40 s of a route's own wait), so a shorter timeout would cut every read of a slow request.
148
+ REQUEST_READ_TIMEOUT_MIN_S = 60.0
149
+
150
+ # A snapshot's take: one workflow id per sandbox. Its delete's id
151
+ # (sandbox-snapshot-delete-<snapshot id>-<uuid>) shares the prefix, so a take is told by its whole shape.
152
+ SNAPSHOT_TAKE_ID = /\Asandbox-snapshot-[0-9a-f-]{36}\z/i
153
+ # A template build's start (sandbox-template-build-<uuid>): its read (sandbox-template-build-get-...) and its cancel
154
+ # are not requests read at /v1/sandboxes/requests. A template's delete: sandbox-template-delete-<template id>-<uuid>.
155
+ TEMPLATE_BUILD_ID = /\Asandbox-template-build-[0-9a-f-]{36}\z/i
156
+ TEMPLATE_DELETE_ID = /\Asandbox-template-delete-[0-9a-f-]{36}-[0-9a-f-]{36}\z/i
157
+
158
+ # The most one file read answers with: 8 MiB (a longer file is read in ranges).
159
+ FILE_READ_MAX_BYTES = 8 * 1024 * 1024
160
+ # The largest file write_file sends: 12 MiB less 64 KiB (12517376 bytes), as the API takes it.
161
+ FILE_WRITE_MAX_BYTES = (12 * 1024 * 1024) - (64 * 1024)
162
+ # The longest wait_ms get_command takes: 20 s.
163
+ COMMAND_WAIT_MAX_MS = 20_000
164
+ # The signals stop_command sends (TERM by default).
165
+ SIGNALS = %w[TERM KILL INT HUP QUIT USR1 USR2].freeze
166
+ # The most ended sandboxes one page answers; 50 when no limit is asked.
167
+ ENDED_PAGE_MAX_LIMIT = 100
168
+ # How many times a session through the platform (open_ssh, a websocket terminal) is asked for in all when redu
169
+ # answers 202: its token is good for a minute and opens one session, so redu keeps none for later and says to open
170
+ # it again.
171
+ SESSION_OPEN_ATTEMPTS = 3
172
+
173
+ # set_lifecycle's max_spend left out (it stays as it is), told apart from max_spend: nil (the cap removed).
174
+ UNSET = Object.new.tap { |o| o.define_singleton_method(:inspect) { "UNSET" } }.freeze
175
+ private_constant :UNSET
176
+
177
+ # The codes of a command's run that say it ran nothing and stay its key's answer.
178
+ RAN_NOTHING_KEY_BOUND = Set["exec_not_started", "sandbox_busy"].freeze
179
+ # Codes that only a command's own run answers with, never the route.
180
+ RUN_OUTCOME_RAN_NOTHING = Set["exec_not_started", "sandbox_busy", "sandbox_not_running"].freeze
181
+
182
+ WAIT_HINT = "Read it later with get_request(workflow_id) or wait_for_request(workflow_id)."
183
+ WAIT_HINTS = {
184
+ create: "#{WAIT_HINT} Do not create another sandbox meanwhile, or there will be two.",
185
+ terminal: "#{WAIT_HINT} A terminal's password comes only with its open's first answer: once this request has " \
186
+ "ended, open the terminal again for a new one (the url stays).",
187
+ fork: "#{WAIT_HINT} Do not fork the sandbox again meanwhile, or there will be two copies.",
188
+ take_snapshot: "#{WAIT_HINT} The snapshot may still be taken: list_snapshots shows it once it is.",
189
+ resize: "#{WAIT_HINT} Do not resize the sandbox again meanwhile (409 resize_busy).",
190
+ change_egress: "#{WAIT_HINT} Do not change its egress rules again meanwhile (409 egress_change_busy).",
191
+ lifecycle: "#{WAIT_HINT} Do not change its lifecycle again meanwhile (409 lifecycle_busy): get_lifecycle shows " \
192
+ "it once it is changed.",
193
+ secrets: "#{WAIT_HINT} Do not change its secrets again meanwhile (409 secrets_change_busy): get lists them " \
194
+ "(names and hosts) once they are changed.",
195
+ ssh_keys: "#{WAIT_HINT} Do not change its SSH keys again meanwhile (409 ssh_keys_busy): get_ssh shows its keys " \
196
+ "once they are changed.",
197
+ template_build: "#{WAIT_HINT} Do not build it again meanwhile: list_template_builds lists it once it is accepted."
198
+ }.freeze
199
+
200
+ def initialize(transport)
201
+ @t = transport
202
+ @o = transport.options
203
+ end
204
+
205
+ # What a request is, from its workflow id (the shapes gives), or nil.
206
+ def self.request_kind_of(workflow_id)
207
+ i = workflow_id.to_s.downcase
208
+ return :take_snapshot if SNAPSHOT_TAKE_ID.match?(i)
209
+ return :template_build if TEMPLATE_BUILD_ID.match?(i)
210
+ return :delete_template if TEMPLATE_DELETE_ID.match?(i)
211
+
212
+ {
213
+ "sandbox-create-" => :create, "sandbox-delete-" => :delete, "sandbox-dns-add-" => :add_public_name,
214
+ "sandbox-dns-remove-" => :remove_public_name, "sandbox-terminal-" => :terminal, "sandbox-extend-" => :extend,
215
+ "sandbox-state-" => :state, "sandbox-fork-" => :fork, "sandbox-snapshot-delete-" => :delete_snapshot,
216
+ "sandbox-resize-" => :resize, "sandbox-egress-rules-" => :change_egress, "sandbox-lifecycle-" => :lifecycle,
217
+ "sandbox-secrets-" => :secrets, "sandbox-ssh-keys-" => :ssh_keys, "sandbox-ssh-revoke-" => :ssh_keys
218
+ }.each { |prefix, kind| return kind if i.start_with?(prefix) }
219
+ nil
220
+ end
221
+
222
+ # A 202 of redu's: no answer within its wait. A sandbox carries an id, and a command's result an exit code.
223
+ def self.pending?(body)
224
+ body.is_a?(Hash) && body["status"] == "pending" && body["workflow_id"].is_a?(String) &&
225
+ !body.key?("id") && !body.key?("exit_code")
226
+ end
227
+
228
+ # -- reads --------------------------------------------------------------------------------------------------------
229
+
230
+ # GET /v1/sandboxes/templates: the templates a sandbox can be made from, each with the size its sandboxes get. A
231
+ # read that answers 202 ("ask again in a moment") or gets no answer is asked again, up to three times in all.
232
+ def templates
233
+ path = "/v1/sandboxes/templates"
234
+ a = read(path, "the templates")
235
+ list = a.body.is_a?(Hash) ? a.body["templates"] : nil
236
+ raise unexpected(a, "GET", path, "the templates") unless a.status == 200 && list.is_a?(Array)
237
+
238
+ list.select { |t| t.is_a?(Hash) }.map { |t| Template.from_h(t) }
239
+ end
240
+
241
+ # GET /v1/sandboxes: the caller's live sandboxes.
242
+ def list
243
+ path = "/v1/sandboxes"
244
+ a = read(path, "the list of sandboxes")
245
+ list = a.body.is_a?(Hash) ? a.body["sandboxes"] : nil
246
+ raise unexpected(a, "GET", path, "the list") unless a.status == 200 && list.is_a?(Array)
247
+
248
+ list.select { |s| s.is_a?(Hash) && s["id"].is_a?(String) }.map { |s| Sandbox.from_h(s) }
249
+ end
250
+
251
+ # GET /v1/sandboxes/:id: one sandbox. 404 sandbox_not_found once it is deleted or has ended.
252
+ def get(sandbox_id)
253
+ path = "/v1/sandboxes/#{seg(sandbox_id, "sandbox_id")}"
254
+ a = read(path, "the sandbox")
255
+ raise unexpected(a, "GET", path, "the sandbox") unless a.status == 200 && a.body.is_a?(Hash) && a.body["id"].is_a?(String)
256
+
257
+ Sandbox.from_h(a.body)
258
+ end
259
+
260
+ # -- create, delete -------------------------------------------------------------------------------------------------
261
+
262
+ # POST /v1/sandboxes: a Sandbox, once it is running (201). Made from a template, or from a snapshot of yours
263
+ # (+snapshot:+ instead of a template: exactly one of the two).
264
+ #
265
+ # template:: a template's name or id from #templates.
266
+ # snapshot:: a snapshot's id from #list_snapshots (an available one): the sandbox starts with its files, memory
267
+ # and running programs, at its size, on the server that keeps it. 404 snapshot_not_found, 409
268
+ # snapshot_unavailable (still being taken, being deleted, or failed), 503 snapshot_server_unavailable.
269
+ # name:: 1 to 255 printable characters.
270
+ # timeout_s:: how long it lives before it is deleted by itself: 60 seconds up to the account's limit (#limits
271
+ # max_lifetime_s: 2592000, 30 days, for an account with no card; up to 31536000, 365 days), 3600 by default. Or 0
272
+ # for a sandbox with NO END, where #limits says no_end true (an account with a card), never with volumes and never
273
+ # for the free sandbox: its expires_at and max_expires_at are then nil, and it runs until it is deleted, or until
274
+ # its max_spend, its API key's monthly cap or a suspended account ends it; it is billed by use as any sandbox. 403
275
+ # no_end_needs_card (no card), 503 no_end_unavailable (not right now; no sandbox was kept), and a 400
276
+ # validation_error on timeout_s that says why otherwise (not offered, volumes attached, above the account's
277
+ # limit). Sent as given: redu decides both the limit and who may have no end.
278
+ # env:: up to 64 variables, 32 KiB in all.
279
+ # public:: on the account's own network, so that it can have public names and a web terminal.
280
+ # max_spend:: a spend cap in GBP (0.10 to 1000): when what it has cost reaches it, it is deleted.
281
+ # vcpus, memory_mb, disk_gb:: its size, from a template only (a sandbox made from a snapshot has the snapshot's):
282
+ # vcpus 1 to 4, memory_mb one of 1024, 2048, 4096 and 8192 (MEMORY_MB), disk_gb 1 to 10 (at least that much disk: a
283
+ # template with more keeps its own). Each one left out is the template's own (#templates). 400 size_unsupported
284
+ # when the template cannot be made at that size. Every read shows the sandbox's size.
285
+ # network_id:: one of your private networks (GET /v1/private_networks): the sandbox reaches your machines there
286
+ # (their own security groups decide what it may reach), all its traffic leaves through that network, and it is not
287
+ # public (not with +public+ true). 404 network_not_found, 409 network_unusable (no IPv4 subnet).
288
+ # egress:: what it may connect out to: a ReduSandbox::EgressPolicy, or a Hash of the same JSON shape
289
+ # ({ default_action:, rules: [{ action:, hosts: | cidrs:, ports: }] }), sent as it is. Left out, everything is
290
+ # allowed. Every read shows it (Sandbox#egress); change_egress changes it while the sandbox runs.
291
+ # volumes:: up to VOLUMES_MAX (2) volumes of yours to attach and mount, from a template only: ReduSandbox::VolumeMount
292
+ # values, Hashes of the same JSON shape ({ id:, mount_path:, format: }), or volume ids (Strings: the default
293
+ # mount path, /mnt/volumes/<id>, and format). When the sandbox is deleted or ends they are unmounted and detached
294
+ # and keep their data. An API key needs volume:attach (or volume:*) beside its sandbox scope. 404
295
+ # volume_not_found, 409 volume_in_use, volume_not_available, volumes_unavailable, 400 volume_unsupported,
296
+ # too_many_volumes, 502 volume_attach_failed (no sandbox was made; the volumes stay available). Every read shows
297
+ # them (Sandbox#volumes). A sandbox with volumes is not snapshotted, forked or suspended (409 sandbox_has_volumes).
298
+ # idle_pause_s:: seconds without activity (no command, file transfer or connection) before the sandbox is paused by
299
+ # itself, 0 to 86400; 0 never pauses it. A paused sandbox is billed for its memory only, and resumes on its next
300
+ # command. Every read shows it (Sandbox#idle_pause_s); set_lifecycle changes it.
301
+ # secrets:: up to 16 secrets bound to hosts: ReduSandbox::SecretInput values, or Hashes with name, value and hosts.
302
+ # The sandbox sees a placeholder in each one's env variable, and the platform puts the real value into requests
303
+ # to its hosts only, so code in the sandbox never reads it. A value is never shown back (every read shows the names
304
+ # and hosts only: Sandbox#secrets), and never echoed by this client. It lives in the sandbox's own memory; to keep
305
+ # the sandbox through the platform's maintenance (an update or a planned restart), it is written into the
306
+ # sandbox's saved state on the server it runs on, readable by the platform only, and removed when the sandbox is
307
+ # brought back. A name may not also be in +env+. set_secrets and remove_secrets change them.
308
+ # free:: true asks for the account's free sandbox: 1 vCPU and 1 GB of memory from a template, never charged, one at
309
+ # a time, with 50 hours a calendar month (UTC) of running and paused time (suspended time does not count). When the
310
+ # month's hours are used it is deleted, and a new one can be made from the 1st of the next month (#limits
311
+ # free_sandbox shows its hours). It never has no end, and lives at most 30 days after its create, extends
312
+ # included. false asks for a paid sandbox. Sent only when given; left out, an account with no card asks for its
313
+ # free sandbox and any other for a paid one. The free sandbox is created through the redu MCP only, so from this
314
+ # client a create that asks for it is refused (403 free_sandbox_mcp_only); once made it is used as any sandbox,
315
+ # and its reads carry raw["free"] true. It takes no snapshot, size other than its own, disk_gb, public,
316
+ # network_id, volumes, max_spend or timeout_s 0 (403 free_sandbox_options). 403 free_sandbox_exists (delete it to
317
+ # make another), 403 free_sandbox_unavailable (the account cannot have a free sandbox now: its setup is not
318
+ # complete), 409 free_sandbox_creating, 402 free_sandbox_hours_used: FREE_SANDBOX_CODES.
319
+ # wait:: when redu answers 202 (still being made after about 40 s), wait for it through
320
+ # GET /v1/sandboxes/requests/:workflow_id (true, the default), or hand the PendingRequest back (false).
321
+ # wait_timeout:: how long to wait for a 202's request, in seconds (default: the longest a create can run, 40 min).
322
+ # idempotency_key:: sent as Idempotency-Key: repeating the create with the same key after it answered gets that
323
+ # answer instead of a second sandbox (redu keeps it 24 hours).
324
+ #
325
+ # The client never sends a create twice by itself: a create whose answer was lost may still be running, and a
326
+ # second one makes a second sandbox (#list shows the first once it is ready).
327
+ def create(template = nil, snapshot: nil, name: nil, timeout_s: nil, env: nil, public: nil, max_spend: nil,
328
+ egress: nil, vcpus: nil, memory_mb: nil, disk_gb: nil, network_id: nil, volumes: nil, idle_pause_s: nil,
329
+ secrets: nil, free: nil, wait: true, wait_timeout: nil, idempotency_key: nil)
330
+ if template.nil? == snapshot.nil?
331
+ raise ArgumentError, "Give exactly one of template (a template's name or id, see templates) and snapshot: " \
332
+ "(a snapshot's id, see list_snapshots)."
333
+ end
334
+ size = { "vcpus" => vcpus, "memory_mb" => memory_mb, "disk_gb" => disk_gb }.compact
335
+ size.each { |k, v| raise ArgumentError, "#{k} must be a whole number." unless v.is_a?(Integer) }
336
+ unless snapshot.nil? || size.empty?
337
+ raise ArgumentError, "A sandbox made from a snapshot has the snapshot's size: leave out vcpus, memory_mb and disk_gb."
338
+ end
339
+ unless network_id.nil?
340
+ raise ArgumentError, "network_id must be a private network's id (GET /v1/private_networks)." unless network_id.is_a?(String) && !network_id.empty?
341
+ raise ArgumentError, "Give public: true or network_id:, not both." if public == true
342
+ end
343
+ unless volumes.nil? || snapshot.nil?
344
+ raise ArgumentError, "A sandbox made from a snapshot cannot be given volumes at its create: create it from a template."
345
+ end
346
+ vols = volumes.nil? ? nil : volumes_body(volumes)
347
+ raise ArgumentError, "idle_pause_s must be a whole number of seconds." unless idle_pause_s.nil? || idle_pause_s.is_a?(Integer)
348
+ unless [nil, true, false].include?(free)
349
+ raise ArgumentError, "free must be true (the account's free sandbox) or false (a paid one)."
350
+ end
351
+
352
+ secret_list = secrets.nil? ? nil : secrets_body(secrets)
353
+
354
+ body =
355
+ if snapshot.nil?
356
+ raise ArgumentError, "template must be a template's name or id (see templates)." unless template.is_a?(String) && !template.empty?
357
+
358
+ { "template" => template }
359
+ else
360
+ raise ArgumentError, "snapshot must be a snapshot's id (see list_snapshots)." unless snapshot.is_a?(String) && !snapshot.empty?
361
+
362
+ { "snapshot" => snapshot }
363
+ end
364
+ body["name"] = name unless name.nil?
365
+ body["timeout_s"] = timeout_s unless timeout_s.nil?
366
+ body["env"] = env.to_h { |k, v| [k.to_s, v] } unless env.nil?
367
+ body["public"] = public unless public.nil?
368
+ body["max_spend"] = max_spend unless max_spend.nil?
369
+ body["egress"] = egress_body(egress) unless egress.nil?
370
+ body.update(size)
371
+ body["network_id"] = network_id unless network_id.nil?
372
+ body["volumes"] = vols unless vols.nil?
373
+ body["idle_pause_s"] = idle_pause_s unless idle_pause_s.nil?
374
+ body["secrets"] = secret_list unless secret_list.nil?
375
+ body["free"] = free unless free.nil?
376
+ path = "/v1/sandboxes"
377
+ a = @t.request("POST", path, body: body, headers: key_header(idempotency_key))
378
+ return Sandbox.from_h(a.body) if a.status == 201 && a.body.is_a?(Hash) && a.body["id"].is_a?(String)
379
+
380
+ if a.status == 202 && self.class.pending?(a.body)
381
+ return PendingRequest.from_h(a.body) unless wait
382
+
383
+ s = wait_for_request(a.body["workflow_id"], timeout: wait_timeout)
384
+ return s.sandbox unless s.sandbox.nil?
385
+ end
386
+ raise unexpected(a, "POST", path, "the create")
387
+ end
388
+
389
+ # DELETE /v1/sandboxes/:id: returns nil once the sandbox is gone (204). A 202 is waited on, unless wait: false,
390
+ # which hands the PendingRequest back.
391
+ def delete(sandbox_id, wait: true, wait_timeout: nil)
392
+ path = "/v1/sandboxes/#{seg(sandbox_id, "sandbox_id")}"
393
+ # No body: the API refuses any field.
394
+ a = @t.request("DELETE", path)
395
+ return nil if a.status == 204
396
+
397
+ if a.status == 202 && self.class.pending?(a.body)
398
+ return PendingRequest.from_h(a.body) unless wait
399
+
400
+ wait_for_request(a.body["workflow_id"], timeout: wait_timeout)
401
+ return nil
402
+ end
403
+ raise unexpected(a, "DELETE", path, "the delete")
404
+ end
405
+
406
+ # -- fork -----------------------------------------------------------------------------------------------------------
407
+
408
+ # POST /v1/sandboxes/:id/fork: a NEW sandbox that is a running copy of one of yours as it is now (its files, memory
409
+ # and running programs), at its template and size, public when it is, with its egress rules. Answers the copy, a
410
+ # Sandbox whose forked_from names the original, once it runs (201); a 202 is waited on, unless wait: false.
411
+ #
412
+ # The original must be running or paused; it goes on, pausing a moment while its memory is copied. The copy has
413
+ # its own +timeout_s+ (60 up to #limits max_lifetime_s, default 3600; never 0: extend_lifetime(copy.id, 0) takes
414
+ # its end away), its own +max_spend+ (the original's is not copied) and only the +env+ given here. Its
415
+ # +idle_pause_s+ (0 to 86400; 0 never pauses it) is the one given here, else the original's. Its programs keep
416
+ # running, so anything they do outside now happens twice. 409 fork_not_now (a command or a file transfer runs in it:
417
+ # fork between commands), fork_unsupported, sandbox_not_running; 503 fork_no_room.
418
+ #
419
+ # Named fork: Kernel#fork is private and has no use on this object, so nothing is lost. The client never sends a
420
+ # fork twice by itself: one whose answer was lost may still be running, and a second one makes a second copy
421
+ # (#list shows the first, with forked_from, once it runs). +idempotency_key+ is sent as Idempotency-Key, as for a
422
+ # create.
423
+ def fork(sandbox_id, name: nil, timeout_s: nil, env: nil, max_spend: nil, idle_pause_s: nil, wait: true,
424
+ wait_timeout: nil, idempotency_key: nil)
425
+ path = "/v1/sandboxes/#{seg(sandbox_id, "sandbox_id")}/fork"
426
+ raise ArgumentError, "idle_pause_s must be a whole number of seconds." unless idle_pause_s.nil? || idle_pause_s.is_a?(Integer)
427
+
428
+ body = {}
429
+ body["name"] = name unless name.nil?
430
+ body["timeout_s"] = timeout_s unless timeout_s.nil?
431
+ body["env"] = env.to_h { |k, v| [k.to_s, v] } unless env.nil?
432
+ body["max_spend"] = max_spend unless max_spend.nil?
433
+ body["idle_pause_s"] = idle_pause_s unless idle_pause_s.nil?
434
+ a = @t.request("POST", path, body: body, headers: key_header(idempotency_key))
435
+ return Sandbox.from_h(a.body) if a.status == 201 && a.body.is_a?(Hash) && a.body["id"].is_a?(String)
436
+
437
+ if a.status == 202 && self.class.pending?(a.body)
438
+ return PendingRequest.from_h(a.body) unless wait
439
+
440
+ s = wait_for_request(a.body["workflow_id"], timeout: wait_timeout)
441
+ return s.sandbox unless s.sandbox.nil?
442
+ end
443
+ raise unexpected(a, "POST", path, "the fork")
444
+ end
445
+
446
+ # -- snapshots ------------------------------------------------------------------------------------------------------
447
+
448
+ # POST /v1/sandboxes/:id/snapshots: a Snapshot of a running or paused sandbox (its files, memory and running
449
+ # programs), once it is taken (201); a 202 is waited on, unless wait: false. The sandbox pauses for about a second
450
+ # while it is written, then goes on. The snapshot is kept until #delete_snapshot, also after the sandbox is gone;
451
+ # create(snapshot: id) starts sandboxes from it. +name+: 1 to 255 printable characters.
452
+ #
453
+ # One take at a time per sandbox: 409 snapshot_in_progress while one runs (its error's workflow_id is that take's:
454
+ # wait_for_request waits for it). 409 sandbox_busy_for_snapshot (a command or a file transfer runs in it),
455
+ # snapshot_not_possible (not running or paused), snapshot_limit_reached (delete one first). 503 snapshot_not_taken
456
+ # (ReduSandbox::SnapshotNotTakenError): nothing was kept, taking it again is safe. 503 snapshot_outcome_unknown
457
+ # (ReduSandbox::SnapshotOutcomeUnknownError): it MAY have been taken, and then it counts against the snapshot limit
458
+ # without being listed (redu kept no record of it, so #list_snapshots cannot show it): wait a few minutes before
459
+ # taking another.
460
+ #
461
+ # The client never sends a take twice by itself: one whose answer never reached the client may have been taken
462
+ # (#list_snapshots shows it once it is). +idempotency_key+ is sent as Idempotency-Key, as for a create.
463
+ def take_snapshot(sandbox_id, name: nil, wait: true, wait_timeout: nil, idempotency_key: nil)
464
+ path = "/v1/sandboxes/#{seg(sandbox_id, "sandbox_id")}/snapshots"
465
+ body = {}
466
+ body["name"] = name unless name.nil?
467
+ a = begin
468
+ @t.request("POST", path, body: body, headers: key_header(idempotency_key))
469
+ rescue Error => e
470
+ # Its hint names the take under way: one workflow id per sandbox.
471
+ raise e.with_context(workflow_id: "sandbox-snapshot-#{sandbox_id}") if e.code == "snapshot_in_progress"
472
+
473
+ raise
474
+ end
475
+ return Snapshot.from_h(a.body) if a.status == 201 && a.body.is_a?(Hash) && a.body["id"].is_a?(String)
476
+
477
+ if a.status == 202 && self.class.pending?(a.body)
478
+ return PendingRequest.from_h(a.body) unless wait
479
+
480
+ s = wait_for_request(a.body["workflow_id"], timeout: wait_timeout)
481
+ return s.snapshot unless s.snapshot.nil?
482
+ end
483
+ raise unexpected(a, "POST", path, "the snapshot's take")
484
+ end
485
+
486
+ # GET /v1/sandboxes/snapshots: your snapshots, oldest first, with their status ("creating", "available",
487
+ # "deleting" or "error").
488
+ def list_snapshots
489
+ path = "/v1/sandboxes/snapshots"
490
+ a = read(path, "the list of snapshots")
491
+ list = a.body.is_a?(Hash) ? a.body["snapshots"] : nil
492
+ raise unexpected(a, "GET", path, "the snapshots") unless a.status == 200 && list.is_a?(Array)
493
+
494
+ list.select { |s| s.is_a?(Hash) && s["id"].is_a?(String) }.map { |s| Snapshot.from_h(s) }
495
+ end
496
+
497
+ # GET /v1/sandboxes/snapshots/:snapshot_id: one Snapshot. 404 snapshot_not_found.
498
+ def get_snapshot(snapshot_id)
499
+ path = "/v1/sandboxes/snapshots/#{seg(snapshot_id, "snapshot_id")}"
500
+ a = read(path, "the snapshot")
501
+ raise unexpected(a, "GET", path, "the snapshot") unless a.status == 200 && a.body.is_a?(Hash) && a.body["id"].is_a?(String)
502
+
503
+ Snapshot.from_h(a.body)
504
+ end
505
+
506
+ # DELETE /v1/sandboxes/snapshots/:snapshot_id: returns nil once the snapshot is gone (204). Sandboxes made from it
507
+ # keep running. A 202 is waited on, unless wait: false, which hands the PendingRequest back. 409 snapshot_deleting
508
+ # while it is still being taken or another delete holds it: try again in a minute.
509
+ def delete_snapshot(snapshot_id, wait: true, wait_timeout: nil)
510
+ path = "/v1/sandboxes/snapshots/#{seg(snapshot_id, "snapshot_id")}"
511
+ # No body: the API refuses any field.
512
+ a = @t.request("DELETE", path)
513
+ return nil if a.status == 204
514
+
515
+ if a.status == 202 && self.class.pending?(a.body)
516
+ return PendingRequest.from_h(a.body) unless wait
517
+
518
+ wait_for_request(a.body["workflow_id"], timeout: wait_timeout)
519
+ return nil
520
+ end
521
+ raise unexpected(a, "DELETE", path, "the snapshot's delete")
522
+ end
523
+
524
+ # -- egress log -----------------------------------------------------------------------------------------------------
525
+
526
+ # GET /v1/sandboxes/:id/egress/log?since=&limit=: one page of the sandbox's outbound connections, oldest first, as
527
+ # an EgressLog: the events after +since+ (0, or the last page's next_since), at most +limit+ (1 to 500; redu's
528
+ # default is 200), its next_since, and more (true when more of the log may follow). A read changes nothing: a 202
529
+ # or a lost answer is asked again, as every read is.
530
+ def egress_log(sandbox_id, since: 0, limit: nil)
531
+ path = egress_log_path(sandbox_id, since, limit)
532
+ a = read(path, "the egress log")
533
+ b = a.body
534
+ unless a.status == 200 && b.is_a?(Hash) && b["events"].is_a?(Array) && b["next_since"].is_a?(Integer)
535
+ raise unexpected(a, "GET", path, "the egress log")
536
+ end
537
+
538
+ EgressLog.from_h(b)
539
+ end
540
+
541
+ # Every connection event of the sandbox's log after +since+, page after page (#egress_log, +limit+ each), each
542
+ # EgressEvent as it comes. Follows next_since while redu says more follows: a page can come back empty with more
543
+ # true when the records it scanned held no connection, and the connections after them are still read. Ends at a
544
+ # page with more false, and returns the since to read from next time. Never loops: a page whose next_since is not
545
+ # past the since it was read from, with events or with more, is redu misbehaving, and raises unexpected_answer
546
+ # (before its events are handed on) rather than being read again. Without a block, an Enumerator.
547
+ def each_egress_event(sandbox_id, since: 0, limit: nil, &block)
548
+ return enum_for(:each_egress_event, sandbox_id, since: since, limit: limit) unless block
549
+
550
+ cursor = whole(since, "since", 0)
551
+ loop do
552
+ page = egress_log(sandbox_id, since: cursor, limit: limit)
553
+ if page.next_since <= cursor
554
+ return cursor if page.events.empty? && !page.more
555
+
556
+ raise ReduSandbox.make_error(
557
+ status: 200, code: "unexpected_answer", http_method: "GET", path: egress_log_path(sandbox_id, cursor, limit),
558
+ message: "redu answered next_since #{page.next_since} to a read after #{cursor}: the log did not move on.",
559
+ hint: "Read it again later from since #{cursor}."
560
+ )
561
+ end
562
+ page.events.each(&block)
563
+ cursor = page.next_since
564
+ return cursor unless page.more
565
+ end
566
+ end
567
+
568
+ # -- audit log ------------------------------------------------------------------------------------------------------
569
+
570
+ # GET /v1/sandboxes/:id/audit?since=&limit=&kind=: one page of the sandbox's own event log, oldest first, as an
571
+ # AuditLog: the events after +since+ (0, or the last page's next_since), at most +limit+ (1 to 500; redu's default
572
+ # is 200), its next_since, and more. +kind+: an event kind or a family of kinds ("exec", "exec.request", "file",
573
+ # "file.write", "egress", "proc", "rule", "vm"), or up to 10 of them as an Array; left out, every kind.
574
+ #
575
+ # The log holds each command sent through the API, each file read or write through the API, the sandbox's outbound
576
+ # connections, the programs started and ended inside it as it reports them, the rule decisions that refuse
577
+ # something, and the machine's own life; never a command's env, its output or a file's content. Each event is
578
+ # passed on as redu answered it (AuditEvent), with its prev and h, so that AuditChain can check the chain: read
579
+ # without kind for that, since a page read with kind leaves the other kinds out. Read only while the sandbox exists.
580
+ #
581
+ # A read changes nothing: a 202 or a lost answer is asked again, as every read is, and so is 429 too_many_log_reads
582
+ # (at most 2 reads of your account's logs run at once), after its Retry-After. 502 event_log_unreadable: the log
583
+ # cannot be read past this since.
584
+ def audit_log(sandbox_id, since: 0, limit: nil, kind: nil)
585
+ path = audit_log_path(sandbox_id, since, limit, kind)
586
+ a = read(path, "the audit log", raw: :text)
587
+ log = a.status == 200 ? AuditLog.parse(a.content) : nil
588
+ raise unexpected(a, "GET", path, "the audit log") if log.nil?
589
+
590
+ log
591
+ end
592
+
593
+ # Every event of the sandbox's audit log after +since+, page after page (#audit_log, +limit+ and +kind+ each), each
594
+ # AuditEvent as it comes, as #each_egress_event follows the connection log: on while redu says more, to a page
595
+ # with more false, and never looping (a next_since that does not move past its since raises unexpected_answer
596
+ # before that page's events are handed on). Returns the since to read from next. Without a block, an Enumerator.
597
+ #
598
+ # chain = ReduSandbox::AuditChain.new
599
+ # redu.sandboxes.each_audit_event(id) { |event| chain.add(event) }
600
+ def each_audit_event(sandbox_id, since: 0, limit: nil, kind: nil, &block)
601
+ return enum_for(:each_audit_event, sandbox_id, since: since, limit: limit, kind: kind) unless block
602
+
603
+ cursor = whole(since, "since", 0)
604
+ loop do
605
+ page = audit_log(sandbox_id, since: cursor, limit: limit, kind: kind)
606
+ if page.next_since <= cursor
607
+ return cursor if page.events.empty? && !page.more
608
+
609
+ raise ReduSandbox.make_error(
610
+ status: 200, code: "unexpected_answer", http_method: "GET",
611
+ path: audit_log_path(sandbox_id, cursor, limit, kind),
612
+ message: "redu answered next_since #{page.next_since} to a read after #{cursor}: the log did not move on.",
613
+ hint: "Read it again later from since #{cursor}."
614
+ )
615
+ end
616
+ page.events.each(&block)
617
+ cursor = page.next_since
618
+ return cursor unless page.more
619
+ end
620
+ end
621
+
622
+ # -- exec ---------------------------------------------------------------------------------------------------------
623
+
624
+ # POST /v1/sandboxes/:id/exec: one command, answered with its exit code and output once it has ended.
625
+ #
626
+ # Give +command+ (a command line, run by /bin/sh -c) or argv: (a program and its arguments), not both. A command
627
+ # runs for at most 30 s (timeout_ms: 1000 to 30000): start longer work with #start_command.
628
+ #
629
+ # Every call carries an Idempotency-Key (+idempotency_key+, or a new random one), and the answers decide what
630
+ # happens next:
631
+ # - 202 (no result after about 40 s), a lost answer, a proxy's page, or a 2xx whose body is not JSON: sent again
632
+ # with the SAME key, which never runs the command twice and answers from its first run;
633
+ # - 502 exec_outcome_unknown: sent once more with the same key; a second one is how the run ended (ran :unknown);
634
+ # - 502 exec_result_lost: raised, ran :yes;
635
+ # - 503 exec_not_started and 429 sandbox_busy: nothing ran, and the key keeps that answer for about a day, so the
636
+ # client tries once more under a NEW key when the key is its own, and otherwise raises (ran :no);
637
+ # - any other refusal: raised, ran :no, or :unknown when an earlier request of this call may have started it.
638
+ # At most +max_attempts+ requests are sent. Every error carries +ran+ and +idempotency_key+.
639
+ def exec(sandbox_id, command = nil, argv: nil, env: nil, cwd: nil, stdin: nil, timeout_ms: nil,
640
+ idempotency_key: nil, max_attempts: 4)
641
+ path = "/v1/sandboxes/#{seg(sandbox_id, "sandbox_id")}/exec"
642
+ body = command_body("exec", command, argv, env, cwd, stdin, timeout_ms)
643
+ accept = ->(a) { a.status == 200 && a.body.is_a?(Hash) && a.body.key?("exit_code") ? a.body : nil }
644
+ value, key, attempts = keyed(path, body, idempotency_key, max_attempts, "the command", "exec", accept)
645
+ ExecResult.from_h(value, key, attempts)
646
+ end
647
+
648
+ # -- lifetime: extend ---------------------------------------------------------------------------------------------
649
+
650
+ # POST /v1/sandboxes/:id/extend: the sandbox then ends +timeout_s+ seconds from now (60 up to #limits
651
+ # max_lifetime_s), never sooner than it already would (extended false), and at most the account's longest life
652
+ # after its create, while it has one (capped true when that cut the ask). +timeout_s+ 0 takes its end away, where
653
+ # #limits says no_end true, for a sandbox with no volumes: its expires_at and max_expires_at are then nil (no end).
654
+ # 403 no_end_needs_card, 503 no_end_unavailable (it keeps the end it had), and a 400 validation_error on timeout_s
655
+ # that says why otherwise. The account's free sandbox never has no end (403 free_sandbox_options) and lives at most
656
+ # 30 days after its create (#limits free_sandbox max_lifetime_s; a 400 validation_error on timeout_s past that).
657
+ # Only the type is checked here: redu decides the rest. Answers an ExtendedSandbox. Calling it again is safe, so it
658
+ # works as a keep-alive: send no idempotency_key for that, since a repeated key replays the first answer and
659
+ # extends nothing. A 202 is waited on.
660
+ #
661
+ # Named extend_lifetime, not extend: Object#extend is Ruby's own and every object needs it.
662
+ def extend_lifetime(sandbox_id, timeout_s, wait: true, wait_timeout: nil, idempotency_key: nil)
663
+ path = "/v1/sandboxes/#{seg(sandbox_id, "sandbox_id")}/extend"
664
+ # only its type: 0 (no end) and the account's longest life are redu's to decide
665
+ unless timeout_s.is_a?(Integer)
666
+ raise ArgumentError, "timeout_s must be a whole number of seconds (0 asks for no end)."
667
+ end
668
+
669
+ a = @t.request("POST", path, body: { "timeout_s" => timeout_s }, headers: key_header(idempotency_key))
670
+ return ExtendedSandbox.from_h(a.body) if a.status == 200 && a.body.is_a?(Hash) && a.body["id"].is_a?(String)
671
+
672
+ if a.status == 202 && self.class.pending?(a.body)
673
+ return PendingRequest.from_h(a.body) unless wait
674
+
675
+ s = wait_for_request(a.body["workflow_id"], timeout: wait_timeout)
676
+ return s.sandbox if s.sandbox.is_a?(ExtendedSandbox)
677
+ end
678
+ raise unexpected(a, "POST", path, "the extend")
679
+ end
680
+
681
+ # -- state: pause, resume, suspend --------------------------------------------------------------------------------
682
+
683
+ # POST /v1/sandboxes/:id/pause: its CPUs stop and it keeps its memory (billed for memory, never CPU; it runs no
684
+ # commands: 409 sandbox_not_running). Answers a SandboxStateResult; a 202 is waited on. 409 sandbox_suspended for
685
+ # a suspended sandbox, 409 sandbox_state_busy while another change of it is under way.
686
+ def pause(sandbox_id, wait: true, wait_timeout: nil)
687
+ change_state(sandbox_id, "pause", wait, wait_timeout)
688
+ end
689
+
690
+ # POST /v1/sandboxes/:id/resume: it runs again (from "disk" after a suspend). 409 sandbox_resume_unavailable when
691
+ # there is no room right now: it stays suspended with its memory and files.
692
+ def resume(sandbox_id, wait: true, wait_timeout: nil)
693
+ change_state(sandbox_id, "resume", wait, wait_timeout)
694
+ end
695
+
696
+ # POST /v1/sandboxes/:id/suspend: its memory and disk are saved and its memory freed (no memory charge); its next
697
+ # command or a resume brings it back. 409 sandbox_cannot_suspend while a command or a file transfer runs in it.
698
+ def suspend(sandbox_id, wait: true, wait_timeout: nil)
699
+ change_state(sandbox_id, "suspend", wait, wait_timeout)
700
+ end
701
+
702
+ # -- resize ---------------------------------------------------------------------------------------------------------
703
+
704
+ # POST /v1/sandboxes/:id/resize: a running sandbox's vCPUs and memory, changed live (nothing restarts; its files
705
+ # and programs stay). Answers a ResizedSandbox: the sandbox at its new size, +resize+ (its size before and after)
706
+ # and +price+ at that size, which it is billed at from then on. A 202 is waited on through
707
+ # GET /v1/sandboxes/requests/sandbox-resize-<id>, unless wait: false, which hands the PendingRequest back.
708
+ #
709
+ # vcpus:: 1 to 4.
710
+ # memory_mb:: 1024 to 8192, within the range its template allows (memory moves in 2 MB steps, and a shrink stops at
711
+ # what the sandbox can free).
712
+ # Give either or both. The size is a target, not a step, so asking again for the same size is safe.
713
+ #
714
+ # 409 resize_not_available (ReduSandbox::ResizeNotAvailableError): its template cannot be resized, and nothing
715
+ # changed: create a sandbox at the size you need. 400 resize_out_of_range; 409 resize_refused (no room right now,
716
+ # or created a moment ago: try again in a minute), resize_busy (another resize of it runs: the error's workflow_id
717
+ # is that resize's, for wait_for_request), sandbox_not_running (resume it first), quota_exceeded; 429
718
+ # resize_limit_reached; 502 resize_failed (nothing changed), resize_incomplete (resized in part: #get shows its
719
+ # size) and resize_outcome_unknown (#get shows its size; the same size again is safe). The free sandbox keeps its
720
+ # size: 403 free_sandbox_size (a paid sandbox, or a paid fork of it, can be any size).
721
+ def resize(sandbox_id, vcpus: nil, memory_mb: nil, wait: true, wait_timeout: nil)
722
+ raise ArgumentError, "Give vcpus:, memory_mb: or both." if vcpus.nil? && memory_mb.nil?
723
+
724
+ body = { "vcpus" => vcpus, "memory_mb" => memory_mb }.compact
725
+ body.each { |k, v| raise ArgumentError, "#{k} must be a whole number." unless v.is_a?(Integer) }
726
+ path = "/v1/sandboxes/#{seg(sandbox_id, "sandbox_id")}/resize"
727
+ a = begin
728
+ @t.request("POST", path, body: body)
729
+ rescue Error => e
730
+ # one resize at a time per sandbox, under one workflow id
731
+ raise e.with_context(workflow_id: "sandbox-resize-#{sandbox_id}") if e.code == "resize_busy"
732
+
733
+ raise
734
+ end
735
+ return ResizedSandbox.from_h(a.body) if a.status == 200 && a.body.is_a?(Hash) && a.body["id"].is_a?(String)
736
+
737
+ if a.status == 202 && self.class.pending?(a.body)
738
+ return PendingRequest.from_h(a.body) unless wait
739
+
740
+ s = wait_for_request(a.body["workflow_id"], timeout: wait_timeout)
741
+ return s.sandbox if s.sandbox.is_a?(ResizedSandbox)
742
+ end
743
+ raise unexpected(a, "POST", path, "the resize")
744
+ end
745
+
746
+ # -- egress rules ---------------------------------------------------------------------------------------------------
747
+
748
+ # PUT /v1/sandboxes/:id/egress: a running or paused sandbox's egress rules replaced, live (nothing restarts; the
749
+ # open connections the new rules refuse are closed). +egress+ is what a create takes: a ReduSandbox::EgressPolicy,
750
+ # or a Hash of the same JSON shape, sent as it is, with the same rules and limits; EgressPolicy.allow_all removes
751
+ # every rule. Answers an EgressChange: the rules now (every read shows them from then on) and connections_closed.
752
+ # A 202 is waited on through GET /v1/sandboxes/requests/sandbox-egress-rules-<id>, unless wait: false, which hands
753
+ # the PendingRequest back. Sending the same rules again is safe: the same rules twice are one change.
754
+ #
755
+ # 409 egress_change_unavailable (ReduSandbox::EgressChangeUnavailableError): this platform cannot change a running
756
+ # sandbox's rules yet, and nothing changed: it keeps the rules it was created with, so create a sandbox with the
757
+ # rules you need. 409 egress_change_busy (another change of its rules runs: the error's workflow_id is that change's,
758
+ # for wait_for_request), egress_change_unsupported (it started before its rules could be changed while it runs),
759
+ # egress_not_filtered, sandbox_suspended (resume it first), sandbox_changing (a resize, a suspend or a resume of it
760
+ # runs: try again in a moment), sandbox_ending, sandbox_not_running; 400 egress_rules_refused; 502
761
+ # egress_change_outcome_unknown (it may have been made: send the same rules again; until then #get shows the rules
762
+ # last confirmed). The client never sends a change twice by itself.
763
+ def change_egress(sandbox_id, egress, wait: true, wait_timeout: nil)
764
+ raise ArgumentError, "Give the egress rules: an EgressPolicy (EgressPolicy.allow_all removes every rule)." if egress.nil?
765
+
766
+ body = egress_body(egress)
767
+ path = "/v1/sandboxes/#{seg(sandbox_id, "sandbox_id")}/egress"
768
+ a = begin
769
+ @t.request("PUT", path, body: body)
770
+ rescue Error => e
771
+ # one change of a sandbox's rules at a time, under one workflow id
772
+ raise e.with_context(workflow_id: "sandbox-egress-rules-#{sandbox_id}") if e.code == "egress_change_busy"
773
+
774
+ raise
775
+ end
776
+ return EgressChange.from_h(a.body) if a.status == 200 && egress_change?(a.body)
777
+
778
+ if a.status == 202 && self.class.pending?(a.body)
779
+ return PendingRequest.from_h(a.body) unless wait
780
+
781
+ s = wait_for_request(a.body["workflow_id"], timeout: wait_timeout)
782
+ return s.egress unless s.egress.nil?
783
+ end
784
+ raise unexpected(a, "PUT", path, "the change of egress rules")
785
+ end
786
+
787
+ # -- files --------------------------------------------------------------------------------------------------------
788
+
789
+ # GET /v1/sandboxes/:id/files?path=: a whole file of at most 8 MiB, as a binary String. A longer one is 413
790
+ # file_too_large (its message says the size): read it with #read_large_file, #each_file_range or
791
+ # #read_file_range. 404 file_not_found when the sandbox has no such file. +path+ is absolute, at most 4096
792
+ # characters.
793
+ def read_file(sandbox_id, path)
794
+ route = file_route(sandbox_id, path)
795
+ a = @t.request("GET", route, raw: true)
796
+ return a.content if [200, 206].include?(a.status)
797
+
798
+ raise ReduSandbox.make_error(status: a.status, code: "unexpected_answer", http_method: "GET", path: route,
799
+ message: "redu answered HTTP #{a.status} to the file's read, which this client does not recognise.")
800
+ end
801
+
802
+ # GET /v1/sandboxes/:id/files?path= with a Range: +length+ bytes from +offset+ (to the end when nil), at most
803
+ # 8 MiB per answer: a longer range is answered with its first 8 MiB, so read +next+ to see where the part ended.
804
+ # 416 range_not_satisfiable when +offset+ is at or past the end of the file.
805
+ def read_file_range(sandbox_id, path, offset = 0, length = nil)
806
+ route = file_route(sandbox_id, path)
807
+ whole(offset, "offset", 0)
808
+ whole(length, "length", 1) unless length.nil?
809
+ range = "bytes=#{offset}-#{length.nil? ? "" : offset + length - 1}"
810
+ a = @t.request("GET", route, headers: { "range" => range }, raw: true)
811
+ data = a.content
812
+ return FileRange.new(data: data, offset: 0, next: data.bytesize, size: data.bytesize) if a.status == 200
813
+
814
+ if a.status == 206
815
+ cr = content_range(a.headers["content-range"])
816
+ first = cr ? cr[0] : offset
817
+ return FileRange.new(data: data, offset: first, next: first + data.bytesize, size: cr ? cr[2] : nil)
818
+ end
819
+ raise ReduSandbox.make_error(status: a.status, code: "unexpected_answer", http_method: "GET", path: route,
820
+ message: "redu answered HTTP #{a.status} to the file's read, which this client does not recognise.")
821
+ end
822
+
823
+ # A file of any size, part by part (at most +chunk_size+, 8 MiB, per request) from +offset+, each FileRange as it
824
+ # comes, so a large file never has to be held whole. Ends at the end of the file (its size, an empty part, or a
825
+ # 416 past the end). An empty file yields nothing. Without a block, an Enumerator.
826
+ def each_file_range(sandbox_id, path, offset: 0, chunk_size: FILE_READ_MAX_BYTES)
827
+ return enum_for(:each_file_range, sandbox_id, path, offset: offset, chunk_size: chunk_size) unless block_given?
828
+
829
+ off = whole(offset, "offset", 0)
830
+ chunk = [whole(chunk_size, "chunk_size", 1), FILE_READ_MAX_BYTES].min
831
+ until off.nil?
832
+ part = next_file_range(sandbox_id, path, off, chunk)
833
+ break if part.nil?
834
+
835
+ yield part
836
+ off = next_offset(part, off)
837
+ end
838
+ nil
839
+ end
840
+
841
+ # A file of any size, read in ranges (#each_file_range) and joined, as a binary String.
842
+ def read_large_file(sandbox_id, path, offset: 0, chunk_size: FILE_READ_MAX_BYTES)
843
+ out = "".b
844
+ each_file_range(sandbox_id, path, offset: offset, chunk_size: chunk_size) { |part| out << part.data }
845
+ out
846
+ end
847
+
848
+ # PUT /v1/sandboxes/:id/files?path=: +data+ (a String: its bytes are written as they are) written to +path+,
849
+ # replacing a file that is there and creating missing parent folders. +mode+ sets its permission bits ("644",
850
+ # "0755", or an Integer such as 0o644). At most 12517376 bytes (12 MiB less 64 KiB): a larger one is refused
851
+ # (ArgumentError) before anything is sent. Answers a WrittenFile. Not sent again by the client on a lost answer
852
+ # (writing the same bytes again is safe).
853
+ def write_file(sandbox_id, path, data, mode: nil)
854
+ route = file_route(sandbox_id, path)
855
+ raise ArgumentError, "data must be a String (its bytes are written as they are)." unless data.is_a?(String)
856
+
857
+ content = data.b
858
+ if content.bytesize > FILE_WRITE_MAX_BYTES
859
+ raise ArgumentError,
860
+ "A file written to a sandbox is at most #{FILE_WRITE_MAX_BYTES} bytes; this one is #{content.bytesize}."
861
+ end
862
+ unless mode.nil?
863
+ m = mode.is_a?(Integer) ? format("%03o", mode) : mode
864
+ raise ArgumentError, 'mode must be 3 or 4 octal digits, such as "644" or 0o755.' unless m.is_a?(String) && m.match?(/\A[0-7]{3,4}\z/)
865
+
866
+ route += "&mode=#{m}"
867
+ end
868
+ a = @t.request("PUT", route, content: content)
869
+ return WrittenFile.from_h(a.body) if a.status == 200 && a.body.is_a?(Hash) && a.body["bytes"].is_a?(Integer)
870
+
871
+ raise unexpected(a, "PUT", route, "the file's write")
872
+ end
873
+
874
+ # -- background commands ------------------------------------------------------------------------------------------
875
+
876
+ # POST /v1/sandboxes/:id/commands: a command started in the background (at most an hour, timeout_ms), returned at
877
+ # once as a StartedCommand. Read its output with #get_command, #follow_command or #wait_for_command; end it with
878
+ # #stop_command. At most 16 run at once per sandbox (429 sandbox_busy). It follows #exec's rules for a lost answer
879
+ # and its Idempotency-Key: the same key never starts it twice, and every error carries +ran+ and +idempotency_key+.
880
+ def start_command(sandbox_id, command = nil, argv: nil, env: nil, cwd: nil, stdin: nil, timeout_ms: nil,
881
+ idempotency_key: nil, max_attempts: 4)
882
+ path = "/v1/sandboxes/#{seg(sandbox_id, "sandbox_id")}/commands"
883
+ body = command_body("start_command", command, argv, env, cwd, stdin, timeout_ms)
884
+ accept = lambda do |a|
885
+ b = a.body
886
+ a.status.between?(200, 299) && b.is_a?(Hash) && command?(b["command"]) ? b["command"] : nil
887
+ end
888
+ value, key, attempts = keyed(path, body, idempotency_key, max_attempts, "the command's start", "start_command", accept)
889
+ StartedCommand.from_h(value, key, attempts)
890
+ end
891
+
892
+ # GET /v1/sandboxes/:id/commands: the running background commands and the last 32 that ended.
893
+ def list_commands(sandbox_id)
894
+ path = "/v1/sandboxes/#{seg(sandbox_id, "sandbox_id")}/commands"
895
+ a = read(path, "the commands")
896
+ list = a.body.is_a?(Hash) ? a.body["commands"] : nil
897
+ raise unexpected(a, "GET", path, "the commands") unless a.status == 200 && list.is_a?(Array)
898
+
899
+ list.select { |c| command?(c) }.map { |c| Command.from_h(c) }
900
+ end
901
+
902
+ # GET /v1/sandboxes/:id/commands/:command_id: the command and its output past the offsets (each stream from 0 by
903
+ # default), as a CommandOutput. With +wait_ms+ (up to 20000) redu waits for output past the offsets, or the
904
+ # command's end. Ask again from stdout_next and stderr_next. 404 command_not_found once it is forgotten.
905
+ def get_command(sandbox_id, command_id, stdout_offset: nil, stderr_offset: nil, wait_ms: nil)
906
+ q = []
907
+ q << "stdout_offset=#{whole(stdout_offset, "stdout_offset", 0)}" unless stdout_offset.nil?
908
+ q << "stderr_offset=#{whole(stderr_offset, "stderr_offset", 0)}" unless stderr_offset.nil?
909
+ q << "wait_ms=#{whole(wait_ms, "wait_ms", 0)}" unless wait_ms.nil?
910
+ path = command_path(sandbox_id, command_id) + (q.empty? ? "" : "?#{q.join("&")}")
911
+ a = read(path, "the command")
912
+ raise unexpected(a, "GET", path, "the command") unless a.status == 200 && a.body.is_a?(Hash) && command?(a.body["command"])
913
+
914
+ CommandOutput.from_h(a.body)
915
+ end
916
+
917
+ # DELETE /v1/sandboxes/:id/commands/:command_id?signal=: +signal+ (TERM by default) sent to the command and what it
918
+ # started. Answers the Command; its end then shows in #get_command. A command that has ended is answered as it is.
919
+ def stop_command(sandbox_id, command_id, signal = "TERM")
920
+ sig = signal.to_s.upcase
921
+ raise ArgumentError, "signal must be one of #{SIGNALS.join(", ")}." unless SIGNALS.include?(sig)
922
+
923
+ path = "#{command_path(sandbox_id, command_id)}?signal=#{sig}"
924
+ a = @t.request("DELETE", path)
925
+ if a.status.between?(200, 299) && a.body.is_a?(Hash) && command?(a.body["command"])
926
+ return Command.from_h(a.body["command"])
927
+ end
928
+
929
+ raise unexpected(a, "DELETE", path, "the command's stop")
930
+ end
931
+
932
+ # A background command's output as it comes: #get_command again and again from where the last answer ended, each
933
+ # waiting up to +wait_ms+ for more, until the command has ended and all its output is read. Yields each
934
+ # CommandOutput that carries output, and the last one. +timeout+ (seconds) stops following with WaitTimeoutError
935
+ # while the command runs on. Without a block, an Enumerator.
936
+ def follow_command(sandbox_id, command_id, stdout_offset: 0, stderr_offset: 0, wait_ms: COMMAND_WAIT_MAX_MS,
937
+ timeout: nil)
938
+ unless block_given?
939
+ return enum_for(:follow_command, sandbox_id, command_id, stdout_offset: stdout_offset,
940
+ stderr_offset: stderr_offset, wait_ms: wait_ms, timeout: timeout)
941
+ end
942
+
943
+ f = Follower.new(stdout_offset, stderr_offset, wait_ms, timeout, command_path(sandbox_id, command_id))
944
+ loop do
945
+ o = get_command(sandbox_id, command_id, stdout_offset: f.stdout_offset, stderr_offset: f.stderr_offset,
946
+ wait_ms: f.wait)
947
+ yield o if f.take(o)
948
+ return nil if f.finished?
949
+ end
950
+ end
951
+
952
+ # #follow_command to the command's end, with its output joined, as a CommandEnd. The sandbox keeps the last 1 MiB
953
+ # of each stream, so output written faster than it is read can be lost: stdout_lost and stderr_lost count it.
954
+ def wait_for_command(sandbox_id, command_id, stdout_offset: 0, stderr_offset: 0, wait_ms: COMMAND_WAIT_MAX_MS,
955
+ timeout: nil)
956
+ out = +""
957
+ err = +""
958
+ lost = [0, 0]
959
+ last = nil
960
+ follow_command(sandbox_id, command_id, stdout_offset: stdout_offset, stderr_offset: stderr_offset,
961
+ wait_ms: wait_ms, timeout: timeout) do |o|
962
+ out << o.stdout
963
+ err << o.stderr
964
+ lost[0] += o.stdout_lost
965
+ lost[1] += o.stderr_lost
966
+ last = o
967
+ end
968
+ CommandEnd.new(command: last.command, stdout: out, stderr: err, stdout_lost: lost[0], stderr_lost: lost[1])
969
+ end
970
+
971
+ # -- public names -------------------------------------------------------------------------------------------------
972
+
973
+ # POST /v1/sandboxes/:id/dns: a public https name for +port+ of a sandbox made with public: true, as a PublicName
974
+ # once it serves. Without +domain+ a name is generated under redu.cloud; a domain of your own must be verified for
975
+ # your account first. A 202 is waited on, unless wait: false.
976
+ def add_public_name(sandbox_id, port, domain: nil, wait: true, wait_timeout: nil, idempotency_key: nil)
977
+ path = "/v1/sandboxes/#{seg(sandbox_id, "sandbox_id")}/dns"
978
+ body = { "port" => port }
979
+ body["domain"] = domain unless domain.nil?
980
+ a = @t.request("POST", path, body: body, headers: key_header(idempotency_key))
981
+ return PublicName.from_h(a.body) if a.status == 201 && a.body.is_a?(Hash) && a.body["domain"].is_a?(String)
982
+
983
+ if a.status == 202 && self.class.pending?(a.body)
984
+ return PendingRequest.from_h(a.body) unless wait
985
+
986
+ s = wait_for_request(a.body["workflow_id"], timeout: wait_timeout)
987
+ return s.name unless s.name.nil?
988
+ end
989
+ raise unexpected(a, "POST", path, "the public name")
990
+ end
991
+
992
+ # DELETE /v1/sandboxes/:id/dns/:dns_id: returns nil once the name no longer serves. A 202 is waited on, unless
993
+ # wait: false.
994
+ def remove_public_name(sandbox_id, dns_id, wait: true, wait_timeout: nil)
995
+ path = "/v1/sandboxes/#{seg(sandbox_id, "sandbox_id")}/dns/#{seg(dns_id.to_s, "dns_id")}"
996
+ a = @t.request("DELETE", path)
997
+ return nil if a.status == 204
998
+
999
+ if a.status == 202 && self.class.pending?(a.body)
1000
+ return PendingRequest.from_h(a.body) unless wait
1001
+
1002
+ wait_for_request(a.body["workflow_id"], timeout: wait_timeout)
1003
+ return nil
1004
+ end
1005
+ raise unexpected(a, "DELETE", path, "the removal")
1006
+ end
1007
+
1008
+ # -- terminal -----------------------------------------------------------------------------------------------------
1009
+
1010
+ # POST /v1/sandboxes/:id/terminal: a root shell in the sandbox, of one of two kinds.
1011
+ #
1012
+ # Where the platform offers terminals over its websocket, any live sandbox gets one, private ones included: a
1013
+ # TerminalSession (kind "websocket") with a +url+ and a one-time +token+, good for 60 seconds and one session.
1014
+ # Connect with a websocket client of your own: open url offering +subprotocols+ (or with the token as a bearer
1015
+ # token). +cols+ and +rows+ (1 to 1000; 80 and 24 by default) set its size, +idle_timeout_s+ (60 to 3600) how long
1016
+ # it may sit with no byte either way. When redu answers 202 (a suspended sandbox is woken first) it keeps no token
1017
+ # for later and says to open it again, so the client does, up to SESSION_OPEN_ATTEMPTS requests in all, then raises
1018
+ # still_pending; wait: false hands the 202 back (a PendingRequest).
1019
+ #
1020
+ # Elsewhere, a sandbox made with public: true gets the web terminal (it ignores cols, rows and idle_timeout_s): a
1021
+ # Terminal (kind "web": url, username, password) once it serves. When redu answers 202 the password comes with that
1022
+ # 202 and the url with the request's end; the client joins the two. With wait: false, a PendingTerminal that holds
1023
+ # the password. 409 sandbox_not_public, 409 terminal_busy while it is being opened or closed.
1024
+ #
1025
+ # Not sent again by the client on a lost answer: opening again restarts the web terminal with a new password (the
1026
+ # url stays) or hands out another token, and redu never stores this route's answer under an Idempotency-Key, so
1027
+ # none is sent. Neither the password nor the token is ever put in an error by this client.
1028
+ def open_terminal(sandbox_id, cols: nil, rows: nil, idle_timeout_s: nil, wait: true, wait_timeout: nil)
1029
+ path = "/v1/sandboxes/#{seg(sandbox_id, "sandbox_id")}/terminal"
1030
+ # strict, and no body is fine (the web terminal takes none of them)
1031
+ body = whole_fields("cols" => cols, "rows" => rows, "idle_timeout_s" => idle_timeout_s)
1032
+ workflow_id = nil
1033
+ status = 0
1034
+ SESSION_OPEN_ATTEMPTS.times do |i|
1035
+ @t.pause(@o.poll_interval) if i.positive?
1036
+ a = @t.request("POST", path, body: body)
1037
+ status = a.status
1038
+ b = a.body
1039
+ return TerminalSession.from_h(b) if a.status == 201 && session?(b)
1040
+ # the web terminal (a websocket answer without its token is not one)
1041
+ return Terminal.from_h(b) if a.status == 201 && b.is_a?(Hash) && b["url"].is_a?(String) && b["kind"] != "websocket"
1042
+
1043
+ if a.status == 202 && self.class.pending?(b) && b["password"].is_a?(String)
1044
+ # the web terminal: its password now, its url at the request's end
1045
+ pending = PendingTerminal.from_h(b)
1046
+ return pending unless wait
1047
+
1048
+ workflow_id = pending.workflow_id
1049
+ s = wait_for_request(pending.workflow_id, timeout: wait_timeout)
1050
+ # The request's end never carries the password: it was answered once, with the 202.
1051
+ return Terminal.from_h(s.terminal.raw, password: pending.password, note: pending.note) unless s.terminal.nil?
1052
+
1053
+ break
1054
+ end
1055
+ break unless a.status == 202 && self.class.pending?(b)
1056
+
1057
+ # a terminal over the websocket that was not ready within redu's wait: its token is not kept, open it again
1058
+ return PendingRequest.from_h(b) unless wait
1059
+
1060
+ workflow_id = b["workflow_id"]
1061
+ raise session_still_pending(path, workflow_id, "terminal") if i == SESSION_OPEN_ATTEMPTS - 1
1062
+ end
1063
+ # Never unexpected(a): this route's 201 and 202 carry the terminal's password or token, and an error's details go
1064
+ # to logs. The request's id is kept, so that its end can still be read.
1065
+ raise ReduSandbox.make_error(
1066
+ status: status, code: "unexpected_answer", http_method: "POST", path: path, workflow_id: workflow_id,
1067
+ message: "redu answered HTTP #{status} to the terminal's open with a body this client does not recognise."
1068
+ )
1069
+ end
1070
+
1071
+ # DELETE /v1/sandboxes/:id/terminal: a TerminalClosed saying what the stop found. Only terminal == "stopped" says a
1072
+ # running web terminal was stopped; platform_terminals says whether the terminals opened over the platform's
1073
+ # websocket were ended too ("ended", with how many) or could not be ("not_closed"). A 202 is waited on, unless
1074
+ # wait: false.
1075
+ def close_terminal(sandbox_id, wait: true, wait_timeout: nil)
1076
+ path = "/v1/sandboxes/#{seg(sandbox_id, "sandbox_id")}/terminal"
1077
+ a = @t.request("DELETE", path)
1078
+ return TerminalClosed.from_h(a.body) if a.status == 200 && a.body.is_a?(Hash) && a.body["terminal"].is_a?(String)
1079
+
1080
+ if a.status == 202 && self.class.pending?(a.body)
1081
+ return PendingRequest.from_h(a.body) unless wait
1082
+
1083
+ s = wait_for_request(a.body["workflow_id"], timeout: wait_timeout)
1084
+ return s.closed unless s.closed.nil?
1085
+ end
1086
+ raise unexpected(a, "DELETE", path, "the terminal's close")
1087
+ end
1088
+
1089
+ # -- lifecycle: idle pause, lifetime and spend cap in one place -----------------------------------------------------
1090
+
1091
+ # GET /v1/sandboxes/:id/lifecycle: what puts the sandbox to sleep and what ends it, as a SandboxLifecycle: its idle
1092
+ # pause (idle_pause_s, and whether set_lifecycle can change it now), its end (expires_at, max_expires_at), and its
1093
+ # spend against its cap (spend, max_spend, and the API key's monthly cap). A read: a 202 or a lost answer is read
1094
+ # again (still_pending after three tries). 404 sandbox_not_found.
1095
+ def get_lifecycle(sandbox_id)
1096
+ path = "/v1/sandboxes/#{seg(sandbox_id, "sandbox_id")}/lifecycle"
1097
+ a = read(path, "the sandbox's lifecycle")
1098
+ raise unexpected(a, "GET", path, "the sandbox's lifecycle") unless a.status == 200 && lifecycle?(a.body)
1099
+
1100
+ SandboxLifecycle.from_h(a.body)
1101
+ end
1102
+
1103
+ # PUT /v1/sandboxes/:id/lifecycle: what ends the sandbox, changed in one place, each field by its own rule and a
1104
+ # field left out staying as it is. Give at least one:
1105
+ # timeout_s:: it then lives this many seconds from now (60 up to #limits max_lifetime_s), as extend_lifetime does:
1106
+ # never less than it already would. Never 0: extend_lifetime(id, 0) takes a sandbox's end away.
1107
+ # max_spend:: a new spend cap in GBP (0.10 to 1000), above what it has cost so far; max_spend: nil REMOVES the cap
1108
+ # (left out, the cap stays as it is).
1109
+ # idle_pause_s:: a new idle pause, 0 to 86400 seconds; 0 never pauses it, and wakes a sandbox asleep for idleness.
1110
+ #
1111
+ # Answers a LifecycleChanged: the lifecycle after the change and +changed+, what it did. A 202 is waited on through
1112
+ # GET /v1/sandboxes/requests/sandbox-lifecycle-<id>, unless wait: false, which hands the PendingRequest back.
1113
+ # Sending the same change again is safe; the client never sends it twice by itself, and never with an
1114
+ # Idempotency-Key. One change of a sandbox's lifecycle runs at a time: 409 lifecycle_busy (its workflow_id is the
1115
+ # change under way). 409 max_spend_below_spend, idle_pause_not_changeable, idle_pause_change_unsupported,
1116
+ # sandbox_deleting; 402 max_spend_reached, spend_cap_reached; 503 usage_not_current (try again in a few minutes);
1117
+ # 502 idle_pause_outcome_unknown (ReduSandbox::IdlePauseOutcomeUnknownError). A change that failed after its idle
1118
+ # pause or its cap was applied says so in the error's details["applied"].
1119
+ def set_lifecycle(sandbox_id, timeout_s: nil, max_spend: UNSET, idle_pause_s: nil, wait: true, wait_timeout: nil)
1120
+ path = "/v1/sandboxes/#{seg(sandbox_id, "sandbox_id")}/lifecycle"
1121
+ body = whole_fields("timeout_s" => timeout_s, "idle_pause_s" => idle_pause_s) || {}
1122
+ unless max_spend.equal?(UNSET)
1123
+ raise ArgumentError, "max_spend must be a number of GBP, or nil to remove the cap." unless max_spend.nil? || max_spend.is_a?(Numeric)
1124
+
1125
+ body["max_spend"] = max_spend
1126
+ end
1127
+ raise ArgumentError, "Give timeout_s:, max_spend: (nil removes the cap) or idle_pause_s:." if body.empty?
1128
+
1129
+ # one change of a sandbox's lifecycle at a time, under one workflow id
1130
+ a = naming_busy("lifecycle_busy", "sandbox-lifecycle-#{sandbox_id}") { @t.request("PUT", path, body: body) }
1131
+ settle(a, "PUT", path, "the lifecycle change", wait, wait_timeout,
1132
+ ok: ->(x) { x.status == 200 && lifecycle?(x.body) }, make: ->(b) { LifecycleChanged.from_h(b) },
1133
+ ended: :lifecycle.to_proc)
1134
+ end
1135
+
1136
+ # -- the account's limits and its ended sandboxes -------------------------------------------------------------------
1137
+
1138
+ # GET /v1/sandboxes/limits: the account's sandbox limits (sandboxes, vCPUs, memory, disk, snapshots), what counts
1139
+ # against them now and what is left, as a SandboxLimits; with an API that has them, how long its sandboxes may live
1140
+ # (max_lifetime_s, and no_end: whether timeout_s 0 may be asked) and its free sandbox's hours (free_sandbox). A
1141
+ # read: a 202 or a lost answer is read again.
1142
+ def limits
1143
+ path = "/v1/sandboxes/limits"
1144
+ a = read(path, "the sandbox limits")
1145
+ b = a.body
1146
+ raise unexpected(a, "GET", path, "the sandbox limits") unless a.status == 200 && b.is_a?(Hash) && b["limits"].is_a?(Hash) && b["used"].is_a?(Hash)
1147
+
1148
+ SandboxLimits.from_h(b)
1149
+ end
1150
+
1151
+ # GET /v1/sandboxes?state=ended: one EndedSandboxPage of the sandboxes that ended in the last 7 days, newest end
1152
+ # first, from redu's own record: each with when and why it ended and what it cost. +limit+ 1 to 100
1153
+ # (ENDED_PAGE_MAX_LIMIT; redu's default is 50); +cursor+ the last page's next_cursor, which is nil on the last page.
1154
+ def list_ended(limit: nil, cursor: nil)
1155
+ q = ["state=ended"]
1156
+ q << "limit=#{whole(limit, "limit", 1)}" unless limit.nil?
1157
+ unless cursor.nil?
1158
+ raise ArgumentError, "cursor must be the next_cursor of the last page." unless cursor.is_a?(String) && !cursor.empty?
1159
+
1160
+ q << "cursor=#{escape(cursor)}"
1161
+ end
1162
+ path = "/v1/sandboxes?#{q.join("&")}"
1163
+ a = read(path, "the ended sandboxes")
1164
+ raise unexpected(a, "GET", path, "the ended sandboxes") unless a.status == 200 && a.body.is_a?(Hash) && a.body["sandboxes"].is_a?(Array)
1165
+
1166
+ EndedSandboxPage.from_h(a.body)
1167
+ end
1168
+
1169
+ # Every ended sandbox, page after page (#list_ended, +limit+ each), each EndedSandbox as it comes, following
1170
+ # next_cursor to the last page. Without a block, an Enumerator.
1171
+ def each_ended(limit: nil, &block)
1172
+ return enum_for(:each_ended, limit: limit) unless block
1173
+
1174
+ cursor = nil
1175
+ loop do
1176
+ page = list_ended(limit: limit, cursor: cursor)
1177
+ page.sandboxes.each(&block)
1178
+ return nil if page.next_cursor.nil? || page.next_cursor == cursor
1179
+
1180
+ cursor = page.next_cursor
1181
+ end
1182
+ end
1183
+
1184
+ # GET /v1/sandboxes/:id?state=ended: one sandbox that ended in the last 7 days, an EndedSandbox. 404
1185
+ # sandbox_not_found otherwise, also for a sandbox that is still live (#get reads that one).
1186
+ def get_ended(sandbox_id)
1187
+ path = "/v1/sandboxes/#{seg(sandbox_id, "sandbox_id")}?state=ended"
1188
+ a = read(path, "the ended sandbox")
1189
+ raise unexpected(a, "GET", path, "the ended sandbox") unless a.status == 200 && a.body.is_a?(Hash) && a.body["id"].is_a?(String)
1190
+
1191
+ EndedSandbox.from_h(a.body)
1192
+ end
1193
+
1194
+ # -- templates built from container images --------------------------------------------------------------------------
1195
+
1196
+ # POST /v1/sandboxes/templates/builds: a private template of your account built from a container image. Answers
1197
+ # the TemplateBuild (status "queued") once redu has accepted it; it then goes on by itself (pulling, unpacking,
1198
+ # building, uploading, registering) to "done", with its template_id, or "failed", with its error:
1199
+ # #get_template_build reads it with its log. Once it is done, create(build.template_id) makes sandboxes from it.
1200
+ #
1201
+ # name:: 1 to 100 letters, digits, '.', '_' and '-', starting with a letter or a digit.
1202
+ # image:: [registry/]repository[:tag][@sha256:digest], Docker Hub when no registry is named, such as python:3.12
1203
+ # or ghcr.io/owner/app:1.0. Never credentials in it: they go in registry_auth.
1204
+ # vcpus, memory_mb, disk_gb:: its sandboxes' default size: vcpus 1 to 4, memory_mb one of MEMORY_MB (1024 when
1205
+ # left out), disk_gb 1 to 10 (it must hold what the image unpacks to).
1206
+ # registry_auth:: for a private image only: a ReduSandbox::RegistryAuth, or a Hash with username and password. Sent
1207
+ # once, for this build: never stored, logged or answered by redu, and never echoed by this client.
1208
+ #
1209
+ # A 202 is waited on through GET /v1/sandboxes/requests/sandbox-template-build-<uuid>, unless wait: false. A built
1210
+ # template is billed as stored data, as a snapshot is, from when its build is done until #delete_template deletes
1211
+ # it; the build itself costs nothing. One build runs at a time per account (409 template_build_in_progress), so a
1212
+ # repeat never starts two; the client never repeats it by itself and sends no Idempotency-Key. 409
1213
+ # template_name_taken, template_limit_reached, template_builds_unavailable; 429 template_build_rate_limited (never
1214
+ # sent again by the client: builds of the last 24 hours count); 400 template_build_refused; 402 spend_cap_reached.
1215
+ def build_template(name:, image:, vcpus: nil, memory_mb: nil, disk_gb: nil, registry_auth: nil, wait: true,
1216
+ wait_timeout: nil)
1217
+ path = "/v1/sandboxes/templates/builds"
1218
+ raise ArgumentError, "name must be the template's name: letters, digits, '.', '_' and '-'." unless name.is_a?(String) && !name.empty?
1219
+ raise ArgumentError, "image must be a container image, such as python:3.12." unless image.is_a?(String) && !image.empty?
1220
+
1221
+ body = { "name" => name, "image" => image }
1222
+ body.update(whole_fields("vcpus" => vcpus, "memory_mb" => memory_mb, "disk_gb" => disk_gb) || {})
1223
+ body["registry_auth"] = registry_auth_body(registry_auth) unless registry_auth.nil?
1224
+ a = @t.request("POST", path, body: body)
1225
+ settle(a, "POST", path, "the template build", wait, wait_timeout,
1226
+ ok: ->(x) { x.status == 201 && build?(x.body) }, make: ->(b) { TemplateBuild.from_h(b) },
1227
+ ended: :build.to_proc)
1228
+ end
1229
+
1230
+ # GET /v1/sandboxes/templates/builds: your template builds, newest first, as redu last recorded them (each a
1231
+ # TemplateBuild, without its log).
1232
+ def list_template_builds
1233
+ path = "/v1/sandboxes/templates/builds"
1234
+ a = read(path, "the template builds")
1235
+ list = a.body.is_a?(Hash) ? a.body["builds"] : nil
1236
+ raise unexpected(a, "GET", path, "the template builds") unless a.status == 200 && list.is_a?(Array)
1237
+
1238
+ list.select { |b| build?(b) }.map { |b| TemplateBuild.from_h(b) }
1239
+ end
1240
+
1241
+ # GET /v1/sandboxes/templates/builds/:build_id: one TemplateBuild as it is now, with its log. 404
1242
+ # template_build_not_found.
1243
+ def get_template_build(build_id)
1244
+ path = "/v1/sandboxes/templates/builds/#{seg(build_id, "build_id")}"
1245
+ a = read(path, "the template build")
1246
+ raise unexpected(a, "GET", path, "the template build") unless a.status == 200 && build?(a.body)
1247
+
1248
+ TemplateBuild.from_h(a.body)
1249
+ end
1250
+
1251
+ # DELETE /v1/sandboxes/templates/builds/:build_id, as a TemplateBuildCancel: a build still running is cancelled
1252
+ # ("cancelling": it stops at its next step, cleans up and then reads failed; cancel it again to forget it), one that
1253
+ # is registering its template can no longer be stopped ("finishing"), and one that ended is forgotten
1254
+ # ("forgotten": no longer listed; the template it made stays, billed until #delete_template deletes it).
1255
+ # "pending": redu had no answer within its wait; cancel it again in a moment (#list_template_builds shows the build
1256
+ # until it is forgotten). 404 template_build_not_found.
1257
+ def cancel_template_build(build_id)
1258
+ path = "/v1/sandboxes/templates/builds/#{seg(build_id, "build_id")}"
1259
+ a = @t.request("DELETE", path)
1260
+ b = a.body
1261
+ if a.status == 204
1262
+ return TemplateBuildCancel.new(id: build_id, status: "forgotten", message: nil, hint: nil, workflow_id: nil)
1263
+ end
1264
+ if a.status == 202 && self.class.pending?(b)
1265
+ return TemplateBuildCancel.new(id: build_id, status: "pending", message: Read.str(b["message"]),
1266
+ hint: Read.str(b["hint"]), workflow_id: b["workflow_id"])
1267
+ end
1268
+ if a.status == 202 && b.is_a?(Hash) && %w[cancelling finishing].include?(b["status"])
1269
+ return TemplateBuildCancel.new(id: b["id"].is_a?(String) ? b["id"] : build_id, status: b["status"],
1270
+ message: Read.str(b["message"]), hint: Read.str(b["hint"]), workflow_id: nil)
1271
+ end
1272
+ raise unexpected(a, "DELETE", path, "the template build's cancel")
1273
+ end
1274
+
1275
+ # DELETE /v1/sandboxes/templates/:template_id: one of your built templates deleted, and its storage charge ended.
1276
+ # Sandboxes made from it keep running. Returns nil once it is gone (204); a 202 is waited on through
1277
+ # GET /v1/sandboxes/requests/sandbox-template-delete-<template_id>-<uuid>, unless wait: false. 404
1278
+ # template_not_found for a template your account did not build; 409 template_in_use while snapshots need it (the
1279
+ # error's details["snapshots"] names them: delete those first).
1280
+ def delete_template(template_id, wait: true, wait_timeout: nil)
1281
+ path = "/v1/sandboxes/templates/#{seg(template_id, "template_id")}"
1282
+ a = @t.request("DELETE", path)
1283
+ return nil if a.status == 204
1284
+
1285
+ if a.status == 202 && self.class.pending?(a.body)
1286
+ return PendingRequest.from_h(a.body) unless wait
1287
+
1288
+ wait_for_request(a.body["workflow_id"], timeout: wait_timeout)
1289
+ return nil
1290
+ end
1291
+ raise unexpected(a, "DELETE", path, "the template's delete")
1292
+ end
1293
+
1294
+ # -- secrets bound to hosts ---------------------------------------------------------------------------------------
1295
+
1296
+ # PUT /v1/sandboxes/:id/secrets: the sandbox's secrets bound to hosts replaced by +secrets+ (SecretInput values or
1297
+ # Hashes with name, value and hosts; up to 16), values included: a value is never shown back, so a change sends
1298
+ # every value again, and [] removes them. Answers a SandboxSecrets: the names and hosts it has now. A value is never
1299
+ # echoed by this client, in an answer or an error; where a value lives: see #create's secrets. A 202 is waited on
1300
+ # through GET /v1/sandboxes/requests/sandbox-secrets-<id>, unless wait: false. One change at a time: 409
1301
+ # secrets_change_busy (its workflow_id is the change under way). 409
1302
+ # secrets_unavailable, secrets_unsupported, secrets_need_egress_filtering, sandbox_not_running; 400 secrets_refused;
1303
+ # 502 secrets_failed, secrets_outcome_unknown (ReduSandbox::SecretsOutcomeUnknownError: send the same list again).
1304
+ def set_secrets(sandbox_id, secrets, wait: true, wait_timeout: nil)
1305
+ path = "/v1/sandboxes/#{seg(sandbox_id, "sandbox_id")}/secrets"
1306
+ change_secrets(sandbox_id, "PUT", path, { "secrets" => secrets_body(secrets) }, wait, wait_timeout)
1307
+ end
1308
+
1309
+ # DELETE /v1/sandboxes/:id/secrets: every secret of the sandbox removed. It always works, whatever the account's
1310
+ # billing state. Answered and waited on as #set_secrets.
1311
+ def remove_secrets(sandbox_id, wait: true, wait_timeout: nil)
1312
+ path = "/v1/sandboxes/#{seg(sandbox_id, "sandbox_id")}/secrets"
1313
+ change_secrets(sandbox_id, "DELETE", path, nil, wait, wait_timeout)
1314
+ end
1315
+
1316
+ # -- SSH --------------------------------------------------------------------------------------------------------------
1317
+
1318
+ # GET /v1/sandboxes/:id/ssh: a SandboxSsh: whether the sandbox's SSH server runs, its authorized keys (type,
1319
+ # fingerprint, comment), its host keys with the known_hosts lines that pin them, and how to connect (+connect+: an
1320
+ # ssh_config block and the ssh command). A read: a 202 or a lost answer is read again. 409 ssh_unavailable.
1321
+ def get_ssh(sandbox_id)
1322
+ path = "/v1/sandboxes/#{seg(sandbox_id, "sandbox_id")}/ssh"
1323
+ a = read(path, "the sandbox's SSH")
1324
+ raise unexpected(a, "GET", path, "the sandbox's SSH") unless a.status == 200 && ssh?(a.body)
1325
+
1326
+ SandboxSsh.from_h(a.body)
1327
+ end
1328
+
1329
+ # POST /v1/sandboxes/:id/ssh/keys: one public key (+key+, one line of a .pub file) added, and the sandbox's SSH
1330
+ # server started with it (keys only, root). Answers its SandboxSsh; a key already there is answered as it is. A 202
1331
+ # is waited on through GET /v1/sandboxes/requests/sandbox-ssh-keys-<id>, unless wait: false. An API key needs
1332
+ # sandbox:ssh. 409 ssh_keys_busy (its workflow_id is the change under way), ssh_unavailable, ssh_unsupported (its
1333
+ # template has no SSH server), ssh_keys_revoked; 400 ssh_key_refused; 403 denied_by_sandbox_rules; 502 ssh_failed,
1334
+ # ssh_outcome_unknown (ReduSandbox::SshOutcomeUnknownError: get_ssh, then add it again).
1335
+ def add_ssh_key(sandbox_id, key, wait: true, wait_timeout: nil)
1336
+ raise ArgumentError, "key must be one public key: the one line of a .pub file." unless key.is_a?(String) && !key.empty?
1337
+
1338
+ path = "/v1/sandboxes/#{seg(sandbox_id, "sandbox_id")}/ssh/keys"
1339
+ change_ssh(sandbox_id, "POST", path, { "key" => key }, wait, wait_timeout)
1340
+ end
1341
+
1342
+ # DELETE /v1/sandboxes/:id/ssh/keys?fingerprint=: one key removed by its SHA256 fingerprint (as get_ssh lists it,
1343
+ # or ssh-keygen -lf prints it; sent URL-encoded). A key already gone is answered as it is. It always works,
1344
+ # whatever the account's billing state. Answered and waited on as #add_ssh_key.
1345
+ def remove_ssh_key(sandbox_id, fingerprint, wait: true, wait_timeout: nil)
1346
+ path = "/v1/sandboxes/#{seg(sandbox_id, "sandbox_id")}/ssh/keys?fingerprint=#{seg(fingerprint, "fingerprint")}"
1347
+ change_ssh(sandbox_id, "DELETE", path, nil, wait, wait_timeout)
1348
+ end
1349
+
1350
+ # DELETE /v1/sandboxes/:id/ssh/keys?all=true: every key removed and the SSH server stopped, which also ends the SSH
1351
+ # sessions open through the platform. It never waits behind another change of the keys. A 202 is waited on through
1352
+ # GET /v1/sandboxes/requests/sandbox-ssh-revoke-<id>, unless wait: false.
1353
+ def remove_all_ssh_keys(sandbox_id, wait: true, wait_timeout: nil)
1354
+ path = "/v1/sandboxes/#{seg(sandbox_id, "sandbox_id")}/ssh/keys?all=true"
1355
+ change_ssh(sandbox_id, "DELETE", path, nil, wait, wait_timeout)
1356
+ end
1357
+
1358
+ # POST /v1/sandboxes/:id/ssh: ONE SSH connection to the sandbox through the platform, any live sandbox of yours,
1359
+ # private ones included, as an SshSession: a websocket +url+ and a one-time +token+ (60 seconds, once), the
1360
+ # +known_hosts+ lines to pin, and a ready +ssh+ command for that one connection (it needs websocat). The sandbox's
1361
+ # SSH server still asks for one of its keys (#add_ssh_key). +idle_timeout_s+: 60 to 3600 seconds with no byte
1362
+ # either way before it closes. When redu answers 202 (a suspended sandbox is woken first), it keeps no token for
1363
+ # later, so the client asks again, up to SESSION_OPEN_ATTEMPTS requests in all, then raises still_pending; wait:
1364
+ # false hands the 202 back (a PendingRequest). An API key needs sandbox:ssh_connect. The token is never put in an
1365
+ # error by this client. 409 ssh_unavailable, sandbox_not_running.
1366
+ def open_ssh(sandbox_id, idle_timeout_s: nil, wait: true)
1367
+ path = "/v1/sandboxes/#{seg(sandbox_id, "sandbox_id")}/ssh"
1368
+ body = whole_fields("idle_timeout_s" => idle_timeout_s)
1369
+ status = 0
1370
+ SESSION_OPEN_ATTEMPTS.times do |i|
1371
+ @t.pause(@o.poll_interval) if i.positive?
1372
+ a = @t.request("POST", path, body: body)
1373
+ status = a.status
1374
+ return SshSession.from_h(a.body) if a.status == 201 && session?(a.body)
1375
+ break unless a.status == 202 && self.class.pending?(a.body)
1376
+ return PendingRequest.from_h(a.body) unless wait
1377
+ raise session_still_pending(path, a.body["workflow_id"], "SSH connection") if i == SESSION_OPEN_ATTEMPTS - 1
1378
+ end
1379
+ # Never unexpected(a): a 201 carries the session's token, and an error's details go to logs.
1380
+ raise ReduSandbox.make_error(
1381
+ status: status, code: "unexpected_answer", http_method: "POST", path: path,
1382
+ message: "redu answered HTTP #{status} to the SSH connection's open with a body this client does not recognise."
1383
+ )
1384
+ end
1385
+
1386
+ # -- requests -----------------------------------------------------------------------------------------------------
1387
+
1388
+ # GET /v1/sandboxes/requests/:workflow_id, read once: a RequestState, still running (done false) or how it ended.
1389
+ # A request that ended in a failure is raised as the error it ended with (redu answers it "as the request itself
1390
+ # would have been"), with workflow_id set. Only the caller's own requests are found.
1391
+ #
1392
+ # redu holds this read open for up to 10 s while the request runs and answers as soon as it ends, so the read
1393
+ # waits at least REQUEST_READ_TIMEOUT_MIN_S (60 s) for its answer, whatever the client's timeout.
1394
+ def get_request(workflow_id)
1395
+ path = "/v1/sandboxes/requests/#{seg(workflow_id, "workflow_id")}"
1396
+ kind = self.class.request_kind_of(workflow_id)
1397
+ begin
1398
+ a = @t.request("GET", path, read_timeout: [@o.timeout, REQUEST_READ_TIMEOUT_MIN_S].max)
1399
+ rescue Error => e
1400
+ raise e.with_context(workflow_id: workflow_id)
1401
+ end
1402
+ b = a.body
1403
+ st = ->(**kw) { RequestState.build(done: true, kind: kind, workflow_id: workflow_id, **kw) }
1404
+ if a.status == 202 && self.class.pending?(b)
1405
+ return RequestState.build(done: false, kind: kind, workflow_id: workflow_id, message: b["message"].to_s)
1406
+ end
1407
+
1408
+ if b.is_a?(Hash)
1409
+ # A fork ends as a create does: 201 with the new sandbox.
1410
+ return st.call(sandbox: Sandbox.from_h(b)) if a.status == 201 && %i[create fork].include?(kind) && b["id"].is_a?(String)
1411
+ return st.call(snapshot: Snapshot.from_h(b)) if a.status == 201 && kind == :take_snapshot && b["id"].is_a?(String)
1412
+ return st.call(name: PublicName.from_h(b)) if a.status == 201 && kind == :add_public_name && b["domain"].is_a?(String)
1413
+ # A terminal's open and close share the id: its open ends 201 with the terminal, its close 200.
1414
+ if a.status == 201 && kind == :terminal && b["url"].is_a?(String)
1415
+ return RequestState.build(done: true, kind: :open_terminal, workflow_id: workflow_id, terminal: Terminal.from_h(b))
1416
+ end
1417
+ if a.status == 200 && kind == :terminal && b["terminal"].is_a?(String)
1418
+ return RequestState.build(done: true, kind: :close_terminal, workflow_id: workflow_id,
1419
+ closed: TerminalClosed.from_h(b))
1420
+ end
1421
+ return st.call(sandbox: ExtendedSandbox.from_h(b)) if a.status == 200 && kind == :extend && b["id"].is_a?(String)
1422
+ return st.call(state: SandboxStateResult.from_h(b)) if a.status == 200 && kind == :state && b["action"].is_a?(String)
1423
+ return st.call(sandbox: ResizedSandbox.from_h(b)) if a.status == 200 && kind == :resize && b["id"].is_a?(String)
1424
+ return st.call(egress: EgressChange.from_h(b)) if a.status == 200 && kind == :change_egress && egress_change?(b)
1425
+ # From the API of 27 Nov 2026, a lifecycle change, a change of secrets and a change of SSH keys answer 200
1426
+ # as the change itself does; a template build's start 201 with the build; a template's delete 204
1427
+ return st.call(lifecycle: LifecycleChanged.from_h(b)) if a.status == 200 && kind == :lifecycle && lifecycle?(b)
1428
+ return st.call(secrets: SandboxSecrets.from_h(b)) if a.status == 200 && kind == :secrets && secrets?(b)
1429
+ return st.call(ssh: SandboxSsh.from_h(b)) if a.status == 200 && kind == :ssh_keys && ssh?(b)
1430
+ return st.call(build: TemplateBuild.from_h(b)) if a.status == 201 && kind == :template_build && build?(b)
1431
+ end
1432
+ return st.call if a.status == 204 && %i[delete remove_public_name delete_snapshot delete_template].include?(kind)
1433
+
1434
+ if kind == :terminal
1435
+ # A terminal's answers may carry its password: never copied into an error's details.
1436
+ raise ReduSandbox.make_error(
1437
+ status: a.status, code: "unexpected_answer", http_method: "GET", path: path, workflow_id: workflow_id,
1438
+ message: "redu answered HTTP #{a.status} to the request with a body this client does not recognise."
1439
+ )
1440
+ end
1441
+ raise unexpected(a, "GET", path, "the request").with_context(workflow_id: workflow_id)
1442
+ end
1443
+
1444
+ # #get_request until the request has ended, reading every poll_interval, for at most +timeout+ seconds (default:
1445
+ # the longest that kind of request can run). A read that got no answer of redu's (a lost connection, a proxy's
1446
+ # page, a rate limit) is read again within the wait. redu's own 500 sandbox_request_failed cannot say whether the
1447
+ # read failed or the request did, so it is read once more, and a second one is the request's outcome. Any other
1448
+ # error is how the request ended, or a refusal of the read (404 sandbox_request_not_found), and is raised. Raises
1449
+ # WaitTimeoutError when it is still running at the end of the wait.
1450
+ def wait_for_request(workflow_id, timeout: nil)
1451
+ kind = self.class.request_kind_of(workflow_id)
1452
+ limit = timeout.nil? ? REQUEST_LIMIT_S.fetch(kind || :create, REQUEST_LIMIT_S[:create]) : timeout.to_f
1453
+ deadline = now + limit
1454
+ failed_once = false
1455
+ last = nil
1456
+ loop do
1457
+ read_started = now
1458
+ begin
1459
+ s = get_request(workflow_id)
1460
+ failed_once = false
1461
+ last = nil
1462
+ return s if s.done
1463
+ rescue Error => e
1464
+ if e.code == "rate_limited" || Transport.no_answer?(e, SANDBOX_ANSWER_CODES)
1465
+ last = e
1466
+ elsif e.code == "sandbox_request_failed" && !failed_once
1467
+ failed_once = true
1468
+ last = e
1469
+ else
1470
+ raise
1471
+ end
1472
+ end
1473
+ # redu holds a read of a request still running up to 10 s, answering as soon as it ends: after a held read the
1474
+ # next one is sent at once, and only a quick answer waits out the rest of poll_interval
1475
+ rest = [@o.poll_interval - (now - read_started), 0].max
1476
+ if now + rest > deadline
1477
+ err = ReduSandbox.make_error(
1478
+ status: last.nil? ? 202 : last.status, code: "wait_timeout", http_method: "GET",
1479
+ path: "/v1/sandboxes/requests/#{escape(workflow_id)}", workflow_id: workflow_id,
1480
+ message: "The request was still running after #{limit.round} s of waiting.",
1481
+ hint: WAIT_HINTS.fetch(kind, WAIT_HINT)
1482
+ )
1483
+ raise err, cause: last
1484
+ end
1485
+ @t.pause(rest)
1486
+ end
1487
+ end
1488
+
1489
+ # The state of following a background command: the offsets to read from, and when to stop.
1490
+ class Follower
1491
+ attr_reader :stdout_offset, :stderr_offset
1492
+
1493
+ def initialize(stdout_offset, stderr_offset, wait_ms, timeout, path)
1494
+ @stdout_offset = Sandboxes.whole(stdout_offset, "stdout_offset", 0)
1495
+ @stderr_offset = Sandboxes.whole(stderr_offset, "stderr_offset", 0)
1496
+ @wait_ms = [Sandboxes.whole(wait_ms, "wait_ms", 0), COMMAND_WAIT_MAX_MS].min
1497
+ @timeout = timeout
1498
+ @deadline = timeout.nil? ? nil : Sandboxes.now + timeout
1499
+ @path = path
1500
+ @done = false
1501
+ @ready = false
1502
+ end
1503
+
1504
+ # The wait_ms of the next read: never past the follow's own end, so none once its time is up.
1505
+ def wait
1506
+ return @wait_ms if @deadline.nil?
1507
+
1508
+ left = [0, ((@deadline - Sandboxes.now) * 1000).ceil].max
1509
+ [@wait_ms, left].min
1510
+ end
1511
+
1512
+ # Read one answer; true when it is worth handing on (it carries output, or the command has ended).
1513
+ def take(o)
1514
+ running = o.command.status == "running"
1515
+ @ready = o.stdout_more || o.stderr_more
1516
+ @done = !running && !@ready
1517
+ @stdout_offset = [@stdout_offset, o.stdout_next].max
1518
+ @stderr_offset = [@stderr_offset, o.stderr_next].max
1519
+ !o.stdout.empty? || !o.stderr.empty? || o.stdout_lost.positive? || o.stderr_lost.positive? || !running
1520
+ end
1521
+
1522
+ # True once all is read. Raises wait_timeout when the follow's own time is up while it runs.
1523
+ def finished?
1524
+ return true if @done
1525
+
1526
+ if !@ready && !@deadline.nil? && Sandboxes.now >= @deadline
1527
+ raise ReduSandbox.make_error(
1528
+ status: 200, code: "wait_timeout", http_method: "GET", path: @path,
1529
+ message: "The command was still running after #{(@timeout || 0).round} s of following it.",
1530
+ hint: "It runs on. Follow it again from stdout_offset #{@stdout_offset} and stderr_offset " \
1531
+ "#{@stderr_offset}, or stop it with stop_command.",
1532
+ details: { "stdout_offset" => @stdout_offset, "stderr_offset" => @stderr_offset }
1533
+ )
1534
+ end
1535
+ false
1536
+ end
1537
+ end
1538
+
1539
+ def self.now
1540
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
1541
+ end
1542
+
1543
+ def self.whole(value, what, least)
1544
+ raise ArgumentError, "#{what} must be a whole number of #{least} or more." unless value.is_a?(Integer) && value >= least
1545
+
1546
+ value
1547
+ end
1548
+
1549
+ def self.new_key
1550
+ "sdk-#{SecureRandom.uuid}"
1551
+ end
1552
+
1553
+ # A path segment or query value, percent-encoded (RFC 3986 unreserved characters kept; a space is %20).
1554
+ def self.escape(value)
1555
+ value.to_s.b.gsub(/[^A-Za-z0-9\-._~]/n) { |c| format("%%%02X", c.ord) }
1556
+ end
1557
+
1558
+ private
1559
+
1560
+ def now
1561
+ self.class.now
1562
+ end
1563
+
1564
+ def whole(value, what, least)
1565
+ self.class.whole(value, what, least)
1566
+ end
1567
+
1568
+ def escape(value)
1569
+ self.class.escape(value)
1570
+ end
1571
+
1572
+ def seg(value, what)
1573
+ raise ArgumentError, "#{what} must be a non-empty string." unless value.is_a?(String) && !value.empty?
1574
+
1575
+ escape(value)
1576
+ end
1577
+
1578
+ def unexpected(a, method, path, what)
1579
+ ReduSandbox.make_error(status: a.status, code: "unexpected_answer", http_method: method, path: path, details: a.body,
1580
+ message: "redu answered HTTP #{a.status} to #{what} with a body this client does not recognise.")
1581
+ end
1582
+
1583
+ def key_header(key)
1584
+ return {} if key.nil?
1585
+ raise ArgumentError, "idempotency_key must be a non-empty string." unless key.is_a?(String) && !key.empty?
1586
+
1587
+ { "idempotency-key" => key }
1588
+ end
1589
+
1590
+ def egress_log_path(sandbox_id, since, limit)
1591
+ q = ["since=#{whole(since, "since", 0)}"]
1592
+ q << "limit=#{whole(limit, "limit", 1)}" unless limit.nil?
1593
+ "/v1/sandboxes/#{seg(sandbox_id, "sandbox_id")}/egress/log?#{q.join("&")}"
1594
+ end
1595
+
1596
+ # The audit log's path: since, limit when given, and kind (a String, or an Array of them sent comma-separated)
1597
+ # when given.
1598
+ def audit_log_path(sandbox_id, since, limit, kind)
1599
+ q = ["since=#{whole(since, "since", 0)}"]
1600
+ q << "limit=#{whole(limit, "limit", 1)}" unless limit.nil?
1601
+ kinds = kind.is_a?(Array) ? kind : [kind].compact
1602
+ raise TypeError, "kind must be a String or an Array of Strings." unless kinds.all? { |k| k.is_a?(String) }
1603
+
1604
+ q << "kind=#{escape(kinds.join(","))}" unless kinds.empty?
1605
+ "/v1/sandboxes/#{seg(sandbox_id, "sandbox_id")}/audit?#{q.join("&")}"
1606
+ end
1607
+
1608
+ # The "egress" of a create: an EgressPolicy as JSON, or a Hash sent as it is (redu refuses an unknown key, so a
1609
+ # typo is answered 400 rather than dropped).
1610
+ def egress_body(egress)
1611
+ return egress.as_json if egress.is_a?(EgressPolicy)
1612
+ return egress if egress.is_a?(Hash)
1613
+
1614
+ raise TypeError, "egress must be a ReduSandbox::EgressPolicy, or a Hash with default_action and rules."
1615
+ end
1616
+
1617
+ # The volumes as POST /v1/sandboxes takes them: VolumeMount values, Hashes (sent as they are) or ids.
1618
+ def volumes_body(volumes)
1619
+ raise TypeError, "volumes must be an Array of ReduSandbox::VolumeMount, Hashes or volume ids." unless volumes.is_a?(Array)
1620
+
1621
+ volumes.map do |v|
1622
+ case v
1623
+ when VolumeMount then v.as_json
1624
+ when Hash then v
1625
+ when String then VolumeMount.new(id: v).as_json
1626
+ else raise TypeError, "volumes must be an Array of ReduSandbox::VolumeMount, Hashes or volume ids."
1627
+ end
1628
+ end
1629
+ end
1630
+
1631
+ # The answer of a change of egress rules: the sandbox's id and its rules.
1632
+ def egress_change?(body)
1633
+ body.is_a?(Hash) && body["id"].is_a?(String) && body["egress"].is_a?(Hash)
1634
+ end
1635
+
1636
+ def command?(value)
1637
+ value.is_a?(Hash) && value["id"].is_a?(String) && value["status"].is_a?(String)
1638
+ end
1639
+
1640
+ # A sandbox's lifecycle: its id, and idle_pause_changeable as every lifecycle answer has it.
1641
+ def lifecycle?(body)
1642
+ body.is_a?(Hash) && body["id"].is_a?(String) && [true, false].include?(body["idle_pause_changeable"])
1643
+ end
1644
+
1645
+ def secrets?(body)
1646
+ body.is_a?(Hash) && body["id"].is_a?(String) && body["secrets"].is_a?(Array)
1647
+ end
1648
+
1649
+ def ssh?(body)
1650
+ body.is_a?(Hash) && body["id"].is_a?(String) && body["keys"].is_a?(Array)
1651
+ end
1652
+
1653
+ def build?(body)
1654
+ body.is_a?(Hash) && body["id"].is_a?(String) && body["image"].is_a?(String) && body["status"].is_a?(String)
1655
+ end
1656
+
1657
+ # A session through the platform's websocket carries its one-time token.
1658
+ def session?(body)
1659
+ body.is_a?(Hash) && body["kind"] == "websocket" && body["url"].is_a?(String) && body["token"].is_a?(String)
1660
+ end
1661
+
1662
+ # The whole-number fields of a body that are given (nil: left out), or nil when none is (then no body is sent).
1663
+ def whole_fields(fields)
1664
+ given = fields.compact
1665
+ given.each { |k, v| raise ArgumentError, "#{k} must be a whole number." unless v.is_a?(Integer) }
1666
+ given.empty? ? nil : given
1667
+ end
1668
+
1669
+ # The request in the block, with a refusal that has +code+ (one change of that kind at a time per sandbox) given
1670
+ # the change under way as its workflow_id, for wait_for_request.
1671
+ def naming_busy(code, workflow_id)
1672
+ yield
1673
+ rescue Error => e
1674
+ raise e.with_context(workflow_id: workflow_id) if e.code == code
1675
+
1676
+ raise
1677
+ end
1678
+
1679
+ # The rest of a change's answer: what +make+ makes of it when +ok+ says it is the change's own answer, or its 202
1680
+ # waited on (unless +wait+ is false, which hands the PendingRequest back) and what +ended+ reads from the
1681
+ # RequestState of its end. Anything else is unexpected_answer.
1682
+ def settle(a, method, path, what, wait, wait_timeout, ok:, make:, ended:)
1683
+ return make.call(a.body) if ok.call(a)
1684
+
1685
+ if a.status == 202 && self.class.pending?(a.body)
1686
+ return PendingRequest.from_h(a.body) unless wait
1687
+
1688
+ value = ended.call(wait_for_request(a.body["workflow_id"], timeout: wait_timeout))
1689
+ return value unless value.nil?
1690
+ end
1691
+ raise unexpected(a, method, path, what)
1692
+ end
1693
+
1694
+ # A change of a sandbox's secrets (PUT with the list, or DELETE): one at a time per sandbox, under one workflow id
1695
+ #. Never sent twice by the client, never with an Idempotency-Key.
1696
+ def change_secrets(sandbox_id, method, path, body, wait, wait_timeout)
1697
+ a = naming_busy("secrets_change_busy", "sandbox-secrets-#{sandbox_id}") { @t.request(method, path, body: body) }
1698
+ settle(a, method, path, "the change of secrets", wait, wait_timeout,
1699
+ ok: ->(x) { x.status == 200 && secrets?(x.body) }, make: ->(b) { SandboxSecrets.from_h(b) },
1700
+ ended: :secrets.to_proc)
1701
+ end
1702
+
1703
+ # A change of a sandbox's SSH keys: an add or a removal of one key runs one at a time per sandbox
1704
+ # (sandbox-ssh-keys-<id>); a removal of every key runs under its own id and never waits behind one.
1705
+ def change_ssh(sandbox_id, method, path, body, wait, wait_timeout)
1706
+ a = naming_busy("ssh_keys_busy", "sandbox-ssh-keys-#{sandbox_id}") { @t.request(method, path, body: body) }
1707
+ settle(a, method, path, "the change of SSH keys", wait, wait_timeout,
1708
+ ok: ->(x) { x.status == 200 && ssh?(x.body) }, make: ->(b) { SandboxSsh.from_h(b) }, ended: :ssh.to_proc)
1709
+ end
1710
+
1711
+ # A session through the platform that was not ready after every open: its 202's id is not read at
1712
+ # /v1/sandboxes/requests (the token is not kept), so the hint is to open it again.
1713
+ def session_still_pending(path, workflow_id, what)
1714
+ ReduSandbox.make_error(
1715
+ status: 202, code: "still_pending", http_method: "POST", path: path, workflow_id: workflow_id,
1716
+ message: "redu had no #{what} ready after #{SESSION_OPEN_ATTEMPTS} tries.",
1717
+ hint: "A suspended sandbox is woken first, which can take a minute or two: open it again in a moment."
1718
+ )
1719
+ end
1720
+
1721
+ # A list of secrets as a body takes it: each one's name, value and hosts only. A refusal names a secret by its
1722
+ # place, and by its name when it has the shape of one, never by its value.
1723
+ def secrets_body(secrets)
1724
+ unless secrets.is_a?(Array)
1725
+ raise TypeError, "secrets must be an Array of ReduSandbox::SecretInput, or of Hashes with name, value and hosts."
1726
+ end
1727
+
1728
+ secrets.each_with_index.map do |x, i|
1729
+ case x
1730
+ when SecretInput then x.as_json
1731
+ when Hash then secret_of(x, i).as_json
1732
+ else raise TypeError, "secrets[#{i}] must be a ReduSandbox::SecretInput, or a Hash with name, value and hosts."
1733
+ end
1734
+ end
1735
+ end
1736
+
1737
+ # A Hash as a SecretInput: an unknown key (a typo) or a missing one raises rather than being dropped.
1738
+ def secret_of(hash, index)
1739
+ fields = hash.to_h { |k, v| [k.to_s.to_sym, v] }
1740
+ SecretInput.new(**fields)
1741
+ rescue ArgumentError, TypeError => e
1742
+ name = fields && fields[:name]
1743
+ at = name.is_a?(String) && SECRET_NAME.match?(name) ? "secrets[#{index}] (#{name})" : "secrets[#{index}]"
1744
+ raise e.class, "#{at}: #{e.message}"
1745
+ end
1746
+
1747
+ # build_template's registry_auth as the API takes it. A refusal never repeats what was given.
1748
+ def registry_auth_body(auth)
1749
+ case auth
1750
+ when RegistryAuth then auth.as_json
1751
+ when Hash then RegistryAuth.new(**auth.to_h { |k, v| [k.to_s.to_sym, v] }).as_json
1752
+ else raise TypeError, "registry_auth must be a ReduSandbox::RegistryAuth, or a Hash with username and password."
1753
+ end
1754
+ end
1755
+
1756
+ # A read (templates, list, get, commands, snapshots, the egress log): its 202 has a workflow id that
1757
+ # GET /v1/sandboxes/requests does not read, and says "Ask again in a moment". So a 202 is asked again, and so is
1758
+ # an answer that never came (a read changes nothing) and a 429 sandbox_busy (a read with wait_ms counts as a
1759
+ # running command), up to three times in all.
1760
+ def read(path, what, raw: false)
1761
+ attempts = 3
1762
+ last = nil
1763
+ attempts.times do |i|
1764
+ if i.positive?
1765
+ wait = [@o.poll_interval, (last.code == "too_many_log_reads" && last.retry_after_s) || 0].max
1766
+ raise last if wait > MAX_RETRY_AFTER_S
1767
+
1768
+ @t.pause(wait)
1769
+ end
1770
+ begin
1771
+ a = @t.request("GET", path, raw: raw)
1772
+ rescue Error => e
1773
+ raise unless Transport.no_answer?(e, SANDBOX_ANSWER_CODES) ||
1774
+ (e.status == 429 && %w[sandbox_busy too_many_log_reads].include?(e.code))
1775
+
1776
+ last = e
1777
+ next
1778
+ end
1779
+ body = raw ? Transport.parse_json(a.content.dup.force_encoding(Encoding::UTF_8)) : a.body
1780
+ if a.status == 202 && self.class.pending?(body)
1781
+ last = ReduSandbox.make_error(
1782
+ status: 202, code: "still_pending", http_method: "GET", path: path, workflow_id: body["workflow_id"],
1783
+ message: "redu had no answer for #{what} after #{attempts} tries.",
1784
+ hint: "The sandbox service is slow right now. Try again in a minute."
1785
+ )
1786
+ next
1787
+ end
1788
+ return a
1789
+ end
1790
+ raise last
1791
+ end
1792
+
1793
+ # The body of exec and start_command: exactly one of argv and command, and only the options given.
1794
+ def command_body(method, command, argv, env, cwd, stdin, timeout_ms)
1795
+ if argv.nil? == command.nil?
1796
+ raise ArgumentError, "Give exactly one of command (a shell command line) and argv (a program and its arguments)."
1797
+ end
1798
+ if !argv.nil? && !(argv.is_a?(Array) && argv.all?(String))
1799
+ # A String is not a list: a command line goes in command (#{method}).
1800
+ raise TypeError, "argv is an Array of Strings (a program and its arguments); give a command line as command (#{method})."
1801
+ end
1802
+ raise TypeError, "command is a String (a shell command line)." if !command.nil? && !command.is_a?(String)
1803
+
1804
+ body = argv.nil? ? { "command" => command } : { "argv" => argv }
1805
+ body["env"] = env.to_h { |k, v| [k.to_s, v] } unless env.nil?
1806
+ body["cwd"] = cwd unless cwd.nil?
1807
+ body["stdin"] = stdin unless stdin.nil?
1808
+ body["timeout_ms"] = timeout_ms unless timeout_ms.nil?
1809
+ body
1810
+ end
1811
+
1812
+ # The rules every command start follows (exec, start_command): see #exec. Returns what +accept+ read from the
1813
+ # successful answer, the key it ran under, and how many requests it took.
1814
+ def keyed(path, body, idempotency_key, max_attempts, what, method, accept)
1815
+ own_key = !idempotency_key.nil?
1816
+ key = own_key ? idempotency_key : self.class.new_key
1817
+ key_header(key)
1818
+ allowed = [1, max_attempts.to_i].max
1819
+ # An earlier request under this key may have started the command (its answer was lost, or was a 202).
1820
+ may_have_started = false
1821
+ outcome_unknown_seen = false
1822
+ renewed = false
1823
+ last = nil
1824
+ fail_with = ->(e, ran) { e.with_context(ran: ran, idempotency_key: key) }
1825
+
1826
+ (1..allowed).each do |attempt|
1827
+ begin
1828
+ a = @t.request("POST", path, body: body, headers: { "idempotency-key" => key })
1829
+ rescue Error => e
1830
+ # A 2xx whose body is not JSON got through, so the command may have run: the same as a lost answer.
1831
+ if Transport.no_answer?(e, SANDBOX_ANSWER_CODES) || e.status.between?(200, 299)
1832
+ may_have_started = true
1833
+ last = fail_with.call(e, :unknown)
1834
+ @t.pause(@o.poll_interval) if attempt < allowed
1835
+ next
1836
+ end
1837
+ if e.code == "exec_outcome_unknown"
1838
+ # A run can end this way, and the route can also lose sight of a run that goes on: one repeat with the
1839
+ # key tells the two apart.
1840
+ last = fail_with.call(e, :unknown)
1841
+ raise last if outcome_unknown_seen
1842
+
1843
+ outcome_unknown_seen = true
1844
+ may_have_started = true
1845
+ next
1846
+ end
1847
+ raise fail_with.call(e, :yes) if e.code == "exec_result_lost"
1848
+
1849
+ if RAN_NOTHING_KEY_BOUND.include?(e.code)
1850
+ # The key's own run ran nothing, and keeps this answer about a day.
1851
+ if !own_key && !renewed && attempt < allowed
1852
+ renewed = true
1853
+ last = fail_with.call(e, :no)
1854
+ key = self.class.new_key
1855
+ may_have_started = false
1856
+ outcome_unknown_seen = false
1857
+ @t.pause(@o.poll_interval)
1858
+ next
1859
+ end
1860
+ raise fail_with.call(e, :no)
1861
+ end
1862
+ # A refusal. After a request whose answer was lost, only a run's own outcome says nothing ran; a refusal
1863
+ # from before the run (404 once the sandbox is deleted, a gate) says nothing about that run.
1864
+ raise fail_with.call(e, may_have_started && !RUN_OUTCOME_RAN_NOTHING.include?(e.code) ? :unknown : :no)
1865
+ end
1866
+ value = accept.call(a)
1867
+ return [value, key, attempt] unless value.nil?
1868
+
1869
+ if a.status == 202 && self.class.pending?(a.body)
1870
+ # Sent within 30 s of its request or never, and one already sent may still start later: asking again with
1871
+ # the key answers from that run once it has a result.
1872
+ may_have_started = true
1873
+ last = ReduSandbox.make_error(
1874
+ status: 202, code: "still_pending", http_method: "POST", path: path, workflow_id: a.body["workflow_id"],
1875
+ ran: :unknown, idempotency_key: key, message: a.body["message"].to_s,
1876
+ hint: "Call #{method} again with exactly the same command and idempotency_key \"#{key}\": that never runs " \
1877
+ "it twice. Check its effects before running it under a new key."
1878
+ )
1879
+ next
1880
+ end
1881
+ raise unexpected(a, "POST", path, what).with_context(ran: :unknown, idempotency_key: key)
1882
+ end
1883
+ raise last
1884
+ end
1885
+
1886
+ # No body, and never an Idempotency-Key: redu keys its replay cache on the credential and the key whatever the
1887
+ # route, so a reused key would replay a pause's answer for a resume.
1888
+ def change_state(sandbox_id, action, wait, wait_timeout)
1889
+ path = "/v1/sandboxes/#{seg(sandbox_id, "sandbox_id")}/#{action}"
1890
+ a = @t.request("POST", path)
1891
+ b = a.body
1892
+ if a.status == 200 && b.is_a?(Hash) && b["status"].is_a?(String) && b["action"].is_a?(String)
1893
+ return SandboxStateResult.from_h(b)
1894
+ end
1895
+
1896
+ if a.status == 202 && self.class.pending?(b)
1897
+ return PendingRequest.from_h(b) unless wait
1898
+
1899
+ s = wait_for_request(b["workflow_id"], timeout: wait_timeout)
1900
+ return s.state unless s.state.nil?
1901
+ end
1902
+ raise unexpected(a, "POST", path, "the #{action}")
1903
+ end
1904
+
1905
+ # A path in the sandbox, as the files routes take it: absolute, at most 4096 characters, no NUL; URL-encoded.
1906
+ def file_route(sandbox_id, path)
1907
+ raise ArgumentError, "path must be an absolute path, starting with /." unless path.is_a?(String) && path.start_with?("/")
1908
+ raise ArgumentError, "path must be at most 4096 characters." if path.length > 4096
1909
+ raise ArgumentError, "path must not contain a NUL character." if path.include?("\0")
1910
+
1911
+ "/v1/sandboxes/#{seg(sandbox_id, "sandbox_id")}/files?path=#{escape(path)}"
1912
+ end
1913
+
1914
+ # Content-Range: bytes <first>-<last>/<size or *>.
1915
+ def content_range(value)
1916
+ m = value&.strip&.match(%r{\Abytes\s+(\d+)-(\d+)/(\d+|\*)\z}i)
1917
+ return nil unless m
1918
+
1919
+ [m[1].to_i, m[2].to_i, m[3] == "*" ? nil : m[3].to_i]
1920
+ end
1921
+
1922
+ # One part of a file read in ranges, or nil at its end (an empty part, or a 416: the range starts at or past the
1923
+ # end of the file).
1924
+ def next_file_range(sandbox_id, path, offset, chunk)
1925
+ part = begin
1926
+ read_file_range(sandbox_id, path, offset, chunk)
1927
+ rescue Error => e
1928
+ return nil if e.status == 416
1929
+
1930
+ raise
1931
+ end
1932
+ part.data.empty? ? nil : part
1933
+ end
1934
+
1935
+ # Where the part after this one starts, or nil when the file has been read to its end.
1936
+ def next_offset(part, offset)
1937
+ return nil if part.next <= offset
1938
+ return nil if !part.size.nil? && part.next >= part.size
1939
+
1940
+ part.next
1941
+ end
1942
+
1943
+ def command_path(sandbox_id, command_id)
1944
+ "/v1/sandboxes/#{seg(sandbox_id, "sandbox_id")}/commands/#{seg(command_id, "command_id")}"
1945
+ end
1946
+ end
1947
+ end