kosa8 0.3.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/lib/kosa8/cloud.rb CHANGED
@@ -4,47 +4,103 @@ require "json"
4
4
  require "net/http"
5
5
  require "openssl"
6
6
  require "socket"
7
+ require "securerandom"
8
+ require "time"
7
9
  require "uri"
8
10
 
9
11
  module Kosa8
10
12
  # The outcome of a cloud exec. +woke_ms+ is set when the sandbox was asleep
11
13
  # and woke for this command.
12
- CloudExecResult = Struct.new(:exit_code, :stdout, :stderr, :woke_ms, keyword_init: true) do
14
+ # +failure_class+ is "ok" (exit 0), "exit_nonzero" (the command failed) or
15
+ # "infra" (the host gave no exit code; +retryable+ true).
16
+ CloudExecResult = Struct.new(:exit_code, :stdout, :stderr, :woke_ms, :failure_class, :retryable,
17
+ keyword_init: true) do
13
18
  def ok?
14
19
  exit_code == 0 # exit_code is nil when the command never ran
15
20
  end
21
+
22
+ def retryable?
23
+ retryable == true
24
+ end
16
25
  end
17
26
 
27
+ # One page of CloudSandboxes#list_page. +next_cursor+ is nil on the last page,
28
+ # and always on a server that does not page yet (it then answers every
29
+ # sandbox in one page).
30
+ CloudSandboxPage = Struct.new(:sandboxes, :next_cursor, keyword_init: true)
31
+
32
+ # What CloudSandbox#rewind answers: the +checkpoint+ it went back to, the
33
+ # automatic +backup+ checkpoint of the sandbox as it was just before, and +ms+.
34
+ CloudRewindResult = Struct.new(:checkpoint, :backup, :ms, keyword_init: true)
35
+
18
36
  # kosa8 Cloud: the same sandboxes, run on kosa8's hosts (or your own, with
19
37
  # bring-your-own-cloud) instead of the local daemon.
20
38
  #
21
39
  # cloud = Kosa8::Cloud.new # KOSA8_API_KEY from the environment
22
- # box = cloud.sandboxes.create(template: "python")
40
+ # box = cloud.sandboxes.create(template: "python", ttl_s: 3600)
23
41
  # box.exec(["python3", "-c", "print(6 * 7)"]).stdout # => "42\n"
24
42
  # box.delete
25
43
  #
26
44
  # Authentication is an API key (k8c_live_...) made in the cloud dashboard.
27
45
  # Errors are the SDK's usual typed errors; each carries the cloud's stable
28
46
  # +code+ (for example payment_required, quota_exceeded). Standard library only.
47
+ #
48
+ # Each exec runs in a fresh container and only /workspace persists; a
49
+ # buffered exec runs at most 90 s (ExecTimeoutError), and a request
50
+ # body is at most 64 KiB.
29
51
  class Cloud
30
52
  DEFAULT_URL = "https://api.kosa8.com"
31
53
  KEY_PREFIX = "k8c_live_"
54
+ # A capability token from cloud.tokens.create works as a key too.
55
+ TOKEN_PREFIX = "k8c_tok_"
32
56
  LOCAL_HOSTS = %w[localhost 127.0.0.1 ::1].freeze
57
+ # A ttl_s is from 60 seconds to 90 days.
58
+ MIN_TTL_S = 60
59
+ MAX_TTL_S = 7_776_000
60
+ # sleep_after_s is from 0 (never) to 7 days.
61
+ MAX_SLEEP_AFTER_S = 604_800
62
+ # A fork makes from 1 to 1000 copies in one call.
63
+ MAX_FORK = 1000
64
+ # The limit kosa8 Cloud puts on a buffered exec, in seconds (504 exec_timeout past it).
65
+ EXEC_LIMIT_S = 90
66
+ EXEC_HINT = "a buffered exec is stopped after #{EXEC_LIMIT_S} s; run long work in the background, " \
67
+ "writing to /workspace, and poll it"
33
68
 
34
69
  attr_reader :base_url, :timeout, :sandboxes, :functions
