kosa8 0.3.0 → 0.4.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
@@ -15,26 +15,50 @@ module Kosa8
15
15
  end
16
16
  end
17
17
 
18
+ # One page of CloudSandboxes#list_page. +next_cursor+ is nil on the last page,
19
+ # and always on a server that does not page yet (it then answers every
20
+ # sandbox in one page).
21
+ CloudSandboxPage = Struct.new(:sandboxes, :next_cursor, keyword_init: true)
22
+
23
+ # What CloudSandbox#rewind answers: the +checkpoint+ it went back to, the
24
+ # automatic +backup+ checkpoint of the sandbox as it was just before, and +ms+.
25
+ CloudRewindResult = Struct.new(:checkpoint, :backup, :ms, keyword_init: true)
26
+
18
27
  # kosa8 Cloud: the same sandboxes, run on kosa8's hosts (or your own, with
19
28
  # bring-your-own-cloud) instead of the local daemon.
20
29
  #
21
30
  # cloud = Kosa8::Cloud.new # KOSA8_API_KEY from the environment
22
- # box = cloud.sandboxes.create(template: "python")
31
+ # box = cloud.sandboxes.create(template: "python", ttl_s: 3600)
23
32
  # box.exec(["python3", "-c", "print(6 * 7)"]).stdout # => "42\n"
24
33
  # box.delete
25
34
  #
26
35
  # Authentication is an API key (k8c_live_...) made in the cloud dashboard.
27
36
  # Errors are the SDK's usual typed errors; each carries the cloud's stable
28
37
  # +code+ (for example payment_required, quota_exceeded). Standard library only.
38
+ #
39
+ # Each exec runs in a fresh container and only /workspace persists; a
40
+ # buffered exec is cut off after about 30 s (ExecTimeoutError), and a request
41
+ # body is at most 64 KiB.
29
42
  class Cloud
30
- DEFAULT_URL = "https://api.kosa8.cloud"
43
+ DEFAULT_URL = "https://api.kosa8.com"
31
44
  KEY_PREFIX = "k8c_live_"
32
45
  LOCAL_HOSTS = %w[localhost 127.0.0.1 ::1].freeze
46
+ # A ttl_s is from 60 seconds to 90 days.
47
+ MIN_TTL_S = 60
48
+ MAX_TTL_S = 7_776_000
49
+ # sleep_after_s is from 0 (never) to 7 days.
50
+ MAX_SLEEP_AFTER_S = 604_800
51
+ # A fork makes from 1 to 100 copies.
52
+ MAX_FORK = 100
53
+ # The limit kosa8 Cloud puts on a buffered exec today, in seconds.
54
+ EXEC_LIMIT_S = 30
55
+ EXEC_HINT = "a buffered exec is limited to about #{EXEC_LIMIT_S} s; run long work in the background, " \
56
+ "writing to /workspace, and poll it"
33
57
 
34
58
  attr_reader :base_url, :timeout, :sandboxes, :functions
35
59
 
36
- # transport: an optional callable (method, url, headers, body_or_nil, timeout) -> [status, body_string],
37
- # used instead of Net::HTTP (tests, proxies).
60
+ # transport: an optional callable (method, url, headers, body_or_nil, timeout) -> [status, body_string]
61
+ # or [status, body_string, response_headers], used instead of Net::HTTP (tests, proxies).
38
62
  def initialize(api_key: nil, base_url: nil, env: ENV, timeout: 120, transport: nil)
39
63
  key = (api_key.nil? ? env["KOSA8_API_KEY"].to_s : api_key.to_s).strip
40
64
  raise Error, "no kosa8 Cloud API key: pass api_key: or set KOSA8_API_KEY" if key.empty?
@@ -65,38 +89,65 @@ module Kosa8
65
89
  request("GET", "/v1/usage")
66
90
  end
67
91
 
92
+ # The templates the org can start: "key", "cpus", "mem_mb", "image", "regions", "warm".
93
+ def templates
94
+ r = request("GET", "/v1/templates")
95
+ r.is_a?(Hash) ? (r["templates"] || []) : []
96
+ end
97
+
68
98
  # One JSON request; raises the typed error for an error answer.
69
99
  def request(method, path, body = nil)
