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,1154 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The shapes /v1/sandboxes answers with, as the redu API defines them (a sandbox's lifecycle, the limits, ended
4
+ # sandboxes, templates, SSH and the sessions from the API of 27 Nov 2026; a sandbox with no end and the free sandbox
5
+ # from the API of 1 Dec 2026). The limits in these comments are the server's; it checks them, this client does not
6
+ # repeat them.
7
+ #
8
+ # Each answer is an immutable Data value with the fields this version knows, plus +raw+: the whole JSON object as redu
9
+ # answered it (string keys), so a field redu adds later is never lost.
10
+ module ReduSandbox
11
+ # What every answer shares: +inspect+ leaves out raw, a terminal's password, a session's one-time token (and the
12
+ # subprotocols that carry it) and a file's bytes, so a log line never carries a secret by accident. A value with
13
+ # more to hide names it in its class's hidden_members (a secret's value, the ssh command that carries a token).
14
+ module Shape
15
+ HIDDEN = %i[raw password data text token subprotocols].freeze
16
+
17
+ def inspect
18
+ hide = self.class.respond_to?(:hidden_members) ? HIDDEN + self.class.hidden_members : HIDDEN
19
+ shown = to_h.reject { |k, _| hide.include?(k) }.map { |k, v| "#{k}=#{v.inspect}" }
20
+ "#<#{self.class.name} #{shown.join(", ")}>"
21
+ end
22
+ alias to_s inspect
23
+
24
+ def pretty_print(q)
25
+ q.text(inspect)
26
+ end
27
+ end
28
+
29
+ # Helpers that read one field of a JSON object.
30
+ module Read
31
+ module_function
32
+
33
+ def str(v)
34
+ v.is_a?(String) ? v : nil
35
+ end
36
+
37
+ def num(v)
38
+ v.is_a?(Numeric) ? v : nil
39
+ end
40
+
41
+ def int(v)
42
+ v.is_a?(Integer) ? v : nil
43
+ end
44
+
45
+ # A number the API may send with a fraction (duration_ms), as a Float.
46
+ def float(v)
47
+ v.is_a?(Numeric) ? v.to_f : nil
48
+ end
49
+
50
+ def bool(v)
51
+ v == true
52
+ end
53
+
54
+ # A boolean the API may leave out: true or false as it says, nil when it says nothing (or something else).
55
+ def opt_bool(v)
56
+ [true, false].include?(v) ? v : nil
57
+ end
58
+
59
+ def obj(v)
60
+ v.is_a?(Hash) ? v : {}
61
+ end
62
+ end
63
+
64
+ # What a template's size costs, in GBP. Needs the API version with sandbox billing; nil before it.
65
+ # cpu_per_vcpu_hour_busy:: per vCPU-hour of busy CPU time: an idle CPU costs nothing.
66
+ # memory_per_gb_hour:: per GB-hour of memory while the sandbox runs or is paused.
67
+ # idle_per_hour, busy_per_hour:: an hour with its CPU idle (memory only), and with every vCPU busy.
68
+ # storage_per_gb_month:: the storage rate, per GB-month: what a paused or suspended sandbox's memory, and a
69
+ # snapshot's size, cost.
70
+ # paused_or_suspended_per_hour, paused_or_suspended_per_month:: an hour, and a month (730 hours), paused or suspended:
71
+ # storage only, its memory at the storage rate (the month shows what the hour's rounding hides).
72
+ # The last three need the API version that prices storage; nil before it.
73
+ SandboxPrice = Data.define(:currency, :cpu_per_vcpu_hour_busy, :memory_per_gb_hour, :included_disk_gb,
74
+ :idle_per_hour, :busy_per_hour, :storage_per_gb_month, :paused_or_suspended_per_hour,
75
+ :paused_or_suspended_per_month) do
76
+ include Shape
77
+
78
+ def self.from_h(d)
79
+ new(currency: (d["currency"] || "GBP").to_s, cpu_per_vcpu_hour_busy: Read.num(d["cpu_per_vcpu_hour_busy"]),
80
+ memory_per_gb_hour: Read.num(d["memory_per_gb_hour"]), included_disk_gb: Read.num(d["included_disk_gb"]),
81
+ idle_per_hour: Read.num(d["idle_per_hour"]), busy_per_hour: Read.num(d["busy_per_hour"]),
82
+ storage_per_gb_month: Read.num(d["storage_per_gb_month"]),
83
+ paused_or_suspended_per_hour: Read.num(d["paused_or_suspended_per_hour"]),
84
+ paused_or_suspended_per_month: Read.num(d["paused_or_suspended_per_month"]))
85
+ end
86
+ end
87
+
88
+ # What a snapshot costs to keep, in GBP, from when it is taken until it is deleted.
89
+ # per_gb_month:: the storage rate: per GB-month of its size (a GB is 2**30 bytes, a month 730 hours).
90
+ # per_month:: a month of keeping it at its size; nil while its size is not known (nothing is charged for it then).
91
+ SnapshotPrice = Data.define(:currency, :per_gb_month, :per_month) do
92
+ include Shape
93
+
94
+ def self.from_h(d)
95
+ new(currency: (d["currency"] || "GBP").to_s, per_gb_month: Read.num(d["per_gb_month"]),
96
+ per_month: Read.num(d["per_month"]))
97
+ end
98
+ end
99
+
100
+ # A template: the size every sandbox made from it gets.
101
+ Template = Data.define(:id, :name, :vcpus, :memory_mb, :disk_gb, :price, :raw) do
102
+ include Shape
103
+
104
+ def self.from_h(d)
105
+ p = d["price"]
106
+ new(id: d["id"].to_s, name: d["name"].to_s, vcpus: Read.int(d["vcpus"]), memory_mb: Read.int(d["memory_mb"]),
107
+ disk_gb: Read.int(d["disk_gb"]), price: p.is_a?(Hash) ? SandboxPrice.from_h(p) : nil, raw: d)
108
+ end
109
+ end
110
+
111
+ # A public name of a sandbox: its id (for remove_public_name), the name, the port it reaches, its url.
112
+ PublicName = Data.define(:id, :domain, :port, :url) do
113
+ include Shape
114
+
115
+ def self.from_h(d)
116
+ new(id: d["id"].to_s, domain: d["domain"].to_s, port: Read.int(d["port"]) || 0, url: d["url"].to_s)
117
+ end
118
+ end
119
+
120
+ # The two actions of an egress rule and of a policy's default.
121
+ EGRESS_ACTIONS = %w[allow deny].freeze
122
+
123
+ # Structural checks of an egress rule or policy built in Ruby: the types only. What a name, a network or a port may
124
+ # be, and the limits (32 rules, 256 names, 128 networks, 32 ports a rule), are redu's to check (400 validation_error,
125
+ # with the field's path in details).
126
+ module EgressCheck
127
+ module_function
128
+
129
+ def action(value, what)
130
+ v = value.is_a?(Symbol) ? value.to_s : value
131
+ raise ArgumentError, "#{what} must be \"allow\" or \"deny\"." unless EGRESS_ACTIONS.include?(v)
132
+
133
+ v
134
+ end
135
+
136
+ def strings(value, what)
137
+ return nil if value.nil?
138
+ raise TypeError, "#{what} must be an Array of Strings." unless value.is_a?(Array) && value.all?(String)
139
+
140
+ value.dup.freeze
141
+ end
142
+
143
+ def ports(value)
144
+ return nil if value.nil?
145
+ unless value.is_a?(Array) && value.all? { |p| p.is_a?(Integer) || p.is_a?(String) }
146
+ raise TypeError, 'ports must be an Array of port numbers (443) or ranges ("8000-8999").'
147
+ end
148
+
149
+ value.dup.freeze
150
+ end
151
+ end
152
+
153
+ # One egress rule: +action+ ("allow" or "deny") for the connections it matches, by +hosts+
154
+ # (exact names such as "pypi.org", or "*.example.com" for every name under it) or by +cidrs+ (IPv4 networks such as
155
+ # "198.51.100.0/24"), not both, with +ports+ (443, or a range "8000-8999") or without; or by +ports+ alone. A host
156
+ # rule matches the name a TLS or HTTP connection carries.
157
+ #
158
+ # ReduSandbox::EgressRule.allow(hosts: ["pypi.org", "*.pythonhosted.org"], ports: [443])
159
+ # ReduSandbox::EgressRule.deny(cidrs: ["192.0.2.0/24"])
160
+ EgressRule = Data.define(:action, :hosts, :cidrs, :ports) do
161
+ include Shape
162
+
163
+ # +check+ false is for a rule read from redu, which redu has checked already.
164
+ def initialize(action:, hosts: nil, cidrs: nil, ports: nil, check: true)
165
+ if check
166
+ super(action: EgressCheck.action(action, "A rule's action"), hosts: EgressCheck.strings(hosts, "hosts"),
167
+ cidrs: EgressCheck.strings(cidrs, "cidrs"), ports: EgressCheck.ports(ports))
168
+ else
169
+ super(action: action.to_s, hosts: hosts, cidrs: cidrs, ports: ports)
170
+ end
171
+ end
172
+
173
+ def self.allow(hosts: nil, cidrs: nil, ports: nil)
174
+ new(action: "allow", hosts: hosts, cidrs: cidrs, ports: ports)
175
+ end
176
+
177
+ def self.deny(hosts: nil, cidrs: nil, ports: nil)
178
+ new(action: "deny", hosts: hosts, cidrs: cidrs, ports: ports)
179
+ end
180
+
181
+ def self.from_h(d)
182
+ list = ->(v) { v.is_a?(Array) ? v.select { |x| x.is_a?(String) }.freeze : nil }
183
+ ports = d["ports"].is_a?(Array) ? d["ports"].select { |x| x.is_a?(Integer) || x.is_a?(String) }.freeze : nil
184
+ new(action: d["action"].to_s, hosts: list.call(d["hosts"]), cidrs: list.call(d["cidrs"]), ports: ports, check: false)
185
+ end
186
+
187
+ # The rule as POST /v1/sandboxes takes it: only the fields given.
188
+ def as_json
189
+ out = { "action" => action }
190
+ out["hosts"] = hosts unless hosts.nil?
191
+ out["cidrs"] = cidrs unless cidrs.nil?
192
+ out["ports"] = ports unless ports.nil?
193
+ out
194
+ end
195
+
196
+ def to_json(*args)
197
+ as_json.to_json(*args)
198
+ end
199
+ end
200
+
201
+ # What a sandbox may connect out to, given at its create (create(..., egress:)): its +rules+,
202
+ # tried in order, the first match deciding, and +default_action+ for a connection no rule matches. A create without
203
+ # one allows everything. +rules+ holds EgressRule values, or Hashes with the same keys.
204
+ #
205
+ # ReduSandbox::EgressPolicy.new(default_action: "deny", rules: [ReduSandbox::EgressRule.allow(hosts: ["pypi.org"])])
206
+ EgressPolicy = Data.define(:default_action, :rules) do
207
+ include Shape
208
+
209
+ def initialize(default_action:, rules: [])
210
+ raise TypeError, "rules must be an Array of ReduSandbox::EgressRule (or Hashes with the same keys)." unless rules.is_a?(Array)
211
+
212
+ list = rules.map do |r|
213
+ next r if r.is_a?(EgressRule)
214
+ raise TypeError, "rules must be an Array of ReduSandbox::EgressRule (or Hashes with the same keys)." unless r.is_a?(Hash)
215
+
216
+ # an unknown key (a typo) raises ArgumentError here rather than being dropped
217
+ EgressRule.new(**r.transform_keys(&:to_sym))
218
+ end
219
+ super(default_action: EgressCheck.action(default_action, "default_action"), rules: list.freeze)
220
+ end
221
+
222
+ # Everything allowed: what a sandbox created without egress rules gets.
223
+ def self.allow_all
224
+ new(default_action: "allow")
225
+ end
226
+
227
+ # The policy as POST /v1/sandboxes takes it ("egress").
228
+ def as_json
229
+ { "default_action" => default_action, "rules" => rules.map(&:as_json) }
230
+ end
231
+
232
+ def to_json(*args)
233
+ as_json.to_json(*args)
234
+ end
235
+ end
236
+
237
+ # A sandbox's egress rules as every read answers them: its policy, and +updated_at+, when
238
+ # it was set, or nil for a sandbox created without rules (default_action "allow", no rules: everything is allowed).
239
+ SandboxEgress = Data.define(:default_action, :rules, :updated_at, :raw) do
240
+ include Shape
241
+
242
+ def self.from_h(d)
243
+ rules = d["rules"].is_a?(Array) ? d["rules"].select { |r| r.is_a?(Hash) }.map { |r| EgressRule.from_h(r) } : []
244
+ new(default_action: d["default_action"].to_s, rules: rules.freeze, updated_at: Read.str(d["updated_at"]), raw: d)
245
+ end
246
+
247
+ # The same rules as an EgressPolicy, for the create of another sandbox.
248
+ def to_policy
249
+ EgressPolicy.new(default_action: default_action, rules: rules)
250
+ end
251
+
252
+ def allow_all?
253
+ default_action == "allow" && rules.empty?
254
+ end
255
+ end
256
+
257
+ # The answer of a change of a sandbox's egress rules (change_egress): the sandbox's
258
+ # +id+, its rules now, a SandboxEgress (as every read shows them from then on), and +connections_closed+, how many of
259
+ # its open connections the new rules closed (nil when the sandbox service did not say).
260
+ EgressChange = Data.define(:id, :egress, :connections_closed, :raw) do
261
+ include Shape
262
+
263
+ def self.from_h(d)
264
+ new(id: d["id"].to_s, egress: SandboxEgress.from_h(Read.obj(d["egress"])),
265
+ connections_closed: Read.int(d["connections_closed"]), raw: d)
266
+ end
267
+ end
268
+
269
+ # The most volumes a create attaches. redu checks it.
270
+ VOLUMES_MAX = 2
271
+
272
+ # A volume of yours to attach and mount at a create (create(..., volumes:)): +id+
273
+ # (from GET /v1/volumes/list), +mount_path+ (an absolute path; nil for redu's default, /mnt/volumes/<id>) and
274
+ # +format+ (nil or true: a volume with no filesystem, partition table or other signature is formatted, so a blank
275
+ # one, and one written raw, loses its data; false: such a volume fails the create instead). A volume with a signature
276
+ # is mounted as it is.
277
+ #
278
+ # ReduSandbox::VolumeMount.new(id: volume_id, mount_path: "/work")
279
+ VolumeMount = Data.define(:id, :mount_path, :format) do
280
+ include Shape
281
+
282
+ def initialize(id:, mount_path: nil, format: nil)
283
+ raise ArgumentError, "A volume's id must be a volume's id (GET /v1/volumes/list)." unless id.is_a?(String) && !id.empty?
284
+ raise TypeError, "mount_path must be a String (an absolute path), or nil for the default." unless mount_path.nil? || mount_path.is_a?(String)
285
+ raise TypeError, "format must be true, false or nil." unless [nil, true, false].include?(format)
286
+
287
+ super
288
+ end
289
+
290
+ # The volume as POST /v1/sandboxes takes it (one of "volumes"): only the fields given.
291
+ def as_json
292
+ { "id" => id, "mount_path" => mount_path, "format" => format }.compact
293
+ end
294
+
295
+ def to_json(*args)
296
+ as_json.to_json(*args)
297
+ end
298
+ end
299
+
300
+ # A volume attached to a sandbox, as every read shows it: +volume_id+, +mount_path+ (nil when
301
+ # the sandbox service does not say) and +status+ ("attaching", "attached", "detaching" or "error").
302
+ SandboxVolume = Data.define(:volume_id, :mount_path, :status) do
303
+ include Shape
304
+
305
+ def self.from_h(d)
306
+ new(volume_id: d["volume_id"].to_s, mount_path: Read.str(d["mount_path"]), status: d["status"].to_s)
307
+ end
308
+ end
309
+
310
+ # The sizes a resize of one sandbox may ask, as the sandbox service reports them: vCPUs
311
+ # from +min_vcpus+ to +max_vcpus+, memory from +min_memory_mb+ to +max_memory_mb+ in steps of +memory_step_mb+ from
312
+ # +min_memory_mb+. Set by the size it was created at, and fixed while it lives.
313
+ SandboxResizeRange = Data.define(:min_vcpus, :max_vcpus, :min_memory_mb, :max_memory_mb, :memory_step_mb) do
314
+ include Shape
315
+
316
+ # nil unless every field is a whole number (redu sends the range whole, or not at all).
317
+ def self.from_h(d)
318
+ v = members.to_h { |k| [k, Read.int(d[k.to_s])] }
319
+ v.values.any?(&:nil?) ? nil : new(**v)
320
+ end
321
+
322
+ # True when a resize to +vcpus+ and +memory_mb+ (either nil: not asked) is inside this range.
323
+ def include?(vcpus: nil, memory_mb: nil)
324
+ ok_v = vcpus.nil? || (vcpus.is_a?(Integer) && vcpus.between?(min_vcpus, max_vcpus))
325
+ ok_m = memory_mb.nil? || (memory_mb.is_a?(Integer) && memory_mb.between?(min_memory_mb, max_memory_mb) &&
326
+ ((memory_mb - min_memory_mb) % memory_step_mb).zero?)
327
+ ok_v && ok_m
328
+ end
329
+ end
330
+
331
+ # The memory sizes a create or a template build may ask, in MiB: 1024 is the smallest.
332
+ # redu checks it.
333
+ MEMORY_MB = [1024, 2048, 4096, 8192].freeze
334
+
335
+ # The shape of a secret's name (an env variable name): what a refusal of the client may repeat to name a secret.
336
+ SECRET_NAME = /\A[A-Z_][A-Z0-9_]{0,63}\z/
337
+
338
+ # One secret bound to hosts (create(..., secrets:) and set_secrets): +name+, the env
339
+ # variable it is placed in (capitals, digits and _, not starting with a digit, at most 64); +value+, 1 to 8192
340
+ # printable ASCII characters; +hosts+, 1 to 16 host names it may be sent to (such as "api.anthropic.com": no
341
+ # wildcards, no addresses). The sandbox sees a placeholder in that variable, and the platform puts the real value
342
+ # into requests to those hosts only, so code in the sandbox never reads it. A value is never shown back: it lives in
343
+ # the sandbox's own memory, and to keep the sandbox through the platform's maintenance (an update or a planned
344
+ # restart) it is written into the sandbox's saved state on the server it runs on, readable by the platform only, and
345
+ # removed when the sandbox is brought back. The client checks the types only; redu checks the rest (400
346
+ # validation_error), and its refusals never repeat a value.
347
+ #
348
+ # +inspect+ leaves the value out, and this client never puts it in an error.
349
+ #
350
+ # ReduSandbox::SecretInput.new(name: "OPENAI_API_KEY", value: ENV.fetch("OPENAI_API_KEY"), hosts: ["api.openai.com"])
351
+ SecretInput = Data.define(:name, :value, :hosts) do
352
+ include Shape
353
+
354
+ def self.hidden_members
355
+ %i[value]
356
+ end
357
+
358
+ def initialize(name:, value:, hosts:)
359
+ raise TypeError, "A secret's name must be a String (an env variable name)." unless name.is_a?(String)
360
+ raise TypeError, "A secret's value must be a String." unless value.is_a?(String)
361
+ unless hosts.is_a?(Array) && hosts.all?(String)
362
+ raise TypeError, 'A secret\'s hosts must be an Array of host names, such as ["api.example.com"].'
363
+ end
364
+
365
+ super(name: name, value: value, hosts: hosts.dup.freeze)
366
+ end
367
+
368
+ # The secret as the API takes it.
369
+ def as_json
370
+ { "name" => name, "value" => value, "hosts" => hosts }
371
+ end
372
+ end
373
+
374
+ # A secret as redu shows it (every read of a sandbox, set_secrets): its name and the hosts it may be sent to, never
375
+ # its value.
376
+ SecretView = Data.define(:name, :hosts) do
377
+ include Shape
378
+
379
+ def self.from_h(d)
380
+ hosts = d["hosts"].is_a?(Array) ? d["hosts"].select { |h| h.is_a?(String) }.freeze : [].freeze
381
+ new(name: d["name"].to_s, hosts: hosts)
382
+ end
383
+ end
384
+
385
+ SANDBOX_MEMBERS = %i[id name template status created_at expires_at ip_address public public_address dns spend
386
+ max_spend spend_updated_at max_expires_at from_snapshot forked_from egress vcpus memory_mb
387
+ disk_gb network_id volumes resize_range idle_pause_s secrets raw].freeze
388
+
389
+ def self.secret_views(list)
390
+ list.is_a?(Array) ? list.select { |x| x.is_a?(Hash) }.map { |x| SecretView.from_h(x) }.freeze : [].freeze
391
+ end
392
+
393
+ def self.sandbox_fields(d)
394
+ dns = d["dns"]
395
+ {
396
+ id: d["id"].to_s, name: Read.str(d["name"]), template: d["template"].to_s, status: d["status"].to_s,
397
+ created_at: Read.str(d["created_at"]), expires_at: Read.str(d["expires_at"]), ip_address: Read.str(d["ip_address"]),
398
+ public: d["public"] == true, public_address: Read.str(d["public_address"]),
399
+ dns: dns.is_a?(Array) ? dns.select { |n| n.is_a?(Hash) }.map { |n| PublicName.from_h(n) } : [],
400
+ spend: Read.num(d["spend"]), max_spend: Read.num(d["max_spend"]), spend_updated_at: Read.str(d["spend_updated_at"]),
401
+ max_expires_at: Read.str(d["max_expires_at"]), from_snapshot: Read.str(d["from_snapshot"]),
402
+ forked_from: Read.str(d["forked_from"]), egress: d["egress"].is_a?(Hash) ? SandboxEgress.from_h(d["egress"]) : nil,
403
+ vcpus: Read.int(d["vcpus"]), memory_mb: Read.int(d["memory_mb"]), disk_gb: Read.int(d["disk_gb"]),
404
+ network_id: Read.str(d["network_id"]),
405
+ volumes: d["volumes"].is_a?(Array) ? d["volumes"].select { |v| v.is_a?(Hash) }.map { |v| SandboxVolume.from_h(v) } : [],
406
+ resize_range: d["resize_range"].is_a?(Hash) ? SandboxResizeRange.from_h(d["resize_range"]) : nil,
407
+ idle_pause_s: Read.int(d["idle_pause_s"]), secrets: secret_views(d["secrets"]), raw: d
408
+ }
409
+ end
410
+
411
+ # A sandbox as /v1/sandboxes answers it.
412
+ # status:: "running" once it can run commands; "paused", "suspended" and others come from the sandbox service.
413
+ # public:: made with public: true: it can have public names and a web terminal.
414
+ # public_address:: the address inside redu its names forward to. Not reachable from the internet.
415
+ # spend, max_spend, spend_updated_at:: what it has cost so far and its own cap, in GBP (the API version with spend
416
+ # caps; nil before it).
417
+ # expires_at:: when it is deleted by itself unless it is extended; nil: no end (created or extended with
418
+ # timeout_s 0), it runs until it is deleted.
419
+ # max_expires_at:: the latest it can live, however often it is extended: the platform's longest life after its
420
+ # create (30 days unless raised); nil: no latest end (a sandbox with no end, or a platform with no longest life).
421
+ # An account with no card is held to 30 days whatever it says (Sandboxes#limits max_lifetime_s).
422
+ # from_snapshot:: the id of the snapshot it was created from (create(snapshot: ...)), else nil.
423
+ # forked_from:: the id of the sandbox it is a copy of (fork), else nil.
424
+ # egress:: its egress rules, a SandboxEgress (nil from an API before egress rules).
425
+ # vcpus, memory_mb, disk_gb:: its size as it is now: its template's, or what its create asked for, and a resize
426
+ # changes vcpus and memory_mb. It is the size it is billed at. nil when redu does not report it.
427
+ # network_id:: the private network it was created on (create(network_id:)), else nil.
428
+ # volumes:: the volumes attached to it (create(volumes:)), each a SandboxVolume; empty when it has none.
429
+ # resize_range:: the sizes a resize of it may ask, a SandboxResizeRange, or nil. redu leaves it out when the sandbox
430
+ # service reported no range (the general bounds apply: vCPUs 1 to 4, memory 1024 to 8192 MB), and sends it null when
431
+ # the service reports that the sandbox cannot be resized; both read nil, and raw tells them apart
432
+ # (raw.key?("resize_range")).
433
+ # idle_pause_s:: seconds without activity before it is paused by itself (create's idle_pause_s; 0 never pauses it),
434
+ # as the sandbox service reports it; nil when it reports none.
435
+ # secrets:: its secrets bound to hosts, each a SecretView (name and hosts, never a value); empty when it has none, or
436
+ # when redu says nothing of secrets (raw.key?("secrets") tells them apart).
437
+ Sandbox = Data.define(*SANDBOX_MEMBERS) do
438
+ include Shape
439
+
440
+ def self.from_h(d)
441
+ new(**ReduSandbox.sandbox_fields(d))
442
+ end
443
+
444
+ def public?
445
+ public
446
+ end
447
+ end
448
+
449
+ # The answer of an extend: the sandbox with its new expires_at, nil after an extend
450
+ # with timeout_s 0 (no end).
451
+ # previous_expires_at:: when it would have ended before this extend (nil: it had no end).
452
+ # capped:: true when the account's longest life from its create cut the ask: it ends sooner than asked.
453
+ # extended:: false when it already lived longer than asked, or already had no end, so its end did not change.
454
+ ExtendedSandbox = Data.define(*SANDBOX_MEMBERS, :previous_expires_at, :capped, :extended) do
455
+ include Shape
456
+
457
+ def self.from_h(d)
458
+ new(**ReduSandbox.sandbox_fields(d), previous_expires_at: Read.str(d["previous_expires_at"]),
459
+ capped: d["capped"] == true, extended: d["extended"] == true)
460
+ end
461
+ end
462
+
463
+ # A sandbox's vCPUs and memory: what a resize changes.
464
+ SandboxSize = Data.define(:vcpus, :memory_mb) do
465
+ include Shape
466
+
467
+ def self.from_h(d)
468
+ new(vcpus: Read.int(d["vcpus"]), memory_mb: Read.int(d["memory_mb"]))
469
+ end
470
+ end
471
+
472
+ # What a resize did: the sandbox's size before (+from+) and after (+to+).
473
+ SandboxResize = Data.define(:from, :to) do
474
+ include Shape
475
+
476
+ def self.from_h(d)
477
+ new(from: SandboxSize.from_h(Read.obj(d["from"])), to: SandboxSize.from_h(Read.obj(d["to"])))
478
+ end
479
+ end
480
+
481
+ # The answer of a resize: the sandbox at its new size, +resize+ (a SandboxResize), and
482
+ # +price+, what an hour of it costs at that size (a SandboxPrice; it is billed at its new size from then on).
483
+ ResizedSandbox = Data.define(*SANDBOX_MEMBERS, :resize, :price) do
484
+ include Shape
485
+
486
+ def self.from_h(d)
487
+ p = d["price"]
488
+ new(**ReduSandbox.sandbox_fields(d), resize: SandboxResize.from_h(Read.obj(d["resize"])),
489
+ price: p.is_a?(Hash) ? SandboxPrice.from_h(p) : nil)
490
+ end
491
+ end
492
+
493
+ # The answer of a pause, a suspend or a resume (SandboxStateResult).
494
+ #
495
+ # "paused": its CPUs stop and it keeps its memory (billed for that memory, never for CPU; it runs no commands).
496
+ # "suspended": its memory and disk are saved and its memory freed (no memory charge; its next command or a resume
497
+ # brings it back). "running": it runs again. Paused or suspended, it is still deleted at expires_at (nil: no end).
498
+ # already:: it was in that state already: nothing changed.
499
+ # from:: "disk" for a resume of a suspended sandbox, else nil.
500
+ SandboxStateResult = Data.define(:id, :action, :status, :already, :from, :expires_at, :raw) do
501
+ include Shape
502
+
503
+ def self.from_h(d)
504
+ new(id: d["id"].to_s, action: d["action"].to_s, status: d["status"].to_s, already: d["already"] == true,
505
+ from: Read.str(d["from"]), expires_at: Read.str(d["expires_at"]), raw: d)
506
+ end
507
+ end
508
+
509
+ # A snapshot of a sandbox: its files, memory and running programs at one moment,
510
+ # kept until it is deleted, also after the sandbox is gone, on the server the sandbox ran on (it is not a backup).
511
+ # name:: the name given at its take, or nil.
512
+ # template:: the template of the sandbox it was taken of; a sandbox created from it gets that template and size.
513
+ # status:: "creating", "available", "deleting" or "error". A sandbox is created only from an available one.
514
+ # size_bytes:: what it holds on its server: its memory, and the blocks of its disk that were used.
515
+ # price:: what it costs to keep, a SnapshotPrice (nil from an API before snapshots were priced).
516
+ Snapshot = Data.define(:id, :name, :sandbox_id, :template, :status, :vcpus, :memory_mb, :disk_gb, :size_bytes,
517
+ :created_at, :price, :raw) do
518
+ include Shape
519
+
520
+ def self.from_h(d)
521
+ p = d["price"]
522
+ new(id: d["id"].to_s, name: Read.str(d["name"]), sandbox_id: d["sandbox_id"].to_s, template: d["template"].to_s,
523
+ status: d["status"].to_s, vcpus: Read.int(d["vcpus"]), memory_mb: Read.int(d["memory_mb"]),
524
+ disk_gb: Read.int(d["disk_gb"]), size_bytes: Read.num(d["size_bytes"]), created_at: Read.str(d["created_at"]),
525
+ price: p.is_a?(Hash) ? SnapshotPrice.from_h(p) : nil, raw: d)
526
+ end
527
+
528
+ def available?
529
+ status == "available"
530
+ end
531
+ end
532
+
533
+ # One entry of a sandbox's connection log. Every event has +type+, +seq+ (the log's own
534
+ # counter) and +at+ (ISO time, or nil); the other fields belong to one type each and are nil on the others:
535
+ # "connect":: host (the name a TLS or HTTP connection carried, when the sandbox's name lookup knows it),
536
+ # claimed_host (a name it carried that the lookup did not know: never matched by a rule), address,
537
+ # requested_address (the address asked for, when the name sent it elsewhere), port, protocol ("tls", "http", "tcp").
538
+ # "denied":: connect_seq (the seq of its connect), rule (the number of the rule that denied it, from 1, or
539
+ # "default").
540
+ # "closed":: connect_seq, bytes_out, bytes_in, duration_ms (a Float).
541
+ # "failed":: connect_seq (the destination did not answer).
542
+ # "refused":: reason ("too_many_open", "too_fast" or "local_address": refused before any rule), counts (a Hash of
543
+ # the three), and address and port when known.
544
+ # The names are what a program in the sandbox sent: shown, never trusted.
545
+ EgressEvent = Data.define(:type, :seq, :at, :host, :claimed_host, :address, :requested_address, :port, :protocol,
546
+ :connect_seq, :rule, :bytes_out, :bytes_in, :duration_ms, :reason, :counts, :raw) do
547
+ include Shape
548
+
549
+ def self.from_h(d)
550
+ rule = d["rule"]
551
+ new(type: d["type"].to_s, seq: Read.int(d["seq"]) || 0, at: Read.str(d["at"]), host: Read.str(d["host"]),
552
+ claimed_host: Read.str(d["claimed_host"]), address: Read.str(d["address"]),
553
+ requested_address: Read.str(d["requested_address"]), port: Read.int(d["port"]), protocol: Read.str(d["protocol"]),
554
+ connect_seq: Read.int(d["connect_seq"]), rule: rule.is_a?(Integer) || rule == "default" ? rule : nil,
555
+ bytes_out: Read.num(d["bytes_out"]), bytes_in: Read.num(d["bytes_in"]), duration_ms: Read.float(d["duration_ms"]),
556
+ reason: Read.str(d["reason"]), counts: d["counts"].is_a?(Hash) ? d["counts"] : nil, raw: d)
557
+ end
558
+ end
559
+
560
+ # One page of a sandbox's connection log: its events, oldest first; +next_since+, the
561
+ # since of the next page; +more+, true when more of the log may follow next_since.
562
+ EgressLog = Data.define(:events, :next_since, :more, :raw) do
563
+ include Shape
564
+
565
+ def self.from_h(d)
566
+ events = d["events"].is_a?(Array) ? d["events"].select { |e| e.is_a?(Hash) }.map { |e| EgressEvent.from_h(e) } : []
567
+ new(events: events.freeze, next_since: Read.int(d["next_since"]) || 0, more: d["more"] == true, raw: d)
568
+ end
569
+ end
570
+
571
+ # A part of a file read from a sandbox: +data+ (binary, at most 8 MiB) starting at +offset+; +next+ is where the
572
+ # next part starts; +size+ is the file's size, or nil while the sandbox does not know it.
573
+ FileRange = Data.define(:data, :offset, :next, :size) do
574
+ include Shape
575
+ end
576
+
577
+ # The answer of a file's write: its path and how many bytes were written.
578
+ WrittenFile = Data.define(:path, :bytes, :raw) do
579
+ include Shape
580
+
581
+ def self.from_h(d)
582
+ new(path: d["path"].to_s, bytes: Read.int(d["bytes"]) || 0, raw: d)
583
+ end
584
+ end
585
+
586
+ COMMAND_MEMBERS = %i[id status cmdline pid exit_code signal error started_at ended_at duration_ms stdout_bytes
587
+ stderr_bytes raw].freeze
588
+
589
+ def self.command_fields(d)
590
+ {
591
+ id: d["id"].to_s, status: d["status"].to_s, cmdline: (d["cmdline"] || "").to_s, pid: Read.int(d["pid"]),
592
+ exit_code: Read.int(d["exit_code"]), signal: Read.int(d["signal"]), error: Read.str(d["error"]),
593
+ started_at: Read.str(d["started_at"]), ended_at: Read.str(d["ended_at"]), duration_ms: Read.float(d["duration_ms"]),
594
+ stdout_bytes: Read.int(d["stdout_bytes"]) || 0, stderr_bytes: Read.int(d["stderr_bytes"]) || 0, raw: d
595
+ }
596
+ end
597
+
598
+ # A background command: status is "running", "exited" (exit_code, or signal when a signal ended it) or "lost" (its
599
+ # connection to the sandbox ended without an exit: error says how). duration_ms is a Float (it can carry a
600
+ # fraction). stdout_bytes and stderr_bytes count what it wrote so far (the sandbox keeps the last 1 MiB of each).
601
+ Command = Data.define(*COMMAND_MEMBERS) do
602
+ include Shape
603
+
604
+ def self.from_h(d)
605
+ new(**ReduSandbox.command_fields(d))
606
+ end
607
+
608
+ def running?
609
+ status == "running"
610
+ end
611
+ end
612
+
613
+ # A command started in the background, with the Idempotency-Key it started under and how many requests it took.
614
+ StartedCommand = Data.define(*COMMAND_MEMBERS, :idempotency_key, :attempts) do
615
+ include Shape
616
+
617
+ def self.from_h(d, idempotency_key, attempts)
618
+ new(**ReduSandbox.command_fields(d), idempotency_key: idempotency_key, attempts: attempts)
619
+ end
620
+
621
+ def running?
622
+ status == "running"
623
+ end
624
+ end
625
+
626
+ # One read of a background command: its state and its output past the offsets asked for. Ask again from
627
+ # stdout_next and stderr_next; *_more says more is ready at once; *_lost counts bytes dropped before the offset asked
628
+ # for (the sandbox keeps the last 1 MiB of each stream).
629
+ CommandOutput = Data.define(:command, :stdout, :stderr, :stdout_offset, :stdout_next, :stdout_lost, :stdout_more,
630
+ :stderr_offset, :stderr_next, :stderr_lost, :stderr_more, :raw) do
631
+ include Shape
632
+
633
+ def self.from_h(d)
634
+ new(command: Command.from_h(Read.obj(d["command"])), stdout: (d["stdout"] || "").to_s,
635
+ stderr: (d["stderr"] || "").to_s,
636
+ stdout_offset: Read.int(d["stdout_offset"]) || 0, stdout_next: Read.int(d["stdout_next"]) || 0,
637
+ stdout_lost: Read.int(d["stdout_lost"]) || 0, stdout_more: d["stdout_more"] == true,
638
+ stderr_offset: Read.int(d["stderr_offset"]) || 0, stderr_next: Read.int(d["stderr_next"]) || 0,
639
+ stderr_lost: Read.int(d["stderr_lost"]) || 0, stderr_more: d["stderr_more"] == true, raw: d)
640
+ end
641
+ end
642
+
643
+ # wait_for_command's answer: the command once it has ended, and all of its output read while following it.
644
+ # stdout_lost, stderr_lost:: bytes of each stream dropped before they were read.
645
+ CommandEnd = Data.define(:command, :stdout, :stderr, :stdout_lost, :stderr_lost) do
646
+ include Shape
647
+ end
648
+
649
+ # One command's end, with the key it ran under and how many requests it took. stdout
650
+ # and stderr are cut at 64 KiB each. duration_ms is a Float. resumed: the command resumed the sandbox from suspend.
651
+ ExecResult = Data.define(:exit_code, :signal, :stdout, :stderr, :stdout_truncated, :stderr_truncated, :duration_ms,
652
+ :idempotency_key, :attempts, :resumed, :raw) do
653
+ include Shape
654
+
655
+ def self.from_h(d, idempotency_key, attempts)
656
+ new(exit_code: Read.int(d["exit_code"]), signal: Read.int(d["signal"]), stdout: (d["stdout"] || "").to_s,
657
+ stderr: (d["stderr"] || "").to_s, stdout_truncated: d["stdout_truncated"] == true,
658
+ stderr_truncated: d["stderr_truncated"] == true, duration_ms: Read.float(d["duration_ms"]),
659
+ idempotency_key: idempotency_key, attempts: attempts, resumed: d["resumed"] == true, raw: d)
660
+ end
661
+ end
662
+
663
+ # The 202 of a request with no answer within redu's wait (about 40 s). Its workflow_id is read with get_request or
664
+ # wait_for_request.
665
+ PendingRequest = Data.define(:workflow_id, :message, :raw) do
666
+ include Shape
667
+
668
+ def self.from_h(d)
669
+ new(workflow_id: d["workflow_id"].to_s, message: d["message"].to_s, raw: d)
670
+ end
671
+
672
+ def status
673
+ "pending"
674
+ end
675
+ end
676
+
677
+ # The 202 of a web terminal's open: the request's workflow id, and the terminal's username and password, which redu
678
+ # answers here and only here. The url comes with the request's end (get_request or wait_for_request). +kind+ is
679
+ # "web".
680
+ PendingTerminal = Data.define(:workflow_id, :message, :username, :password, :note, :kind, :raw) do
681
+ include Shape
682
+
683
+ def self.from_h(d)
684
+ new(workflow_id: d["workflow_id"].to_s, message: d["message"].to_s, username: d["username"].to_s,
685
+ password: d["password"].to_s, note: d["note"].to_s, kind: Read.str(d["kind"]) || "web", raw: d)
686
+ end
687
+
688
+ def status
689
+ "pending"
690
+ end
691
+ end
692
+
693
+ # A sandbox's web terminal (a root shell in the browser): open url and sign in with username and password. The
694
+ # password is answered once and kept nowhere by redu: to get a new one, open the terminal again (the old one stops
695
+ # working, the url stays). password is nil only on a Terminal read from a request's end (get_request).
696
+ # dns_id, domain, port:: the terminal's public name (the sandbox's name for port 7681).
697
+ # kind:: "web" (an answer from before the field leaves it out, and reads "web" too); a terminal over the platform's
698
+ # websocket is a TerminalSession, whose kind is "websocket".
699
+ Terminal = Data.define(:url, :username, :password, :dns_id, :domain, :port, :note, :kind, :raw) do
700
+ include Shape
701
+
702
+ def self.from_h(d, password: nil, note: nil)
703
+ pw = d["password"]
704
+ new(url: d["url"].to_s, username: d["username"].to_s, password: pw.is_a?(String) ? pw : password,
705
+ dns_id: d["dns_id"].to_s, domain: d["domain"].to_s, port: Read.int(d["port"]) || 0,
706
+ note: (d["note"] || note || "").to_s, kind: Read.str(d["kind"]) || "web", raw: d)
707
+ end
708
+
709
+ def web?
710
+ true
711
+ end
712
+
713
+ def websocket?
714
+ false
715
+ end
716
+ end
717
+
718
+ SESSION_MEMBERS = %i[id kind session_id url token protocol subprotocols expires_at idle_timeout_s note raw].freeze
719
+
720
+ def self.session_fields(d)
721
+ subs = d["subprotocols"].is_a?(Array) ? d["subprotocols"].select { |x| x.is_a?(String) }.freeze : [].freeze
722
+ { id: d["id"].to_s, kind: d["kind"].to_s, session_id: d["session_id"].to_s, url: d["url"].to_s,
723
+ token: d["token"].to_s, protocol: d["protocol"].to_s, subprotocols: subs, expires_at: Read.str(d["expires_at"]),
724
+ idle_timeout_s: Read.int(d["idle_timeout_s"]), note: Read.str(d["note"]), raw: d }
725
+ end
726
+
727
+ # A root shell in the sandbox over the platform's websocket (open_terminal): any live
728
+ # sandbox, private ones included. Open +url+ within 60 seconds, once, with a websocket client of your own, offering
729
+ # +subprotocols+ (or with +token+ as a bearer token); binary messages are the terminal's input and output.
730
+ # +idle_timeout_s+ is how long it may sit with no byte either way. +kind+ is "websocket". The token is answered once
731
+ # and opens one session: +inspect+ leaves it out (and the subprotocols, which carry it), and this client never puts
732
+ # it in an error.
733
+ TerminalSession = Data.define(*SESSION_MEMBERS) do
734
+ include Shape
735
+
736
+ def self.from_h(d)
737
+ new(**ReduSandbox.session_fields(d))
738
+ end
739
+
740
+ def web?
741
+ false
742
+ end
743
+
744
+ def websocket?
745
+ true
746
+ end
747
+ end
748
+
749
+ # One SSH connection to a sandbox through the platform (open_ssh): a session as a
750
+ # TerminalSession is (+url+, a one-time +token+, +subprotocols+, 60 seconds, once), with +user+ ("root"),
751
+ # +host_key_alias+, the +known_hosts+ lines that pin the sandbox's host keys, and +ssh+, a ready ssh command for this
752
+ # one connection (it needs websocat). The sandbox's SSH server still asks for one of its keys (add_ssh_key). +ssh+
753
+ # carries the token, so +inspect+ leaves it out too.
754
+ SshSession = Data.define(*SESSION_MEMBERS, :user, :host_key_alias, :known_hosts, :ssh) do
755
+ include Shape
756
+
757
+ def self.hidden_members
758
+ %i[ssh]
759
+ end
760
+
761
+ def self.from_h(d)
762
+ kh = d["known_hosts"].is_a?(Array) ? d["known_hosts"].select { |x| x.is_a?(String) }.freeze : [].freeze
763
+ new(**ReduSandbox.session_fields(d), user: d["user"].to_s, host_key_alias: d["host_key_alias"].to_s,
764
+ known_hosts: kh, ssh: d["ssh"].to_s)
765
+ end
766
+ end
767
+
768
+ # What a terminal's close found. terminal is "stopped" (one was running and is
769
+ # stopped), "none" (none was running) or "not_stopped" (it may run again with its old password once the sandbox
770
+ # runs: see hint). dns_id is the public name removed, or nil.
771
+ # platform_terminals:: the terminals opened over the platform's websocket (TerminalSession): "ended" when the close
772
+ # ended them (how many in platform_terminals_ended; a token handed out before no longer opens one), "not_closed"
773
+ # when it could not (they end when their connection closes, after their idle_timeout_s, or when the sandbox is
774
+ # deleted); nil from an API from before them. platform_terminals_note says it in redu's words.
775
+ TerminalClosed = Data.define(:id, :terminal, :stopped, :dns_id, :note, :hint, :platform_terminals,
776
+ :platform_terminals_ended, :platform_terminals_note, :raw) do
777
+ include Shape
778
+
779
+ def self.from_h(d)
780
+ new(id: d["id"].to_s, terminal: d["terminal"].to_s, stopped: d["stopped"] == true,
781
+ dns_id: d["dns_id"].nil? ? nil : d["dns_id"].to_s, note: d["note"].to_s, hint: Read.str(d["hint"]),
782
+ platform_terminals: Read.str(d["platform_terminals"]),
783
+ platform_terminals_ended: Read.int(d["platform_terminals_ended"]),
784
+ platform_terminals_note: Read.str(d["platform_terminals_note"]), raw: d)
785
+ end
786
+ end
787
+
788
+ # -- a sandbox's lifecycle (GET and PUT /v1/sandboxes/:id/lifecycle) ----------------------------------------------
789
+
790
+ # An API key's monthly sandbox spend cap and what its sandboxes and snapshots have cost this month, in GBP.
791
+ KeySpendCap = Data.define(:cap, :spent) do
792
+ include Shape
793
+
794
+ def self.from_h(d)
795
+ new(cap: Read.num(d["cap"]), spent: Read.num(d["spent"]))
796
+ end
797
+ end
798
+
799
+ LIFECYCLE_MEMBERS = %i[id status idle_pause_s idle_pause_changeable created_at expires_at max_expires_at spend
800
+ max_spend spend_updated_at key_spend_cap raw].freeze
801
+
802
+ def self.lifecycle_fields(d)
803
+ k = d["key_spend_cap"]
804
+ { id: d["id"].to_s, status: d["status"].to_s, idle_pause_s: Read.int(d["idle_pause_s"]),
805
+ idle_pause_changeable: d["idle_pause_changeable"] == true, created_at: Read.str(d["created_at"]),
806
+ expires_at: Read.str(d["expires_at"]), max_expires_at: Read.str(d["max_expires_at"]),
807
+ spend: Read.num(d["spend"]) || 0, max_spend: Read.num(d["max_spend"]),
808
+ spend_updated_at: Read.str(d["spend_updated_at"]), key_spend_cap: k.is_a?(Hash) ? KeySpendCap.from_h(k) : nil,
809
+ raw: d }
810
+ end
811
+
812
+ # What puts a sandbox to sleep and what ends it, in one place (get_lifecycle).
813
+ # idle_pause_s:: seconds without activity before it is paused by itself, or nil when none was set; 0 never pauses it.
814
+ # idle_pause_changeable:: whether set_lifecycle can change its idle pause on this platform now.
815
+ # expires_at, max_expires_at:: when it is deleted by itself unless it is extended, and the latest it can live, as a
816
+ # Sandbox reads them: expires_at nil is no end, max_expires_at nil no latest end.
817
+ # spend, max_spend:: what it has cost so far and its own cap (nil: none), in GBP.
818
+ # key_spend_cap:: the monthly cap of the API key that made it (a KeySpendCap), or nil.
819
+ SandboxLifecycle = Data.define(*LIFECYCLE_MEMBERS) do
820
+ include Shape
821
+
822
+ def self.from_h(d)
823
+ new(**ReduSandbox.lifecycle_fields(d))
824
+ end
825
+ end
826
+
827
+ # A change of one value: what it was (+from+) and what it is now (+to+). A max_spend of nil is no cap; an
828
+ # idle_pause_s of nil (from) is none set.
829
+ ValueChange = Data.define(:from, :to) do
830
+ include Shape
831
+
832
+ def self.from_h(d)
833
+ new(from: d["from"], to: d["to"])
834
+ end
835
+ end
836
+
837
+ # A change of a sandbox's end: +from+ and +to+ (ISO times; nil: no end), +capped+ (the account's longest life from its
838
+ # create cut the ask) and +extended+ (false when it already lived longer than asked).
839
+ ExpiresAtChange = Data.define(:from, :to, :capped, :extended) do
840
+ include Shape
841
+
842
+ def self.from_h(d)
843
+ new(from: Read.str(d["from"]), to: Read.str(d["to"]), capped: d["capped"] == true, extended: d["extended"] == true)
844
+ end
845
+ end
846
+
847
+ # What a lifecycle change did, each part only when it changed it, else nil:
848
+ # +idle_pause_s+ and +max_spend+ (ValueChange), +expires_at+ (ExpiresAtChange). The parts it changed are also its
849
+ # Hash, read with +to_h+.
850
+ LifecycleChanges = Data.define(:idle_pause_s, :max_spend, :expires_at) do
851
+ include Shape
852
+
853
+ def self.from_h(d)
854
+ part = ->(k, type) { d[k].is_a?(Hash) ? type.from_h(d[k]) : nil }
855
+ new(idle_pause_s: part.call("idle_pause_s", ValueChange), max_spend: part.call("max_spend", ValueChange),
856
+ expires_at: part.call("expires_at", ExpiresAtChange))
857
+ end
858
+ end
859
+
860
+ # set_lifecycle's answer: the lifecycle after the change (as get_lifecycle reads it), +changed+ (a
861
+ # LifecycleChanges), and +as_recorded+: true when the change was made but the read of the sandbox just after it
862
+ # failed, so this view is the platform's record (get_lifecycle again for the live one).
863
+ LifecycleChanged = Data.define(*LIFECYCLE_MEMBERS, :changed, :as_recorded) do
864
+ include Shape
865
+
866
+ def self.from_h(d)
867
+ new(**ReduSandbox.lifecycle_fields(d), changed: LifecycleChanges.from_h(Read.obj(d["changed"])),
868
+ as_recorded: d["as_recorded"] == true)
869
+ end
870
+ end
871
+
872
+ # -- the account's limits (GET /v1/sandboxes/limits) -------------------------------------------------------------
873
+
874
+ # Sandboxes, vCPUs, memory (MiB) and disk (GB): a limit, what is used, or what is left.
875
+ SandboxResourceCounts = Data.define(:sandboxes, :vcpus, :memory_mb, :disk_gb) do
876
+ include Shape
877
+
878
+ def self.from_h(d)
879
+ new(**members.to_h { |k| [k, Read.num(d[k.to_s]) || 0] })
880
+ end
881
+ end
882
+
883
+ # The sandboxes that count against the limits, by state: starting is a sandbox being made.
884
+ SandboxStatusCounts = Data.define(:starting, :running, :paused, :suspended) do
885
+ include Shape
886
+
887
+ def self.from_h(d)
888
+ new(**members.to_h { |k| [k, Read.int(d[k.to_s]) || 0] })
889
+ end
890
+ end
891
+
892
+ # The account's snapshot limit, and how many it holds.
893
+ SnapshotCounts = Data.define(:limit, :used) do
894
+ include Shape
895
+
896
+ def self.from_h(d)
897
+ new(limit: Read.int(d["limit"]) || 0, used: Read.int(d["used"]) || 0)
898
+ end
899
+ end
900
+
901
+ # Why an account cannot have its free sandbox now, in redu's words: +code+ (such as free_sandbox_unavailable,
902
+ # trial_exhausted or account_suspended), +message+ and +hint+ (nil when redu gives none).
903
+ FreeSandboxReason = Data.define(:code, :message, :hint) do
904
+ include Shape
905
+
906
+ def self.from_h(d)
907
+ new(code: d["code"].to_s, message: d["message"].to_s, hint: Read.str(d["hint"]))
908
+ end
909
+ end
910
+
911
+ # The account's free sandbox this calendar month, as GET /v1/sandboxes/limits shows it: one sandbox of 1 vCPU and 1 GB
912
+ # of memory from a template, never charged, one at a time, with 50 hours a calendar month (UTC) of running and paused
913
+ # time. Each field is nil when redu does not say it; +raw+ keeps the whole object as redu answered it.
914
+ # available:: whether the account can have its free sandbox now (true or false); when false, +reason+ says why.
915
+ # reason:: why it cannot, a FreeSandboxReason, or nil.
916
+ # size:: its size, a SandboxSize (1 vCPU, 1024 MB).
917
+ # hours_per_month:: its hours in a calendar month (50).
918
+ # hours_used, hours_left:: the hours counted this month, and the hours left of them.
919
+ # month:: the calendar month counted (UTC), as YYYY-MM.
920
+ # resets_at:: when the hours count from 0 again: the start of the next calendar month (UTC), an ISO time.
921
+ # sandbox_id:: the id of the account's live free sandbox, or nil when it has none.
922
+ # counted, at_limit:: what counts toward the hours, and what happens when they are used, in redu's words.
923
+ # max_lifetime_s:: the longest it lives after its create, extends included, in seconds (2592000, 30 days): the free
924
+ # sandbox never has no end, whatever SandboxLimits#no_end says of the account's other sandboxes.
925
+ FreeSandbox = Data.define(:available, :reason, :size, :hours_per_month, :hours_used, :hours_left, :month,
926
+ :resets_at, :sandbox_id, :counted, :at_limit, :max_lifetime_s, :raw) do
927
+ include Shape
928
+
929
+ def self.from_h(d)
930
+ r = d["reason"]
931
+ size = d["size"]
932
+ new(available: Read.opt_bool(d["available"]), reason: r.is_a?(Hash) ? FreeSandboxReason.from_h(r) : nil,
933
+ size: size.is_a?(Hash) ? SandboxSize.from_h(size) : nil, hours_per_month: Read.num(d["hours_per_month"]),
934
+ hours_used: Read.num(d["hours_used"]), hours_left: Read.num(d["hours_left"]), month: Read.str(d["month"]),
935
+ resets_at: Read.str(d["resets_at"]), sandbox_id: Read.str(d["sandbox_id"]), counted: Read.str(d["counted"]),
936
+ at_limit: Read.str(d["at_limit"]), max_lifetime_s: Read.int(d["max_lifetime_s"]), raw: d)
937
+ end
938
+ end
939
+
940
+ # The account's sandbox limits and what counts against them now (limits): +limits+,
941
+ # +used+ and +available+ (limits less used, never below 0), each a SandboxResourceCounts; +by_status+ (a
942
+ # SandboxStatusCounts); +snapshots+ (a SnapshotCounts); +counted+, what counts against the limits, and
943
+ # +how_to_raise+ (redu's "raise"), how to have them raised, both in redu's words. Each of the last three is nil from
944
+ # an API without it:
945
+ # max_lifetime_s:: the largest timeout_s above 0 the account may give a create, a fork, an extend or a lifecycle
946
+ # change, in seconds: 2592000 (30 days) for an account with no card, up to 31536000 (365 days). While no_end is
947
+ # false it is also the longest a sandbox lives after its create, extends included.
948
+ # no_end:: true when the account may ask for a sandbox with no end (timeout_s 0 at a create or an extend): the
949
+ # platform offers it and the account has a card. It does not say that the account's billing lets a create through.
950
+ # free_sandbox:: the account's free sandbox this month, a FreeSandbox.
951
+ SandboxLimits = Data.define(:limits, :used, :available, :by_status, :snapshots, :counted, :how_to_raise,
952
+ :max_lifetime_s, :no_end, :free_sandbox, :raw) do
953
+ include Shape
954
+
955
+ def self.from_h(d)
956
+ c = ->(k) { SandboxResourceCounts.from_h(Read.obj(d[k])) }
957
+ free = d["free_sandbox"]
958
+ new(limits: c.call("limits"), used: c.call("used"), available: c.call("available"),
959
+ by_status: SandboxStatusCounts.from_h(Read.obj(d["by_status"])),
960
+ snapshots: SnapshotCounts.from_h(Read.obj(d["snapshots"])), counted: d["counted"].to_s,
961
+ how_to_raise: d["raise"].to_s, max_lifetime_s: Read.int(d["max_lifetime_s"]),
962
+ no_end: Read.opt_bool(d["no_end"]), free_sandbox: free.is_a?(Hash) ? FreeSandbox.from_h(free) : nil, raw: d)
963
+ end
964
+ end
965
+
966
+ # -- ended sandboxes (GET /v1/sandboxes?state=ended, GET /v1/sandboxes/:id?state=ended) ---------------------------
967
+
968
+ # Why a sandbox ended, as far as redu's record tells: "deleted", "expired", "max_spend",
969
+ # "key_spend_cap" or "lost" (a sandbox with no end that a hardware failure ended, then deleted by the platform); nil
970
+ # when no reason was recorded, and another string may come from a later API.
971
+ END_REASONS = %w[deleted expired max_spend key_spend_cap lost].freeze
972
+
973
+ # A sandbox that ended in the last 7 days, from redu's own record. status is "ended";
974
+ # end_reason one of END_REASONS or nil; spend what it cost in all, in GBP; readable_until, until when it can be read
975
+ # (7 days after it ended). vcpus, memory_mb and disk_gb are nil when the record has no size.
976
+ EndedSandbox = Data.define(:id, :name, :template, :status, :vcpus, :memory_mb, :disk_gb, :created_at, :ended_at,
977
+ :end_reason, :spend, :max_spend, :readable_until, :from_snapshot, :forked_from,
978
+ :network_id, :raw) do
979
+ include Shape
980
+
981
+ def self.from_h(d)
982
+ new(id: d["id"].to_s, name: Read.str(d["name"]), template: d["template"].to_s, status: d["status"].to_s,
983
+ vcpus: Read.int(d["vcpus"]), memory_mb: Read.int(d["memory_mb"]), disk_gb: Read.int(d["disk_gb"]),
984
+ created_at: Read.str(d["created_at"]), ended_at: Read.str(d["ended_at"]), end_reason: Read.str(d["end_reason"]),
985
+ spend: Read.num(d["spend"]) || 0, max_spend: Read.num(d["max_spend"]),
986
+ readable_until: Read.str(d["readable_until"]), from_snapshot: Read.str(d["from_snapshot"]),
987
+ forked_from: Read.str(d["forked_from"]), network_id: Read.str(d["network_id"]), raw: d)
988
+ end
989
+ end
990
+
991
+ # One page of ended sandboxes, newest end first: +sandboxes+ (EndedSandbox values) and +next_cursor+, which asks for
992
+ # the next page (list_ended(cursor:)), nil on the last one.
993
+ EndedSandboxPage = Data.define(:sandboxes, :next_cursor, :raw) do
994
+ include Shape
995
+
996
+ def self.from_h(d)
997
+ list = d["sandboxes"].is_a?(Array) ? d["sandboxes"].select { |s| s.is_a?(Hash) && s["id"].is_a?(String) } : []
998
+ new(sandboxes: list.map { |s| EndedSandbox.from_h(s) }.freeze, next_cursor: Read.str(d["next_cursor"]), raw: d)
999
+ end
1000
+ end
1001
+
1002
+ # -- templates built from container images ----------------------------------------------------------------------
1003
+
1004
+ # The statuses of a template build: under way (queued to registering), or ended (done or failed). Another string
1005
+ # may come from a later API.
1006
+ TEMPLATE_BUILD_STATUSES = %w[queued pulling unpacking building uploading registering done failed].freeze
1007
+
1008
+ # The credentials of a private image's registry (build_template(..., registry_auth:)): used for that one build, kept
1009
+ # nowhere by redu, and never echoed by this client. +password+ is a password, or an access token where the registry
1010
+ # takes one; +inspect+ leaves it out.
1011
+ RegistryAuth = Data.define(:username, :password) do
1012
+ include Shape
1013
+
1014
+ def initialize(username:, password:)
1015
+ raise TypeError, "registry_auth's username and password must be Strings." unless username.is_a?(String) && password.is_a?(String)
1016
+
1017
+ super
1018
+ end
1019
+
1020
+ def as_json
1021
+ { "username" => username, "password" => password }
1022
+ end
1023
+ end
1024
+
1025
+ # A template build as redu answers it.
1026
+ # status:: one of TEMPLATE_BUILD_STATUSES.
1027
+ # template_id:: the template it made, once it is done: create(template_id) makes sandboxes from it.
1028
+ # error:: why it failed, when it did.
1029
+ # size_bytes:: the size of the template it made: what it is billed for while it is kept.
1030
+ # price:: what a month of keeping its template costs, a SnapshotPrice: a built template is billed as a snapshot is.
1031
+ # log:: its log, from get_template_build only (nil elsewhere).
1032
+ TemplateBuild = Data.define(:id, :name, :image, :status, :template_id, :digest, :error, :size_bytes, :vcpus,
1033
+ :memory_mb, :disk_gb, :cancel_requested, :created_at, :started_at, :finished_at, :price,
1034
+ :log, :raw) do
1035
+ include Shape
1036
+
1037
+ def self.from_h(d)
1038
+ p = d["price"]
1039
+ new(id: d["id"].to_s, name: d["name"].to_s, image: d["image"].to_s, status: d["status"].to_s,
1040
+ template_id: Read.str(d["template_id"]), digest: Read.str(d["digest"]), error: Read.str(d["error"]),
1041
+ size_bytes: Read.num(d["size_bytes"]), vcpus: Read.int(d["vcpus"]), memory_mb: Read.int(d["memory_mb"]),
1042
+ disk_gb: Read.int(d["disk_gb"]), cancel_requested: d["cancel_requested"] == true,
1043
+ created_at: Read.str(d["created_at"]), started_at: Read.str(d["started_at"]),
1044
+ finished_at: Read.str(d["finished_at"]), price: p.is_a?(Hash) ? SnapshotPrice.from_h(p) : nil,
1045
+ log: Read.str(d["log"]), raw: d)
1046
+ end
1047
+
1048
+ # True once it is done or failed.
1049
+ def ended?
1050
+ %w[done failed].include?(status)
1051
+ end
1052
+ end
1053
+
1054
+ # What cancel_template_build did. status:: "forgotten" (a build that had ended is no longer listed; the template it
1055
+ # made stays), "cancelling" (a running build stops at its next step and then reads failed), "finishing" (too late to
1056
+ # stop: it is registering its template) or "pending" (redu had no answer within its wait: cancel it again in a
1057
+ # moment; +workflow_id+ is that request's, which /v1/sandboxes/requests does not read). message and hint are redu's.
1058
+ TemplateBuildCancel = Data.define(:id, :status, :message, :hint, :workflow_id) do
1059
+ include Shape
1060
+ end
1061
+
1062
+ # -- secrets bound to hosts ---------------------------------------------------------------------------------------
1063
+
1064
+ # set_secrets' and remove_secrets' answer: the secrets the sandbox has now, each a SecretView (names and hosts,
1065
+ # never a value).
1066
+ SandboxSecrets = Data.define(:id, :secrets, :raw) do
1067
+ include Shape
1068
+
1069
+ def self.from_h(d)
1070
+ new(id: d["id"].to_s, secrets: ReduSandbox.secret_views(d["secrets"]), raw: d)
1071
+ end
1072
+ end
1073
+
1074
+ # -- SSH ------------------------------------------------------------------------------------------------------------
1075
+
1076
+ # One authorized key of a sandbox (public data): +fingerprint+ is its SHA256 fingerprint, as ssh-keygen -lf prints
1077
+ # it, which remove_ssh_key takes.
1078
+ SshKey = Data.define(:type, :fingerprint, :comment) do
1079
+ include Shape
1080
+
1081
+ def self.from_h(d)
1082
+ new(type: d["type"].to_s, fingerprint: d["fingerprint"].to_s, comment: d["comment"].to_s)
1083
+ end
1084
+ end
1085
+
1086
+ # One host key of a sandbox's SSH server.
1087
+ SshHostKey = Data.define(:type, :fingerprint, :key) do
1088
+ include Shape
1089
+
1090
+ def self.from_h(d)
1091
+ new(type: d["type"].to_s, fingerprint: d["fingerprint"].to_s, key: d["key"].to_s)
1092
+ end
1093
+ end
1094
+
1095
+ # How to connect to a sandbox over SSH through the platform: +ssh_config+, a block for
1096
+ # ~/.ssh/config whose ProxyCommand opens a new session for each connection, and +ssh+, the command to run with it.
1097
+ SshConnect = Data.define(:user, :host_key_alias, :ssh, :ssh_config, :note) do
1098
+ include Shape
1099
+
1100
+ def self.from_h(d)
1101
+ new(user: d["user"].to_s, host_key_alias: d["host_key_alias"].to_s, ssh: d["ssh"].to_s,
1102
+ ssh_config: d["ssh_config"].to_s, note: d["note"].to_s)
1103
+ end
1104
+ end
1105
+
1106
+ # A sandbox's SSH (get_ssh, and every change of its keys): +server+ ("running" or "stopped"), its authorized +keys+
1107
+ # (SshKey), its +host_keys+ (SshHostKey) with the +known_hosts+ lines that pin them, and +connect+ (an SshConnect).
1108
+ SandboxSsh = Data.define(:id, :server, :keys, :host_keys, :known_hosts, :connect, :raw) do
1109
+ include Shape
1110
+
1111
+ def self.from_h(d)
1112
+ list = ->(k, type) { d[k].is_a?(Array) ? d[k].select { |x| x.is_a?(Hash) }.map { |x| type.from_h(x) }.freeze : [].freeze }
1113
+ kh = d["known_hosts"].is_a?(Array) ? d["known_hosts"].select { |x| x.is_a?(String) }.freeze : [].freeze
1114
+ new(id: d["id"].to_s, server: d["server"].to_s, keys: list.call("keys", SshKey),
1115
+ host_keys: list.call("host_keys", SshHostKey), known_hosts: kh,
1116
+ connect: SshConnect.from_h(Read.obj(d["connect"])), raw: d)
1117
+ end
1118
+
1119
+ def running?
1120
+ server == "running"
1121
+ end
1122
+ end
1123
+
1124
+ # One read of a request that answered 202: still running (done false), or how it ended. A request that ended in a
1125
+ # failure is raised as the ReduSandbox::Error it ended with, never returned.
1126
+ #
1127
+ # kind:: what it is, from its workflow id: :create, :delete, :add_public_name, :remove_public_name, :terminal
1128
+ # (:open_terminal or :close_terminal once it has ended), :extend, :state, :fork, :take_snapshot,
1129
+ # :delete_snapshot, :resize, :change_egress, :lifecycle, :secrets, :ssh_keys, :template_build or
1130
+ # :delete_template; nil for an id of another shape.
1131
+ # sandbox:: a create's or a fork's Sandbox, an extend's ExtendedSandbox, or a resize's ResizedSandbox.
1132
+ # name, terminal, closed, state:: a name's add, a terminal's open, a terminal's close, a pause, suspend or resume.
1133
+ # snapshot:: a snapshot's take: the Snapshot.
1134
+ # egress:: a change of egress rules: the EgressChange.
1135
+ # lifecycle:: a lifecycle change: the LifecycleChanged.
1136
+ # secrets:: a change of secrets: the SandboxSecrets (names and hosts).
1137
+ # ssh:: a change of SSH keys: the SandboxSsh.
1138
+ # build:: a template build's start: the TemplateBuild once redu accepted it (it then goes on by itself).
1139
+ RequestState = Data.define(:done, :kind, :workflow_id, :message, :sandbox, :name, :terminal, :closed, :state,
1140
+ :snapshot, :egress, :lifecycle, :secrets, :ssh, :build) do
1141
+ include Shape
1142
+
1143
+ def self.build(done:, kind:, workflow_id:, **rest)
1144
+ new(done: done, kind: kind, workflow_id: workflow_id, message: rest[:message], sandbox: rest[:sandbox],
1145
+ name: rest[:name], terminal: rest[:terminal], closed: rest[:closed], state: rest[:state],
1146
+ snapshot: rest[:snapshot], egress: rest[:egress], lifecycle: rest[:lifecycle], secrets: rest[:secrets],
1147
+ ssh: rest[:ssh], build: rest[:build])
1148
+ end
1149
+
1150
+ def done?
1151
+ done
1152
+ end
1153
+ end
1154
+ end