35
-
36
- # transport: an optional callable (method, url, headers, body_or_nil, timeout) -> [status, body_string],
37
- # used instead of Net::HTTP (tests, proxies).
38
- def initialize(api_key: nil, base_url: nil, env: ENV, timeout: 120, transport: nil)
70
+ # The RetryPolicy applied to every request where trying again is safe.
71
+ attr_accessor :retry_policy
72
+ # How retries and polls wait: a callable taking seconds (default Kernel#sleep).
73
+ attr_accessor :sleeper
74
+ # Set by Kosa8::RL::Run while it is open: {"run_id" => id, "lease_s" => s}
75
+ # given to every create, batch, fork and grade that does not name its own.
76
+ attr_accessor :run_defaults
77
+
78
+ # transport: an optional callable (method, url, headers, body_or_nil, timeout) -> [status, body_string]
79
+ # or [status, body_string, response_headers], used instead of Net::HTTP (tests, proxies).
80
+ #
81
+ # retry_policy: (default RetryPolicy.new: 3 tries, backoff with full
82
+ # jitter) is applied where trying again is safe: reads, PUTs, deletes,
83
+ # heartbeats and drains on infra failures; the calls that make sandboxes
84
+ # (create, batch, fork, grade), which carry an Idempotency-Key reused on
85
+ # every retry; and any request answered 429, waiting at least its
86
+ # Retry-After. RetryPolicy::NONE turns it off. sleeper: replaces
87
+ # Kernel#sleep for those waits (tests).
88
+ def initialize(api_key: nil, base_url: nil, env: ENV, timeout: 120, transport: nil, retry_policy: nil,
89
+ sleeper: nil)
39
90
  key = (api_key.nil? ? env["KOSA8_API_KEY"].to_s : api_key.to_s).strip
40
91
  raise Error, "no kosa8 Cloud API key: pass api_key: or set KOSA8_API_KEY" if key.empty?
41
- raise Error, "a kosa8 Cloud API key starts with #{KEY_PREFIX}" unless key.start_with?(KEY_PREFIX)
92
+ unless key.start_with?(KEY_PREFIX) || key.start_with?(TOKEN_PREFIX)
93
+ raise Error, "a kosa8 Cloud API key starts with #{KEY_PREFIX} (a capability token with #{TOKEN_PREFIX})"
94
+ end
42
95
 
43
96
  @key = key
44
97
  base = [base_url, env["KOSA8_CLOUD_URL"]].find { |v| v && !v.to_s.empty? } || DEFAULT_URL
45
98
  @base_url = Cloud.check_base(base.to_s)
46
99
  @timeout = timeout
47
100
  @transport = transport || method(:net_http)
101
+ @retry_policy = retry_policy || RetryPolicy.new
102
+ @sleeper = sleeper || Kernel.method(:sleep)
103
+ @run_defaults = nil
48
104
  @sandboxes = CloudSandboxes.new(self)
49
105
  @functions = CloudFunctions.new(self)
50
106
  end
@@ -65,38 +121,114 @@ module Kosa8
65
121
  request("GET", "/v1/usage")
66
122
  end
67
123
 