70
- headers = { "Authorization" => "Bearer #{@key}", "Accept" => "application/json" }
71
- data = nil
72
- unless body.nil?
100
+ perform(method, path, body, nil, false)
101
+ end
102
+
103
+ # One request whose body is +data+ (raw bytes, application/octet-stream)
104
+ # when given; with +raw+ a successful answer's bytes come back as a binary
105
+ # String instead of parsed JSON. Raises the typed error for an error answer.
106
+ def request_bytes(method, path, data: nil, raw: false)
107
+ perform(method, path, nil, data, raw)
108
+ end
109
+
110
+ private def perform(method, path, body, data, raw)
111
+ headers = { "Authorization" => "Bearer #{@key}", "User-Agent" => "kosa8-ruby/#{VERSION}",
112
+ "Accept" => raw ? "application/octet-stream" : "application/json" }
113
+ payload = nil
114
+ if !data.nil?
115
+ headers["Content-Type"] = "application/octet-stream"
116
+ payload = data.to_s.b
117
+ elsif !body.nil?
73
118
  headers["Content-Type"] = "application/json"
74
- data = JSON.generate(body)
119
+ payload = JSON.generate(body)
75
120
  end
76
121
  begin
77
- status, raw = @transport.call(method, @base_url + path, headers, data, @timeout)
122
+ status, content, resp_headers = @transport.call(method, @base_url + path, headers, payload, @timeout)
78
123
  rescue Net::OpenTimeout, Net::ReadTimeout, Timeout::Error => e
124
+ if Cloud.exec_path?(path)
125
+ raise ExecTimeoutError.new("kosa8 Cloud did not answer within #{@timeout} s (#{EXEC_HINT})",
126
+ method: method, path: path, code: "exec_timeout")
127
+ end
79
128
  raise TimeoutError.new("kosa8 Cloud did not answer within #{@timeout} s (#{e.message})",
80
129
  method: method, path: path)
81
130
  rescue SystemCallError, IOError, SocketError, OpenSSL::SSL::SSLError => e
82
131
  raise ConnectionError.new("could not reach kosa8 Cloud at #{@base_url}: #{e.message}",
83
132
  method: method, path: path)
84
133
  end
85
- text = raw.to_s.dup.force_encoding(Encoding::UTF_8)
134
+ return content.to_s.b if raw && status.to_i < 400
135
+
136
+ text = content.to_s.dup.force_encoding(Encoding::UTF_8)
86
137
  text = text.scrub unless text.valid_encoding?
87
138
  parsed = begin
88
139
  text.strip.empty? ? nil : JSON.parse(text)
89
140
  rescue JSON::ParserError
90
141
  text
91
142
  end
92
- raise Cloud.error(status.to_i, parsed, method, path) if status.to_i >= 400
143
+ raise Cloud.error(status.to_i, parsed, method, path, resp_headers) if status.to_i >= 400
93
144
 
94
145
  parsed
95
146
  end
96
147
 
97
148
  # The cloud answers {"error": code, "message": sentence}: the sentence is
98
149
  # the message, and the code is kept.
99
- def self.error(status, body, method, path)
150
+ def self.error(status, body, method, path, headers = nil)
100
151
  code = nil
101
152
  msg_body = body
102
153
  if body.is_a?(Hash)
@@ -104,11 +155,60 @@ module Kosa8
104
155
  m = body["message"]
105
156
  msg_body = { "error" => m.is_a?(String) && !m.empty? ? m : body["error"] }
106
157
  end
107
- e = Kosa8.error_from_response(status, msg_body, method: method, path: path, code: code)
158
+ message = (msg_body.is_a?(Hash) ? msg_body["error"] : msg_body).to_s
159
+ e = if exec_timeout?(status, code, message, path)
160
+ said = message.empty? ? nil : message
161
+ ExecTimeoutError.new("#{said || "request failed with HTTP #{status}"} (#{EXEC_HINT})",
162
+ status: status, daemon_message: said, method: method, path: path,
163
+ code: code || "exec_timeout")
164
+ else
165
+ Kosa8.error_from_response(status, msg_body, method: method, path: path, code: code)
166
+ end
108
167
  e.instance_variable_set(:@body, body)
168
+ e.retry_after = retry_after(headers) if e.is_a?(RateLimitError)
109
169
  e
110
170
  end
111
171
 
