kosa8 0.5.3 → 0.7.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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +246 -0
- data/README.md +101 -25
- data/lib/kosa8/cloud.rb +149 -32
- data/lib/kosa8/cloud_features.rb +99 -28
- data/lib/kosa8/cloud_more.rb +1012 -0
- data/lib/kosa8/cloud_rl.rb +4 -4
- data/lib/kosa8/cloud_stream.rb +329 -0
- data/lib/kosa8/errors.rb +101 -16
- data/lib/kosa8/rl.rb +16 -9
- data/lib/kosa8/toolbox.rb +2 -1
- data/lib/kosa8/version.rb +1 -1
- data/lib/kosa8.rb +2 -0
- metadata +14 -6
data/lib/kosa8/cloud.rb
CHANGED
|
@@ -13,7 +13,12 @@ module Kosa8
|
|
|
13
13
|
# and woke for this command.
|
|
14
14
|
# +failure_class+ is "ok" (exit 0), "exit_nonzero" (the command failed) or
|
|
15
15
|
# "infra" (the host gave no exit code; +retryable+ true).
|
|
16
|
+
# A buffered exec keeps the first and last 1 MiB of each stream:
|
|
17
|
+
# +stdout_truncated+ / +stderr_truncated+ are true when the middle was
|
|
18
|
+
# dropped, and +stdout_bytes+ / +stderr_bytes+ count what the command
|
|
19
|
+
# wrote, kept or not (nil when the server did not say).
|
|
16
20
|
CloudExecResult = Struct.new(:exit_code, :stdout, :stderr, :woke_ms, :failure_class, :retryable,
|
|
21
|
+
:stdout_truncated, :stderr_truncated, :stdout_bytes, :stderr_bytes,
|
|
17
22
|
keyword_init: true) do
|
|
18
23
|
def ok?
|
|
19
24
|
exit_code == 0 # exit_code is nil when the command never ran
|
|
@@ -45,9 +50,10 @@ module Kosa8
|
|
|
45
50
|
# Errors are the SDK's usual typed errors; each carries the cloud's stable
|
|
46
51
|
# +code+ (for example payment_required, quota_exceeded). Standard library only.
|
|
47
52
|
#
|
|
48
|
-
# Each exec
|
|
49
|
-
#
|
|
50
|
-
#
|
|
53
|
+
# Each exec is a fresh process; files in /workspace persist for the
|
|
54
|
+
# sandbox's life; installed packages need persistent: true. A buffered
|
|
55
|
+
# exec runs at most 90 s (ExecTimeoutError), and a request body is at
|
|
56
|
+
# most 64 KiB.
|
|
51
57
|
class Cloud
|
|
52
58
|
DEFAULT_URL = "https://api.kosa8.com"
|
|
53
59
|
KEY_PREFIX = "k8c_live_"
|
|
@@ -86,9 +92,14 @@ module Kosa8
|
|
|
86
92
|
# retry_policy: (default RetryPolicy.new: 3 tries, backoff with full
|
|
87
93
|
# jitter) is applied where trying again is safe: reads, PUTs, deletes,
|
|
88
94
|
# heartbeats and drains on infra failures; the calls that make sandboxes
|
|
89
|
-
# (create, batch, fork, grade),
|
|
90
|
-
#
|
|
91
|
-
#
|
|
95
|
+
# (create, batch, fork, grade), job submits and rollout records, which
|
|
96
|
+
# carry an Idempotency-Key (the SDK's own is reused after no answer, a
|
|
97
|
+
# 429 or a 409, and renewed after a 5xx; yours is never changed); and
|
|
98
|
+
# any request the
|
|
99
|
+
# server refused before running it (429, 503 database_busy, 409
|
|
100
|
+
# template_building), waiting at least its Retry-After (or the body's
|
|
101
|
+
# retry_after / retry_after_s). An answer with retryable: false is never
|
|
102
|
+
# retried. RetryPolicy::NONE turns it off. sleeper: replaces
|
|
92
103
|
# Kernel#sleep for those waits (tests).
|
|
93
104
|
def initialize(api_key: nil, base_url: nil, env: ENV, timeout: 120, transport: nil, retry_policy: nil,
|
|
94
105
|
sleeper: nil)
|
|
@@ -137,8 +148,10 @@ module Kosa8
|
|
|
137
148
|
|
|
138
149
|
# One JSON request, retried as retry_policy allows; raises the typed
|
|
139
150
|
# error for an error answer. A call that makes sandboxes (Cloud.keyed?)
|
|
140
|
-
# sends +idempotency_key+ (a new UUID when not given),
|
|
141
|
-
#
|
|
151
|
+
# sends +idempotency_key+ (a new UUID when not given), so it may be
|
|
152
|
+
# retried after a timeout or a 5xx too. A given key goes unchanged with
|
|
153
|
+
# every retry; the SDK's own is kept after no answer, a 429 or a 409 and
|
|
154
|
+
# replaced after a 5xx (Cloud.renews_idempotency_key?).
|
|
142
155
|
#
|
|
143
156
|
# +opts+ (a Hash, not keywords, so an empty body Hash stays the body):
|
|
144
157
|
# :idempotency_key and :retry_policy.
|
|
@@ -149,17 +162,24 @@ module Kosa8
|
|
|
149
162
|
|
|
150
163
|
# One request whose body is +data+ (raw bytes, application/octet-stream)
|
|
151
164
|
# when given; with +raw+ a successful answer's bytes come back as a binary
|
|
152
|
-
# String instead of parsed JSON.
|
|
153
|
-
|
|
154
|
-
|
|
165
|
+
# String instead of parsed JSON. +headers+ are sent too (such as Range).
|
|
166
|
+
# Raises the typed error for an error answer.
|
|
167
|
+
def request_bytes(method, path, data: nil, raw: false, retry_policy: nil, headers: nil)
|
|
168
|
+
perform(method, path, nil, data, raw, nil, retry_policy, headers)
|
|
155
169
|
end
|
|
156
170
|
|
|
157
|
-
# Methods safe to send twice. Other POSTs are retried only
|
|
158
|
-
#
|
|
171
|
+
# Methods safe to send twice. Other POSTs are retried only when the
|
|
172
|
+
# server refused them before doing anything (PRE_EXECUTION_CODES, any
|
|
173
|
+
# 429), unless they carry an Idempotency-Key.
|
|
159
174
|
IDEMPOTENT_METHODS = %w[GET HEAD PUT DELETE].freeze
|
|
160
175
|
IDEMPOTENT_POSTS = %w[/v1/sandboxes/heartbeat /v1/sandboxes/drain].freeze
|
|
176
|
+
# Refusals made before the request ran, so any request may be sent again:
|
|
177
|
+
# 503 database_busy (the API's database was overloaded) and 409
|
|
178
|
+
# template_building (the environment is still being built). Both carry
|
|
179
|
+
# retryable: true and when to try again (retry_after / Retry-After).
|
|
180
|
+
PRE_EXECUTION_CODES = %w[database_busy template_building].freeze
|
|
161
181
|
# The POSTs kosa8 Cloud keeps an Idempotency-Key for (24 hours).
|
|
162
|
-
KEYED_POSTS = %r{\A/v1/sandboxes(/batch|/[A-Za-z0-9_%]{1,64}/(fork|grade))
|
|
182
|
+
KEYED_POSTS = %r{\A/v1/(sandboxes(/batch|/[A-Za-z0-9_%]{1,64}/(fork|grade))?|jobs|rl/runs/[A-Za-z0-9_%]{1,64}/rollouts)\z}.freeze
|
|
163
183
|
IDEMPOTENCY_KEY = /\A[\x21-\x7e]{1,255}\z/.freeze
|
|
164
184
|
|
|
165
185
|
# Whether kosa8 Cloud honours an Idempotency-Key on this call.
|
|
@@ -167,29 +187,57 @@ module Kosa8
|
|
|
167
187
|
method == "POST" && KEYED_POSTS.match?(path.to_s.split("?", 2)[0])
|
|
168
188
|
end
|
|
169
189
|
|
|
190
|
+
# Whether +e+ is a refusal made before the request ran (any 429, 503
|
|
191
|
+
# database_busy, 409 template_building), so even a POST may be resent.
|
|
192
|
+
def self.pre_execution?(e)
|
|
193
|
+
e.is_a?(Error) && (e.status == 429 || PRE_EXECUTION_CODES.include?(e.code))
|
|
194
|
+
end
|
|
195
|
+
|
|
196
|
+
# Whether a retry after +e+ gets a new SDK-made Idempotency-Key: only
|
|
197
|
+
# when kosa8 Cloud answered with a 5xx (502 host_failed, 503
|
|
198
|
+
# no_capacity, ...), so each retry of a server-side failure is a new
|
|
199
|
+
# attempt. No answer (a timeout or a dropped connection: the first try
|
|
200
|
+
# may still be running and may have made the sandbox), a 429 and a 409
|
|
201
|
+
# (idempotency_in_progress, template_building) keep the key.
|
|
202
|
+
def self.renews_idempotency_key?(e)
|
|
203
|
+
e.is_a?(Error) && e.status.is_a?(Integer) && e.status >= 500
|
|
204
|
+
end
|
|
205
|
+
|
|
206
|
+
# Whether +path+ is a file write with append= (not safe to send twice).
|
|
207
|
+
def self.append_write?(path)
|
|
208
|
+
q = path.to_s.split("?", 2)[1].to_s
|
|
209
|
+
URI.decode_www_form(q).any? { |k, v| k == "append" && %w[1 true].include?(v) }
|
|
210
|
+
rescue ArgumentError
|
|
211
|
+
false
|
|
212
|
+
end
|
|
213
|
+
|
|
170
214
|
def self.check_idempotency_key(key)
|
|
171
215
|
return if key.nil? || (key.is_a?(String) && IDEMPOTENCY_KEY.match?(key))
|
|
172
216
|
|
|
173
217
|
raise ArgumentError, "idempotency_key must be 1-255 printable ASCII characters, e.g. a UUID"
|
|
174
218
|
end
|
|
175
219
|
|
|
176
|
-
private def perform(method, path, body, data, raw, idempotency_key, policy)
|
|
220
|
+
private def perform(method, path, body, data, raw, idempotency_key, policy, headers = nil)
|
|
177
221
|
Cloud.check_idempotency_key(idempotency_key)
|
|
178
|
-
extra = {}
|
|
179
|
-
|
|
222
|
+
extra = (headers || {}).map { |k, v| [k.to_s, v.to_s] }.to_h
|
|
223
|
+
own_key = idempotency_key.nil? && Cloud.keyed?(method, path)
|
|
224
|
+
if !idempotency_key.nil? || own_key
|
|
180
225
|
extra["Idempotency-Key"] = idempotency_key || SecureRandom.uuid
|
|
181
226
|
end
|
|
182
227
|
policy ||= @retry_policy
|
|
183
228
|
bare = path.to_s.split("?", 2)[0]
|
|
184
|
-
safe =
|
|
229
|
+
safe = extra.key?("Idempotency-Key") || IDEMPOTENT_METHODS.include?(method) || IDEMPOTENT_POSTS.include?(bare)
|
|
230
|
+
# An append adds the body again if sent twice: retried only when refused before it ran.
|
|
231
|
+
safe = false if method == "PUT" && Cloud.append_write?(path)
|
|
185
232
|
attempt = 1
|
|
186
233
|
loop do
|
|
187
234
|
begin
|
|
188
235
|
return perform_once(method, path, body, data, raw, extra)
|
|
189
236
|
rescue Error => e
|
|
190
|
-
raise unless policy.retry?(e, attempt) && (safe || e
|
|
237
|
+
raise unless policy.retry?(e, attempt) && (safe || Cloud.pre_execution?(e))
|
|
191
238
|
|
|
192
239
|
@sleeper.call(policy.delay(e, attempt))
|
|
240
|
+
extra["Idempotency-Key"] = SecureRandom.uuid if own_key && Cloud.renews_idempotency_key?(e)
|
|
193
241
|
attempt += 1
|
|
194
242
|
end
|
|
195
243
|
end
|
|
@@ -260,7 +308,10 @@ module Kosa8
|
|
|
260
308
|
e.instance_variable_set(:@body, body)
|
|
261
309
|
e.retry_after = retry_after(headers)
|
|
262
310
|
if e.retry_after.nil? && body.is_a?(Hash)
|
|
263
|
-
|
|
311
|
+
# e.g. 409 idempotency_in_progress, 503 no_capacity (retry_after_s),
|
|
312
|
+
# 503 database_busy (retry_after too).
|
|
313
|
+
ra = body["retry_after_s"]
|
|
314
|
+
ra = body["retry_after"] unless ra.is_a?(Numeric) && ra.positive?
|
|
264
315
|
e.retry_after = ra.to_f if ra.is_a?(Numeric) && ra.positive?
|
|
265
316
|
end
|
|
266
317
|
e.request_id = header(headers, "x-request-id") || header(headers, "cf-ray")
|
|
@@ -478,6 +529,11 @@ module Kosa8
|
|
|
478
529
|
# data plane. On hosts without it the API answers 501 (not_available /
|
|
479
530
|
# not_supported), raised as Kosa8::UnsupportedError; not every kosa8 Cloud
|
|
480
531
|
# host has it yet.
|
|
532
|
+
#
|
|
533
|
+
# A sandbox kosa8 placed on its overflow capacity (Cloudflare) has no
|
|
534
|
+
# fork, checkpoint, rewind or sleep: those answer 501 not_available, raised
|
|
535
|
+
# as Kosa8::UnsupportedError with the server's sentence. The SDK does not
|
|
536
|
+
# retry or imitate them.
|
|
481
537
|
class CloudSandbox
|
|
482
538
|
attr_reader :info
|
|
483
539
|
|
|
@@ -525,7 +581,9 @@ module Kosa8
|
|
|
525
581
|
fc = r["failure_class"] if r["failure_class"].is_a?(String)
|
|
526
582
|
rt = r["retryable"] if r["retryable"] == true || r["retryable"] == false
|
|
527
583
|
CloudExecResult.new(exit_code: r["exit"], stdout: r["stdout"] || "", stderr: r["stderr"] || "",
|
|
528
|
-
woke_ms: r["woke_ms"], failure_class: fc, retryable: rt
|
|
584
|
+
woke_ms: r["woke_ms"], failure_class: fc, retryable: rt,
|
|
585
|
+
stdout_truncated: r["stdout_truncated"] == true, stderr_truncated: r["stderr_truncated"] == true,
|
|
586
|
+
stdout_bytes: r["stdout_bytes"], stderr_bytes: r["stderr_bytes"])
|
|
529
587
|
end
|
|
530
588
|
|
|
531
589
|
# Snapshot it and free its VM; it then costs only snapshot storage.
|
|
@@ -642,7 +700,7 @@ module Kosa8
|
|
|
642
700
|
# of failing the call; false is all or nothing. The API's default is true
|
|
643
701
|
# when a fan-out option is given or n is over 100. A fork that made none
|
|
644
702
|
# raises the first refusal. The call carries an Idempotency-Key
|
|
645
|
-
# (+idempotency_key+, default a new UUID
|
|
703
|
+
# (+idempotency_key+, default a new UUID; see Cloud#request for retries).
|
|
646
704
|
#
|
|
647
705
|
# Needs the host's data plane; on hosts without it the API answers 501
|
|
648
706
|
# (not_available/not_supported), raised as Kosa8::UnsupportedError. Not
|
|
@@ -676,10 +734,15 @@ module Kosa8
|
|
|
676
734
|
end
|
|
677
735
|
end
|
|
678
736
|
|
|
679
|
-
# sandbox.files: files in a cloud sandbox
|
|
680
|
-
#
|
|
681
|
-
#
|
|
682
|
-
# "
|
|
737
|
+
# sandbox.files: files in a cloud sandbox. Paths are absolute, such as
|
|
738
|
+
# /workspace/app.py; only /workspace outlives an exec. A sleeping sandbox
|
|
739
|
+
# wakes first. File info Hashes have "name", "path", "type" ("file" or
|
|
740
|
+
# "dir"), "size", "mode" and "mod_time".
|
|
741
|
+
#
|
|
742
|
+
# The bytes stream to and from the sandbox's host, so a file has no size
|
|
743
|
+
# cap but its disk; one request body is at most 100 MB through the API
|
|
744
|
+
# (#upload sends a bigger one in parts). Hosts without streamed files
|
|
745
|
+
# take at most 8 MiB a file (413 too_large).
|
|
683
746
|
#
|
|
684
747
|
# Needs the host's data plane; on hosts without it the API answers 501
|
|
685
748
|
# (not_available/not_supported), raised as Kosa8::UnsupportedError. Not every
|
|
@@ -694,9 +757,11 @@ module Kosa8
|
|
|
694
757
|
"#<Kosa8::CloudFiles sandbox=#{@sandbox.id.inspect}>"
|
|
695
758
|
end
|
|
696
759
|
|
|
697
|
-
# The file's bytes, as a binary (ASCII-8BIT) String.
|
|
698
|
-
|
|
699
|
-
|
|
760
|
+
# The file's bytes, as a binary (ASCII-8BIT) String. +range+ reads part
|
|
761
|
+
# of it: a Range of byte offsets (100..199, 100..), a negative Integer
|
|
762
|
+
# for the last bytes (-500), or "bytes=a-b" as sent.
|
|
763
|
+
def read(path, range: nil)
|
|
764
|
+
@cloud.request_bytes("GET", query("/files", path), raw: true, headers: CloudFiles.range_header(range))
|
|
700
765
|
end
|
|
701
766
|
|
|
702
767
|
# The file as text (UTF-8 by default).
|
|
@@ -705,12 +770,64 @@ module Kosa8
|
|
|
705
770
|
end
|
|
706
771
|
|
|
707
772
|
# Create or replace a file with +content+ (a String; sent as raw bytes).
|
|
708
|
-
# Returns its info Hash.
|
|
709
|
-
|
|
710
|
-
|
|
773
|
+
# Returns its info Hash. +offset:+ writes it at that byte, keeping the
|
|
774
|
+
# rest of the file (parts of a big file, in any order); +append: true+
|
|
775
|
+
# adds it at the end (never retried after no answer, so it is not added
|
|
776
|
+
# twice); +mode:+ sets permission bits ("755" or 0o755).
|
|
777
|
+
def write(path, content, offset: nil, append: false, mode: nil)
|
|
778
|
+
r = @cloud.request_bytes("PUT", query("/files", path, CloudFiles.put_params(offset, append, mode)),
|
|
779
|
+
data: content.to_s)
|
|
711
780
|
r.is_a?(Hash) ? (r["file"] || {}) : {}
|
|
712
781
|
end
|
|
713
782
|
|
|
783
|
+
# The Range header for +range+ (see #read), or nil.
|
|
784
|
+
def self.range_header(range)
|
|
785
|
+
return nil if range.nil?
|
|
786
|
+
|
|
787
|
+
v = case range
|
|
788
|
+
when String then range
|
|
789
|
+
when Integer
|
|
790
|
+
raise ArgumentError, "range: a negative Integer reads the last bytes, e.g. -500" unless range.negative?
|
|
791
|
+
|
|
792
|
+
"bytes=#{range}"
|
|
793
|
+
when Range
|
|
794
|
+
first = range.begin
|
|
795
|
+
last = range.end
|
|
796
|
+
unless first.is_a?(Integer) && first >= 0 && (last.nil? || (last.is_a?(Integer) && last >= first))
|
|
797
|
+
raise ArgumentError, "range: byte offsets from 0, e.g. 0..1023 or 1024.."
|
|
798
|
+
end
|
|
799
|
+
|
|
800
|
+
last -= 1 if !last.nil? && range.exclude_end?
|
|
801
|
+
raise ArgumentError, "range: an empty Range" if !last.nil? && last < first
|
|
802
|
+
|
|
803
|
+
"bytes=#{first}-#{last}"
|
|
804
|
+
else raise ArgumentError, "range: a Range of byte offsets, a negative Integer or \"bytes=a-b\""
|
|
805
|
+
end
|
|
806
|
+
raise ArgumentError, "range: one byte range, bytes=a-b, a- or -n" unless /\Abytes=(\d+-\d*|-\d+)\z/.match?(v)
|
|
807
|
+
|
|
808
|
+
{ "Range" => v }
|
|
809
|
+
end
|
|
810
|
+
|
|
811
|
+
# The query parameters of a write (offset=, append=, mode=).
|
|
812
|
+
def self.put_params(offset, append, mode)
|
|
813
|
+
out = []
|
|
814
|
+
raise ArgumentError, "give offset: or append: true, not both" if !offset.nil? && append
|
|
815
|
+
|
|
816
|
+
unless offset.nil?
|
|
817
|
+
raise ArgumentError, "offset: a whole number of bytes, 0 or more" unless offset.is_a?(Integer) && offset >= 0
|
|
818
|
+
|
|
819
|
+
out << ["offset", offset.to_s]
|
|
820
|
+
end
|
|
821
|
+
out << %w[append 1] if append
|
|
822
|
+
unless mode.nil?
|
|
823
|
+
m = mode.is_a?(Integer) ? format("%o", mode) : mode.to_s
|
|
824
|
+
raise ArgumentError, 'mode: permission bits in octal, e.g. "755" or 0o755' unless /\A[0-7]{3,4}\z/.match?(m)
|
|
825
|
+
|
|
826
|
+
out << ["mode", m]
|
|
827
|
+
end
|
|
828
|
+
out
|
|
829
|
+
end
|
|
830
|
+
|
|
714
831
|
# A folder's entries (default /workspace), as info Hashes.
|
|
715
832
|
def list(path = "/workspace")
|
|
716
833
|
r = @cloud.request("GET", query("/files/list", path))
|
data/lib/kosa8/cloud_features.rb
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
# frozen_string_literal: true
|
|
2
2
|
|
|
3
3
|
require "json"
|
|
4
|
+
require "stringio"
|
|
4
5
|
require "uri"
|
|
5
6
|
|
|
6
7
|
# More of kosa8 Cloud: sized and Docker creates, env, background commands,
|
|
@@ -10,8 +11,17 @@ require "uri"
|
|
|
10
11
|
# Kosa8::UnsupportedError; Cloud#capabilities says what the org can do.
|
|
11
12
|
module Kosa8
|
|
12
13
|
class Cloud
|
|
13
|
-
# The sizes
|
|
14
|
+
# The standard sizes (vCPU x GiB), which every sized call takes
|
|
15
|
+
# (sandboxes, org templates, pipelines).
|
|
14
16
|
SIZES = %w[2x4 4x8 8x16 16x32].freeze
|
|
17
|
+
# Small sizes, for fleets of mostly idle sandboxes (RL rollouts, evals):
|
|
18
|
+
# a fraction of a vCPU reserved, bursting while the host has idle CPU.
|
|
19
|
+
# Only a sandbox create takes them, and only hosts that run them (else
|
|
20
|
+
# 501 not_available, Kosa8::UnsupportedError). As cpus:/mem_mb:
|
|
21
|
+
# 0.25/512, 0.5/1024, 1/2048.
|
|
22
|
+
SMALL_SIZES = %w[0.25x0.5 0.5x1 1x2].freeze
|
|
23
|
+
# Every size a sandbox create takes.
|
|
24
|
+
SANDBOX_SIZES = (SMALL_SIZES + SIZES).freeze
|
|
15
25
|
ENV_NAME = /\A[A-Za-z_][A-Za-z0-9_]*\z/.freeze
|
|
16
26
|
SANDBOX_NAME = /\A[A-Za-z0-9][A-Za-z0-9._-]{0,63}\z/.freeze
|
|
17
27
|
SNAPSHOT_ID = /\Asnap_[A-Za-z0-9]{8,40}\z/.freeze
|
|
@@ -91,17 +101,25 @@ module Kosa8
|
|
|
91
101
|
# Start a sandbox. Besides template:, region:, sleep_after_s:, ttl_s:,
|
|
92
102
|
# delete_after: and accept_price:
|
|
93
103
|
#
|
|
94
|
-
# - size: "2x4", "4x8", "8x16" or "16x32" (vCPU x GiB),
|
|
95
|
-
#
|
|
96
|
-
#
|
|
104
|
+
# - size: "2x4", "4x8", "8x16" or "16x32" (vCPU x GiB), a small size
|
|
105
|
+
# "0.25x0.5", "0.5x1" or "1x2" (Cloud::SMALL_SIZES), or cpus: and
|
|
106
|
+
# mem_mb: (cpus: 0.25, mem_mb: 512 is the smallest); image: an OCI image (such as
|
|
107
|
+
# "kosa8-template/universal-24.04-20261115.2"); disk_gb: 8..500 (past 200 only on plans with a bigger sandbox disk:
|
|
108
|
+
# Team 256, Scale 500; GET /v1/templates max_disk_gb is yours). Any of
|
|
97
109
|
# these boots the sandbox cold at that size: create waits for it to
|
|
98
110
|
# run unless wait: false (then call #wait_running).
|
|
111
|
+
# - kvm: true (preview) gives it /dev/kvm for an emulator at hardware
|
|
112
|
+
# speed; needs a size or image, implies persistent and docker, never
|
|
113
|
+
# sleeps (501 not_available while no host has nested KVM).
|
|
99
114
|
# - docker: true lets it run its own Docker engine (start dockerd first);
|
|
100
115
|
# persistent: true runs every exec in one long-lived container;
|
|
101
116
|
# cpu: "dedicated" gives it whole physical cores.
|
|
102
117
|
# - name:, labels: (up to 16), env: (given to every command; values are
|
|
103
118
|
# never logged or returned), secrets: (names from cloud.secrets),
|
|
104
119
|
# egress: ({internet:, allow:, deny:, presets:}).
|
|
120
|
+
# - record: true saves its desktop as an MP4 to cloud.recordings when
|
|
121
|
+
# it is deleted; ai_gateway: true points OPENAI_BASE_URL,
|
|
122
|
+
# ANTHROPIC_BASE_URL and the like at the org's AI gateway (cloud.ai).
|
|
105
123
|
# - snapshot: "snap_..." starts it from a durable snapshot; then give
|
|
106
124
|
# only env:, name:, labels:, a lifetime or sleep_after_s:.
|
|
107
125
|
#
|
|
@@ -109,19 +127,22 @@ module Kosa8
|
|
|
109
127
|
# #heartbeat extends it, so a crashed client leaks nothing (not with
|
|
110
128
|
# ttl_s: or delete_after:). run_id: labels it kosa8.run=<run_id>.
|
|
111
129
|
# - idempotency_key: is sent as the Idempotency-Key header (default a new
|
|
112
|
-
# UUID)
|
|
113
|
-
# or a
|
|
130
|
+
# UUID). The default is reused after a timeout, a dropped connection,
|
|
131
|
+
# a 429 or a 409, so a retried create makes one sandbox, not two, and
|
|
132
|
+
# renewed after a 5xx, so that retry is a new attempt. A key you pass
|
|
133
|
+
# goes unchanged with every retry.
|
|
114
134
|
#
|
|
115
135
|
# Bad arguments raise ArgumentError before any request.
|
|
116
136
|
def create(template: nil, region: nil, sleep_after_s: nil, ttl_s: nil, delete_after: nil, accept_price: nil,
|
|
117
137
|
size: nil, cpus: nil, mem_mb: nil, image: nil, disk_gb: nil, persistent: nil, docker: nil, cpu: nil,
|
|
118
138
|
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
|
|
139
|
+
poll_interval: 1, lease_s: nil, run_id: nil, idempotency_key: nil, record: nil, ai_gateway: nil,
|
|
140
|
+
kvm: nil)
|
|
120
141
|
body = create_body(template: template, region: region, sleep_after_s: sleep_after_s, ttl_s: ttl_s,
|
|
121
142
|
delete_after: delete_after, accept_price: accept_price, size: size, cpus: cpus,
|
|
122
143
|
mem_mb: mem_mb, image: image, disk_gb: disk_gb, persistent: persistent, docker: docker,
|
|
123
144
|
cpu: cpu, name: name, labels: labels, env: env, secrets: secrets, egress: egress,
|
|
124
|
-
snapshot: snapshot)
|
|
145
|
+
snapshot: snapshot, record: record, ai_gateway: ai_gateway, kvm: kvm)
|
|
125
146
|
amb = @cloud.run_defaults || {}
|
|
126
147
|
run_id = amb["run_id"] if run_id.nil?
|
|
127
148
|
if lease_s.nil? && ttl_s.nil? && delete_after.nil?
|
|
@@ -147,7 +168,7 @@ module Kosa8
|
|
|
147
168
|
def create_body(template: nil, region: nil, sleep_after_s: nil, ttl_s: nil, delete_after: nil,
|
|
148
169
|
accept_price: nil, size: nil, cpus: nil, mem_mb: nil, image: nil, disk_gb: nil,
|
|
149
170
|
persistent: nil, docker: nil, cpu: nil, name: nil, labels: nil, env: nil, secrets: nil,
|
|
150
|
-
egress: nil, snapshot: nil)
|
|
171
|
+
egress: nil, snapshot: nil, record: nil, ai_gateway: nil, kvm: nil)
|
|
151
172
|
Cloud.check_lifetime(ttl_s, delete_after)
|
|
152
173
|
Cloud.check_sleep_after(sleep_after_s)
|
|
153
174
|
if !accept_price.nil? && !accept_price.is_a?(Numeric)
|
|
@@ -171,10 +192,13 @@ module Kosa8
|
|
|
171
192
|
body["env"] = Cloud.check_env(env) unless env.nil?
|
|
172
193
|
body["secrets"] = secrets.to_a.map { |n| Cloud.check_secret_name(n) } unless secrets.nil?
|
|
173
194
|
body["egress"] = Cloud.egress_body(egress) unless egress.nil?
|
|
195
|
+
body["record"] = record == true unless record.nil?
|
|
196
|
+
body["ai_gateway"] = ai_gateway == true unless ai_gateway.nil?
|
|
197
|
+
body["kvm"] = kvm == true unless kvm.nil?
|
|
174
198
|
unless snapshot.nil?
|
|
175
199
|
raise ArgumentError, "snapshot: is a snapshot id (snap_...)" unless Cloud::SNAPSHOT_ID.match?(snapshot.to_s)
|
|
176
200
|
|
|
177
|
-
clash = %w[template region size cpus image disk_gb persistent docker cpu] & body.keys
|
|
201
|
+
clash = %w[template region size cpus mem_mb image disk_gb persistent docker kvm cpu] & body.keys
|
|
178
202
|
unless clash.empty?
|
|
179
203
|
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
204
|
end
|
|
@@ -212,7 +236,9 @@ module Kosa8
|
|
|
212
236
|
|
|
213
237
|
def sized(body, size, cpus, mem_mb, image, disk_gb, persistent, docker, cpu)
|
|
214
238
|
unless size.nil?
|
|
215
|
-
|
|
239
|
+
unless Cloud::SANDBOX_SIZES.include?(size.to_s)
|
|
240
|
+
raise ArgumentError, "size must be one of #{Cloud::SANDBOX_SIZES.join(', ')}"
|
|
241
|
+
end
|
|
216
242
|
|
|
217
243
|
body["size"] = size.to_s
|
|
218
244
|
end
|
|
@@ -220,13 +246,17 @@ module Kosa8
|
|
|
220
246
|
|
|
221
247
|
unless cpus.nil?
|
|
222
248
|
raise ArgumentError, "give size: or cpus: and mem_mb:, not both" unless size.nil?
|
|
249
|
+
unless cpus.is_a?(Numeric) && cpus.positive?
|
|
250
|
+
raise ArgumentError, "cpus must be a positive number (0.25, 0.5, 1, 2, 4, 8 or 16)"
|
|
251
|
+
end
|
|
223
252
|
|
|
224
|
-
|
|
253
|
+
# 0.25 and 0.5 are sent as they are; a whole number as an Integer.
|
|
254
|
+
body["cpus"] = cpus == cpus.to_i ? cpus.to_i : cpus.to_f
|
|
225
255
|
body["mem_mb"] = Integer(mem_mb)
|
|
226
256
|
end
|
|
227
257
|
body["image"] = image.to_s unless image.nil?
|
|
228
258
|
unless disk_gb.nil?
|
|
229
|
-
raise ArgumentError, "disk_gb must be 8 to
|
|
259
|
+
raise ArgumentError, "disk_gb must be 8 to 500" unless disk_gb.is_a?(Integer) && disk_gb.between?(8, 500)
|
|
230
260
|
|
|
231
261
|
body["disk_gb"] = disk_gb
|
|
232
262
|
end
|
|
@@ -259,11 +289,17 @@ module Kosa8
|
|
|
259
289
|
# limit). Returns the background command (a Hash: "id" (bg_...),
|
|
260
290
|
# "state", "pid", "output_path", ...); poll it with #background_exec or
|
|
261
291
|
# #wait_background.
|
|
262
|
-
|
|
292
|
+
# +timeout_s+ (1 s to a day) has the host end it then ("timed_out" in
|
|
293
|
+
# #background_exec).
|
|
294
|
+
def exec_background(cmd, image: nil, env: nil, timeout_s: nil)
|
|
263
295
|
argv = cmd.is_a?(String) ? ["sh", "-c", cmd] : cmd.to_a
|
|
264
296
|
raise ArgumentError, "exec_background needs a command" if argv.empty?
|
|
297
|
+
unless timeout_s.nil? || (timeout_s.is_a?(Integer) && timeout_s.between?(1, 86_400))
|
|
298
|
+
raise ArgumentError, "timeout_s must be a whole number of seconds from 1 to 86400"
|
|
299
|
+
end
|
|
265
300
|
|
|
266
301
|
body = { "cmd" => argv, "background" => true }
|
|
302
|
+
body["timeout_s"] = timeout_s unless timeout_s.nil?
|
|
267
303
|
body["image"] = image unless image.nil?
|
|
268
304
|
body["env"] = Cloud.env_list(env) if env && !env.empty?
|
|
269
305
|
@cloud.request("POST", path("/exec"), body)["exec"]
|
|
@@ -274,7 +310,17 @@ module Kosa8
|
|
|
274
310
|
def background_exec(exec_id)
|
|
275
311
|
raise ArgumentError, "background_exec needs an exec id (bg_...)" if exec_id.nil? || exec_id.to_s.empty?
|
|
276
312
|
|
|
277
|
-
@cloud.request("GET",
|
|
313
|
+
@cloud.request("GET", "/v1/sandboxes/#{Kosa8.enc(id)}/exec/#{Kosa8.enc(exec_id)}")["exec"]
|
|
314
|
+
end
|
|
315
|
+
|
|
316
|
+
# Stop a background command and what it started (SIGTERM, then SIGKILL
|
|
317
|
+
# after 5 s); returns the command as it now is.
|
|
318
|
+
def stop_background(exec_id)
|
|
319
|
+
exec_id = exec_id["id"] if exec_id.is_a?(Hash)
|
|
320
|
+
raise ArgumentError, "stop_background needs an exec id (bg_...)" if exec_id.nil? || exec_id.to_s.empty?
|
|
321
|
+
|
|
322
|
+
r = @cloud.request("POST", "/v1/sandboxes/#{Kosa8.enc(id)}/exec/#{Kosa8.enc(exec_id)}/stop", {})
|
|
323
|
+
r.is_a?(Hash) ? (r["exec"] || r) : {}
|
|
278
324
|
end
|
|
279
325
|
|
|
280
326
|
# Poll a background command until it exits; returns it.
|
|
@@ -370,7 +416,7 @@ module Kosa8
|
|
|
370
416
|
end
|
|
371
417
|
|
|
372
418
|
def delete_code_context(name)
|
|
373
|
-
@cloud.request("DELETE",
|
|
419
|
+
@cloud.request("DELETE", "/v1/sandboxes/#{Kosa8.enc(id)}/code/contexts/#{Kosa8.enc(name)}")
|
|
374
420
|
nil
|
|
375
421
|
end
|
|
376
422
|
|
|
@@ -395,16 +441,40 @@ module Kosa8
|
|
|
395
441
|
end
|
|
396
442
|
|
|
397
443
|
class CloudFiles
|
|
398
|
-
#
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
444
|
+
# The most one upload request carries; a bigger file goes in parts.
|
|
445
|
+
UPLOAD_PART_BYTES = 64 * 1024 * 1024
|
|
446
|
+
|
|
447
|
+
# A file of any size (no 8 MiB cap), as a binary String; +range:+ as #read.
|
|
448
|
+
def download(path, range: nil)
|
|
449
|
+
@cloud.request_bytes("GET", query("/files/raw", path), raw: true, headers: CloudFiles.range_header(range))
|
|
450
|
+
end
|
|
451
|
+
|
|
452
|
+
# Write +content+ (a String, or an IO such as a File, read a part at a
|
|
453
|
+
# time) to a file of any size; returns its info Hash. Past +part_size+
|
|
454
|
+
# bytes (default 64 MiB; one request through the API is at most 100 MB)
|
|
455
|
+
# it is sent in parts with offset=, each retried on its own; a host
|
|
456
|
+
# without offset writes answers 501 (Kosa8::UnsupportedError): use
|
|
457
|
+
# #link(path, method: "PUT") then. +mode:+ as #write.
|
|
458
|
+
def upload(path, content, part_size: UPLOAD_PART_BYTES, mode: nil)
|
|
459
|
+
unless part_size.is_a?(Integer) && part_size.positive?
|
|
460
|
+
raise ArgumentError, "part_size: a whole number of bytes, more than 0"
|
|
461
|
+
end
|
|
402
462
|
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
463
|
+
CloudFiles.put_params(nil, false, mode) # a bad mode: is refused before any part is sent
|
|
464
|
+
io = content.respond_to?(:read) ? content : StringIO.new(content.to_s.b)
|
|
465
|
+
cur = (io.read(part_size) || +"").b
|
|
466
|
+
offset = 0
|
|
467
|
+
loop do
|
|
468
|
+
nxt = cur.bytesize == part_size ? io.read(part_size) : nil
|
|
469
|
+
last = nxt.nil? || nxt.empty?
|
|
470
|
+
# The first part replaces the file; the rest are written at their offset.
|
|
471
|
+
params = CloudFiles.put_params(offset.zero? ? nil : offset, false, last ? mode : nil)
|
|
472
|
+
r = @cloud.request_bytes("PUT", query("/files/raw", path, params), data: cur)
|
|
473
|
+
offset += cur.bytesize
|
|
474
|
+
return r.is_a?(Hash) ? (r["file"] || {}) : {} if last
|
|
475
|
+
|
|
476
|
+
cur = nxt.b
|
|
477
|
+
end
|
|
408
478
|
end
|
|
409
479
|
|
|
410
480
|
# A presigned URL for one download (GET) or upload (PUT) of +path+,
|
|
@@ -462,7 +532,7 @@ module Kosa8
|
|
|
462
532
|
end
|
|
463
533
|
|
|
464
534
|
def delete(port)
|
|
465
|
-
@cloud.request("DELETE", @sandbox.
|
|
535
|
+
@cloud.request("DELETE", "/v1/sandboxes/#{Kosa8.enc(@sandbox.id)}/previews/#{check(port)}")
|
|
466
536
|
nil
|
|
467
537
|
end
|
|
468
538
|
|
|
@@ -503,7 +573,7 @@ module Kosa8
|
|
|
503
573
|
end
|
|
504
574
|
|
|
505
575
|
def delete(id)
|
|
506
|
-
@cloud.request("DELETE", @sandbox.
|
|
576
|
+
@cloud.request("DELETE", "/v1/sandboxes/#{Kosa8.enc(@sandbox.id)}/schedules/#{Kosa8.enc(id)}")
|
|
507
577
|
nil
|
|
508
578
|
end
|
|
509
579
|
|
|
@@ -657,7 +727,8 @@ module Kosa8
|
|
|
657
727
|
|
|
658
728
|
# One artifact's bytes (a .tar.gz), as a binary String.
|
|
659
729
|
def download_artifact(id, job, idx)
|
|
660
|
-
@cloud.request_bytes("GET",
|
|
730
|
+
@cloud.request_bytes("GET", "/v1/pipelines/runs/#{Kosa8.enc(id)}/artifacts/#{Kosa8.enc(job)}/#{Integer(idx)}",
|
|
731
|
+
raw: true)
|
|
661
732
|
end
|
|
662
733
|
|
|
663
734
|
# A webhook URL for a repository's pushes and pull requests, and with
|