68
- # One JSON request; raises the typed error for an error answer.
69
- def request(method, path, body = nil)
70
- headers = { "Authorization" => "Bearer #{@key}", "Accept" => "application/json" }
71
- data = nil
72
- unless body.nil?
124
+ # The templates the org can start: "key", "cpus", "mem_mb", "image", "regions", "warm".
125
+ def templates
126
+ r = request("GET", "/v1/templates")
127
+ r.is_a?(Hash) ? (r["templates"] || []) : []
128
+ end
129
+
130
+ # One JSON request, retried as retry_policy allows; raises the typed
131
+ # error for an error answer. A call that makes sandboxes (Cloud.keyed?)
132
+ # sends +idempotency_key+ (a new UUID when not given), the same on every
133
+ # retry, so it may be retried after a timeout or a 5xx too.
134
+ #
135
+ # +opts+ (a Hash, not keywords, so an empty body Hash stays the body):
136
+ # :idempotency_key and :retry_policy.
137
+ def request(method, path, body = nil, opts = nil)
138
+ opts ||= {}
139
+ perform(method, path, body, nil, false, opts[:idempotency_key], opts[:retry_policy])
140
+ end
141
+
142
+ # One request whose body is +data+ (raw bytes, application/octet-stream)
143
+ # when given; with +raw+ a successful answer's bytes come back as a binary
144
+ # String instead of parsed JSON. Raises the typed error for an error answer.
145
+ def request_bytes(method, path, data: nil, raw: false, retry_policy: nil)
146
+ perform(method, path, nil, data, raw, nil, retry_policy)
147
+ end
148
+
149
+ # Methods safe to send twice. Other POSTs are retried only on 429 (refused
150
+ # before anything was done), unless they carry an Idempotency-Key.
151
+ IDEMPOTENT_METHODS = %w[GET HEAD PUT DELETE].freeze
152
+ IDEMPOTENT_POSTS = %w[/v1/sandboxes/heartbeat /v1/sandboxes/drain].freeze
153
+ # The POSTs kosa8 Cloud keeps an Idempotency-Key for (24 hours).
154
+ KEYED_POSTS = %r{\A/v1/sandboxes(/batch|/[A-Za-z0-9_%]{1,64}/(fork|grade))?\z}.freeze
155
+ IDEMPOTENCY_KEY = /\A[\x21-\x7e]{1,255}\z/.freeze
156
+
157
+ # Whether kosa8 Cloud honours an Idempotency-Key on this call.
158
+ def self.keyed?(method, path)
159
+ method == "POST" && KEYED_POSTS.match?(path.to_s.split("?", 2)[0])
160
+ end
161
+
162
+ def self.check_idempotency_key(key)
163
+ return if key.nil? || (key.is_a?(String) && IDEMPOTENCY_KEY.match?(key))
164
+
165
+ raise ArgumentError, "idempotency_key must be 1-255 printable ASCII characters, e.g. a UUID"
166
+ end
167
+
168
+ private def perform(method, path, body, data, raw, idempotency_key, policy)
169
+ Cloud.check_idempotency_key(idempotency_key)
170
+ extra = {}
171
+ if !idempotency_key.nil? || Cloud.keyed?(method, path)
172
+ extra["Idempotency-Key"] = idempotency_key || SecureRandom.uuid
173
+ end
174
+ policy ||= @retry_policy
175
+ bare = path.to_s.split("?", 2)[0]
176
+ safe = !extra.empty? || IDEMPOTENT_METHODS.include?(method) || IDEMPOTENT_POSTS.include?(bare)
177
+ attempt = 1
178
+ loop do
179
+ begin
180
+ return perform_once(method, path, body, data, raw, extra)
181
+ rescue Error => e
182
+ raise unless policy.retry?(e, attempt) && (safe || e.status == 429)
183
+
184
+ @sleeper.call(policy.delay(e, attempt))
185
+ attempt += 1
186
+ end
187
+ end
188
+ end
189
+
190
+ private def perform_once(method, path, body, data, raw, extra)
191
+ headers = { "Authorization" => "Bearer #{@key}", "User-Agent" => "kosa8-ruby/#{VERSION}",
192
+ "Accept" => raw ? "application/octet-stream" : "application/json" }
193
+ headers.update(extra)
194
+ payload = nil
195
+ if !data.nil?
196
+ headers["Content-Type"] = "application/octet-stream"
197
+ payload = data.to_s.b
198
+ elsif !body.nil?
73
199
  headers["Content-Type"] = "application/json"
74
- data = JSON.generate(body)
200
+ payload = JSON.generate(body)
75
201
  end
76
202
  begin
77
- status, raw = @transport.call(method, @base_url + path, headers, data, @timeout)
203
+ status, content, resp_headers = @transport.call(method, @base_url + path, headers, payload, @timeout)
78
204
  rescue Net::OpenTimeout, Net::ReadTimeout, Timeout::Error => e
205
+ if Cloud.exec_path?(path)
206
+ raise ExecTimeoutError.new("kosa8 Cloud did not answer within #{@timeout} s (#{EXEC_HINT})",
207
+ method: method, path: path, code: "exec_timeout")
208
+ end
79
209
  raise TimeoutError.new("kosa8 Cloud did not answer within #{@timeout} s (#{e.message})",
80
210
  method: method, path: path)
81
211
  rescue SystemCallError, IOError, SocketError, OpenSSL::SSL::SSLError => e
82
212
  raise ConnectionError.new("could not reach kosa8 Cloud at #{@base_url}: #{e.message}",
83
213
  method: method, path: path)
84
214
  end
85
- text = raw.to_s.dup.force_encoding(Encoding::UTF_8)
215
+ return content.to_s.b if raw && status.to_i < 400
216
+
217
+ text = content.to_s.dup.force_encoding(Encoding::UTF_8)
86
218
  text = text.scrub unless text.valid_encoding?
87
219
  parsed = begin
88
220
  text.strip.empty? ? nil : JSON.parse(text)
89
221
  rescue JSON::ParserError
90
222
  text
91
223
  end
92
- raise Cloud.error(status.to_i, parsed, method, path) if status.to_i >= 400
224
+ raise Cloud.error(status.to_i, parsed, method, path, resp_headers) if status.to_i >= 400
93
225
 