172
+ def self.exec_path?(path)
173
+ path.to_s.split("?", 2)[0].end_with?("/exec")
174
+ end
175
+
176
+ # 504, code exec_timeout, or today's 502 host_failed "... timed out" on /exec.
177
+ def self.exec_timeout?(status, code, message, path)
178
+ return true if status == 504 || code == "exec_timeout"
179
+
180
+ status == 502 && exec_path?(path) && message.downcase.include?("timed out")
181
+ end
182
+
183
+ # Retry-After in seconds (a number), or nil.
184
+ def self.retry_after(headers)
185
+ return nil unless headers.respond_to?(:each)
186
+
187
+ v = nil
188
+ headers.each { |k, val| v = val if k.to_s.casecmp("retry-after").zero? }
189
+ v = v.first if v.is_a?(Array)
190
+ Float(v.to_s.strip)
191
+ rescue ArgumentError, TypeError
192
+ nil
193
+ end
194
+
195
+ # Argument checks shared by create and update; raise ArgumentError before any request.
196
+ def self.check_lifetime(ttl_s, delete_after)
197
+ raise ArgumentError, "give ttl_s or delete_after, not both" if !ttl_s.nil? && !delete_after.nil?
198
+ if !ttl_s.nil? && !(ttl_s.is_a?(Integer) && ttl_s.between?(MIN_TTL_S, MAX_TTL_S))
199
+ raise ArgumentError, "ttl_s must be a whole number of seconds from #{MIN_TTL_S} to #{MAX_TTL_S}"
200
+ end
201
+ return if delete_after.nil? || delete_after.is_a?(Integer)
202
+
203
+ raise ArgumentError, "delete_after must be a Unix time in milliseconds"
204
+ end
205
+
206
+ def self.check_sleep_after(sleep_after_s)
207
+ return if sleep_after_s.nil? || (sleep_after_s.is_a?(Integer) && sleep_after_s.between?(0, MAX_SLEEP_AFTER_S))
208
+
209
+ raise ArgumentError, "sleep_after_s must be a whole number of seconds from 0 (never) to #{MAX_SLEEP_AFTER_S}"
210
+ end
211
+
112
212
  def self.check_base(url)
113
213
  u = begin
114
214
  URI.parse(url)
@@ -142,7 +242,7 @@ module Kosa8
142
242
  req.body = body unless body.nil?
143
243
  http.start do |h|
144
244
  resp = h.request(req)
145
- [resp.code.to_i, resp.body.to_s]
245
+ [resp.code.to_i, resp.body.to_s, resp.to_hash]
146
246
  end
147
247
  end
148
248
  end
@@ -158,18 +258,74 @@ module Kosa8
158
258
  end
159
259
 
160
260
  # 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)
261
+ #
262
+ # +template+ is a key from Cloud#templates (default the org's default,
263
+ # "base": Alpine, busybox sh, no bash or python) or a kosa8 Store item,
264
+ # "creator/name" or "creator/name@1.2.3". +ttl_s+ (60 s to 90 days) or
265
+ # +delete_after+ (Unix ms) deletes it automatically: set one so a crashed
266
+ # script cannot leave it running. +sleep_after_s+ is the idle time before it
267
+ # sleeps (0 never; default 300). +accept_price+ is a paid Store item's
268
+ # current price in USD, which the person agreed to. Bad arguments raise
269
+ # ArgumentError before any request.
270
+ def create(template: nil, region: nil, sleep_after_s: nil, ttl_s: nil, delete_after: nil, accept_price: nil)
271
+ Cloud.check_lifetime(ttl_s, delete_after)
272
+ Cloud.check_sleep_after(sleep_after_s)
273
+ if !accept_price.nil? && !accept_price.is_a?(Numeric)
274
+ raise ArgumentError, "accept_price must be a number (USD)"
275
+ end
276
+
162
277
  body = {}
163
278
  body["template"] = template unless template.nil?
164
279
  body["region"] = region unless region.nil?
165
280
  body["sleep_after_s"] = sleep_after_s unless sleep_after_s.nil?
281
+ body["ttl_s"] = ttl_s unless ttl_s.nil?
282
+ body["delete_after"] = delete_after unless delete_after.nil?
283
+ body["accept_price"] = accept_price unless accept_price.nil?
166
284
  CloudSandbox.new(@cloud, @cloud.request("POST", "/v1/sandboxes", body)["sandbox"])
167
285
  end
