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.
data/docs/reference.md ADDED
@@ -0,0 +1,865 @@
1
+ # redu sandbox SDK for Ruby: reference
2
+
3
+ The short version is the [README](../README.md).
4
+
5
+ A Ruby client for the redu.cloud API. Version 0.1 covers sandboxes: isolated machines started from a template, for
6
+ running commands. It is the Ruby twin of the Python, TypeScript and Go SDKs: the same routes, the same retry rules,
7
+ idiomatic Ruby.
8
+
9
+ - Ruby 3.2 or later. Standard library only (`net/http`, `json`): no runtime gems.
10
+ - Answers are immutable `Data` values; errors are `ReduSandbox::Error` subclasses.
11
+ - Apache-2.0 licensed (see "License").
12
+
13
+ An account that sandboxes are not open to gets `403 sandboxes_not_available` on every sandbox route;
14
+ `redu.sandboxes_enabled?` tells whether they are open to yours. The documentation of the service is at
15
+ https://docs.redu.cloud/Services/sandboxes.
16
+
17
+ ## Install
18
+
19
+ ```sh
20
+ gem install redu-sandbox-sdk
21
+ ```
22
+
23
+ With Bundler, put `gem "redu-sandbox-sdk"` in your Gemfile and run `bundle install`. The gem is `redu-sandbox-sdk`;
24
+ you `require "redu_sandbox"`, and everything is in the `ReduSandbox` module.
25
+
26
+ ## Quick start
27
+
28
+ ```ruby
29
+ require "redu_sandbox"
30
+
31
+ redu = ReduSandbox::Client.new # the API key from REDU_API_KEY
32
+
33
+ sandbox = redu.sandboxes.create("ubuntu-node", timeout_s: 600)
34
+ begin
35
+ result = redu.sandboxes.exec(sandbox.id, "node -v")
36
+ puts result.exit_code, result.stdout
37
+ ensure
38
+ redu.sandboxes.delete(sandbox.id)
39
+ end
40
+ ```
41
+
42
+ ## Credentials
43
+
44
+ | Option | Sent as | Notes |
45
+ |---|---|---|
46
+ | `api_key:` | `Authorization: Bearer` | The key needs `sandbox:*`, or the route's own `sandbox:<action>`. A full-access `*` key does not include sandboxes: `403 insufficient_scope`. |
47
+ | `token:` | `Authorization: Bearer` | A signed-in session's access token, or anything that answers `#call` with a fresh one for each request (a lambda). |
48
+
49
+ Give one of them. With neither, the client reads `REDU_API_KEY` from the environment. `base_url:` defaults to
50
+ `REDU_API_BASE`, else `https://console.redu.cloud`.
51
+
52
+ `redu.sandboxes_enabled?` tells whether sandboxes are on for the caller's account (from `GET /v1/capabilities`).
53
+
54
+ ## Sandboxes
55
+
56
+ | Method | Route | Returns |
57
+ |---|---|---|
58
+ | `templates` | `GET /v1/sandboxes/templates` | `Array<Template>` (name, vcpus, memory_mb, disk_gb, price) |
59
+ | `list` | `GET /v1/sandboxes` | your live sandboxes |
60
+ | `get(id)` | `GET /v1/sandboxes/:id` | one `Sandbox` |
61
+ | `create(template, ...)`, `create(snapshot: id, ...)` | `POST /v1/sandboxes` | the `Sandbox` once it is running |
62
+ | `fork(id, ...)` | `POST /v1/sandboxes/:id/fork` | the copy, a new `Sandbox` (its `forked_from` names the original) |
63
+ | `take_snapshot(id, name: nil)` | `POST /v1/sandboxes/:id/snapshots` | the `Snapshot` once it is taken |
64
+ | `list_snapshots`, `get_snapshot(snapshot_id)` | `GET /v1/sandboxes/snapshots`, `/snapshots/:snapshot_id` | your snapshots, or one |
65
+ | `delete_snapshot(snapshot_id)` | `DELETE /v1/sandboxes/snapshots/:snapshot_id` | `nil` once it is gone |
66
+ | `change_egress(id, egress)` | `PUT /v1/sandboxes/:id/egress` | `EgressChange`: its rules now, and how many connections they closed |
67
+ | `egress_log(id, since: 0, limit: nil)` | `GET /v1/sandboxes/:id/egress/log` | one `EgressLog` page: events, next_since, more |
68
+ | `each_egress_event(id, since: 0)` | the same, page after page | each `EgressEvent`; returns the `since` to read from next |
69
+ | `audit_log(id, since: 0, limit: nil, kind: nil)` | `GET /v1/sandboxes/:id/audit` | one `AuditLog` page: events, next_since, more |
70
+ | `each_audit_event(id, since: 0, kind: nil)` | the same, page after page | each `AuditEvent`; returns the `since` to read from next |
71
+ | `resize(id, vcpus: nil, memory_mb: nil)` | `POST /v1/sandboxes/:id/resize` | `ResizedSandbox`: the sandbox at its new size, `resize`, `price` |
72
+ | `exec(id, command, ...)` | `POST /v1/sandboxes/:id/exec` | `ExecResult`: exit code, stdout, stderr |
73
+ | `delete(id)` | `DELETE /v1/sandboxes/:id` | `nil` once it is gone |
74
+ | `add_public_name(id, port, domain: nil)` | `POST /v1/sandboxes/:id/dns` | `PublicName` (id, domain, port, url) once it serves |
75
+ | `remove_public_name(id, dns_id)` | `DELETE /v1/sandboxes/:id/dns/:dns_id` | `nil` once it no longer serves |
76
+ | `open_terminal(id, cols: nil, rows: nil, idle_timeout_s: nil)` | `POST /v1/sandboxes/:id/terminal` | a `TerminalSession` over the platform's websocket (kind `websocket`: url, one-time token), or the web `Terminal` (kind `web`: url, username, password) |
77
+ | `close_terminal(id)` | `DELETE /v1/sandboxes/:id/terminal` | `TerminalClosed`: what the stop found, `platform_terminals` included |
78
+ | `get_lifecycle(id)` | `GET /v1/sandboxes/:id/lifecycle` | `SandboxLifecycle`: its idle pause, its end and its spend in one view |
79
+ | `set_lifecycle(id, timeout_s:, max_spend:, idle_pause_s:)` | `PUT /v1/sandboxes/:id/lifecycle` | `LifecycleChanged`: the lifecycle after the change, and `changed` |
80
+ | `limits` | `GET /v1/sandboxes/limits` | `SandboxLimits`: the account's limits, what is used and what is left, how long its sandboxes may live, and its free sandbox |
81
+ | `list_ended(limit: nil, cursor: nil)`, `each_ended` | `GET /v1/sandboxes?state=ended` | one `EndedSandboxPage` of the sandboxes that ended in the last 7 days, or each of them |
82
+ | `get_ended(id)` | `GET /v1/sandboxes/:id?state=ended` | one `EndedSandbox` |
83
+ | `build_template(name:, image:, ...)` | `POST /v1/sandboxes/templates/builds` | the `TemplateBuild`, once accepted (`queued`) |
84
+ | `list_template_builds`, `get_template_build(build_id)` | `GET /v1/sandboxes/templates/builds`, `/builds/:build_id` | your builds, newest first, or one with its log |
85
+ | `cancel_template_build(build_id)` | `DELETE /v1/sandboxes/templates/builds/:build_id` | `TemplateBuildCancel`: `cancelling`, `finishing`, `forgotten` or `pending` |
86
+ | `delete_template(template_id)` | `DELETE /v1/sandboxes/templates/:template_id` | `nil` once it is gone |
87
+ | `set_secrets(id, secrets)`, `remove_secrets(id)` | `PUT`, `DELETE /v1/sandboxes/:id/secrets` | `SandboxSecrets`: names and hosts, never a value |
88
+ | `get_ssh(id)` | `GET /v1/sandboxes/:id/ssh` | `SandboxSsh`: its SSH server, keys, host keys and how to connect |
89
+ | `add_ssh_key(id, key)`, `remove_ssh_key(id, fingerprint)`, `remove_all_ssh_keys(id)` | `POST`, `DELETE /v1/sandboxes/:id/ssh/keys` | the sandbox's `SandboxSsh` after the change |
90
+ | `open_ssh(id, idle_timeout_s: nil)` | `POST /v1/sandboxes/:id/ssh` | `SshSession`: one connection (url, one-time token, known_hosts, a ready ssh command) |
91
+ | `extend_lifetime(id, timeout_s)` | `POST /v1/sandboxes/:id/extend` | `ExtendedSandbox`: the sandbox with its new `expires_at` (`nil`: no end) |
92
+ | `pause(id)`, `resume(id)`, `suspend(id)` | `POST /v1/sandboxes/:id/pause`, `/resume`, `/suspend` | `SandboxStateResult` (status, already, from, expires_at) |
93
+ | `read_file(id, path)` | `GET /v1/sandboxes/:id/files?path=` | the bytes (a binary `String`) of a file of at most 8 MiB |
94
+ | `read_file_range(id, path, offset = 0, length = nil)` | the same, with a `Range` | one `FileRange` (data, offset, next, size) |
95
+ | `each_file_range(id, path)`, `read_large_file(id, path)` | the same, part after part | each part as it comes, or the whole file |
96
+ | `write_file(id, path, data, mode: nil)` | `PUT /v1/sandboxes/:id/files?path=` | `WrittenFile` (path, bytes) |
97
+ | `start_command(id, command, ...)` | `POST /v1/sandboxes/:id/commands` | `StartedCommand`, running in the background |
98
+ | `list_commands(id)` | `GET /v1/sandboxes/:id/commands` | the running ones and the last 32 that ended |
99
+ | `get_command(id, command_id, ...)` | `GET /v1/sandboxes/:id/commands/:command_id` | `CommandOutput`: the command and its output past the offsets |
100
+ | `follow_command(id, command_id)`, `wait_for_command(...)` | the same, until it ends | its output as it comes, or `CommandEnd` with all of it |
101
+ | `stop_command(id, command_id, signal = "TERM")` | `DELETE /v1/sandboxes/:id/commands/:command_id` | the `Command`, signalled |
102
+ | `get_request(workflow_id)` | `GET /v1/sandboxes/requests/:workflow_id` | one read of a request that answered 202 |
103
+ | `wait_for_request(workflow_id)` | the same, until it ends | how it ended |
104
+
105
+ Every answer keeps redu's whole JSON object in `.raw` (string keys), so a field redu adds later is never lost.
106
+ `inspect` leaves out `raw`, a terminal's password, a session's one-time token (and the subprotocols and ssh command
107
+ that carry it), and a secret's value.
108
+
109
+ The extend is `extend_lifetime`, not `extend`: `Object#extend` is Ruby's own, and every object needs it.
110
+
111
+ Extend, pause, suspend, resume, files and background commands need the redu API version that adds them (the API of
112
+ 20 Nov 2026). An API from before answers them `404 not_found`. Snapshots, forks, egress rules and the egress log need
113
+ the version after that (later on 20 Nov 2026): an API from before answers them `404 not_found` and refuses `snapshot:`
114
+ and `egress:` in a create (`400 validation_error`). A create's size and private network, the resize and the audit log
115
+ need the version after that (20 Nov 2026, later): an API from before answers them `404 not_found` and refuses `vcpus:`,
116
+ `memory_mb:`, `disk_gb:`, `network_id:` and `volumes:` in a create. The storage prices (a template's
117
+ `storage_per_gb_month` and `paused_or_suspended_*`, a snapshot's `price`) need the version of the evening of
118
+ 20 Nov 2026, and `change_egress` and `resize_range` the version of 21 Nov 2026: an API from before answers
119
+ `change_egress` `404 not_found`, and the fields it does not send are `nil`. A sandbox's lifecycle, the limits, ended
120
+ sandboxes, templates built from images, secrets, SSH and the terminal over the platform's websocket need the API version
121
+ of 27 Nov 2026: an API from before answers their routes `404 not_found` and refuses `idle_pause_s:` or `secrets:` in a
122
+ create (`400 validation_error`). A sandbox with no end (`timeout_s: 0`), the free sandbox (`free:`) and the limits'
123
+ `max_lifetime_s`, `no_end` and `free_sandbox` need the API version of 1 Dec 2026: an API from before refuses
124
+ `timeout_s: 0` and `free:` (`400 validation_error`), and those three fields read `nil`.
125
+
126
+ ### create
127
+
128
+ ```ruby
129
+ sandbox = redu.sandboxes.create(
130
+ "ubuntu-node", # a name or id from templates
131
+ name: "build-42", # optional
132
+ timeout_s: 3600, # deleted by itself when it runs out: 60 up to your limit, or 0 (default 3600)
133
+ env: { "NODE_ENV" => "test" },
134
+ public: true # optional: it can then have public names and a web terminal
135
+ )
136
+ ```
137
+
138
+ redu answers 201 once the sandbox is running. When it is still being made after about 40 seconds, redu answers 202
139
+ with a `workflow_id`, and the client waits for it through `GET /v1/sandboxes/requests/:workflow_id`, reading it every
140
+ `poll_interval` (5 s) for up to the longest that kind of request can run (40 minutes for a create; `wait_timeout:`
141
+ sets your own). Pass `wait: false` to get the 202 back instead (a `PendingRequest`), and read it later with
142
+ `get_request` or `wait_for_request`.
143
+
144
+ The client never sends a create twice by itself: a create whose answer was lost may still be running, and a second
145
+ one makes a second sandbox (`list` shows the first one once it is ready). An `idempotency_key:` lets you repeat a
146
+ create safely once the first one has answered: redu stores that answer for the key for 24 hours.
147
+
148
+ `max_spend:` is a cap in GBP for one sandbox (0.10 to 1000): when what it has cost reaches it, the sandbox is deleted.
149
+ It needs the API version with spend caps; an API without it refuses the field (`400 validation_error`).
150
+
151
+ Give `snapshot:` (a snapshot's id) instead of a template to start from a snapshot (see "Snapshots"), and `egress:` to
152
+ limit what the sandbox may connect to (see "Egress rules"). Every `Sandbox` read shows `from_snapshot`, `forked_from`
153
+ and `egress`. `idle_pause_s:` pauses it by itself after that long without activity (see "Lifecycle"), and
154
+ `secrets:` binds secrets to hosts (see "Secrets"); every read shows `idle_pause_s` and `secrets` (names and hosts).
155
+
156
+ ```ruby
157
+ big = redu.sandboxes.create("ubuntu-node", vcpus: 2, memory_mb: 2048, disk_gb: 8)
158
+ puts "#{big.vcpus} vCPUs, #{big.memory_mb} MB, #{big.disk_gb} GB" # 2 vCPUs, 2048 MB, 8 GB
159
+ ```
160
+
161
+ A create from a template takes a size: `vcpus:` 1 to 4, `memory_mb:` one of 1024, 2048, 4096 and 8192
162
+ (`ReduSandbox::MEMORY_MB`: 1 GB is the smallest), and
163
+ `disk_gb:` 1 to 10 (at least that much disk: a template with more keeps its own). Each one left out is the template's
164
+ own (`templates` lists them), and a sandbox made from a snapshot has the snapshot's size (the client refuses a size with
165
+ `snapshot:`). `400 size_unsupported` when the template cannot be made at that size. It is billed at the same price for
166
+ its size. `network_id:` puts the sandbox on one of your private networks (`GET /v1/private_networks`): it reaches your
167
+ machines there (their own security groups decide what it may reach), all its traffic leaves through that network (one
168
+ with no router to the internet gives it no internet), and it is not public, so not with `public: true`.
169
+ `404 network_not_found`, `409 network_unusable` (no IPv4 subnet). Every read shows `vcpus`, `memory_mb`, `disk_gb`
170
+ and `network_id`. The client checks only the types; redu checks the bounds (`400 validation_error`).
171
+
172
+ ```ruby
173
+ work = redu.sandboxes.create("ubuntu-node", volumes: [
174
+ ReduSandbox::VolumeMount.new(id: "6a0e3c43-0d7e-4b8e-9b1f-2a6f5f1b9c01", mount_path: "/work") # from GET /v1/volumes/list
175
+ ])
176
+ puts work.volumes.map { |v| "#{v.mount_path} #{v.status}" }.join(", ") # /work attached
177
+ redu.sandboxes.delete(work.id) # the volume is unmounted and detached, and keeps its data
178
+ ```
179
+
180
+ `volumes:` attaches and mounts up to two volumes of yours (`ReduSandbox::VOLUMES_MAX`), from a template only (the
181
+ client refuses it with `snapshot:`): each a `VolumeMount` (`id`; `mount_path`, by default `/mnt/volumes/<id>`; and
182
+ `format`), a Hash of the same JSON shape, or a volume's id. `format` (true by default) formats a volume on which no
183
+ filesystem, partition table or other signature is found, so a blank one, and one written raw, loses its data; one with
184
+ a signature is mounted as it is (`format: false`: a volume with none fails the create instead). When the sandbox is
185
+ deleted or ends, its volumes are unmounted and detached and keep their data; a volume is never deleted with its
186
+ sandbox, and it is billed as any volume. An API key needs `volume:attach` (or `volume:*`) beside its sandbox scope.
187
+ Every read shows them as `volumes` (each a `SandboxVolume`: `volume_id`, `mount_path`, `status`). A sandbox with
188
+ volumes is not snapshotted, forked or suspended (`409 sandbox_has_volumes`: pause it instead). `404 volume_not_found`,
189
+ `409 volume_in_use`, `volume_not_available`, `volumes_unavailable`, `400 volume_unsupported`, `too_many_volumes`,
190
+ `502 volume_attach_failed` (no sandbox was made, and the volumes stay available): `Sandboxes::VOLUME_CODES`.
191
+
192
+ ### Lifetime
193
+
194
+ A sandbox is deleted by itself at its `expires_at`, `timeout_s` seconds after its create (3600 by default), unless it
195
+ is extended (see "Extend"). A `timeout_s` is 60 up to your account's longest life, `limits.max_lifetime_s` (2592000,
196
+ 30 days, for an account with no card; at most 31536000, 365 days). redu checks it, not this client. While
197
+ `limits.no_end` is false, a sandbox lives at most `max_lifetime_s` after its create, extends included.
198
+
199
+ `timeout_s: 0`, at a create or an extend (`extend_lifetime(id, 0)`), asks for a sandbox with no end: it runs until you
200
+ delete it, or until its `max_spend`, its API key's monthly cap or a suspended account ends it, and it is billed by use
201
+ as any sandbox (`idle_pause_s:` still puts it to sleep). It reads `expires_at` nil and `max_expires_at` nil, which never
202
+ means it has ended. It is for an account with a card, where `limits.no_end` is true, and never for a sandbox with
203
+ volumes or for the free sandbox. A fork and a lifecycle change never take 0: extend the sandbox for that.
204
+
205
+ ```ruby
206
+ limits = redu.sandboxes.limits
207
+ puts "timeout_s at most #{limits.max_lifetime_s}, no end: #{limits.no_end}"
208
+ if limits.no_end
209
+ kept = redu.sandboxes.create("ubuntu-node", timeout_s: 0)
210
+ puts "expires_at #{kept.expires_at.inspect}" # expires_at nil: no end
211
+ redu.sandboxes.delete(kept.id) # it runs until it is deleted
212
+ end
213
+ ```
214
+
215
+ | Code | What it means |
216
+ |---|---|
217
+ | `403 no_end_needs_card` | the account has no card: give `timeout_s` in seconds, or add a payment method |
218
+ | `503 no_end_unavailable` | no end cannot be given right now: nothing was made or changed. Try again in a few minutes, or give `timeout_s` in seconds and extend it later |
219
+ | `400 validation_error` | on `timeout_s`, with the reason: no end is not offered, the sandbox has volumes, or the ask is above your longest life |
220
+
221
+ The first two are `Sandboxes::NO_END_CODES`. The client sends `timeout_s` as you give it and leaves these checks to
222
+ redu.
223
+
224
+ The platform's maintenance (an update or a planned restart of the server a sandbox runs on) pauses a sandbox with no end
225
+ for a few minutes and brings it back as it was; open connections, terminals and SSH sessions are cut. A sandbox lives
226
+ on one server with its memory and disk, so a hardware failure there can still end it: the platform then deletes it, and
227
+ it ends as `lost` (see "Limits and ended sandboxes").
228
+
229
+ ### The free sandbox
230
+
231
+ An account with the free tier has one free sandbox: 1 vCPU and 1 GB of memory from a template, never charged, one at a
232
+ time, with 50 hours a calendar month (UTC) of running and paused time (suspended time does not count). An account with
233
+ no card has it during its 7-day trial; an account with a card has it every month, beside its paid sandboxes. When the
234
+ month's hours are used it is deleted, and a new one can be made from the 1st of the next month. It never has no end, and
235
+ it lives at most 30 days after its create, extends included. `create(template, free: true)` asks for it, `free: false`
236
+ for a paid sandbox; left out, nothing is sent, and an account with no card gets its free sandbox while any other gets a
237
+ paid one. It takes no `snapshot:`, other size, `disk_gb:`, `public:`, `network_id:`, `volumes:`, `max_spend:` or
238
+ `timeout_s: 0`, and it is created through the redu MCP only: a create from this client that asks for it (`free: true`,
239
+ or an account with no card leaving `free` out) answers `403 free_sandbox_mcp_only` once nothing else refuses it.
240
+
241
+ Once made it is used as any sandbox, and its reads carry `raw["free"]` true. It keeps its size (a resize answers
242
+ `403 free_sandbox_size`) and takes no `max_spend` (`403 free_sandbox_options`); an extend of it with 0 answers
243
+ `403 free_sandbox_options`, and one past its 30 days a `400 validation_error` on `timeout_s`. `limits.free_sandbox`
244
+ says whether your account can have it now (`available`, and `reason` when not), its hours used and left this month, and
245
+ when they reset:
246
+
247
+ ```ruby
248
+ free = redu.sandboxes.limits.free_sandbox # nil from an API without it
249
+ puts "free sandbox: #{free.hours_left} hours left this month, until #{free.resets_at}" if free
250
+ ```
251
+
252
+ | Code | What it means |
253
+ |---|---|
254
+ | `403 free_sandbox_mcp_only` | it is created through the redu MCP only |
255
+ | `403 free_sandbox_options` | the create asked for something it does not take |
256
+ | `403 free_sandbox_exists` | the account has its free sandbox already: use it, or delete it to make another |
257
+ | `409 free_sandbox_creating` | the account's free sandbox is being created |
258
+ | `402 free_sandbox_hours_used` | its hours for this month are used: a new one can be made from the 1st (UTC) |
259
+ | `403 free_sandbox_size` | a resize of it: it keeps its size (a paid sandbox, or a paid fork of it, can be any size) |
260
+ | `403 free_sandbox_unavailable` | the account cannot have a free sandbox now: its setup is not complete |
261
+
262
+ These seven are `Sandboxes::FREE_SANDBOX_CODES`, each redu's own answer, never sent again by the client.
263
+
264
+ ### exec
265
+
266
+ ```ruby
267
+ r = redu.sandboxes.exec(
268
+ sandbox.id,
269
+ argv: ["node", "-e", "console.log(1 + 1)"], # or a command line: exec(sandbox.id, "echo hi")
270
+ env: { "A" => "1" }, cwd: "/root", stdin: "...",
271
+ timeout_ms: 30_000 # 1000 to 30000
272
+ )
273
+ p [r.exit_code, r.signal, r.stdout, r.stderr, r.stdout_truncated, r.stderr_truncated, r.duration_ms]
274
+ p [r.idempotency_key, r.attempts]
275
+ ```
276
+
277
+ `duration_ms` is a `Float`: it can carry a fraction. A command runs for at most 30 seconds (start longer work with
278
+ `start_command`); stdout and stderr are cut at 64 KiB each.
279
+
280
+ A command is not safe to run twice, so every call carries an `Idempotency-Key` (yours, or a new random one), and the
281
+ answers decide what happens next:
282
+
283
+ | Answer | Did it run? | What the client does |
284
+ |---|---|---|
285
+ | 200 | yes | returns the result |
286
+ | 202 (no result after about 40 s) | may have | sends it again with the **same** key, which never runs it twice and answers from the first run |
287
+ | no answer (lost connection, timeout, a proxy's error page) | may have | the same: sends it again with the same key |
288
+ | a 2xx whose body is not JSON (`unexpected_answer`) | may have | the same; on the last attempt it raises with `ran == :unknown` |
289
+ | 502 `exec_outcome_unknown` | may have | sends it once more with the same key; a second one is final (`ran == :unknown`) |
290
+ | 502 `exec_result_lost` | yes | raises (`ran == :yes`): check its effects before running it again |
291
+ | 503 `exec_not_started`, 429 `sandbox_busy` | no | the key keeps this answer for about a day, so with its own key the client tries once more under a new key; with your key it raises (`ran == :no`) |
292
+ | 409 `idempotency_key_reused` | no | raises: the same key was used for another command |
293
+ | any other error | no, or unknown after an earlier lost answer | raises |
294
+
295
+ At most `max_attempts:` requests (default 4) are sent per call. Every exec error carries `ran` and `idempotency_key`.
296
+ To repeat a command after `ran == :unknown`, call `exec` again with the same input and that key:
297
+
298
+ ```ruby
299
+ begin
300
+ redu.sandboxes.exec(sandbox.id, "echo hi")
301
+ rescue ReduSandbox::Error => e
302
+ raise unless e.ran == :unknown && e.idempotency_key
303
+
304
+ redu.sandboxes.exec(sandbox.id, "echo hi", idempotency_key: e.idempotency_key)
305
+ end
306
+ ```
307
+
308
+ ### Public names
309
+
310
+ A sandbox made with `public: true` can have one public https name per port. The program must listen on
311
+ `0.0.0.0:<port>` and keep running after the command that starts it.
312
+
313
+ ```ruby
314
+ redu.sandboxes.exec(sandbox.id, "nohup python3 -m http.server 8000 > /tmp/http.log 2>&1 &")
315
+ name = redu.sandboxes.add_public_name(sandbox.id, 8000)
316
+ puts name.url # https://...redu.cloud
317
+ redu.sandboxes.remove_public_name(sandbox.id, name.id)
318
+ ```
319
+
320
+ Without `domain:` a name is generated under redu.cloud; a domain of your own must be verified for your account first.
321
+
322
+ ### Terminal
323
+
324
+ `open_terminal` gives a root shell in the sandbox. Where the platform offers terminals over its websocket, any live
325
+ sandbox gets one, private ones included; elsewhere a sandbox made with `public: true` gets the web terminal.
326
+
327
+ ```ruby
328
+ terminal = redu.sandboxes.open_terminal(sandbox.id, cols: 120, rows: 40)
329
+ if terminal.websocket?
330
+ puts terminal.url, terminal.protocol # open url within 60 seconds, once, with a websocket client of your own
331
+ else
332
+ puts terminal.url, terminal.username, terminal.password # the web terminal: anyone with both has the shell
333
+ end
334
+ closed = redu.sandboxes.close_terminal(sandbox.id)
335
+ puts "#{closed.terminal} #{closed.platform_terminals}" # "stopped", "none" or "not_stopped"; "ended" or "not_closed"
336
+ ```
337
+
338
+ A websocket terminal is a `TerminalSession` (`kind` `"websocket"`) with a one-time `token`, good for 60 seconds and
339
+ one session: open `url` offering `subprotocols` (or with the token as a bearer token); binary messages are the
340
+ terminal's input and output. `cols:` and `rows:` (1 to 1000) set its size, and `idle_timeout_s:` (60 to 3600) how long
341
+ it may sit with no byte either way. When redu answers 202 (a suspended sandbox is woken first) it keeps no token for
342
+ later, so the client opens it again, up to 3 requests in all (`Sandboxes::SESSION_OPEN_ATTEMPTS`, then
343
+ `still_pending`); `wait: false` hands the 202 back as a `PendingRequest`. The client never puts the token in an error,
344
+ and `inspect` leaves it out. `close_terminal` ends these too where the platform can (`platform_terminals` `"ended"`,
345
+ with how many in `platform_terminals_ended`); `"not_closed"` means they end when their connection closes, after their
346
+ idle timeout, or when the sandbox is deleted.
347
+
348
+ The web terminal is a `Terminal` (`kind` `"web"`): a root shell in the browser, behind a username and a password. The
349
+ password is answered once and redu keeps it nowhere: to get a new one, open the terminal again (the old one stops
350
+ working, the url stays). When redu answers 202 the password comes with that 202 and the url with the request's end;
351
+ the client joins the two. With `wait: false` you get a `PendingTerminal` that holds the password. The client never
352
+ sends an open again by itself. Only `"stopped"` says a running web terminal was stopped; `"not_stopped"` means it may
353
+ run again with its old password once the sandbox runs (close it again then, or delete the sandbox).
354
+
355
+ ### Extend
356
+
357
+ ```ruby
358
+ x = redu.sandboxes.extend_lifetime(sandbox.id, 7200) # 60 up to limits.max_lifetime_s seconds from now, or 0
359
+ p [x.expires_at, x.previous_expires_at, x.extended, x.capped, x.max_expires_at]
360
+ ```
361
+
362
+ The sandbox then ends `timeout_s` seconds from now, never sooner than it already would (`extended` is false then),
363
+ and, where a longest life holds, at most that long after it was created (`limits.max_lifetime_s` while
364
+ `limits.no_end` is false; `capped` is true when that cut the ask). `max_expires_at` is the latest it can live, as the
365
+ platform holds it (`nil`: no latest end). `extend_lifetime(id, 0)` takes its end away where `limits.no_end` is true,
366
+ for a sandbox with no volumes, never the free sandbox: its `expires_at` and `max_expires_at` are then `nil` (see
367
+ "Lifetime"). Calling it again is safe, so it works as a keep-alive; send no `idempotency_key:` for that, since a
368
+ repeated key replays the first answer and extends nothing. A sandbox costs while it lives. `409 sandbox_deleting`,
369
+ `402 max_spend_reached` or `spend_cap_reached`, and `404 sandbox_not_found` once it has ended.
370
+
371
+ ### Pause, suspend, resume
372
+
373
+ ```ruby
374
+ redu.sandboxes.pause(sandbox.id) # CPUs stop, memory kept: billed for memory, never CPU; no commands
375
+ redu.sandboxes.suspend(sandbox.id) # memory and disk saved, memory freed: no memory charge
376
+ r = redu.sandboxes.resume(sandbox.id)
377
+ puts "#{r.status} #{r.from}" # running disk
378
+ ```
379
+
380
+ Each returns a `SandboxStateResult`: `status`, `already` (it was in that state), `from` (`"disk"` after a suspend) and
381
+ `expires_at`. A paused sandbox refuses commands (`409 sandbox_not_running`); a suspended one is resumed by its next
382
+ command (its `ExecResult#resumed` is true). Both are still deleted at `expires_at`. A 202 is waited on. Codes:
383
+ `409 sandbox_suspended`, `409 sandbox_cannot_suspend` (a command or file transfer runs in it: try again in a minute),
384
+ `409 sandbox_resume_unavailable` (no room right now: it stays suspended), `409 sandbox_state_busy`. No
385
+ `Idempotency-Key` is ever sent with these: redu's replay cache keys on the credential and the key, whatever the route,
386
+ so a reused key would replay a pause's answer for a resume.
387
+
388
+ A paused or suspended sandbox is billed for storage only: its memory at the storage rate. Each template's `price`
389
+ shows it: `paused_or_suspended_per_hour`, `paused_or_suspended_per_month` (730 hours) and `storage_per_gb_month`.
390
+
391
+ ### Files
392
+
393
+ ```ruby
394
+ redu.sandboxes.write_file(sandbox.id, "/root/app/main.rb", "puts 'hi'\n", mode: "644")
395
+ data = redu.sandboxes.read_file(sandbox.id, "/root/app/main.rb") # at most 8 MiB
396
+ whole = redu.sandboxes.read_large_file(sandbox.id, "/root/app/main.rb") # any size, in 8 MiB ranges
397
+ redu.sandboxes.each_file_range(sandbox.id, "/root/app/main.rb") do |part|
398
+ puts "#{part.offset} #{part.data.bytesize} #{part.size}"
399
+ end
400
+ ```
401
+
402
+ Paths are absolute (at most 4096 characters). Reads answer binary `String`s. `read_file` raises `413 file_too_large`
403
+ for a file over 8 MiB (its message says the size): read it with `read_large_file`, or part by part with
404
+ `each_file_range` or `read_file_range(id, path, offset, length)`, which follows the `Content-Range` of each answer.
405
+ `416 range_not_satisfiable` past the end, `404 file_not_found` when there is no such file. `write_file` writes a
406
+ `String`'s bytes as they are, at most 12517376 (12 MiB less 64 KiB; a larger one is refused with `ArgumentError`
407
+ before anything is sent), replaces a file that is there and creates missing parent folders. `mode:` is `"644"`,
408
+ `"0755"` or an Integer such as `0o755`.
409
+
410
+ ### Background commands
411
+
412
+ ```ruby
413
+ cmd = redu.sandboxes.start_command(sandbox.id, "npm run build", cwd: "/root/app")
414
+ redu.sandboxes.follow_command(sandbox.id, cmd.id) { |out| print out.stdout }
415
+ done = redu.sandboxes.wait_for_command(sandbox.id, cmd.id) # or all of it at the end
416
+ p [done.command.exit_code, done.stdout, done.stdout_lost]
417
+ redu.sandboxes.stop_command(sandbox.id, cmd.id, "KILL") # TERM by default
418
+ ```
419
+
420
+ A background command runs for up to an hour (`timeout_ms:`, default and most 3600000), at most 16 at once per sandbox
421
+ (`429 sandbox_busy`). `start_command` follows exec's rules for a lost answer and its `Idempotency-Key` (the table
422
+ above): the same key never starts it twice, and its errors carry `ran` and `idempotency_key`.
423
+ `get_command(id, command_id, stdout_offset:, stderr_offset:, wait_ms:)` reads the output past the offsets, waiting up
424
+ to `wait_ms` (20000 at most) for more; ask again from `stdout_next` and `stderr_next`. `follow_command` does that until
425
+ the command has ended and all its output is read (without a block it is an `Enumerator`; `timeout:`, in seconds, stops
426
+ following with `ReduSandbox::WaitTimeoutError` while the command runs on). The sandbox keeps the last 1 MiB of each stream:
427
+ what was written faster than it was read is counted in `stdout_lost` and `stderr_lost`. `404 command_not_found` once
428
+ it is forgotten (the last 32 ended ones are kept). A command's `duration_ms` is a `Float`.
429
+
430
+ ### Snapshots
431
+
432
+ ```ruby
433
+ snap = redu.sandboxes.take_snapshot(sandbox.id, name: "after-build")
434
+ puts "#{snap.name} #{snap.status} #{snap.size_bytes}" # after-build available ...
435
+ again = redu.sandboxes.create(snapshot: snap.id, timeout_s: 600)
436
+ puts "from #{again.from_snapshot}"
437
+ redu.sandboxes.list_snapshots.each { |s| puts "#{s.id} #{s.name} #{s.status}" }
438
+ redu.sandboxes.delete(again.id)
439
+ redu.sandboxes.delete_snapshot(snap.id)
440
+ ```
441
+
442
+ A snapshot holds a running or paused sandbox's files, memory and running programs; the sandbox pauses for about a
443
+ second while it is written. It costs storage by its size from when it is taken until it is deleted: its `price`
444
+ (a `SnapshotPrice`) has `per_gb_month`, the storage rate, and `per_month`, a month of it at its size. It is kept until you delete it, also after the sandbox is gone, on the server the sandbox
445
+ ran on (it is not a backup), and `create(snapshot: id)` starts new sandboxes from it as the sandbox was then, at its
446
+ size. `status` is `creating`, `available`, `deleting` or `error`; a sandbox is created only from an available one
447
+ (`409 snapshot_unavailable`). A 202 is waited on as a create's is (`wait: false` hands back the `PendingRequest`).
448
+
449
+ One take at a time per sandbox: `409 snapshot_in_progress` while one runs, and that error's `workflow_id` is the take
450
+ under way (`wait_for_request` waits for it). `409 sandbox_busy_for_snapshot`: a command or a file transfer runs in it,
451
+ take it between commands. `409 snapshot_not_possible`: it is not running or paused (resume a suspended one first).
452
+ `409 snapshot_limit_reached`: delete a snapshot first. `409 snapshot_deleting` on a delete while it is still being
453
+ taken. `404 snapshot_not_found`. A create from a snapshot can answer `503 snapshot_server_unavailable`: the server
454
+ that keeps it is full or down, try again later or use a template.
455
+
456
+ The client never sends a take twice by itself, and a lost answer may still have taken the snapshot. Two answers say
457
+ how a take whose answer redu lost ended, and they must not be confused:
458
+
459
+ ```ruby
460
+ begin
461
+ redu.sandboxes.take_snapshot(sandbox.id, name: "nightly")
462
+ rescue ReduSandbox::SnapshotNotTakenError
463
+ # 503 snapshot_not_taken: nothing was kept, so taking it again is safe
464
+ rescue ReduSandbox::SnapshotOutcomeUnknownError => e
465
+ # 503 snapshot_outcome_unknown: it MAY have been taken, and then it counts against your snapshot limit
466
+ # without being listed: list_snapshots cannot show it. Wait a few minutes before you take another.
467
+ warn e.hint
468
+ end
469
+ ```
470
+
471
+ Both are `ReduSandbox::ServerError`s too. A snapshot taken by a take that answered `snapshot_outcome_unknown` is never
472
+ listed, since redu kept no record of it: if `snapshot_limit_reached` answers while fewer snapshots are listed, write to
473
+ support@redu.cloud (the error's `hint` says so). A take that got no answer at all (`network_error`) may also have been
474
+ taken: `list_snapshots` shows it once it is.
475
+
476
+ ### Resize
477
+
478
+ ```ruby
479
+ resized = redu.sandboxes.resize(big.id, vcpus: 4, memory_mb: 4096)
480
+ puts "#{resized.resize.from.vcpus} to #{resized.resize.to.vcpus} vCPUs, GBP #{resized.price.busy_per_hour} an hour busy"
481
+ ```
482
+
483
+ `resize` changes a running sandbox's vCPUs (1 to 4) and memory (1024 to 8192 MB, within its template's range: memory
484
+ moves in 2 MB steps, and a shrink stops at what the sandbox can free) live: nothing restarts, and its files and programs
485
+ stay. Give either or both. It answers a `ResizedSandbox`: the sandbox at its new size, `resize` (`from` and `to`, each
486
+ a `SandboxSize`) and `price` at that size, which it is billed at from then on. The size is a target, not a step, so
487
+ asking again for the same size is safe. A 202 is waited on through `GET /v1/sandboxes/requests/sandbox-resize-<id>`
488
+ (`wait: false` hands it back). `409 resize_not_available` is a `ReduSandbox::ResizeNotAvailableError` (a
489
+ `ConflictError`): the template cannot be resized, nothing changed, and a new sandbox at the size you need is the way.
490
+ `409 resize_busy` carries the resize under way as its `workflow_id`. `400 resize_out_of_range`, `409 resize_refused`
491
+ (try again in a minute), `429 resize_limit_reached`, `502 resize_failed` (nothing changed), `resize_incomplete` and
492
+ `resize_outcome_unknown` (`get` shows the size it has, which is what it is billed at). The free sandbox keeps its size:
493
+ `403 free_sandbox_size`.
494
+
495
+ ```ruby
496
+ range = redu.sandboxes.get(big.id).resize_range
497
+ puts "#{range.min_vcpus} to #{range.max_vcpus} vCPUs, up to #{range.max_memory_mb} MB" if range
498
+ puts range.include?(vcpus: 2, memory_mb: 2048) if range # true
499
+ ```
500
+
501
+ Every read shows the sandbox's own `resize_range` when the sandbox service reports it (a `SandboxResizeRange`: vCPUs
502
+ `min_vcpus` to `max_vcpus`, memory `min_memory_mb` to `max_memory_mb` in steps of `memory_step_mb`), set by the size
503
+ it was created at and fixed while it lives. It is `nil` when redu leaves it out (the service reported no range: the
504
+ general bounds apply) and when redu sends it `null` (the service reports that the sandbox cannot be resized);
505
+ `raw.key?("resize_range")` tells the two apart. `include?(vcpus:, memory_mb:)` says whether a resize to that size is
506
+ inside it; redu answers one outside it `400 resize_out_of_range`.
507
+
508
+ ### Fork
509
+
510
+ ```ruby
511
+ copy = redu.sandboxes.fork(sandbox.id, name: "try-b", timeout_s: 1800)
512
+ puts "#{copy.id} forked from #{copy.forked_from}"
513
+ redu.sandboxes.delete(copy.id)
514
+ ```
515
+
516
+ A fork is a NEW sandbox, a running copy of one of yours as it is now (running or paused): its files, memory and
517
+ running programs, at its template and size, public when it is (with no public names yet), with its egress rules. Its
518
+ `timeout_s` (60 up to `limits.max_lifetime_s`, default 3600; never 0: extend the copy for no end), `max_spend` and
519
+ `env` are its own: the original's cap and environment are not copied. Its `idle_pause_s:` is the one given, else the
520
+ original's.
521
+ Programs keep running in the copy, so anything they do outside now happens twice, and connections open at the moment
522
+ of the copy are cut in the copy. `409 fork_not_now`: a command or a file transfer runs in it, fork between commands.
523
+ `409 fork_unsupported`, `409 sandbox_not_running`, `503 fork_no_room` (a copy starts on its original's server, which
524
+ is full: try again in a few minutes). A 202 is waited on. The client never sends a fork twice by itself: one whose
525
+ answer was lost may still make its copy (`list` shows it, with `forked_from`), so do not fork again meanwhile.
526
+
527
+ ### Egress rules
528
+
529
+ ```ruby
530
+ policy = ReduSandbox::EgressPolicy.new(
531
+ default_action: "deny",
532
+ rules: [
533
+ ReduSandbox::EgressRule.allow(hosts: ["pypi.org", "*.pythonhosted.org"], ports: [443]),
534
+ ReduSandbox::EgressRule.allow(cidrs: ["198.51.100.0/24"])
535
+ ]
536
+ )
537
+ locked = redu.sandboxes.create("ubuntu-node", egress: policy)
538
+ puts "#{locked.egress.default_action} #{locked.egress.rules.length} rules" # deny 2 rules
539
+ ```
540
+
541
+ What a sandbox may connect out to is set at its create, and every read shows it as `egress` (a `SandboxEgress`:
542
+ `default_action`, `rules`, `updated_at`). Rules are tried in order and the first match decides; `default_action`
543
+ decides the rest. A rule matches `hosts` (exact names, or `*.example.com` for every name under it, matched against the
544
+ name a TLS or HTTP connection carries) or `cidrs` (IPv4 networks), not both, with `ports` (443, or a range
545
+ `"8000-8999"`) or without, or `ports` alone. Without `egress:` everything is allowed. A fork keeps its original's
546
+ rules. `egress:` also takes a Hash of the same JSON shape, sent as it is. The client checks only the types; redu
547
+ checks the rest (at most 32 rules, 256 names, 128 networks and 32 ports a rule) and answers `400 validation_error`
548
+ with the field's path in `details`.
549
+
550
+ ```ruby
551
+ change = redu.sandboxes.change_egress(locked.id, ReduSandbox::EgressPolicy.new(
552
+ default_action: "deny",
553
+ rules: [ReduSandbox::EgressRule.allow(hosts: ["pypi.org", "*.pythonhosted.org", "registry.npmjs.org"], ports: [443])]
554
+ ))
555
+ puts "#{change.egress.rules[0].hosts.length} hosts, #{change.connections_closed} connections closed"
556
+ ```
557
+
558
+ `change_egress` replaces a running or paused sandbox's rules, live: nothing restarts, and the open connections the new
559
+ rules refuse are closed. It takes what a create's `egress:` takes, with the same rules and limits;
560
+ `EgressPolicy.allow_all` removes every rule. It answers an `EgressChange`: `egress`, the rules now (every read shows
561
+ them from then on), and `connections_closed`. A 202 is waited on through
562
+ `GET /v1/sandboxes/requests/sandbox-egress-rules-<id>` (`wait: false` hands it back). One change of a sandbox's rules
563
+ runs at a time: `409 egress_change_busy` carries the one under way as its `workflow_id`. Sending the same rules again
564
+ is safe, but the client never sends a change twice by itself: after `502 egress_change_outcome_unknown` (it may have
565
+ been made; `get` shows the rules last confirmed) send the same rules again yourself.
566
+
567
+ `409 egress_change_unavailable` is a `ReduSandbox::EgressChangeUnavailableError` (a `ConflictError`): this platform
568
+ cannot change a running sandbox's rules yet, nothing changed, and it keeps the rules it was created with, so create a
569
+ sandbox with the rules you need. `409 egress_change_unsupported` (it started before its rules could be changed while
570
+ it runs), `egress_not_filtered`, `sandbox_suspended` (resume it first), `sandbox_changing` (a resize, a suspend or a
571
+ resume of it runs: try again in a moment), `sandbox_ending`, `sandbox_not_running`; `400 egress_rules_refused`. The
572
+ codes are `Sandboxes::EGRESS_CHANGE_CODES`.
573
+
574
+ ### Egress log
575
+
576
+ ```ruby
577
+ page = redu.sandboxes.egress_log(locked.id, limit: 100)
578
+ page.events.each { |e| puts "#{e.seq} #{e.type} #{e.host || e.address}:#{e.port}" }
579
+ since = redu.sandboxes.each_egress_event(locked.id, since: page.next_since) do |e|
580
+ puts "rule #{e.rule} denied connection #{e.connect_seq}" if e.type == "denied"
581
+ end
582
+ puts "read again later from #{since}"
583
+ redu.sandboxes.delete(locked.id)
584
+ ```
585
+
586
+ The sandbox's outbound connections, oldest first, one `EgressEvent` each: `connect` (`host`, `claimed_host`,
587
+ `address`, `requested_address`, `port`, `protocol`), `denied` (`connect_seq`, `rule`: the rule's number from 1, or
588
+ `"default"`), `closed` (`connect_seq`, `bytes_out`, `bytes_in`, `duration_ms`), `failed` (`connect_seq`) and
589
+ `refused` (`reason`: `too_many_open`, `too_fast` or `local_address`, with `counts`), each with `seq` and `at`.
590
+ `egress_log` reads one page after `since` (0, or the last page's `next_since`), at most `limit` events (1 to 500,
591
+ redu's default 200). `each_egress_event` follows `next_since` page after page while redu says `more` (a page can
592
+ come back empty with `more` true when the records it scanned held no connection: it reads on), ends at a page with
593
+ `more` false, and returns the `since` to read from next time. It never loops: a page whose `next_since` does not move
594
+ past its `since`, with events or with `more`, raises `unexpected_answer` rather than being read again. Host names are
595
+ what a program in the sandbox sent: shown, never trusted.
596
+
597
+ ### Audit log
598
+
599
+ ```ruby
600
+ chain = ReduSandbox::AuditChain.new
601
+ commands = 0
602
+ redu.sandboxes.each_audit_event(big.id) do |event|
603
+ chain.add(event) # raises ReduSandbox::AuditChainError where the chain breaks
604
+ commands += 1 if event.kind == "exec.request"
605
+ end
606
+ puts "#{chain.checked} records checked, #{chain.withheld} withheld, #{commands} commands"
607
+ redu.sandboxes.delete(big.id)
608
+ ```
609
+
610
+ The sandbox's own event log, oldest first: each command sent to it through the API (`exec.request`, `exec.result`,
611
+ `exec.kill`), each file read or write through the API (`file.read`, `file.write`), its outbound connections
612
+ (`egress.connect`, `egress.close`, ...), the programs started and ended inside it as it reports them (`proc.exec`,
613
+ `proc.exit`), the rule decisions that refuse something (`rule.deny`), and the machine's own life (`sandbox.claim`,
614
+ `vm.paused`, `vm.resumed`, ...); never a command's env, its output or a file's content. Each `AuditEvent` is a record
615
+ exactly as the sandbox service wrote it: `seq`, `t_ns` and `mono_ns` (whole numbers past 2**53, exact), `sandbox_id`,
616
+ `source`, `kind`, `trust`, `data`, `prev` and `h`, with `raw` (the whole record) and `text` (its own JSON text). trust
617
+ `"host"` is written by the host from what it saw; `"guest"` is reported from inside the sandbox, which a program with
618
+ root there can stop or forge. A record redu cannot answer whole comes `withheld` in its place (`"platform_detail"`,
619
+ `"too_large"` or `"not_json"`), with its `seq`, `at`, `kind`, `source`, `trust`, `prev`, `h` and `bytes`.
620
+
621
+ `ReduSandbox::AuditChain` checks the hash chain exactly as redu describes it: `seq` counts 1, 2, 3 without gaps, `prev`
622
+ is the `h` of the record before (64 zeros for seq 1), and `h` is the SHA-256 of the record without its `h`, written as
623
+ Python's `json.dumps(record, sort_keys=True, separators=(",", ":"))` writes it. `add` raises
624
+ `ReduSandbox::AuditChainError` (with `seq` and `reason`: `:seq`, `:prev`, `:hash` or `:unreadable`) at the first
625
+ break; a withheld record's own `h` cannot be checked, the order across it can. `AuditChain.verify(events)` checks a
626
+ list, `AuditChain.new(seq:, h:)` goes on from a record checked before, and `AuditChain.digest(text)` is the `h` of one
627
+ record's text. Read from `since: 0` to check from the first record. `kind:` (an event kind or a family of kinds such as
628
+ `"exec"`, `"file.write"` or `"vm"`, or up to 10 of them as an Array) leaves the other kinds out, so a page read with it
629
+ is checked record by record with `AuditChain.verify_each`. The chain has no key or signature: it shows a record changed
630
+ or removed in the middle, not a log cut at its end or replaced as a whole.
631
+
632
+ `audit_log` reads one page (`limit` 1 to 500, redu's default 200); `each_audit_event` follows `next_since` as
633
+ `each_egress_event` does, and never loops. At most 2 reads of your account's logs run at once: `429 too_many_log_reads`
634
+ is asked again after its Retry-After, as a 202 is. `502 event_log_unreadable`: the log cannot be read past that since.
635
+ The log is read only while the sandbox exists.
636
+
637
+ ### Lifecycle
638
+
639
+ What puts a sandbox to sleep and what ends it, in one place: its idle pause, its end, and its spend against its cap.
640
+
641
+ ```ruby
642
+ l = redu.sandboxes.get_lifecycle(sandbox.id)
643
+ puts "#{l.idle_pause_s.inspect} #{l.expires_at} #{l.max_expires_at} GBP #{l.spend} of #{l.max_spend.inspect}"
644
+ after = redu.sandboxes.set_lifecycle(sandbox.id, idle_pause_s: 300, max_spend: 5, timeout_s: 7200)
645
+ puts "idle pause #{after.changed.idle_pause_s.to}, cap #{after.changed.max_spend.to}" # idle pause 300, cap 5
646
+ redu.sandboxes.set_lifecycle(sandbox.id, max_spend: nil) # nil removes the cap; left out, the cap stays
647
+ ```
648
+
649
+ `idle_pause_s` (0 to 86400 seconds; 0 never pauses it) also goes in a create or a fork: the sandbox is paused after
650
+ that long without activity (no command, file transfer or connection), billed for its memory only, and resumes on its
651
+ next command. In `set_lifecycle` a field left out stays as it is: `timeout_s:` works as `extend_lifetime` does (never
652
+ shorter; 60 up to `limits.max_lifetime_s`, never 0), `max_spend:` must be above what it has cost so far
653
+ (`409 max_spend_below_spend`) and `max_spend: nil` removes the cap, and `idle_pause_s:` sets a new idle pause
654
+ (`409 idle_pause_not_changeable` where the platform cannot yet). It answers a `LifecycleChanged`: the lifecycle after
655
+ the change and `changed`, a `LifecycleChanges` whose `idle_pause_s`, `max_spend` (each a `ValueChange`: `from`, `to`)
656
+ and `expires_at` (an `ExpiresAtChange`: `from`, `to`, `capped`, `extended`) are set for what it changed. A 202 is
657
+ waited on through `GET /v1/sandboxes/requests/sandbox-lifecycle-<id>` (`wait: false` hands it back). One change of a
658
+ sandbox's lifecycle runs at a time (`409 lifecycle_busy`, with the change under way as its `workflow_id`). Sending the
659
+ same change again is safe, but the client never sends it twice by itself. `502 idle_pause_outcome_unknown` is a
660
+ `ReduSandbox::IdlePauseOutcomeUnknownError`; a change that failed after its idle pause or its cap was applied says so
661
+ in the error's `details["applied"]`. `503 usage_not_current`: try again in a few minutes. The codes are
662
+ `Sandboxes::LIFECYCLE_CODES`.
663
+
664
+ ### Limits and ended sandboxes
665
+
666
+ ```ruby
667
+ limits = redu.sandboxes.limits
668
+ puts "#{limits.available.vcpus} vCPUs left, #{limits.used.sandboxes} sandboxes counted"
669
+ redu.sandboxes.each_ended(limit: 20) { |s| puts "#{s.id} #{s.end_reason} GBP #{s.spend}" }
670
+ page = redu.sandboxes.list_ended(limit: 20) # one page; page.next_cursor asks for the next, nil on the last
671
+ puts redu.sandboxes.get_ended(page.sandboxes.first.id).ended_at unless page.sandboxes.empty?
672
+ ```
673
+
674
+ `limits` answers the account's sandbox limits (`limits`), what counts against them now (`used`) and what is left
675
+ (`available`), each with `sandboxes`, `vcpus`, `memory_mb` and `disk_gb`; the counted sandboxes `by_status`; its
676
+ `snapshots` (`limit`, `used`); and `counted` and `how_to_raise` (redu's `raise`), in redu's words. A sandbox asleep
677
+ still counts. `max_lifetime_s` and `no_end` say how long your sandboxes may live (see "Lifetime"), and
678
+ `free_sandbox` (a `FreeSandbox`) shows your free sandbox (see "The free sandbox"); each of the three is `nil` when redu
679
+ does not answer it. A `FreeSandbox` has `available` (when false, `reason` says why: a `FreeSandboxReason` with `code`,
680
+ `message` and `hint`), `size`, `hours_per_month`, `hours_used`, `hours_left`, `month`, `resets_at`, `sandbox_id` (the
681
+ live one, or nil), `counted`, `at_limit` and `max_lifetime_s` (its own longest life, 30 days), each `nil` when redu
682
+ does not say it.
683
+
684
+ Ended sandboxes are the ones that ended in the last 7 days, newest end first, from redu's own record (`EndedSandbox`:
685
+ `ended_at`, `end_reason` (`deleted`, `expired`, `max_spend`, `key_spend_cap`, `lost` for a sandbox with no end that a
686
+ hardware failure ended, or nil: `ReduSandbox::END_REASONS`), `spend`, `max_spend`, `readable_until`, and its size).
687
+ `list_ended` reads one page (`limit` 1 to 100, `Sandboxes::ENDED_PAGE_MAX_LIMIT`; redu's default 50) after `cursor`;
688
+ `each_ended` follows `next_cursor` to the last page. `get_ended(id)` reads one (`404 sandbox_not_found` otherwise,
689
+ also for a sandbox that is still live).
690
+
691
+ ### Templates from container images
692
+
693
+ ```ruby
694
+ build = redu.sandboxes.build_template(name: "my-python", image: "python:3.12", memory_mb: 2048)
695
+ until build.ended?
696
+ sleep 15
697
+ build = redu.sandboxes.get_template_build(build.id) # with its log
698
+ end
699
+ if build.status == "done"
700
+ mine = redu.sandboxes.create(build.template_id)
701
+ puts "#{mine.template} #{mine.memory_mb} MB" # my-python 2048 MB
702
+ redu.sandboxes.delete(mine.id)
703
+ redu.sandboxes.delete_template(build.template_id)
704
+ end
705
+ ```
706
+
707
+ A build is accepted (`queued`) and then goes on by itself, through `pulling`, `unpacking`, `building`, `uploading`
708
+ and `registering`, to `done` (with its `template_id`) or `failed` (with its `error`). `image:` is
709
+ `[registry/]repository[:tag][@sha256:digest]`, Docker Hub when no registry is named. `registry_auth:` (a
710
+ `ReduSandbox::RegistryAuth`, or a Hash with `username` and `password`) is for a private image: it is used for that one
711
+ build, kept nowhere by redu, never echoed by this client, and left out of `inspect`. One build runs at a time per
712
+ account (`409 template_build_in_progress`), so a repeat never starts two; the client never repeats one by itself.
713
+ `409 template_name_taken`, `template_limit_reached`, `template_builds_unavailable`; `429 template_build_rate_limited`
714
+ (builds of the last 24 hours count; never sent again by the client); `400 template_build_refused`. A 202 is waited on
715
+ through `GET /v1/sandboxes/requests/sandbox-template-build-<uuid>`.
716
+
717
+ A built template is billed as stored data, as a snapshot is (`price`, a `SnapshotPrice`), from when its build is done
718
+ until `delete_template` deletes it (`409 template_in_use` while snapshots need it: the error's `details["snapshots"]`
719
+ names them). `cancel_template_build(build.id)` answers a `TemplateBuildCancel`: `cancelling` (a running build stops at
720
+ its next step, then reads failed), `finishing` (it is registering its template: too late to stop), `forgotten` (one
721
+ that ended is no longer listed; its template stays) or `pending` (no answer in time: cancel it again). The codes are
722
+ `Sandboxes::TEMPLATE_BUILD_CODES`.
723
+
724
+ ### Secrets
725
+
726
+ ```ruby
727
+ keyed = redu.sandboxes.create("ubuntu-node", secrets: [
728
+ ReduSandbox::SecretInput.new(name: "OPENAI_API_KEY", value: ENV.fetch("OPENAI_API_KEY"), hosts: ["api.openai.com"])
729
+ ])
730
+ puts keyed.secrets.map { |s| "#{s.name} for #{s.hosts.join(", ")}" } # OPENAI_API_KEY for api.openai.com
731
+ redu.sandboxes.set_secrets(keyed.id, []) # replaces them all, values included; [] removes them
732
+ redu.sandboxes.remove_secrets(keyed.id)
733
+ redu.sandboxes.delete(keyed.id)
734
+ ```
735
+
736
+ A secret is bound to hosts: the sandbox sees a placeholder in its env variable, and the platform puts the real value
737
+ into requests to those hosts only, so code in the sandbox never reads it. Up to 16, each a `SecretInput` or a Hash with
738
+ `name` (an env variable name, not also in `env:`), `value` (1 to 8192 printable ASCII characters) and `hosts` (1 to 16
739
+ host names, no wildcards). Answers name each secret and its hosts (`SecretView`), never its value, and this client
740
+ never echoes one, in an answer, an error or `inspect`; its own refusals name a secret by its place and name. A value is
741
+ never shown back: it lives in the sandbox's own memory, and to keep the sandbox through the platform's maintenance (an
742
+ update or a planned restart) it is written into the sandbox's saved state on the server it runs on, readable by the
743
+ platform only, and removed when the sandbox is brought back. `set_secrets` replaces the whole list, values included.
744
+ One change at a time (`409 secrets_change_busy`, with the change under way as its `workflow_id`); a 202 is waited on
745
+ through `GET /v1/sandboxes/requests/sandbox-secrets-<id>`. `409 secrets_unavailable`, `secrets_unsupported`,
746
+ `secrets_need_egress_filtering`, `sandbox_not_running`; `400 secrets_refused`; `502 secrets_failed`,
747
+ `secrets_outcome_unknown` (a `ReduSandbox::SecretsOutcomeUnknownError`: send the same list again). The codes are
748
+ `Sandboxes::SECRETS_CODES`.
749
+
750
+ ### SSH
751
+
752
+ ```ruby
753
+ public_key = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOMqqnkVzrm0SdG6UOoqKLsabgH5C9okWi0dh2l9GKJl me@laptop" # your .pub
754
+ ssh = redu.sandboxes.add_ssh_key(sandbox.id, public_key)
755
+ puts ssh.connect.ssh_config # for ~/.ssh/config
756
+ puts ssh.known_hosts # for ~/.ssh/known_hosts
757
+ once = redu.sandboxes.open_ssh(sandbox.id)
758
+ command = once.ssh # a ready ssh command for this one connection, within 60 seconds (it needs websocat)
759
+ redu.sandboxes.remove_ssh_key(sandbox.id, ssh.keys.first.fingerprint)
760
+ puts redu.sandboxes.remove_all_ssh_keys(sandbox.id).server # stopped
761
+ ```
762
+
763
+ SSH reaches any live sandbox of yours through the platform, private ones included, when its template has an SSH server
764
+ (`409 ssh_unsupported` otherwise; `409 ssh_unavailable` where the platform has none). `add_ssh_key` adds one public key
765
+ (one line of a `.pub` file) and starts the SSH server (keys only, root); `get_ssh` reads its keys (each with its
766
+ SHA256 `fingerprint`), host keys, `known_hosts` lines and `connect` (an `ssh_config` block whose ProxyCommand opens a
767
+ session for each connection, and the `ssh` command). `remove_ssh_key` removes one by its fingerprint (sent URL-encoded);
768
+ `remove_all_ssh_keys` removes every key, stops the SSH server and ends the sessions open through the platform. Adding
769
+ or removing a key needs an API key with `sandbox:ssh`; `open_ssh` needs `sandbox:ssh_connect`. A change of keys runs
770
+ one at a time (`409 ssh_keys_busy`, with the change under way as its `workflow_id`), and a 202 is waited on through
771
+ `GET /v1/sandboxes/requests/sandbox-ssh-keys-<id>` (`sandbox-ssh-revoke-<id>` for every key). `open_ssh` answers an
772
+ `SshSession` with a one-time token, opened again on a 202 as a websocket terminal is; the token is never in an error,
773
+ and `inspect` leaves it out (and the `ssh` command that carries it). `400 ssh_key_refused`,
774
+ `403 denied_by_sandbox_rules`, `409 ssh_keys_revoked`, `502 ssh_failed` and `ssh_outcome_unknown` (a
775
+ `ReduSandbox::SshOutcomeUnknownError`: `get_ssh`, then add or remove the key again). The codes are
776
+ `Sandboxes::SSH_CODES`.
777
+
778
+ ## Errors
779
+
780
+ Every refusal or failure is a `ReduSandbox::Error`:
781
+
782
+ ```ruby
783
+ sandbox_id = "00000000-0000-4000-8000-000000000000"
784
+ begin
785
+ redu.sandboxes.get(sandbox_id)
786
+ rescue ReduSandbox::Error => e
787
+ raise unless e.code == "sandbox_not_found"
788
+
789
+ puts "#{e.status} #{e.message} #{e.hint}" # 404, and redu's own sentences
790
+ end
791
+
792
+ begin
793
+ redu.sandboxes.get(sandbox_id)
794
+ rescue ReduSandbox::NotFoundError => e # the same error, rescued by its class
795
+ puts e.code
796
+ end
797
+ ```
798
+
799
+ | Field | Meaning |
800
+ |---|---|
801
+ | `status` | the HTTP status, or 0 when no answer came back |
802
+ | `code` | redu's stable code (`quota_exceeded`, `sandbox_not_public`, ...), or one of the client's own: `network_error`, `wait_timeout`, `still_pending`, `unexpected_answer` |
803
+ | `message`, `hint` | redu's sentences, unchanged |
804
+ | `details` | the rest of redu's error (a validation error's issues, a scope error's `required_scope`) |
805
+ | `retry_after_s` | from Retry-After |
806
+ | `workflow_id` | when the error is how a request ended after its 202, on `snapshot_in_progress` the take under way, on `resize_busy` the resize under way, and on `egress_change_busy`, `lifecycle_busy`, `secrets_change_busy` and `ssh_keys_busy` the change under way |
807
+ | `ran`, `idempotency_key` | on exec and start_command errors: `:yes`, `:no` or `:unknown` (see the table above) |
808
+ | `http_method`, `path` | the request it answers |
809
+
810
+ The class says what kind of answer it was: `NetworkError`, `WaitTimeoutError`, `StillPendingError`,
811
+ `UnexpectedAnswerError` (the client's own codes), then by status `BadRequestError` (400, 422), `AuthenticationError`
812
+ (401), `PaymentRequiredError` (402), `PermissionDeniedError` (403), `NotFoundError` (404), `ConflictError` (409),
813
+ `RateLimitError` (429) and `ServerError` (5xx). Seven of redu's codes have a class of their own:
814
+ `SnapshotNotTakenError` (`snapshot_not_taken`) and `SnapshotOutcomeUnknownError` (`snapshot_outcome_unknown`), each
815
+ a `ServerError` too, the two ends of a snapshot's take that must not be confused (see "Snapshots");
816
+ `IdlePauseOutcomeUnknownError`, `SecretsOutcomeUnknownError` and `SshOutcomeUnknownError` (`502
817
+ idle_pause_outcome_unknown`, `secrets_outcome_unknown`, `ssh_outcome_unknown`), each a `ServerError`: a change whose
818
+ answer was lost, which is safe to send again; and `ResizeNotAvailableError` (`409 resize_not_available`) and
819
+ `EgressChangeUnavailableError` (`409 egress_change_unavailable`), each a `ConflictError`. `e.to_h` gives the fields a log needs; an uncaught one
820
+ prints its code, status and hint. A break in an audit log's chain is not an answer of redu's: `ReduSandbox::AuditChainError` is
821
+ a `StandardError` of its own (see "Audit log").
822
+
823
+ A `429 rate_limited` is sent again by the client after its Retry-After (up to `max_rate_limit_retries`, default 2):
824
+ redu's rate limits answer before any route runs, so nothing was done.
825
+
826
+ ## Options
827
+
828
+ ```ruby
829
+ client = ReduSandbox::Client.new(
830
+ api_key: "...", # or token: ...; default REDU_API_KEY
831
+ base_url: "https://console.redu.cloud",
832
+ timeout: 120, # seconds per HTTP request; redu holds a sandbox request up to about 40 s
833
+ poll_interval: 5, # seconds between reads of a request that answered 202
834
+ max_rate_limit_retries: 2,
835
+ user_agent: "my-agent/1.0"
836
+ )
837
+ puts client.base_url
838
+ ```
839
+
840
+ A read of a request that answered 202 (`get_request`, and every wait on a 202) is held by redu for up to 10 s while
841
+ the request runs, so it answers as soon as the request ends; that read waits at least 60 s for its answer, whatever
842
+ `timeout:` says.
843
+
844
+ ## Development
845
+
846
+ ```sh
847
+ ruby -Ilib -Itest -e 'Dir["test/test_*.rb"].sort.each { |f| require File.expand_path(f) }'
848
+ ruby -Ilib -Itest test/test_features.rb # one file
849
+ ```
850
+
851
+ The tests use minitest (bundled with Ruby) and need no gems. They run against `test/fake_redu.rb`, a fake redu served on
852
+ a local `TCPServer` that answers as the redu API's sandbox routes do (the same fake as redu-sandbox-sdk-python's); when
853
+ those routes change, change the fake with them. `test/test_readme.rb` runs every Ruby block of this reference, and then the README's quick start, in order,
854
+ against the fake, so an example that stops working fails the tests. `test/test_no_dashes.rb` fails on an em dash or an
855
+ en dash in any file. `test/fixtures/audit-chain.json` holds a real audit log as the sandbox service wrote it, and JSON
856
+ texts with the hash Python's `json` module gives them, which the chain check must match. `.github/workflows/test.yml`
857
+ runs the whole suite on Ruby 3.2, 3.3 and 3.4 on every push and pull request.
858
+
859
+ To release a version: set it in `lib/redu_sandbox/version.rb`, run the tests, then `gem build redu-sandbox-sdk.gemspec`
860
+ and `gem push redu-sandbox-sdk-<version>.gem`. The gemspec lets a push go to rubygems.org only, from an account with
861
+ multi-factor authentication (`rubygems_mfa_required`).
862
+
863
+ ## License
864
+
865
+ Apache License 2.0 (`Apache-2.0`): see the [LICENSE](../LICENSE) file. Copyright 2026 REDU CLOUD LTD.