94
226
  parsed
95
227
  end
96
228
 
97
229
  # The cloud answers {"error": code, "message": sentence}: the sentence is
98
230
  # the message, and the code is kept.
99
- def self.error(status, body, method, path)
231
+ def self.error(status, body, method, path, headers = nil)
100
232
  code = nil
101
233
  msg_body = body
102
234
  if body.is_a?(Hash)
@@ -104,11 +236,73 @@ module Kosa8
104
236
  m = body["message"]
105
237
  msg_body = { "error" => m.is_a?(String) && !m.empty? ? m : body["error"] }
106
238
  end
107
- e = Kosa8.error_from_response(status, msg_body, method: method, path: path, code: code)
239
+ message = (msg_body.is_a?(Hash) ? msg_body["error"] : msg_body).to_s
240
+ e = if exec_timeout?(status, code, message, path)
241
+ said = message.empty? ? nil : message
242
+ ExecTimeoutError.new("#{said || "request failed with HTTP #{status}"} (#{EXEC_HINT})",
243
+ status: status, daemon_message: said, method: method, path: path,
244
+ code: code || "exec_timeout")
245
+ else
246
+ Kosa8.error_from_response(status, msg_body, method: method, path: path, code: code)
247
+ end
108
248
  e.instance_variable_set(:@body, body)
249
+ e.retry_after = retry_after(headers)
250
+ if e.retry_after.nil? && body.is_a?(Hash)
251
+ ra = body["retry_after_s"] # e.g. 409 idempotency_in_progress, 503 no_capacity
252
+ e.retry_after = ra.to_f if ra.is_a?(Numeric) && ra.positive?
253
+ end
109
254
  e
110
255
  end
111
256
 
257
+ def self.exec_path?(path)
258
+ path.to_s.split("?", 2)[0].end_with?("/exec")
259
+ end
260
+
261
+ # 504, code exec_timeout, or today's 502 host_failed "... timed out" on /exec.
262
+ def self.exec_timeout?(status, code, message, path)
263
+ return true if status == 504 || code == "exec_timeout"
264
+
265
+ status == 502 && exec_path?(path) && message.downcase.include?("timed out")
266
+ end
267
+
268
+ # Retry-After in seconds (delta-seconds or an HTTP date), or nil.
269
+ def self.retry_after(headers, now: Time.now)
270
+ return nil unless headers.respond_to?(:each)
271
+
272
+ v = nil
273
+ headers.each { |k, val| v = val if k.to_s.casecmp("retry-after").zero? }
274
+ v = v.first if v.is_a?(Array)
275
+ return nil if v.nil?
276
+
277
+ s = v.to_s.strip
278
+ begin
279
+ Float(s)
280
+ rescue ArgumentError, TypeError
281
+ begin
282
+ [Time.httpdate(s) - now, 0.0].max
283
+ rescue ArgumentError
284
+ nil
285
+ end
286
+ end
287
+ end
288
+
289
+ # Argument checks shared by create and update; raise ArgumentError before any request.
290
+ def self.check_lifetime(ttl_s, delete_after)
291
+ raise ArgumentError, "give ttl_s or delete_after, not both" if !ttl_s.nil? && !delete_after.nil?
292
+ if !ttl_s.nil? && !(ttl_s.is_a?(Integer) && ttl_s.between?(MIN_TTL_S, MAX_TTL_S))
293
+ raise ArgumentError, "ttl_s must be a whole number of seconds from #{MIN_TTL_S} to #{MAX_TTL_S}"
294
+ end
295
+ return if delete_after.nil? || delete_after.is_a?(Integer)
296
+
297
+ raise ArgumentError, "delete_after must be a Unix time in milliseconds"
298
+ end
299
+
300
+ def self.check_sleep_after(sleep_after_s)
301
+ return if sleep_after_s.nil? || (sleep_after_s.is_a?(Integer) && sleep_after_s.between?(0, MAX_SLEEP_AFTER_S))
302
+
303
+ raise ArgumentError, "sleep_after_s must be a whole number of seconds from 0 (never) to #{MAX_SLEEP_AFTER_S}"
304
+ end
305
+
112
306
  def self.check_base(url)
113
307
  u = begin
114
308
  URI.parse(url)
@@ -142,7 +336,7 @@ module Kosa8
142
336
  req.body = body unless body.nil?
143
337
  http.start do |h|
144
338
  resp = h.request(req)