168
286
 
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) }
287
+ # The org's sandboxes, newest first, as an Array; with all: true, deleted
288
+ # ones too. With +limit:+ or +cursor:+ this is one page: #list_page also
289
+ # gives the next cursor, and #each walks every page.
290
+ def list(all: false, limit: nil, cursor: nil)
291
+ list_page(all: all, limit: limit, cursor: cursor).sandboxes
292
+ end
293
+
294
+ # One page of sandboxes (a CloudSandboxPage) and the cursor of the next
295
+ # (nil at the end).
296
+ def list_page(all: false, limit: nil, cursor: nil)
297
+ q = []
298
+ q << %w[all 1] if all
299
+ unless limit.nil?
300
+ raise ArgumentError, "limit must be a positive whole number" unless limit.is_a?(Integer) && limit.positive?
301
+
302
+ q << ["limit", limit.to_s]
303
+ end
304
+ q << ["cursor", cursor.to_s] if cursor && !cursor.to_s.empty?
305
+ r = @cloud.request("GET", "/v1/sandboxes" + (q.empty? ? "" : "?#{URI.encode_www_form(q)}"))
306
+ r = {} unless r.is_a?(Hash)
307
+ nxt = r["next_cursor"]
308
+ CloudSandboxPage.new(sandboxes: (r["sandboxes"] || []).map { |s| CloudSandbox.new(@cloud, s) },
309
+ next_cursor: nxt.is_a?(String) && !nxt.empty? ? nxt : nil)
310
+ end
311
+
312
+ # Every sandbox, following next_cursor page by page; stops if the server
313
+ # sends a cursor it already sent. Without a block, an Enumerator. A server
314
+ # that does not page answers everything at once, which is then the only page.
315
+ def each(all: false, page_size: nil)
316
+ return enum_for(:each, all: all, page_size: page_size) unless block_given?
317
+
318
+ cursor = nil
319
+ seen = {}
320
+ loop do
321
+ page = list_page(all: all, limit: page_size, cursor: cursor)
322
+ page.sandboxes.each { |s| yield s }
323
+ break if page.next_cursor.nil? || seen[page.next_cursor]
324
+
325
+ seen[page.next_cursor] = true
326
+ cursor = page.next_cursor
327
+ end
328
+ self
173
329
  end
174
330
 
175
331
  def get(id)
@@ -177,7 +333,14 @@ module Kosa8
177
333
  end
178
334
  end
179
335
 
180
- # One cloud sandbox. +info+ is its state as of the last call.
336
+ # One cloud sandbox. +info+ is its state as of the last call (a Hash with
337
+ # "id", "state", "template", "parent_id", "delete_after", "sleep_after_s",
338
+ # "source", "region", "cost_usd", ... as the Cloud API's Sandbox schema).
339
+ #
340
+ # #checkpoint, #checkpoints, #rewind, #fork, #ports and #files need the host's
341
+ # data plane. On hosts without it the API answers 501 (not_available /
342
+ # not_supported), raised as Kosa8::UnsupportedError; not every kosa8 Cloud
343
+ # host has it yet.
181
344
  class CloudSandbox
182
345
  attr_reader :info
183
346
 
@@ -200,6 +363,13 @@ module Kosa8
200
363
 
201
364
  # Run a command and wait for it. A String runs through sh -c, an Array is
202
365
  # the argv. A sleeping sandbox wakes for it.
366
+ #
367
+ # Each exec runs in a fresh container: only /workspace persists, so cd,
368
+ # export and packages installed elsewhere are gone by the next one. kosa8
369
+ # Cloud cuts a buffered exec off after about 30 s, raised as
370
+ # Kosa8::ExecTimeoutError; run long work in the background
371
+ # (nohup sh -c '...' > /workspace/job.log 2>&1 &) and poll it. The request
372
+ # (command and env) is at most 64 KiB (413 too_large).
203
373
  def exec(cmd, image: nil, env: nil)
204
374
  argv = cmd.is_a?(String) ? ["sh", "-c", cmd] : cmd.to_a
205
375
  body = { "cmd" => argv }
@@ -232,13 +402,184 @@ module Kosa8
232
402
  nil
233
403
  end
234
404
 
235
- private
405
+ # Change its lifetime or sleep timer (PATCH). +ttl_s+ counts from now;
406
+ # +clear_lifetime: true+ removes the automatic delete (sends ttl_s: null).
407
+ # A new +sleep_after_s+ is recorded; the host keeps the idle time the
408
+ # sandbox started with until it can change it in place. +notes+ holds the
409
+ # server's notes, if any. Raises ArgumentError when nothing is given.
410
+ def update(ttl_s: nil, delete_after: nil, sleep_after_s: nil, clear_lifetime: false)
411
+ if clear_lifetime && !(ttl_s.nil? && delete_after.nil?)
412
+ raise ArgumentError, "clear_lifetime cannot be combined with ttl_s or delete_after"
413
+ end
236
414
 
