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.
@@ -0,0 +1,695 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "uri"
5
+
6
+ # More of kosa8 Cloud: sized and Docker creates, env, background commands,
7
+ # durable snapshots, previews, terminals, streamed files and presigned links,
8
+ # egress, secrets, schedules, the code interpreter, metrics, logs, labels and
9
+ # Pipelines. Hosts that lack a feature answer 501, raised as
10
+ # Kosa8::UnsupportedError; Cloud#capabilities says what the org can do.
11
+ module Kosa8
12
+ class Cloud
13
+ # The sizes a sized create takes: vCPU x GiB.
14
+ SIZES = %w[2x4 4x8 8x16 16x32].freeze
15
+ ENV_NAME = /\A[A-Za-z_][A-Za-z0-9_]*\z/.freeze
16
+ SANDBOX_NAME = /\A[A-Za-z0-9][A-Za-z0-9._-]{0,63}\z/.freeze
17
+ SNAPSHOT_ID = /\Asnap_[A-Za-z0-9]{8,40}\z/.freeze
18
+ SECRET_NAME = /\A[a-z0-9-]{1,32}\z/.freeze
19
+ LABEL_KEY = %r{\A[A-Za-z0-9._/-]{1,63}\z}.freeze
20
+ MAX_ENV = 64
21
+ MAX_ENV_VALUE = 8192
22
+ MAX_LABELS = 16
23
+ MAX_LABEL_VALUE = 256
24
+ FINISHED_RUN_STATES = %w[success failure cancelled skipped error].freeze
25
+
26
+ attr_reader :snapshots, :secrets, :pipelines
27
+
28
+ alias initialize_without_features initialize
29
+ def initialize(**kw)
30
+ initialize_without_features(**kw)
31
+ @snapshots = CloudSnapshots.new(self)
32
+ @secrets = CloudSecrets.new(self)
33
+ @pipelines = CloudPipelines.new(self)
34
+ end
35
+
36
+ # What the org and its hosts can do (GET /v1/capabilities), for feature detection.
37
+ def capabilities
38
+ request("GET", "/v1/capabilities")
39
+ end
40
+
41
+ # The named host lists an egress policy's "presets" can use.
42
+ def egress_presets
43
+ r = request("GET", "/v1/egress/presets")
44
+ r.is_a?(Hash) ? (r["presets"] || {}) : {}
45
+ end
46
+
47
+ def self.check_env(env)
48
+ raise ArgumentError, "env is a Hash of NAME => value" unless env.is_a?(Hash)
49
+ raise ArgumentError, "at most #{MAX_ENV} environment variables" if env.size > MAX_ENV
50
+
51
+ env.each do |k, v|
52
+ unless ENV_NAME.match?(k.to_s)
53
+ raise ArgumentError, "environment variable name #{k.to_s.inspect}: letters, digits and _, not starting with a digit"
54
+ end
55
+ raise ArgumentError, "environment variable #{k} is longer than 8 KiB" if v.to_s.bytesize > MAX_ENV_VALUE
56
+ end
57
+ env.map { |k, v| [k.to_s, v.to_s] }.to_h
58
+ end
59
+
60
+ def self.check_labels(labels)
61
+ raise ArgumentError, "labels is a Hash of key => value" unless labels.is_a?(Hash)
62
+ raise ArgumentError, "at most #{MAX_LABELS} labels" if labels.size > MAX_LABELS
63
+
64
+ labels.each do |k, v|
65
+ raise ArgumentError, "label key #{k.to_s.inspect}: 1 to 63 of letters, digits, '.', '_', '/' or '-'" unless LABEL_KEY.match?(k.to_s)
66
+ raise ArgumentError, "label #{k} is longer than #{MAX_LABEL_VALUE} characters" if v.to_s.length > MAX_LABEL_VALUE
67
+ end
68
+ labels.map { |k, v| [k.to_s, v.to_s] }.to_h
69
+ end
70
+
71
+ def self.check_secret_name(name)
72
+ return name.to_s if SECRET_NAME.match?(name.to_s)
73
+
74
+ raise ArgumentError, "secret name #{name.to_s.inspect}: 1 to 32 of lowercase letters, digits and -"
75
+ end
76
+
77
+ def self.egress_body(egress)
78
+ e = egress.to_h.map { |k, v| [k.to_s, v] }.to_h
79
+ { "internet" => e["internet"] == true, "allow" => Array(e["allow"]), "deny" => Array(e["deny"]),
80
+ "presets" => Array(e["presets"]) }
81
+ end
82
+
83
+ def self.env_list(env)
84
+ env.map { |k, v| [k.to_s, v.to_s] }.sort.map { |k, v| "#{k}=#{v}" }
85
+ end
86
+ end
87
+
88
+ class CloudSandboxes
89
+ alias create_without_features create
90
+
91
+ # Start a sandbox. Besides template:, region:, sleep_after_s:, ttl_s:,
92
+ # delete_after: and accept_price:
93
+ #
94
+ # - size: "2x4", "4x8", "8x16" or "16x32" (vCPU x GiB), or cpus: and
95
+ # mem_mb:; image: an OCI image (such as
96
+ # "kosa8-template/universal-24.04-20261115.2"); disk_gb: 8..200. Any of
97
+ # these boots the sandbox cold at that size: create waits for it to
98
+ # run unless wait: false (then call #wait_running).
99
+ # - docker: true lets it run its own Docker engine (start dockerd first);
100
+ # persistent: true runs every exec in one long-lived container;
101
+ # cpu: "dedicated" gives it whole physical cores.
102
+ # - name:, labels: (up to 16), env: (given to every command; values are
103
+ # never logged or returned), secrets: (names from cloud.secrets),
104
+ # egress: ({internet:, allow:, deny:, presets:}).
105
+ # - snapshot: "snap_..." starts it from a durable snapshot; then give
106
+ # only env:, name:, labels:, a lifetime or sleep_after_s:.
107
+ #
108
+ # - lease_s: (60..86400) leases it: deleted lease_s from now unless
109
+ # #heartbeat extends it, so a crashed client leaks nothing (not with
110
+ # ttl_s: or delete_after:). run_id: labels it kosa8.run=<run_id>.
111
+ # - idempotency_key: is sent as the Idempotency-Key header (default a new
112
+ # UUID) and reused on every retry, so a create retried after a timeout
113
+ # or a 5xx makes one sandbox, not two.
114
+ #
115
+ # Bad arguments raise ArgumentError before any request.
116
+ def create(template: nil, region: nil, sleep_after_s: nil, ttl_s: nil, delete_after: nil, accept_price: nil,
117
+ size: nil, cpus: nil, mem_mb: nil, image: nil, disk_gb: nil, persistent: nil, docker: nil, cpu: nil,
118
+ name: nil, labels: nil, env: nil, secrets: nil, egress: nil, snapshot: nil, wait: true,
119
+ poll_interval: 1, lease_s: nil, run_id: nil, idempotency_key: nil)
120
+ body = create_body(template: template, region: region, sleep_after_s: sleep_after_s, ttl_s: ttl_s,
121
+ delete_after: delete_after, accept_price: accept_price, size: size, cpus: cpus,
122
+ mem_mb: mem_mb, image: image, disk_gb: disk_gb, persistent: persistent, docker: docker,
123
+ cpu: cpu, name: name, labels: labels, env: env, secrets: secrets, egress: egress,
124
+ snapshot: snapshot)
125
+ amb = @cloud.run_defaults || {}
126
+ run_id = amb["run_id"] if run_id.nil?
127
+ if lease_s.nil? && ttl_s.nil? && delete_after.nil?
128
+ lease_s = amb["lease_s"]
129
+ end
130
+ unless lease_s.nil?
131
+ raise ArgumentError, "give lease_s or ttl_s/delete_after, not both" unless ttl_s.nil? && delete_after.nil?
132
+
133
+ body["lease_s"] = Cloud.check_lease(lease_s)
134
+ end
135
+ unless run_id.nil?
136
+ body["labels"] = (body["labels"] || {}).merge(Cloud::RUN_LABEL => Cloud.check_run_id(run_id))
137
+ raise ArgumentError, "at most #{Cloud::MAX_LABELS} labels, kosa8.run included" if body["labels"].size > Cloud::MAX_LABELS
138
+ end
139
+ Cloud.check_idempotency_key(idempotency_key)
140
+ r = @cloud.request("POST", "/v1/sandboxes", body, idempotency_key: idempotency_key)
141
+ box = CloudSandbox.new(@cloud, r["sandbox"])
142
+ box.wait_running(poll_interval: poll_interval) if wait && box.state == "creating"
143
+ box
144
+ end
145
+
146
+ # The body of POST /v1/sandboxes for these options (ArgumentError on a bad one).
147
+ def create_body(template: nil, region: nil, sleep_after_s: nil, ttl_s: nil, delete_after: nil,
148
+ accept_price: nil, size: nil, cpus: nil, mem_mb: nil, image: nil, disk_gb: nil,
149
+ persistent: nil, docker: nil, cpu: nil, name: nil, labels: nil, env: nil, secrets: nil,
150
+ egress: nil, snapshot: nil)
151
+ Cloud.check_lifetime(ttl_s, delete_after)
152
+ Cloud.check_sleep_after(sleep_after_s)
153
+ if !accept_price.nil? && !accept_price.is_a?(Numeric)
154
+ raise ArgumentError, "accept_price must be a number (USD)"
155
+ end
156
+
157
+ body = {}
158
+ body["template"] = template unless template.nil?
159
+ body["region"] = region unless region.nil?
160
+ body["sleep_after_s"] = sleep_after_s unless sleep_after_s.nil?
161
+ body["ttl_s"] = ttl_s unless ttl_s.nil?
162
+ body["delete_after"] = delete_after unless delete_after.nil?
163
+ body["accept_price"] = accept_price unless accept_price.nil?
164
+ sized(body, size, cpus, mem_mb, image, disk_gb, persistent, docker, cpu)
165
+ unless name.nil?
166
+ raise ArgumentError, "name: 1 to 64 of letters, digits, '.', '_' or '-'" unless Cloud::SANDBOX_NAME.match?(name.to_s)
167
+
168
+ body["name"] = name.to_s
169
+ end
170
+ body["labels"] = Cloud.check_labels(labels) unless labels.nil?
171
+ body["env"] = Cloud.check_env(env) unless env.nil?
172
+ body["secrets"] = secrets.to_a.map { |n| Cloud.check_secret_name(n) } unless secrets.nil?
173
+ body["egress"] = Cloud.egress_body(egress) unless egress.nil?
174
+ unless snapshot.nil?
175
+ raise ArgumentError, "snapshot: is a snapshot id (snap_...)" unless Cloud::SNAPSHOT_ID.match?(snapshot.to_s)
176
+
177
+ clash = %w[template region size cpus image disk_gb persistent docker cpu] & body.keys
178
+ unless clash.empty?
179
+ raise ArgumentError, "a create from a snapshot takes the snapshot's #{clash.join(', ')}; give only env:, name:, labels:, a lifetime or sleep_after_s:"
180
+ end
181
+
182
+ body["snapshot"] = snapshot.to_s
183
+ end
184
+ body
185
+ end
186
+
187
+ # One page of sandboxes; name: finds one by name, labels: keeps those
188
+ # with every label ({"team" => "a"}; a nil value matches any value).
189
+ alias list_page_without_features list_page
190
+ def list_page(all: false, limit: nil, cursor: nil, name: nil, labels: nil)
191
+ return list_page_without_features(all: all, limit: limit, cursor: cursor) if name.nil? && labels.nil?
192
+
193
+ q = []
194
+ q << %w[all 1] if all
195
+ q << ["limit", Integer(limit).to_s] unless limit.nil?
196
+ q << ["cursor", cursor.to_s] if cursor && !cursor.to_s.empty?
197
+ q << ["name", name.to_s] unless name.nil?
198
+ (labels || {}).sort_by { |k, _| k.to_s }.each { |k, v| q << ["label", v.nil? ? k.to_s : "#{k}=#{v}"] }
199
+ r = @cloud.request("GET", "/v1/sandboxes?#{URI.encode_www_form(q)}")
200
+ r = {} unless r.is_a?(Hash)
201
+ nxt = r["next_cursor"]
202
+ CloudSandboxPage.new(sandboxes: (r["sandboxes"] || []).map { |s| CloudSandbox.new(@cloud, s) },
203
+ next_cursor: nxt.is_a?(String) && !nxt.empty? ? nxt : nil)
204
+ end
205
+
206
+ alias list_without_features list
207
+ def list(all: false, limit: nil, cursor: nil, name: nil, labels: nil)
208
+ list_page(all: all, limit: limit, cursor: cursor, name: name, labels: labels).sandboxes
209
+ end
210
+
211
+ private
212
+
213
+ def sized(body, size, cpus, mem_mb, image, disk_gb, persistent, docker, cpu)
214
+ unless size.nil?
215
+ raise ArgumentError, "size must be one of #{Cloud::SIZES.join(', ')}" unless Cloud::SIZES.include?(size.to_s)
216
+
217
+ body["size"] = size.to_s
218
+ end
219
+ raise ArgumentError, "give cpus: and mem_mb: together" if cpus.nil? != mem_mb.nil?
220
+
221
+ unless cpus.nil?
222
+ raise ArgumentError, "give size: or cpus: and mem_mb:, not both" unless size.nil?
223
+
224
+ body["cpus"] = Integer(cpus)
225
+ body["mem_mb"] = Integer(mem_mb)
226
+ end
227
+ body["image"] = image.to_s unless image.nil?
228
+ unless disk_gb.nil?
229
+ raise ArgumentError, "disk_gb must be 8 to 200" unless disk_gb.is_a?(Integer) && disk_gb.between?(8, 200)
230
+
231
+ body["disk_gb"] = disk_gb
232
+ end
233
+ body["persistent"] = persistent == true unless persistent.nil?
234
+ body["docker"] = docker == true unless docker.nil?
235
+ return if cpu.nil?
236
+ raise ArgumentError, 'cpu must be "shared" or "dedicated"' unless %w[shared dedicated].include?(cpu.to_s)
237
+
238
+ body["cpu"] = cpu.to_s
239
+ end
240
+ end
241
+
242
+ class CloudSandbox
243
+ # Poll until it is no longer "creating" (a sized create boots cold);
244
+ # raises Kosa8::Error if it ends in any state but running.
245
+ def wait_running(timeout: 600, poll_interval: 1)
246
+ deadline = Time.now + timeout
247
+ while state == "creating"
248
+ raise TimeoutError, "sandbox #{id} was still creating after #{timeout} s" if Time.now > deadline
249
+
250
+ Kernel.sleep(poll_interval)
251
+ refresh
252
+ end
253
+ return self if state == "running"
254
+
255
+ raise Error, "sandbox #{id} is #{state}, not running#{@info['last_error'] ? ": #{@info['last_error']}" : ''}"
256
+ end
257
+
258
+ # Start a command that keeps running after this returns (no 90 s
259
+ # limit). Returns the background command (a Hash: "id" (bg_...),
260
+ # "state", "pid", "output_path", ...); poll it with #background_exec or
261
+ # #wait_background.
262
+ def exec_background(cmd, image: nil, env: nil)
263
+ argv = cmd.is_a?(String) ? ["sh", "-c", cmd] : cmd.to_a
264
+ raise ArgumentError, "exec_background needs a command" if argv.empty?
265
+
266
+ body = { "cmd" => argv, "background" => true }
267
+ body["image"] = image unless image.nil?
268
+ body["env"] = Cloud.env_list(env) if env && !env.empty?
269
+ @cloud.request("POST", path("/exec"), body)["exec"]
270
+ end
271
+
272
+ # A background command: "state" ("running" or "exited"), "exit" and the
273
+ # "output" so far.
274
+ def background_exec(exec_id)
275
+ raise ArgumentError, "background_exec needs an exec id (bg_...)" if exec_id.nil? || exec_id.to_s.empty?
276
+
277
+ @cloud.request("GET", path("/exec/#{Kosa8.enc(exec_id)}"))["exec"]
278
+ end
279
+
280
+ # Poll a background command until it exits; returns it.
281
+ def wait_background(exec_id, timeout: 3600, poll_interval: 2)
282
+ exec_id = exec_id["id"] if exec_id.is_a?(Hash)
283
+ deadline = Time.now + timeout
284
+ loop do
285
+ e = background_exec(exec_id)
286
+ return e if e["state"] == "exited" || !e["exit"].nil?
287
+ raise TimeoutError, "background command #{exec_id} was still running after #{timeout} s" if Time.now > deadline
288
+
289
+ Kernel.sleep(poll_interval)
290
+ end
291
+ end
292
+
293
+ # Save it as a durable snapshot (kept until deleted, whatever happens to
294
+ # the sandbox) and return it (a Hash: "id" (snap_...), "state", "bytes",
295
+ # ...). Start new sandboxes from it with create(snapshot: id).
296
+ def snapshot(name = nil)
297
+ body = {}
298
+ body["name"] = name.to_s unless name.nil?
299
+ @cloud.request("POST", path("/snapshots"), body)["snapshot"]
300
+ end
301
+
302
+ # Its previews: a CloudPreviews (ports at https URLs).
303
+ def previews
304
+ CloudPreviews.new(@cloud, self)
305
+ end
306
+
307
+ # A short-lived wss:// URL for an interactive terminal (a Hash: "url",
308
+ # "expires_at", "protocol"). The URL carries its token: keep it secret.
309
+ def terminal(cols: nil, rows: nil, command: nil)
310
+ body = {}
311
+ body["cols"] = cols unless cols.nil?
312
+ body["rows"] = rows unless rows.nil?
313
+ body["command"] = command.to_a unless command.nil?
314
+ @cloud.request("POST", path("/terminal"), body)["terminal"]
315
+ end
316
+
317
+ # The egress policy it runs with ("internet", "allow", "deny", "presets", "source").
318
+ def egress
319
+ @cloud.request("GET", path("/egress"))["egress"]
320
+ end
321
+
322
+ # Change what it may reach, at once: internet:, allow:, deny:, presets:.
323
+ def set_egress(internet: false, allow: [], deny: [], presets: [])
324
+ body = Cloud.egress_body(internet: internet, allow: allow, deny: deny, presets: presets)
325
+ @cloud.request("PUT", path("/egress"), body)["egress"]
326
+ end
327
+
328
+ # Back to the organization's default egress policy.
329
+ def reset_egress
330
+ @cloud.request("DELETE", path("/egress"))["egress"]
331
+ end
332
+
333
+ # The names of the secrets it holds.
334
+ def secrets
335
+ r = @cloud.request("GET", path("/secrets"))
336
+ r.is_a?(Hash) ? (r["secrets"] || []) : []
337
+ end
338
+
339
+ # Its schedules: a CloudSchedules.
340
+ def schedules
341
+ CloudSchedules.new(@cloud, self)
342
+ end
343
+
344
+ # Run a Python cell in a stateful context (globals persist; charts come
345
+ # back as images in "results"). A cell that raised has "error" set; it
346
+ # is not an exception. Needs a persistent sandbox with python3.
347
+ def run_code(code, context: nil, timeout_s: nil)
348
+ raise ArgumentError, "run_code needs code" if code.nil? || code.to_s.empty?
349
+
350
+ body = { "code" => code.to_s, "language" => "python" }
351
+ body["context"] = context.to_s unless context.nil?
352
+ body["timeout_s"] = timeout_s unless timeout_s.nil?
353
+ @cloud.request("POST", path("/code"), body)
354
+ end
355
+
356
+ def code_contexts
357
+ r = @cloud.request("GET", path("/code/contexts"))
358
+ r.is_a?(Hash) ? (r["contexts"] || []) : []
359
+ end
360
+
361
+ def create_code_context(name = nil)
362
+ body = {}
363
+ body["name"] = name.to_s unless name.nil?
364
+ @cloud.request("POST", path("/code/contexts"), body)["context"]
365
+ end
366
+
367
+ def reset_code_context(name)
368
+ @cloud.request("POST", path("/code/contexts/#{Kosa8.enc(name)}/reset"), {})
369
+ nil
370
+ end
371
+
372
+ def delete_code_context(name)
373
+ @cloud.request("DELETE", path("/code/contexts/#{Kosa8.enc(name)}"))
374
+ nil
375
+ end
376
+
377
+ # CPU, memory, disk and network use, read on the host.
378
+ def metrics
379
+ @cloud.request("GET", path("/metrics"))["metrics"]
380
+ end
381
+
382
+ # Its last commands, with exit codes and output tails.
383
+ def logs(limit: nil)
384
+ r = @cloud.request("GET", path("/logs") + (limit.nil? ? "" : "?limit=#{Integer(limit)}"))
385
+ r.is_a?(Hash) ? (r["entries"] || []) : []
386
+ end
387
+
388
+ # Replace its labels (nil or {} clears them); returns the new labels.
389
+ def set_labels(labels)
390
+ body = { "labels" => labels.nil? || labels.empty? ? nil : Cloud.check_labels(labels) }
391
+ r = @cloud.request("PUT", path("/labels"), body)
392
+ @info = @info.merge("labels" => r["labels"] || {}) if r.is_a?(Hash)
393
+ r.is_a?(Hash) ? (r["labels"] || {}) : {}
394
+ end
395
+ end
396
+
397
+ class CloudFiles
398
+ # A file of any size (no 8 MiB cap), as a binary String.
399
+ def download(path)
400
+ @cloud.request_bytes("GET", query("/files/raw", path), raw: true)
401
+ end
402
+
403
+ # Write +content+ to a file of any size; returns its info Hash.
404
+ def upload(path, content)
405
+ content = content.read if content.respond_to?(:read)
406
+ r = @cloud.request_bytes("PUT", query("/files/raw", path), data: content.to_s)
407
+ r.is_a?(Hash) ? (r["file"] || {}) : {}
408
+ end
409
+
410
+ # A presigned URL for one download (GET) or upload (PUT) of +path+,
411
+ # straight to the host (a Hash: "url", "method", "path", "expires_at").
412
+ def link(path, method: "GET", ttl_s: nil)
413
+ raise ArgumentError, "a path is required, e.g. /workspace/app.py" if path.nil? || path.to_s.empty?
414
+
415
+ m = method.to_s.upcase
416
+ raise ArgumentError, 'method must be "GET" or "PUT"' unless %w[GET PUT].include?(m)
417
+
418
+ body = { "path" => path.to_s, "method" => m }
419
+ body["ttl_s"] = ttl_s unless ttl_s.nil?
420
+ @cloud.request("POST", @sandbox.path("/files/link"), body)["link"]
421
+ end
422
+ end
423
+
424
+ # sandbox.previews: a port of the sandbox at its own https URL, private (a
425
+ # signed link) unless public.
426
+ class CloudPreviews
427
+ def initialize(cloud, sandbox)
428
+ @cloud = cloud
429
+ @sandbox = sandbox
430
+ end
431
+
432
+ def inspect
433
+ "#<Kosa8::CloudPreviews sandbox=#{@sandbox.id.inspect}>"
434
+ end
435
+
436
+ # Open +port+; returns the preview (a Hash: "url", "host", "token", ...).
437
+ def create(port, public: false, expires_in_s: nil, wake: nil, wake_per_hour: nil)
438
+ body = { "port" => check(port) }
439
+ body["public"] = true if public
440
+ body["expires_in_s"] = expires_in_s unless expires_in_s.nil?
441
+ body["wake"] = wake unless wake.nil?
442
+ body["wake_per_hour"] = wake_per_hour unless wake_per_hour.nil?
443
+ @cloud.request("POST", @sandbox.path("/previews"), body)["preview"]
444
+ end
445
+
446
+ # Its previews (without tokens).
447
+ def list
448
+ r = @cloud.request("GET", @sandbox.path("/previews"))
449
+ r.is_a?(Hash) ? (r["previews"] || []) : []
450
+ end
451
+
452
+ # A new signed link for a private preview.
453
+ def link(port, expires_in_s: nil)
454
+ body = {}
455
+ body["expires_in_s"] = expires_in_s unless expires_in_s.nil?
456
+ @cloud.request("POST", @sandbox.path("/previews/#{check(port)}/link"), body)["preview"]
457
+ end
458
+
459
+ # A new host name, so every old link stops working.
460
+ def rotate(port)
461
+ @cloud.request("POST", @sandbox.path("/previews/#{check(port)}/rotate"), {})["preview"]
462
+ end
463
+
464
+ def delete(port)
465
+ @cloud.request("DELETE", @sandbox.path("/previews/#{check(port)}"))
466
+ nil
467
+ end
468
+
469
+ private
470
+
471
+ def check(port)
472
+ return port if port.is_a?(Integer) && port.between?(1, 65_535)
473
+
474
+ raise ArgumentError, "a port is 1 to 65535"
475
+ end
476
+ end
477
+
478
+ # sandbox.schedules: commands run in the sandbox on a cron schedule (UTC).
479
+ class CloudSchedules
480
+ def initialize(cloud, sandbox)
481
+ @cloud = cloud
482
+ @sandbox = sandbox
483
+ end
484
+
485
+ def inspect
486
+ "#<Kosa8::CloudSchedules sandbox=#{@sandbox.id.inspect}>"
487
+ end
488
+
489
+ def create(cron:, cmd:, env: nil, name: nil, wake: nil)
490
+ argv = cmd.is_a?(String) ? ["sh", "-c", cmd] : cmd.to_a
491
+ raise ArgumentError, "a schedule needs cron: and cmd:" if cron.to_s.empty? || argv.empty?
492
+
493
+ body = { "cron" => cron.to_s, "cmd" => argv }
494
+ body["env"] = Cloud.env_list(env) if env && !env.empty?
495
+ body["name"] = name.to_s unless name.nil?
496
+ body["wake"] = wake unless wake.nil?
497
+ @cloud.request("POST", @sandbox.path("/schedules"), body)["schedule"]
498
+ end
499
+
500
+ def list
501
+ r = @cloud.request("GET", @sandbox.path("/schedules"))
502
+ r.is_a?(Hash) ? (r["schedules"] || []) : []
503
+ end
504
+
505
+ def delete(id)
506
+ @cloud.request("DELETE", @sandbox.path("/schedules/#{Kosa8.enc(id)}"))
507
+ nil
508
+ end
509
+
510
+ # Run it now; returns the run ("status", "exit", "output", ...).
511
+ def run(id)
512
+ @cloud.request("POST", @sandbox.path("/schedules/#{Kosa8.enc(id)}/run"), {})["run"]
513
+ end
514
+ end
515
+
516
+ # cloud.snapshots: the org's durable snapshots.
517
+ class CloudSnapshots
518
+ def initialize(cloud)
519
+ @cloud = cloud
520
+ end
521
+
522
+ def inspect
523
+ "#<Kosa8::CloudSnapshots>"
524
+ end
525
+
526
+ # Newest first; sandbox_id: only one sandbox's.
527
+ def list(sandbox_id: nil)
528
+ q = sandbox_id.nil? ? "" : "?#{URI.encode_www_form([['sandbox_id', sandbox_id.to_s]])}"
529
+ r = @cloud.request("GET", "/v1/snapshots#{q}")
530
+ r.is_a?(Hash) ? (r["snapshots"] || []) : []
531
+ end
532
+
533
+ def get(id)
534
+ @cloud.request("GET", "/v1/snapshots/#{Kosa8.enc(id)}")["snapshot"]
535
+ end
536
+
537
+ def delete(id)
538
+ @cloud.request("DELETE", "/v1/snapshots/#{Kosa8.enc(id)}")
539
+ nil
540
+ end
541
+ end
542
+
543
+ # cloud.secrets: the org's secrets. A sandbox created with secrets: holds
544
+ # only a placeholder; its egress broker adds the value on the way out.
545
+ class CloudSecrets
546
+ def initialize(cloud)
547
+ @cloud = cloud
548
+ end
549
+
550
+ def inspect
551
+ "#<Kosa8::CloudSecrets>"
552
+ end
553
+
554
+ # Store (or replace) a secret. +value+ is never logged or returned; read
555
+ # it from a file or $stdin, not from code. pipelines: true lets Pipelines
556
+ # runs use it. Returns the secret (without its value).
557
+ def set(name, value:, upstream: nil, header: nil, scheme: nil, methods: nil, paths: nil, env: nil,
558
+ pipelines: false)
559
+ raise ArgumentError, "a secret needs a value" if value.nil? || value.to_s.empty?
560
+
561
+ body = { "value" => value.to_s }
562
+ body["upstream"] = upstream.to_s unless upstream.nil?
563
+ body["header"] = header.to_s unless header.nil?
564
+ body["scheme"] = scheme.to_s unless scheme.nil?
565
+ body["methods"] = methods.to_a unless methods.nil?
566
+ body["paths"] = paths.to_a unless paths.nil?
567
+ body["env"] = env.to_h unless env.nil?
568
+ body["pipelines"] = true if pipelines
569
+ @cloud.request("PUT", "/v1/secrets/#{Kosa8.enc(Cloud.check_secret_name(name))}", body)["secret"]
570
+ end
571
+
572
+ def list
573
+ r = @cloud.request("GET", "/v1/secrets")
574
+ r.is_a?(Hash) ? (r["secrets"] || []) : []
575
+ end
576
+
577
+ # Delete it; returns the ids of sandboxes still holding it.
578
+ def delete(name)
579
+ r = @cloud.request("DELETE", "/v1/secrets/#{Kosa8.enc(Cloud.check_secret_name(name))}")
580
+ r.is_a?(Hash) ? (r["still_held_by"] || []) : []
581
+ end
582
+ end
583
+
584
+ # cloud.pipelines: kosa8 Pipelines, CI on kosa8 Cloud.
585
+ #
586
+ # run = cloud.pipelines.run(repo_url: "https://github.com/me/app", ref: "main")
587
+ # run = cloud.pipelines.wait(run["id"])
588
+ # run["state"] # => "success"
589
+ class CloudPipelines
590
+ def initialize(cloud)
591
+ @cloud = cloud
592
+ end
593
+
594
+ def inspect
595
+ "#<Kosa8::CloudPipelines>"
596
+ end
597
+
598
+ # Start a run of the repository's .kosa8/pipeline.yml (or its
599
+ # .github/workflows through act). secrets: names secrets marked
600
+ # pipelines: true.
601
+ def run(repo_url:, ref: nil, event: nil, workflow: nil, job: nil, inputs: nil, size: nil, secrets: nil,
602
+ token_secret: nil, status_secret: nil, timeout_s: nil)
603
+ raise ArgumentError, "a run needs repo_url:" if repo_url.to_s.empty?
604
+
605
+ body = { "repo_url" => repo_url.to_s }
606
+ { "ref" => ref, "event" => event, "workflow" => workflow, "job" => job, "size" => size,
607
+ "token_secret" => token_secret, "status_secret" => status_secret }.each { |k, v| body[k] = v.to_s unless v.nil? }
608
+ body["inputs"] = inputs.to_h unless inputs.nil?
609
+ body["secrets"] = secrets.to_a unless secrets.nil?
610
+ body["timeout_s"] = timeout_s unless timeout_s.nil?
611
+ @cloud.request("POST", "/v1/pipelines/runs", body)["run"]
612
+ end
613
+
614
+ # Runs, newest first.
615
+ def runs(state: nil, limit: nil)
616
+ q = []
617
+ q << ["state", state.to_s] unless state.nil?
618
+ q << ["limit", Integer(limit).to_s] unless limit.nil?
619
+ r = @cloud.request("GET", "/v1/pipelines/runs" + (q.empty? ? "" : "?#{URI.encode_www_form(q)}"))
620
+ r.is_a?(Hash) ? (r["runs"] || []) : []
621
+ end
622
+
623
+ def get(id)
624
+ @cloud.request("GET", run_path(id))["run"]
625
+ end
626
+
627
+ # Poll a run until it finishes; returns it.
628
+ def wait(id, timeout: 6 * 3600, poll_interval: 5)
629
+ deadline = Time.now + timeout
630
+ loop do
631
+ r = get(id)
632
+ return r if Cloud::FINISHED_RUN_STATES.include?(r["state"])
633
+ raise TimeoutError, "pipeline run #{id} was still #{r['state']} after #{timeout} s" if Time.now > deadline
634
+
635
+ Kernel.sleep(poll_interval)
636
+ end
637
+ end
638
+
639
+ # Its logs by job ("logs": [{"job", "text", "next", ...}], "done"),
640
+ # secrets replaced with ***. after: a previous answer's "next" reads only
641
+ # newer text.
642
+ def logs(id, job: nil, after: nil)
643
+ q = []
644
+ q << ["job", job.to_s] unless job.nil?
645
+ q << ["after", Integer(after).to_s] unless after.nil?
646
+ @cloud.request("GET", run_path(id, "/logs") + (q.empty? ? "" : "?#{URI.encode_www_form(q)}"))
647
+ end
648
+
649
+ def cancel(id)
650
+ @cloud.request("POST", run_path(id, "/cancel"), {})["run"]
651
+ end
652
+
653
+ def artifacts(id)
654
+ r = @cloud.request("GET", run_path(id, "/artifacts"))
655
+ r.is_a?(Hash) ? (r["artifacts"] || []) : []
656
+ end
657
+
658
+ # One artifact's bytes (a .tar.gz), as a binary String.
659
+ def download_artifact(id, job, idx)
660
+ @cloud.request_bytes("GET", run_path(id, "/artifacts/#{Kosa8.enc(job)}/#{Integer(idx)}"), raw: true)
661
+ end
662
+
663
+ # A webhook URL for a repository's pushes and pull requests, and with
664
+ # cron: a schedule. The answer's "secret" is shown only now: give it and
665
+ # "url" to the git host.
666
+ def create_hook(repo_url:, provider: nil, name: nil, secret: nil, size: nil, secrets: nil, token_secret: nil,
667
+ status_secret: nil, workflow: nil, timeout_s: nil, cron: nil, cron_ref: nil)
668
+ raise ArgumentError, "a hook needs repo_url:" if repo_url.to_s.empty?
669
+
670
+ body = { "repo_url" => repo_url.to_s }
671
+ { "provider" => provider, "name" => name, "secret" => secret, "size" => size, "token_secret" => token_secret,
672
+ "status_secret" => status_secret, "workflow" => workflow, "cron" => cron,
673
+ "cron_ref" => cron_ref }.each { |k, v| body[k] = v.to_s unless v.nil? }
674
+ body["secrets"] = secrets.to_a unless secrets.nil?
675
+ body["timeout_s"] = timeout_s unless timeout_s.nil?
676
+ @cloud.request("POST", "/v1/pipelines/hooks", body)["hook"]
677
+ end
678
+
679
+ def hooks
680
+ r = @cloud.request("GET", "/v1/pipelines/hooks")
681
+ r.is_a?(Hash) ? (r["hooks"] || []) : []
682
+ end
683
+
684
+ def delete_hook(id)
685
+ @cloud.request("DELETE", "/v1/pipelines/hooks/#{Kosa8.enc(id)}")
686
+ nil
687
+ end
688
+
689
+ private
690
+
691
+ def run_path(id, suffix = "")
692
+ "/v1/pipelines/runs/#{Kosa8.enc(id)}#{suffix}"
693
+ end
694
+ end
695
+ end