145
- [resp.code.to_i, resp.body.to_s]
339
+ [resp.code.to_i, resp.body.to_s, resp.to_hash]
146
340
  end
147
341
  end
148
342
  end
@@ -158,18 +352,74 @@ module Kosa8
158
352
  end
159
353
 
160
354
  # Start a sandbox; returns once it is running. Unset options take the org's settings.
161
- def create(template: nil, region: nil, sleep_after_s: nil)
355
+ #
356
+ # +template+ is a key from Cloud#templates (default the org's default,
357
+ # "base": Alpine, busybox sh, no bash or python) or a kosa8 Store item,
358
+ # "creator/name" or "creator/name@1.2.3". +ttl_s+ (60 s to 90 days) or
359
+ # +delete_after+ (Unix ms) deletes it automatically: set one so a crashed
360
+ # script cannot leave it running. +sleep_after_s+ is the idle time before it
361
+ # sleeps (0 never; default 300). +accept_price+ is a paid Store item's
362
+ # current price in USD, which the person agreed to. Bad arguments raise
363
+ # ArgumentError before any request.
364
+ def create(template: nil, region: nil, sleep_after_s: nil, ttl_s: nil, delete_after: nil, accept_price: nil)
365
+ Cloud.check_lifetime(ttl_s, delete_after)
366
+ Cloud.check_sleep_after(sleep_after_s)
367
+ if !accept_price.nil? && !accept_price.is_a?(Numeric)
368
+ raise ArgumentError, "accept_price must be a number (USD)"
369
+ end
370
+
162
371
  body = {}
163
372
  body["template"] = template unless template.nil?
164
373
  body["region"] = region unless region.nil?
165
374
  body["sleep_after_s"] = sleep_after_s unless sleep_after_s.nil?
375
+ body["ttl_s"] = ttl_s unless ttl_s.nil?
376
+ body["delete_after"] = delete_after unless delete_after.nil?
377
+ body["accept_price"] = accept_price unless accept_price.nil?
166
378
  CloudSandbox.new(@cloud, @cloud.request("POST", "/v1/sandboxes", body)["sandbox"])
167
379
  end
168
380
 
169
- # The org's sandboxes; with all: true, deleted ones too.
170
- def list(all: false)
171
- r = @cloud.request("GET", "/v1/sandboxes" + (all ? "?all=1" : ""))
172
- r["sandboxes"].map { |s| CloudSandbox.new(@cloud, s) }
381
+ # The org's sandboxes, newest first, as an Array; with all: true, deleted
382
+ # ones too. With +limit:+ or +cursor:+ this is one page: #list_page also
383
+ # gives the next cursor, and #each walks every page.
384
+ def list(all: false, limit: nil, cursor: nil)
385
+ list_page(all: all, limit: limit, cursor: cursor).sandboxes
386
+ end
387
+
388
+ # One page of sandboxes (a CloudSandboxPage) and the cursor of the next
389
+ # (nil at the end).
390
+ def list_page(all: false, limit: nil, cursor: nil)
391
+ q = []
392
+ q << %w[all 1] if all
393
+ unless limit.nil?
394
+ raise ArgumentError, "limit must be a positive whole number" unless limit.is_a?(Integer) && limit.positive?
395
+
396
+ q << ["limit", limit.to_s]
397
+ end
398
+ q << ["cursor", cursor.to_s] if cursor && !cursor.to_s.empty?
399
+ r = @cloud.request("GET", "/v1/sandboxes" + (q.empty? ? "" : "?#{URI.encode_www_form(q)}"))
400
+ r = {} unless r.is_a?(Hash)
401
+ nxt = r["next_cursor"]
402
+ CloudSandboxPage.new(sandboxes: (r["sandboxes"] || []).map { |s| CloudSandbox.new(@cloud, s) },
403
+ next_cursor: nxt.is_a?(String) && !nxt.empty? ? nxt : nil)
404
+ end
405
+
406
+ # Every sandbox, following next_cursor page by page; stops if the server
407
+ # sends a cursor it already sent. Without a block, an Enumerator. A server
408
+ # that does not page answers everything at once, which is then the only page.
409
+ def each(all: false, page_size: nil)
410
+ return enum_for(:each, all: all, page_size: page_size) unless block_given?
411
+
412
+ cursor = nil
413
+ seen = {}
414
+ loop do
415
+ page = list_page(all: all, limit: page_size, cursor: cursor)
416
+ page.sandboxes.each { |s| yield s }
417
+ break if page.next_cursor.nil? || seen[page.next_cursor]
418
+
419
+ seen[page.next_cursor] = true
420
+ cursor = page.next_cursor
421
+ end
422
+ self
173
423
  end