415
+ Cloud.check_lifetime(ttl_s, delete_after)
416
+ Cloud.check_sleep_after(sleep_after_s)
417
+ body = {}
418
+ body["ttl_s"] = nil if clear_lifetime
419
+ body["ttl_s"] = ttl_s unless ttl_s.nil?
420
+ body["delete_after"] = delete_after unless delete_after.nil?
421
+ body["sleep_after_s"] = sleep_after_s unless sleep_after_s.nil?
422
+ raise ArgumentError, "give ttl_s:, delete_after:, sleep_after_s: or clear_lifetime: true" if body.empty?
423
+
424
+ r = @cloud.request("PATCH", path, body)
425
+ @info = r["sandbox"]
426
+ @notes = r["notes"].is_a?(Array) ? r["notes"] : []
427
+ self
428
+ end
429
+
430
+ # The server's notes from the last #update (an Array of sentences).
431
+ def notes
432
+ @notes || []
433
+ end
434
+
435
+ # Files in the sandbox: a CloudFiles. Needs the host's data plane; on hosts
436
+ # without it the API answers 501 (not_available/not_supported), raised as
437
+ # Kosa8::UnsupportedError. Not every kosa8 Cloud host has it yet.
438
+ def files
439
+ CloudFiles.new(@cloud, self)
440
+ end
441
+
442
+ # Save memory, processes and disk as a checkpoint and return it (a Hash:
443
+ # "id", "label", "auto", "created_at", "bytes"). The newest 10 are kept.
444
+ #
445
+ # Needs the host's data plane; on hosts without it the API answers 501
446
+ # (not_available/not_supported), raised as Kosa8::UnsupportedError. Not
447
+ # every kosa8 Cloud host has it yet.
448
+ def checkpoint(label = nil)
449
+ body = {}
450
+ unless label.nil?
451
+ raise ArgumentError, "a checkpoint label is at most 200 characters" if label.to_s.length > 200
452
+
453
+ body["label"] = label.to_s
454
+ end
455
+ @cloud.request("POST", path("/checkpoints"), body)["checkpoint"]
456
+ end
457
+
458
+ # Its checkpoints, oldest first. Does not wake a sleeping sandbox.
459
+ #
460
+ # Needs the host's data plane; on hosts without it the API answers 501
461
+ # (not_available/not_supported), raised as Kosa8::UnsupportedError. Not
462
+ # every kosa8 Cloud host has it yet.
463
+ def checkpoints
464
+ r = @cloud.request("GET", path("/checkpoints"))
465
+ r.is_a?(Hash) ? (r["checkpoints"] || []) : []
466
+ end
467
+
468
+ # Go back to a checkpoint (its id, or the Hash #checkpoint returned). The
469
+ # sandbox as it was is first saved as an automatic checkpoint, returned as
470
+ # +backup+ in a CloudRewindResult.
471
+ #
472
+ # Needs the host's data plane; on hosts without it the API answers 501
473
+ # (not_available/not_supported), raised as Kosa8::UnsupportedError. Not
474
+ # every kosa8 Cloud host has it yet.
475
+ def rewind(checkpoint_id)
476
+ checkpoint_id = checkpoint_id["id"] if checkpoint_id.is_a?(Hash)
477
+ raise ArgumentError, "rewind needs a checkpoint id" if checkpoint_id.nil? || checkpoint_id.to_s.empty?
478
+
479
+ r = @cloud.request("POST", path("/rewind"), { "checkpoint_id" => checkpoint_id.to_s })
480
+ r = {} unless r.is_a?(Hash)
481
+ @info = r["sandbox"] if r["sandbox"].is_a?(Hash)
482
+ CloudRewindResult.new(checkpoint: r["checkpoint"] || {}, backup: r["backup"], ms: r["ms"])
483
+ end
484
+
485
+ # +n+ (1 to 100) live copies of the sandbox as it is now, on its host, as
486
+ # an Array of CloudSandbox. Each is held to the rules of a create
487
+ # (payment, quotas); all or nothing.
488
+ #
489
+ # Needs the host's data plane; on hosts without it the API answers 501
490
+ # (not_available/not_supported), raised as Kosa8::UnsupportedError. Not
491
+ # every kosa8 Cloud host has it yet.
492
+ def fork(n = 1)
493
+ unless n.is_a?(Integer) && n.between?(1, Cloud::MAX_FORK)
494
+ raise ArgumentError, "n must be a whole number from 1 to #{Cloud::MAX_FORK}"
495
+ end
496
+
497
+ r = @cloud.request("POST", path("/fork"), { "n" => n })
498
+ r = {} unless r.is_a?(Hash)
499
+ (r["sandboxes"] || []).map { |s| CloudSandbox.new(@cloud, s) }
500
+ end
501
+
502
+ # TCP ports listening in its running containers (Hashes: "port",
503
+ # "address", "container", "loopback").
504
+ #
505
+ # Needs the host's data plane; on hosts without it the API answers 501
506
+ # (not_available/not_supported), raised as Kosa8::UnsupportedError. Not
507
+ # every kosa8 Cloud host has it yet.
508
+ def ports
509
+ r = @cloud.request("GET", path("/ports"))
510
+ r.is_a?(Hash) ? (r["ports"] || []) : []
511
+ end
512
+
513
+ # "/v1/sandboxes/{id}" plus +suffix+.
237
514
  def path(suffix = "")
