kosa8 0.3.1 → 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.
@@ -0,0 +1,659 @@
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
+ # Bad arguments raise ArgumentError before any request.
109
+ def create(template: nil, region: nil, sleep_after_s: nil, ttl_s: nil, delete_after: nil, accept_price: nil,
110
+ size: nil, cpus: nil, mem_mb: nil, image: nil, disk_gb: nil, persistent: nil, docker: nil, cpu: nil,
111
+ name: nil, labels: nil, env: nil, secrets: nil, egress: nil, snapshot: nil, wait: true,
112
+ poll_interval: 1)
113
+ Cloud.check_lifetime(ttl_s, delete_after)
114
+ Cloud.check_sleep_after(sleep_after_s)
115
+ if !accept_price.nil? && !accept_price.is_a?(Numeric)
116
+ raise ArgumentError, "accept_price must be a number (USD)"
117
+ end
118
+
119
+ body = {}
120
+ body["template"] = template unless template.nil?
121
+ body["region"] = region unless region.nil?
122
+ body["sleep_after_s"] = sleep_after_s unless sleep_after_s.nil?
123
+ body["ttl_s"] = ttl_s unless ttl_s.nil?
124
+ body["delete_after"] = delete_after unless delete_after.nil?
125
+ body["accept_price"] = accept_price unless accept_price.nil?
126
+ sized(body, size, cpus, mem_mb, image, disk_gb, persistent, docker, cpu)
127
+ unless name.nil?
128
+ raise ArgumentError, "name: 1 to 64 of letters, digits, '.', '_' or '-'" unless Cloud::SANDBOX_NAME.match?(name.to_s)
129
+
130
+ body["name"] = name.to_s
131
+ end
132
+ body["labels"] = Cloud.check_labels(labels) unless labels.nil?
133
+ body["env"] = Cloud.check_env(env) unless env.nil?
134
+ body["secrets"] = secrets.to_a.map { |n| Cloud.check_secret_name(n) } unless secrets.nil?
135
+ body["egress"] = Cloud.egress_body(egress) unless egress.nil?
136
+ unless snapshot.nil?
137
+ raise ArgumentError, "snapshot: is a snapshot id (snap_...)" unless Cloud::SNAPSHOT_ID.match?(snapshot.to_s)
138
+
139
+ clash = %w[template region size cpus image disk_gb persistent docker cpu] & body.keys
140
+ unless clash.empty?
141
+ raise ArgumentError, "a create from a snapshot takes the snapshot's #{clash.join(', ')}; give only env:, name:, labels:, a lifetime or sleep_after_s:"
142
+ end
143
+
144
+ body["snapshot"] = snapshot.to_s
145
+ end
146
+ box = CloudSandbox.new(@cloud, @cloud.request("POST", "/v1/sandboxes", body)["sandbox"])
147
+ box.wait_running(poll_interval: poll_interval) if wait && box.state == "creating"
148
+ box
149
+ end
150
+
151
+ # One page of sandboxes; name: finds one by name, labels: keeps those
152
+ # with every label ({"team" => "a"}; a nil value matches any value).
153
+ alias list_page_without_features list_page
154
+ def list_page(all: false, limit: nil, cursor: nil, name: nil, labels: nil)
155
+ return list_page_without_features(all: all, limit: limit, cursor: cursor) if name.nil? && labels.nil?
156
+
157
+ q = []
158
+ q << %w[all 1] if all
159
+ q << ["limit", Integer(limit).to_s] unless limit.nil?
160
+ q << ["cursor", cursor.to_s] if cursor && !cursor.to_s.empty?
161
+ q << ["name", name.to_s] unless name.nil?
162
+ (labels || {}).sort_by { |k, _| k.to_s }.each { |k, v| q << ["label", v.nil? ? k.to_s : "#{k}=#{v}"] }
163
+ r = @cloud.request("GET", "/v1/sandboxes?#{URI.encode_www_form(q)}")
164
+ r = {} unless r.is_a?(Hash)
165
+ nxt = r["next_cursor"]
166
+ CloudSandboxPage.new(sandboxes: (r["sandboxes"] || []).map { |s| CloudSandbox.new(@cloud, s) },
167
+ next_cursor: nxt.is_a?(String) && !nxt.empty? ? nxt : nil)
168
+ end
169
+
170
+ alias list_without_features list
171
+ def list(all: false, limit: nil, cursor: nil, name: nil, labels: nil)
172
+ list_page(all: all, limit: limit, cursor: cursor, name: name, labels: labels).sandboxes
173
+ end
174
+
175
+ private
176
+
177
+ def sized(body, size, cpus, mem_mb, image, disk_gb, persistent, docker, cpu)
178
+ unless size.nil?
179
+ raise ArgumentError, "size must be one of #{Cloud::SIZES.join(', ')}" unless Cloud::SIZES.include?(size.to_s)
180
+
181
+ body["size"] = size.to_s
182
+ end
183
+ raise ArgumentError, "give cpus: and mem_mb: together" if cpus.nil? != mem_mb.nil?
184
+
185
+ unless cpus.nil?
186
+ raise ArgumentError, "give size: or cpus: and mem_mb:, not both" unless size.nil?
187
+
188
+ body["cpus"] = Integer(cpus)
189
+ body["mem_mb"] = Integer(mem_mb)
190
+ end
191
+ body["image"] = image.to_s unless image.nil?
192
+ unless disk_gb.nil?
193
+ raise ArgumentError, "disk_gb must be 8 to 200" unless disk_gb.is_a?(Integer) && disk_gb.between?(8, 200)
194
+
195
+ body["disk_gb"] = disk_gb
196
+ end
197
+ body["persistent"] = persistent == true unless persistent.nil?
198
+ body["docker"] = docker == true unless docker.nil?
199
+ return if cpu.nil?
200
+ raise ArgumentError, 'cpu must be "shared" or "dedicated"' unless %w[shared dedicated].include?(cpu.to_s)
201
+
202
+ body["cpu"] = cpu.to_s
203
+ end
204
+ end
205
+
206
+ class CloudSandbox
207
+ # Poll until it is no longer "creating" (a sized create boots cold);
208
+ # raises Kosa8::Error if it ends in any state but running.
209
+ def wait_running(timeout: 600, poll_interval: 1)
210
+ deadline = Time.now + timeout
211
+ while state == "creating"
212
+ raise TimeoutError, "sandbox #{id} was still creating after #{timeout} s" if Time.now > deadline
213
+
214
+ Kernel.sleep(poll_interval)
215
+ refresh
216
+ end
217
+ return self if state == "running"
218
+
219
+ raise Error, "sandbox #{id} is #{state}, not running#{@info['last_error'] ? ": #{@info['last_error']}" : ''}"
220
+ end
221
+
222
+ # Start a command that keeps running after this returns (no 30 s
223
+ # limit). Returns the background command (a Hash: "id" (bg_...),
224
+ # "state", "pid", "output_path", ...); poll it with #background_exec or
225
+ # #wait_background.
226
+ def exec_background(cmd, image: nil, env: nil)
227
+ argv = cmd.is_a?(String) ? ["sh", "-c", cmd] : cmd.to_a
228
+ raise ArgumentError, "exec_background needs a command" if argv.empty?
229
+
230
+ body = { "cmd" => argv, "background" => true }
231
+ body["image"] = image unless image.nil?
232
+ body["env"] = Cloud.env_list(env) if env && !env.empty?
233
+ @cloud.request("POST", path("/exec"), body)["exec"]
234
+ end
235
+
236
+ # A background command: "state" ("running" or "exited"), "exit" and the
237
+ # "output" so far.
238
+ def background_exec(exec_id)
239
+ raise ArgumentError, "background_exec needs an exec id (bg_...)" if exec_id.nil? || exec_id.to_s.empty?
240
+
241
+ @cloud.request("GET", path("/exec/#{Kosa8.enc(exec_id)}"))["exec"]
242
+ end
243
+
244
+ # Poll a background command until it exits; returns it.
245
+ def wait_background(exec_id, timeout: 3600, poll_interval: 2)
246
+ exec_id = exec_id["id"] if exec_id.is_a?(Hash)
247
+ deadline = Time.now + timeout
248
+ loop do
249
+ e = background_exec(exec_id)
250
+ return e if e["state"] == "exited" || !e["exit"].nil?
251
+ raise TimeoutError, "background command #{exec_id} was still running after #{timeout} s" if Time.now > deadline
252
+
253
+ Kernel.sleep(poll_interval)
254
+ end
255
+ end
256
+
257
+ # Save it as a durable snapshot (kept until deleted, whatever happens to
258
+ # the sandbox) and return it (a Hash: "id" (snap_...), "state", "bytes",
259
+ # ...). Start new sandboxes from it with create(snapshot: id).
260
+ def snapshot(name = nil)
261
+ body = {}
262
+ body["name"] = name.to_s unless name.nil?
263
+ @cloud.request("POST", path("/snapshots"), body)["snapshot"]
264
+ end
265
+
266
+ # Its previews: a CloudPreviews (ports at https URLs).
267
+ def previews
268
+ CloudPreviews.new(@cloud, self)
269
+ end
270
+
271
+ # A short-lived wss:// URL for an interactive terminal (a Hash: "url",
272
+ # "expires_at", "protocol"). The URL carries its token: keep it secret.
273
+ def terminal(cols: nil, rows: nil, command: nil)
274
+ body = {}
275
+ body["cols"] = cols unless cols.nil?
276
+ body["rows"] = rows unless rows.nil?
277
+ body["command"] = command.to_a unless command.nil?
278
+ @cloud.request("POST", path("/terminal"), body)["terminal"]
279
+ end
280
+
281
+ # The egress policy it runs with ("internet", "allow", "deny", "presets", "source").
282
+ def egress
283
+ @cloud.request("GET", path("/egress"))["egress"]
284
+ end
285
+
286
+ # Change what it may reach, at once: internet:, allow:, deny:, presets:.
287
+ def set_egress(internet: false, allow: [], deny: [], presets: [])
288
+ body = Cloud.egress_body(internet: internet, allow: allow, deny: deny, presets: presets)
289
+ @cloud.request("PUT", path("/egress"), body)["egress"]
290
+ end
291
+
292
+ # Back to the organization's default egress policy.
293
+ def reset_egress
294
+ @cloud.request("DELETE", path("/egress"))["egress"]
295
+ end
296
+
297
+ # The names of the secrets it holds.
298
+ def secrets
299
+ r = @cloud.request("GET", path("/secrets"))
300
+ r.is_a?(Hash) ? (r["secrets"] || []) : []
301
+ end
302
+
303
+ # Its schedules: a CloudSchedules.
304
+ def schedules
305
+ CloudSchedules.new(@cloud, self)
306
+ end
307
+
308
+ # Run a Python cell in a stateful context (globals persist; charts come
309
+ # back as images in "results"). A cell that raised has "error" set; it
310
+ # is not an exception. Needs a persistent sandbox with python3.
311
+ def run_code(code, context: nil, timeout_s: nil)
312
+ raise ArgumentError, "run_code needs code" if code.nil? || code.to_s.empty?
313
+
314
+ body = { "code" => code.to_s, "language" => "python" }
315
+ body["context"] = context.to_s unless context.nil?
316
+ body["timeout_s"] = timeout_s unless timeout_s.nil?
317
+ @cloud.request("POST", path("/code"), body)
318
+ end
319
+
320
+ def code_contexts
321
+ r = @cloud.request("GET", path("/code/contexts"))
322
+ r.is_a?(Hash) ? (r["contexts"] || []) : []
323
+ end
324
+
325
+ def create_code_context(name = nil)
326
+ body = {}
327
+ body["name"] = name.to_s unless name.nil?
328
+ @cloud.request("POST", path("/code/contexts"), body)["context"]
329
+ end
330
+
331
+ def reset_code_context(name)
332
+ @cloud.request("POST", path("/code/contexts/#{Kosa8.enc(name)}/reset"), {})
333
+ nil
334
+ end
335
+
336
+ def delete_code_context(name)
337
+ @cloud.request("DELETE", path("/code/contexts/#{Kosa8.enc(name)}"))
338
+ nil
339
+ end
340
+
341
+ # CPU, memory, disk and network use, read on the host.
342
+ def metrics
343
+ @cloud.request("GET", path("/metrics"))["metrics"]
344
+ end
345
+
346
+ # Its last commands, with exit codes and output tails.
347
+ def logs(limit: nil)
348
+ r = @cloud.request("GET", path("/logs") + (limit.nil? ? "" : "?limit=#{Integer(limit)}"))
349
+ r.is_a?(Hash) ? (r["entries"] || []) : []
350
+ end
351
+
352
+ # Replace its labels (nil or {} clears them); returns the new labels.
353
+ def set_labels(labels)
354
+ body = { "labels" => labels.nil? || labels.empty? ? nil : Cloud.check_labels(labels) }
355
+ r = @cloud.request("PUT", path("/labels"), body)
356
+ @info = @info.merge("labels" => r["labels"] || {}) if r.is_a?(Hash)
357
+ r.is_a?(Hash) ? (r["labels"] || {}) : {}
358
+ end
359
+ end
360
+
361
+ class CloudFiles
362
+ # A file of any size (no 8 MiB cap), as a binary String.
363
+ def download(path)
364
+ @cloud.request_bytes("GET", query("/files/raw", path), raw: true)
365
+ end
366
+
367
+ # Write +content+ to a file of any size; returns its info Hash.
368
+ def upload(path, content)
369
+ content = content.read if content.respond_to?(:read)
370
+ r = @cloud.request_bytes("PUT", query("/files/raw", path), data: content.to_s)
371
+ r.is_a?(Hash) ? (r["file"] || {}) : {}
372
+ end
373
+
374
+ # A presigned URL for one download (GET) or upload (PUT) of +path+,
375
+ # straight to the host (a Hash: "url", "method", "path", "expires_at").
376
+ def link(path, method: "GET", ttl_s: nil)
377
+ raise ArgumentError, "a path is required, e.g. /workspace/app.py" if path.nil? || path.to_s.empty?
378
+
379
+ m = method.to_s.upcase
380
+ raise ArgumentError, 'method must be "GET" or "PUT"' unless %w[GET PUT].include?(m)
381
+
382
+ body = { "path" => path.to_s, "method" => m }
383
+ body["ttl_s"] = ttl_s unless ttl_s.nil?
384
+ @cloud.request("POST", @sandbox.path("/files/link"), body)["link"]
385
+ end
386
+ end
387
+
388
+ # sandbox.previews: a port of the sandbox at its own https URL, private (a
389
+ # signed link) unless public.
390
+ class CloudPreviews
391
+ def initialize(cloud, sandbox)
392
+ @cloud = cloud
393
+ @sandbox = sandbox
394
+ end
395
+
396
+ def inspect
397
+ "#<Kosa8::CloudPreviews sandbox=#{@sandbox.id.inspect}>"
398
+ end
399
+
400
+ # Open +port+; returns the preview (a Hash: "url", "host", "token", ...).
401
+ def create(port, public: false, expires_in_s: nil, wake: nil, wake_per_hour: nil)
402
+ body = { "port" => check(port) }
403
+ body["public"] = true if public
404
+ body["expires_in_s"] = expires_in_s unless expires_in_s.nil?
405
+ body["wake"] = wake unless wake.nil?
406
+ body["wake_per_hour"] = wake_per_hour unless wake_per_hour.nil?
407
+ @cloud.request("POST", @sandbox.path("/previews"), body)["preview"]
408
+ end
409
+
410
+ # Its previews (without tokens).
411
+ def list
412
+ r = @cloud.request("GET", @sandbox.path("/previews"))
413
+ r.is_a?(Hash) ? (r["previews"] || []) : []
414
+ end
415
+
416
+ # A new signed link for a private preview.
417
+ def link(port, expires_in_s: nil)
418
+ body = {}
419
+ body["expires_in_s"] = expires_in_s unless expires_in_s.nil?
420
+ @cloud.request("POST", @sandbox.path("/previews/#{check(port)}/link"), body)["preview"]
421
+ end
422
+
423
+ # A new host name, so every old link stops working.
424
+ def rotate(port)
425
+ @cloud.request("POST", @sandbox.path("/previews/#{check(port)}/rotate"), {})["preview"]
426
+ end
427
+
428
+ def delete(port)
429
+ @cloud.request("DELETE", @sandbox.path("/previews/#{check(port)}"))
430
+ nil
431
+ end
432
+
433
+ private
434
+
435
+ def check(port)
436
+ return port if port.is_a?(Integer) && port.between?(1, 65_535)
437
+
438
+ raise ArgumentError, "a port is 1 to 65535"
439
+ end
440
+ end
441
+
442
+ # sandbox.schedules: commands run in the sandbox on a cron schedule (UTC).
443
+ class CloudSchedules
444
+ def initialize(cloud, sandbox)
445
+ @cloud = cloud
446
+ @sandbox = sandbox
447
+ end
448
+
449
+ def inspect
450
+ "#<Kosa8::CloudSchedules sandbox=#{@sandbox.id.inspect}>"
451
+ end
452
+
453
+ def create(cron:, cmd:, env: nil, name: nil, wake: nil)
454
+ argv = cmd.is_a?(String) ? ["sh", "-c", cmd] : cmd.to_a
455
+ raise ArgumentError, "a schedule needs cron: and cmd:" if cron.to_s.empty? || argv.empty?
456
+
457
+ body = { "cron" => cron.to_s, "cmd" => argv }
458
+ body["env"] = Cloud.env_list(env) if env && !env.empty?
459
+ body["name"] = name.to_s unless name.nil?
460
+ body["wake"] = wake unless wake.nil?
461
+ @cloud.request("POST", @sandbox.path("/schedules"), body)["schedule"]
462
+ end
463
+
464
+ def list
465
+ r = @cloud.request("GET", @sandbox.path("/schedules"))
466
+ r.is_a?(Hash) ? (r["schedules"] || []) : []
467
+ end
468
+
469
+ def delete(id)
470
+ @cloud.request("DELETE", @sandbox.path("/schedules/#{Kosa8.enc(id)}"))
471
+ nil
472
+ end
473
+
474
+ # Run it now; returns the run ("status", "exit", "output", ...).
475
+ def run(id)
476
+ @cloud.request("POST", @sandbox.path("/schedules/#{Kosa8.enc(id)}/run"), {})["run"]
477
+ end
478
+ end
479
+
480
+ # cloud.snapshots: the org's durable snapshots.
481
+ class CloudSnapshots
482
+ def initialize(cloud)
483
+ @cloud = cloud
484
+ end
485
+
486
+ def inspect
487
+ "#<Kosa8::CloudSnapshots>"
488
+ end
489
+
490
+ # Newest first; sandbox_id: only one sandbox's.
491
+ def list(sandbox_id: nil)
492
+ q = sandbox_id.nil? ? "" : "?#{URI.encode_www_form([['sandbox_id', sandbox_id.to_s]])}"
493
+ r = @cloud.request("GET", "/v1/snapshots#{q}")
494
+ r.is_a?(Hash) ? (r["snapshots"] || []) : []
495
+ end
496
+
497
+ def get(id)
498
+ @cloud.request("GET", "/v1/snapshots/#{Kosa8.enc(id)}")["snapshot"]
499
+ end
500
+
501
+ def delete(id)
502
+ @cloud.request("DELETE", "/v1/snapshots/#{Kosa8.enc(id)}")
503
+ nil
504
+ end
505
+ end
506
+
507
+ # cloud.secrets: the org's secrets. A sandbox created with secrets: holds
508
+ # only a placeholder; its egress broker adds the value on the way out.
509
+ class CloudSecrets
510
+ def initialize(cloud)
511
+ @cloud = cloud
512
+ end
513
+
514
+ def inspect
515
+ "#<Kosa8::CloudSecrets>"
516
+ end
517
+
518
+ # Store (or replace) a secret. +value+ is never logged or returned; read
519
+ # it from a file or $stdin, not from code. pipelines: true lets Pipelines
520
+ # runs use it. Returns the secret (without its value).
521
+ def set(name, value:, upstream: nil, header: nil, scheme: nil, methods: nil, paths: nil, env: nil,
522
+ pipelines: false)
523
+ raise ArgumentError, "a secret needs a value" if value.nil? || value.to_s.empty?
524
+
525
+ body = { "value" => value.to_s }
526
+ body["upstream"] = upstream.to_s unless upstream.nil?
527
+ body["header"] = header.to_s unless header.nil?
528
+ body["scheme"] = scheme.to_s unless scheme.nil?
529
+ body["methods"] = methods.to_a unless methods.nil?
530
+ body["paths"] = paths.to_a unless paths.nil?
531
+ body["env"] = env.to_h unless env.nil?
532
+ body["pipelines"] = true if pipelines
533
+ @cloud.request("PUT", "/v1/secrets/#{Kosa8.enc(Cloud.check_secret_name(name))}", body)["secret"]
534
+ end
535
+
536
+ def list
537
+ r = @cloud.request("GET", "/v1/secrets")
538
+ r.is_a?(Hash) ? (r["secrets"] || []) : []
539
+ end
540
+
541
+ # Delete it; returns the ids of sandboxes still holding it.
542
+ def delete(name)
543
+ r = @cloud.request("DELETE", "/v1/secrets/#{Kosa8.enc(Cloud.check_secret_name(name))}")
544
+ r.is_a?(Hash) ? (r["still_held_by"] || []) : []
545
+ end
546
+ end
547
+
548
+ # cloud.pipelines: kosa8 Pipelines, CI on kosa8 Cloud.
549
+ #
550
+ # run = cloud.pipelines.run(repo_url: "https://github.com/me/app", ref: "main")
551
+ # run = cloud.pipelines.wait(run["id"])
552
+ # run["state"] # => "success"
553
+ class CloudPipelines
554
+ def initialize(cloud)
555
+ @cloud = cloud
556
+ end
557
+
558
+ def inspect
559
+ "#<Kosa8::CloudPipelines>"
560
+ end
561
+
562
+ # Start a run of the repository's .kosa8/pipeline.yml (or its
563
+ # .github/workflows through act). secrets: names secrets marked
564
+ # pipelines: true.
565
+ def run(repo_url:, ref: nil, event: nil, workflow: nil, job: nil, inputs: nil, size: nil, secrets: nil,
566
+ token_secret: nil, status_secret: nil, timeout_s: nil)
567
+ raise ArgumentError, "a run needs repo_url:" if repo_url.to_s.empty?
568
+
569
+ body = { "repo_url" => repo_url.to_s }
570
+ { "ref" => ref, "event" => event, "workflow" => workflow, "job" => job, "size" => size,
571
+ "token_secret" => token_secret, "status_secret" => status_secret }.each { |k, v| body[k] = v.to_s unless v.nil? }
572
+ body["inputs"] = inputs.to_h unless inputs.nil?
573
+ body["secrets"] = secrets.to_a unless secrets.nil?
574
+ body["timeout_s"] = timeout_s unless timeout_s.nil?
575
+ @cloud.request("POST", "/v1/pipelines/runs", body)["run"]
576
+ end
577
+
578
+ # Runs, newest first.
579
+ def runs(state: nil, limit: nil)
580
+ q = []
581
+ q << ["state", state.to_s] unless state.nil?
582
+ q << ["limit", Integer(limit).to_s] unless limit.nil?
583
+ r = @cloud.request("GET", "/v1/pipelines/runs" + (q.empty? ? "" : "?#{URI.encode_www_form(q)}"))
584
+ r.is_a?(Hash) ? (r["runs"] || []) : []
585
+ end
586
+
587
+ def get(id)
588
+ @cloud.request("GET", run_path(id))["run"]
589
+ end
590
+
591
+ # Poll a run until it finishes; returns it.
592
+ def wait(id, timeout: 6 * 3600, poll_interval: 5)
593
+ deadline = Time.now + timeout
594
+ loop do
595
+ r = get(id)
596
+ return r if Cloud::FINISHED_RUN_STATES.include?(r["state"])
597
+ raise TimeoutError, "pipeline run #{id} was still #{r['state']} after #{timeout} s" if Time.now > deadline
598
+
599
+ Kernel.sleep(poll_interval)
600
+ end
601
+ end
602
+
603
+ # Its logs by job ("logs": [{"job", "text", "next", ...}], "done"),
604
+ # secrets replaced with ***. after: a previous answer's "next" reads only
605
+ # newer text.
606
+ def logs(id, job: nil, after: nil)
607
+ q = []
608
+ q << ["job", job.to_s] unless job.nil?
609
+ q << ["after", Integer(after).to_s] unless after.nil?
610
+ @cloud.request("GET", run_path(id, "/logs") + (q.empty? ? "" : "?#{URI.encode_www_form(q)}"))
611
+ end
612
+
613
+ def cancel(id)
614
+ @cloud.request("POST", run_path(id, "/cancel"), {})["run"]
615
+ end
616
+
617
+ def artifacts(id)
618
+ r = @cloud.request("GET", run_path(id, "/artifacts"))
619
+ r.is_a?(Hash) ? (r["artifacts"] || []) : []
620
+ end
621
+
622
+ # One artifact's bytes (a .tar.gz), as a binary String.
623
+ def download_artifact(id, job, idx)
624
+ @cloud.request_bytes("GET", run_path(id, "/artifacts/#{Kosa8.enc(job)}/#{Integer(idx)}"), raw: true)
625
+ end
626
+
627
+ # A webhook URL for a repository's pushes and pull requests, and with
628
+ # cron: a schedule. The answer's "secret" is shown only now: give it and
629
+ # "url" to the git host.
630
+ def create_hook(repo_url:, provider: nil, name: nil, secret: nil, size: nil, secrets: nil, token_secret: nil,
631
+ status_secret: nil, workflow: nil, timeout_s: nil, cron: nil, cron_ref: nil)
632
+ raise ArgumentError, "a hook needs repo_url:" if repo_url.to_s.empty?
633
+
634
+ body = { "repo_url" => repo_url.to_s }
635
+ { "provider" => provider, "name" => name, "secret" => secret, "size" => size, "token_secret" => token_secret,
636
+ "status_secret" => status_secret, "workflow" => workflow, "cron" => cron,
637
+ "cron_ref" => cron_ref }.each { |k, v| body[k] = v.to_s unless v.nil? }
638
+ body["secrets"] = secrets.to_a unless secrets.nil?
639
+ body["timeout_s"] = timeout_s unless timeout_s.nil?
640
+ @cloud.request("POST", "/v1/pipelines/hooks", body)["hook"]
641
+ end
642
+
643
+ def hooks
644
+ r = @cloud.request("GET", "/v1/pipelines/hooks")
645
+ r.is_a?(Hash) ? (r["hooks"] || []) : []
646
+ end
647
+
648
+ def delete_hook(id)
649
+ @cloud.request("DELETE", "/v1/pipelines/hooks/#{Kosa8.enc(id)}")
650
+ nil
651
+ end
652
+
653
+ private
654
+
655
+ def run_path(id, suffix = "")
656
+ "/v1/pipelines/runs/#{Kosa8.enc(id)}#{suffix}"
657
+ end
658
+ end
659
+ end