174
424
 
175
425
  def get(id)
@@ -177,7 +427,14 @@ module Kosa8
177
427
  end
178
428
  end
179
429
 
180
- # One cloud sandbox. +info+ is its state as of the last call.
430
+ # One cloud sandbox. +info+ is its state as of the last call (a Hash with
431
+ # "id", "state", "template", "parent_id", "delete_after", "sleep_after_s",
432
+ # "source", "region", "cost_usd", ... as the Cloud API's Sandbox schema).
433
+ #
434
+ # #checkpoint, #checkpoints, #rewind, #fork, #ports and #files need the host's
435
+ # data plane. On hosts without it the API answers 501 (not_available /
436
+ # not_supported), raised as Kosa8::UnsupportedError; not every kosa8 Cloud
437
+ # host has it yet.
181
438
  class CloudSandbox
182
439
  attr_reader :info
183
440
 
@@ -200,14 +457,24 @@ module Kosa8
200
457
 
201
458
  # Run a command and wait for it. A String runs through sh -c, an Array is
202
459
  # the argv. A sleeping sandbox wakes for it.
460
+ #
461
+ # Each exec runs in a fresh container: only /workspace persists, so cd,
462
+ # export and packages installed elsewhere are gone by the next one. kosa8
463
+ # Cloud stops a buffered exec after 90 s, raised as
464
+ # Kosa8::ExecTimeoutError; run long work in the background
465
+ # (nohup sh -c '...' > /workspace/job.log 2>&1 &) and poll it. The request
466
+ # (command and env) is at most 64 KiB (413 too_large).
203
467
  def exec(cmd, image: nil, env: nil)
204
468
  argv = cmd.is_a?(String) ? ["sh", "-c", cmd] : cmd.to_a
205
469
  body = { "cmd" => argv }
206
470
  body["image"] = image unless image.nil?
207
471
  body["env"] = env.map { |k, v| "#{k}=#{v}" } if env && !env.empty?
208
472
  r = @cloud.request("POST", path("/exec"), body)
473
+ fc, rt = Kosa8.exec_failure(r["exit"])
474
+ fc = r["failure_class"] if r["failure_class"].is_a?(String)
475
+ rt = r["retryable"] if r["retryable"] == true || r["retryable"] == false
209
476
  CloudExecResult.new(exit_code: r["exit"], stdout: r["stdout"] || "", stderr: r["stderr"] || "",
210
- woke_ms: r["woke_ms"])
477
+ woke_ms: r["woke_ms"], failure_class: fc, retryable: rt)
211
478
  end
212
479
 
213
480
  # Snapshot it and free its VM; it then costs only snapshot storage.
@@ -232,13 +499,196 @@ module Kosa8
232
499
  nil
233
500
  end
234
501
 
235
- private
502
+ # Change its lifetime or sleep timer (PATCH). +ttl_s+ counts from now;
503
+ # +clear_lifetime: true+ removes the automatic delete (sends ttl_s: null).
504
+ # A new +sleep_after_s+ is recorded; the host keeps the idle time the
505
+ # sandbox started with until it can change it in place. +notes+ holds the
506
+ # server's notes, if any. Raises ArgumentError when nothing is given.
507
+ def update(ttl_s: nil, delete_after: nil, sleep_after_s: nil, clear_lifetime: false)
508
+ if clear_lifetime && !(ttl_s.nil? && delete_after.nil?)
509
+ raise ArgumentError, "clear_lifetime cannot be combined with ttl_s or delete_after"
510
+ end
511
+
512
+ Cloud.check_lifetime(ttl_s, delete_after)
513
+ Cloud.check_sleep_after(sleep_after_s)
514
+ body = {}
515
+ body["ttl_s"] = nil if clear_lifetime
516
+ body["ttl_s"] = ttl_s unless ttl_s.nil?
517
+ body["delete_after"] = delete_after unless delete_after.nil?
518
+ body["sleep_after_s"] = sleep_after_s unless sleep_after_s.nil?
519
+ raise ArgumentError, "give ttl_s:, delete_after:, sleep_after_s: or clear_lifetime: true" if body.empty?
236
520
 