238
515
  "/v1/sandboxes/#{Kosa8.enc(id)}#{suffix}"
239
516
  end
240
517
  end
241
518
 
519
+ # sandbox.files: files in a cloud sandbox, at most 8 MiB each. Paths are
520
+ # absolute, such as /workspace/app.py; only /workspace outlives an exec. A
521
+ # sleeping sandbox wakes first. File info Hashes have "name", "path",
522
+ # "type" ("file" or "dir"), "size", "mode" and "mod_time".
523
+ #
524
+ # Needs the host's data plane; on hosts without it the API answers 501
525
+ # (not_available/not_supported), raised as Kosa8::UnsupportedError. Not every
526
+ # kosa8 Cloud host has it yet.
527
+ class CloudFiles
528
+ def initialize(cloud, sandbox)
529
+ @cloud = cloud
530
+ @sandbox = sandbox
531
+ end
532
+
533
+ def inspect
534
+ "#<Kosa8::CloudFiles sandbox=#{@sandbox.id.inspect}>"
535
+ end
536
+
537
+ # The file's bytes, as a binary (ASCII-8BIT) String.
538
+ def read(path)
539
+ @cloud.request_bytes("GET", query("/files", path), raw: true)
540
+ end
541
+
542
+ # The file as text (UTF-8 by default).
543
+ def read_text(path, encoding: Encoding::UTF_8)
544
+ read(path).force_encoding(encoding)
545
+ end
546
+
547
+ # Create or replace a file with +content+ (a String; sent as raw bytes).
548
+ # Returns its info Hash.
549
+ def write(path, content)
550
+ r = @cloud.request_bytes("PUT", query("/files", path), data: content.to_s)
551
+ r.is_a?(Hash) ? (r["file"] || {}) : {}
552
+ end
553
+
554
+ # A folder's entries (default /workspace), as info Hashes.
555
+ def list(path = "/workspace")
556
+ r = @cloud.request("GET", query("/files/list", path))
557
+ r.is_a?(Hash) ? (r["files"] || []) : []
558
+ end
559
+
560
+ # Make a folder and its parents; returns its info Hash.
561
+ def mkdir(path)
562
+ raise ArgumentError, "a path is required, e.g. /workspace/data" if path.nil? || path.to_s.empty?
563
+
564
+ r = @cloud.request("POST", @sandbox.path("/files/mkdir"), { "path" => path.to_s })
565
+ r.is_a?(Hash) ? (r["file"] || {}) : {}
566
+ end
567
+
568
+ # Remove a file, or a folder and everything in it with +recursive: true+.
569
+ def delete(path, recursive: false)
570
+ @cloud.request("DELETE", query("/files", path, recursive ? [%w[recursive 1]] : []))
571
+ nil
572
+ end
573
+
574
+ private
575
+
576
+ def query(suffix, path, extra = [])
577
+ raise ArgumentError, "a path is required, e.g. /workspace/app.py" if path.nil? || path.to_s.empty?
578
+
579
+ "#{@sandbox.path(suffix)}?#{URI.encode_www_form([["path", path.to_s]] + extra).gsub('+', '%20')}"
580
+ end
581
+ end
582
+
242
583
  # cloud.functions
243
584
  class CloudFunctions
244
585
  def initialize(cloud)