521
+ r = @cloud.request("PATCH", path, body)
522
+ @info = r["sandbox"]
523
+ @notes = r["notes"].is_a?(Array) ? r["notes"] : []
524
+ self
525
+ end
526
+
527
+ # The server's notes from the last #update (an Array of sentences).
528
+ def notes
529
+ @notes || []
530
+ end
531
+
532
+ # Files in the sandbox: a CloudFiles. Needs the host's data plane; on hosts
533
+ # without it the API answers 501 (not_available/not_supported), raised as
534
+ # Kosa8::UnsupportedError. Not every kosa8 Cloud host has it yet.
535
+ def files
536
+ CloudFiles.new(@cloud, self)
537
+ end
538
+
539
+ # Save memory, processes and disk as a checkpoint and return it (a Hash:
540
+ # "id", "label", "auto", "created_at", "bytes"). The newest 10 are kept.
541
+ #
542
+ # Needs the host's data plane; on hosts without it the API answers 501
543
+ # (not_available/not_supported), raised as Kosa8::UnsupportedError. Not
544
+ # every kosa8 Cloud host has it yet.
545
+ def checkpoint(label = nil)
546
+ body = {}
547
+ unless label.nil?
548
+ raise ArgumentError, "a checkpoint label is at most 200 characters" if label.to_s.length > 200
549
+
550
+ body["label"] = label.to_s
551
+ end
552
+ @cloud.request("POST", path("/checkpoints"), body)["checkpoint"]
553
+ end
554
+
555
+ # Its checkpoints, oldest first. Does not wake a sleeping sandbox.
556
+ #
557
+ # Needs the host's data plane; on hosts without it the API answers 501
558
+ # (not_available/not_supported), raised as Kosa8::UnsupportedError. Not
559
+ # every kosa8 Cloud host has it yet.
560
+ def checkpoints
561
+ r = @cloud.request("GET", path("/checkpoints"))
562
+ r.is_a?(Hash) ? (r["checkpoints"] || []) : []
563
+ end
564
+
565
+ # Go back to a checkpoint (its id, or the Hash #checkpoint returned). The
566
+ # sandbox as it was is first saved as an automatic checkpoint, returned as
567
+ # +backup+ in a CloudRewindResult.
568
+ #
569
+ # Needs the host's data plane; on hosts without it the API answers 501
570
+ # (not_available/not_supported), raised as Kosa8::UnsupportedError. Not
571
+ # every kosa8 Cloud host has it yet.
572
+ def rewind(checkpoint_id)
573
+ checkpoint_id = checkpoint_id["id"] if checkpoint_id.is_a?(Hash)
574
+ raise ArgumentError, "rewind needs a checkpoint id" if checkpoint_id.nil? || checkpoint_id.to_s.empty?
575
+
576
+ r = @cloud.request("POST", path("/rewind"), { "checkpoint_id" => checkpoint_id.to_s })
577
+ r = {} unless r.is_a?(Hash)
578
+ @info = r["sandbox"] if r["sandbox"].is_a?(Hash)
579
+ CloudRewindResult.new(checkpoint: r["checkpoint"] || {}, backup: r["backup"], ms: r["ms"])
580
+ end
581
+
582
+ # +n+ (1 to 1000) live copies of the sandbox as it is now, on its host, as
583
+ # a SandboxBatch (an Array of CloudSandbox with +failed+). Each is held to
584
+ # the rules of a create (payment, quotas).
585
+ #
586
+ # labels: go on every copy, run_id: labels them kosa8.run=<run_id>
587
+ # (heartbeat and drain select by it), lease_s: (60..86400) deletes each
588
+ # lease_s from now unless heartbeats extend it, prefix: names them
589
+ # <prefix>-0001, ... With partial_ok: true copies that could not be made
590
+ # (no room on the host, the running limit) are listed in +failed+ instead
591
+ # of failing the call; false is all or nothing. The API's default is true
592
+ # when a fan-out option is given or n is over 100. A fork that made none
593
+ # raises the first refusal. The call carries an Idempotency-Key
594
+ # (+idempotency_key+, default a new UUID) reused on every retry.
595
+ #
596
+ # Needs the host's data plane; on hosts without it the API answers 501
597
+ # (not_available/not_supported), raised as Kosa8::UnsupportedError. Not
598
+ # every kosa8 Cloud host has it yet.
599
+ def fork(n = 1, labels: nil, run_id: nil, lease_s: nil, prefix: nil, partial_ok: nil, idempotency_key: nil)
600
+ unless n.is_a?(Integer) && n.between?(1, Cloud::MAX_FORK)
601
+ raise ArgumentError, "n must be a whole number from 1 to #{Cloud::MAX_FORK}"
602
+ end
603
+
604
+ body = { "n" => n }.merge(Cloud.fanout_body(@cloud, labels: labels, run_id: run_id, lease_s: lease_s,
605
+ prefix: prefix, partial_ok: partial_ok))
606
+ Cloud.check_idempotency_key(idempotency_key)
607
+ r = @cloud.request("POST", path("/fork"), body, idempotency_key: idempotency_key)
608
+ SandboxBatch.from(@cloud, r, n)
609
+ end
610
+
611
+ # TCP ports listening in its running containers (Hashes: "port",
612
+ # "address", "container", "loopback").
613
+ #
614
+ # Needs the host's data plane; on hosts without it the API answers 501
615
+ # (not_available/not_supported), raised as Kosa8::UnsupportedError. Not
616
+ # every kosa8 Cloud host has it yet.
617
+ def ports
618
+ r = @cloud.request("GET", path("/ports"))
619
+ r.is_a?(Hash) ? (r["ports"] || []) : []
620
+ end
621
+
622
+ # "/v1/sandboxes/{id}" plus +suffix+.
237
623
  def path(suffix = "")
238
624
  "/v1/sandboxes/#{Kosa8.enc(id)}#{suffix}"
239
625
  end
240
626
  end
241
627
 
628
+ # sandbox.files: files in a cloud sandbox, at most 8 MiB each. Paths are
629
+ # absolute, such as /workspace/app.py; only /workspace outlives an exec. A
630
+ # sleeping sandbox wakes first. File info Hashes have "name", "path",
631
+ # "type" ("file" or "dir"), "size", "mode" and "mod_time".
632
+ #
633
+ # Needs the host's data plane; on hosts without it the API answers 501
634
+ # (not_available/not_supported), raised as Kosa8::UnsupportedError. Not every
635
+ # kosa8 Cloud host has it yet.
636
+ class CloudFiles
637
+ def initialize(cloud, sandbox)
638
+ @cloud = cloud
639
+ @sandbox = sandbox
640
+ end
641
+
642
+ def inspect
643
+ "#<Kosa8::CloudFiles sandbox=#{@sandbox.id.inspect}>"
644
+ end
645
+
646
+ # The file's bytes, as a binary (ASCII-8BIT) String.
647
+ def read(path)
648
+ @cloud.request_bytes("GET", query("/files", path), raw: true)
649
+ end
650
+
651
+ # The file as text (UTF-8 by default).
652
+ def read_text(path, encoding: Encoding::UTF_8)
653
+ read(path).force_encoding(encoding)
654
+ end
655
+
656
+ # Create or replace a file with +content+ (a String; sent as raw bytes).
657
+ # Returns its info Hash.
658
+ def write(path, content)
659
+ r = @cloud.request_bytes("PUT", query("/files", path), data: content.to_s)
660
+ r.is_a?(Hash) ? (r["file"] || {}) : {}
661
+ end
662
+
663
+ # A folder's entries (default /workspace), as info Hashes.
664
+ def list(path = "/workspace")
665
+ r = @cloud.request("GET", query("/files/list", path))
666
+ r.is_a?(Hash) ? (r["files"] || []) : []
667
+ end
668
+
669
+ # Make a folder and its parents; returns its info Hash.
670
+ def mkdir(path)
671
+ raise ArgumentError, "a path is required, e.g. /workspace/data" if path.nil? || path.to_s.empty?
672
+
673
+ r = @cloud.request("POST", @sandbox.path("/files/mkdir"), { "path" => path.to_s })
674
+ r.is_a?(Hash) ? (r["file"] || {}) : {}
675
+ end
676
+
677
+ # Remove a file, or a folder and everything in it with +recursive: true+.
678
+ def delete(path, recursive: false)
679
+ @cloud.request("DELETE", query("/files", path, recursive ? [%w[recursive 1]] : []))
680
+ nil
681
+ end
682
+
683
+ private
684
+
685
+ def query(suffix, path, extra = [])
686
+ raise ArgumentError, "a path is required, e.g. /workspace/app.py" if path.nil? || path.to_s.empty?
687
+
688
+ "#{@sandbox.path(suffix)}?#{URI.encode_www_form([["path", path.to_s]] + extra).gsub('+', '%20')}"
689
+ end
690
+ end
691
+
242
692
  # cloud.functions
243
693
  class CloudFunctions
244
694
  def initialize(cloud)