kosa8 0.6.0 → 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 +31 -12
- data/lib/kosa8/cloud.rb +115 -22
- data/lib/kosa8/cloud_features.rb +57 -18
- data/lib/kosa8/cloud_more.rb +5 -2
- data/lib/kosa8/cloud_rl.rb +4 -4
- data/lib/kosa8/cloud_stream.rb +329 -0
- data/lib/kosa8/errors.rb +94 -15
- 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 +1 -0
- metadata +13 -6
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,
|
|
@@ -103,9 +104,13 @@ module Kosa8
|
|
|
103
104
|
# - size: "2x4", "4x8", "8x16" or "16x32" (vCPU x GiB), a small size
|
|
104
105
|
# "0.25x0.5", "0.5x1" or "1x2" (Cloud::SMALL_SIZES), or cpus: and
|
|
105
106
|
# mem_mb: (cpus: 0.25, mem_mb: 512 is the smallest); image: an OCI image (such as
|
|
106
|
-
# "kosa8-template/universal-24.04-20261115.2"); disk_gb: 8..200
|
|
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
|
|
107
109
|
# these boots the sandbox cold at that size: create waits for it to
|
|
108
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).
|
|
109
114
|
# - docker: true lets it run its own Docker engine (start dockerd first);
|
|
110
115
|
# persistent: true runs every exec in one long-lived container;
|
|
111
116
|
# cpu: "dedicated" gives it whole physical cores.
|
|
@@ -122,19 +127,22 @@ module Kosa8
|
|
|
122
127
|
# #heartbeat extends it, so a crashed client leaks nothing (not with
|
|
123
128
|
# ttl_s: or delete_after:). run_id: labels it kosa8.run=<run_id>.
|
|
124
129
|
# - idempotency_key: is sent as the Idempotency-Key header (default a new
|
|
125
|
-
# UUID)
|
|
126
|
-
# 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.
|
|
127
134
|
#
|
|
128
135
|
# Bad arguments raise ArgumentError before any request.
|
|
129
136
|
def create(template: nil, region: nil, sleep_after_s: nil, ttl_s: nil, delete_after: nil, accept_price: nil,
|
|
130
137
|
size: nil, cpus: nil, mem_mb: nil, image: nil, disk_gb: nil, persistent: nil, docker: nil, cpu: nil,
|
|
131
138
|
name: nil, labels: nil, env: nil, secrets: nil, egress: nil, snapshot: nil, wait: true,
|
|
132
|
-
poll_interval: 1, lease_s: nil, run_id: nil, idempotency_key: nil, record: nil, ai_gateway: nil
|
|
139
|
+
poll_interval: 1, lease_s: nil, run_id: nil, idempotency_key: nil, record: nil, ai_gateway: nil,
|
|
140
|
+
kvm: nil)
|
|
133
141
|
body = create_body(template: template, region: region, sleep_after_s: sleep_after_s, ttl_s: ttl_s,
|
|
134
142
|
delete_after: delete_after, accept_price: accept_price, size: size, cpus: cpus,
|
|
135
143
|
mem_mb: mem_mb, image: image, disk_gb: disk_gb, persistent: persistent, docker: docker,
|
|
136
144
|
cpu: cpu, name: name, labels: labels, env: env, secrets: secrets, egress: egress,
|
|
137
|
-
snapshot: snapshot, record: record, ai_gateway: ai_gateway)
|
|
145
|
+
snapshot: snapshot, record: record, ai_gateway: ai_gateway, kvm: kvm)
|
|
138
146
|
amb = @cloud.run_defaults || {}
|
|
139
147
|
run_id = amb["run_id"] if run_id.nil?
|
|
140
148
|
if lease_s.nil? && ttl_s.nil? && delete_after.nil?
|
|
@@ -160,7 +168,7 @@ module Kosa8
|
|
|
160
168
|
def create_body(template: nil, region: nil, sleep_after_s: nil, ttl_s: nil, delete_after: nil,
|
|
161
169
|
accept_price: nil, size: nil, cpus: nil, mem_mb: nil, image: nil, disk_gb: nil,
|
|
162
170
|
persistent: nil, docker: nil, cpu: nil, name: nil, labels: nil, env: nil, secrets: nil,
|
|
163
|
-
egress: nil, snapshot: nil, record: nil, ai_gateway: nil)
|
|
171
|
+
egress: nil, snapshot: nil, record: nil, ai_gateway: nil, kvm: nil)
|
|
164
172
|
Cloud.check_lifetime(ttl_s, delete_after)
|
|
165
173
|
Cloud.check_sleep_after(sleep_after_s)
|
|
166
174
|
if !accept_price.nil? && !accept_price.is_a?(Numeric)
|
|
@@ -186,10 +194,11 @@ module Kosa8
|
|
|
186
194
|
body["egress"] = Cloud.egress_body(egress) unless egress.nil?
|
|
187
195
|
body["record"] = record == true unless record.nil?
|
|
188
196
|
body["ai_gateway"] = ai_gateway == true unless ai_gateway.nil?
|
|
197
|
+
body["kvm"] = kvm == true unless kvm.nil?
|
|
189
198
|
unless snapshot.nil?
|
|
190
199
|
raise ArgumentError, "snapshot: is a snapshot id (snap_...)" unless Cloud::SNAPSHOT_ID.match?(snapshot.to_s)
|
|
191
200
|
|
|
192
|
-
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
|
|
193
202
|
unless clash.empty?
|
|
194
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:"
|
|
195
204
|
end
|
|
@@ -247,7 +256,7 @@ module Kosa8
|
|
|
247
256
|
end
|
|
248
257
|
body["image"] = image.to_s unless image.nil?
|
|
249
258
|
unless disk_gb.nil?
|
|
250
|
-
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)
|
|
251
260
|
|
|
252
261
|
body["disk_gb"] = disk_gb
|
|
253
262
|
end
|
|
@@ -280,11 +289,17 @@ module Kosa8
|
|
|
280
289
|
# limit). Returns the background command (a Hash: "id" (bg_...),
|
|
281
290
|
# "state", "pid", "output_path", ...); poll it with #background_exec or
|
|
282
291
|
# #wait_background.
|
|
283
|
-
|
|
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)
|
|
284
295
|
argv = cmd.is_a?(String) ? ["sh", "-c", cmd] : cmd.to_a
|
|
285
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
|
|
286
300
|
|
|
287
301
|
body = { "cmd" => argv, "background" => true }
|
|
302
|
+
body["timeout_s"] = timeout_s unless timeout_s.nil?
|
|
288
303
|
body["image"] = image unless image.nil?
|
|
289
304
|
body["env"] = Cloud.env_list(env) if env && !env.empty?
|
|
290
305
|
@cloud.request("POST", path("/exec"), body)["exec"]
|
|
@@ -426,16 +441,40 @@ module Kosa8
|
|
|
426
441
|
end
|
|
427
442
|
|
|
428
443
|
class CloudFiles
|
|
429
|
-
#
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
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
|
|
433
462
|
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
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
|
|
439
478
|
end
|
|
440
479
|
|
|
441
480
|
# A presigned URL for one download (GET) or upload (PUT) of +path+,
|
data/lib/kosa8/cloud_more.rb
CHANGED
|
@@ -280,7 +280,10 @@ module Kosa8
|
|
|
280
280
|
def screenshot(url, full_page: false)
|
|
281
281
|
p = page(url, screenshot: true, full_page: full_page ? true : nil)
|
|
282
282
|
b64 = p.is_a?(Hash) ? p["screenshot_png_base64"] : nil
|
|
283
|
-
|
|
283
|
+
if b64.nil? || b64.empty?
|
|
284
|
+
note = p.is_a?(Hash) && p["screenshot_note"].is_a?(String) ? ": #{p['screenshot_note']}" : ""
|
|
285
|
+
raise Error, "the API sent no screenshot#{note}"
|
|
286
|
+
end
|
|
284
287
|
|
|
285
288
|
b64.unpack1("m").b
|
|
286
289
|
end
|
|
@@ -437,7 +440,7 @@ module Kosa8
|
|
|
437
440
|
# cloud.jobs: hosted eval and RL jobs. kosa8 runs each task in its own
|
|
438
441
|
# sandbox (template:, image: or snapshot:), runs the solver then the sealed
|
|
439
442
|
# grader, records every rollout under the job's RL run and stops at
|
|
440
|
-
# +budget_usd+. A submit carries an Idempotency-Key
|
|
443
|
+
# +budget_usd+. A submit carries an Idempotency-Key (see Cloud#request).
|
|
441
444
|
class CloudJobs
|
|
442
445
|
DONE_STATES = %w[done failed cancelled budget_reached].freeze
|
|
443
446
|
MAX_TASKS = 10_000
|
data/lib/kosa8/cloud_rl.rb
CHANGED
|
@@ -263,8 +263,8 @@ module Kosa8
|
|
|
263
263
|
# <prefix>-0001, ...) and partial_ok: (default true: make what fits and
|
|
264
264
|
# list the rest in +failed+; false: all or nothing). Nothing made raises
|
|
265
265
|
# the first refusal. Carries an Idempotency-Key (+idempotency_key+,
|
|
266
|
-
# default a new UUID) reused
|
|
267
|
-
# doubles the fleet.
|
|
266
|
+
# default a new UUID) reused after a timeout, so a retried batch never
|
|
267
|
+
# doubles the fleet (the default is renewed after a 5xx).
|
|
268
268
|
def create_many(count, labels: nil, run_id: nil, lease_s: nil, prefix: nil, partial_ok: nil,
|
|
269
269
|
idempotency_key: nil, **create_opts)
|
|
270
270
|
unless count.is_a?(Integer) && count.between?(1, Cloud::MAX_BATCH)
|
|
@@ -340,8 +340,8 @@ module Kosa8
|
|
|
340
340
|
# 0 and 0.0 otherwise; nil when the command did not finish. With run_id:
|
|
341
341
|
# it is recorded as a rollout of that run (rollout: step, group, index,
|
|
342
342
|
# meta), so do not record it again. files: at most 64, 8 MiB in all;
|
|
343
|
-
# timeout_s: 1 to 90. The call carries an Idempotency-Key reused
|
|
344
|
-
#
|
|
343
|
+
# timeout_s: 1 to 90. The call carries an Idempotency-Key reused after a
|
|
344
|
+
# timeout: that retry gets the first answer and records nothing twice.
|
|
345
345
|
def grade(cmd, files: nil, timeout_s: nil, env: nil, keep: false, run_id: nil, rollout: nil, idempotency_key: nil)
|
|
346
346
|
run_id = (@cloud.run_defaults || {})["run_id"] if run_id.nil?
|
|
347
347
|
body = Cloud.grade_body(cmd, files: files, timeout_s: timeout_s, env: env, keep: keep, run_id: run_id,
|
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "json"
|
|
4
|
+
require "net/http"
|
|
5
|
+
require "openssl"
|
|
6
|
+
require "socket"
|
|
7
|
+
require "uri"
|
|
8
|
+
|
|
9
|
+
# Streamed exec on kosa8 Cloud: POST /v1/sandboxes/{id}/exec {stream: true}
|
|
10
|
+
# answers NDJSON frames while the command prints ({stream, data: base64},
|
|
11
|
+
# an empty stdout frame with heartbeat: true every 15 s of silence, then
|
|
12
|
+
# {done: true, exit} or {done: true, error, code}). Not held to the 90 s of
|
|
13
|
+
# a buffered exec.
|
|
14
|
+
module Kosa8
|
|
15
|
+
class Cloud
|
|
16
|
+
# The longest timeout_s a streamed or background command takes (a day).
|
|
17
|
+
STREAM_MAX_TIMEOUT_S = 86_400
|
|
18
|
+
# A read that waits longer than this without a byte is a dead
|
|
19
|
+
# connection, not a quiet command (heartbeats come every 15 s).
|
|
20
|
+
STREAM_MIN_READ_TIMEOUT_S = 30
|
|
21
|
+
|
|
22
|
+
alias initialize_without_stream initialize
|
|
23
|
+
# stream_transport: an optional callable (method, url, headers, body,
|
|
24
|
+
# read_timeout) { |chunk| ... } -> [status, error_body_or_nil, headers]
|
|
25
|
+
# used for streamed answers instead of Net::HTTP (tests, proxies): it
|
|
26
|
+
# yields each chunk of a 2xx answer as it arrives and returns the
|
|
27
|
+
# body of an error answer.
|
|
28
|
+
def initialize(stream_transport: nil, **kw)
|
|
29
|
+
initialize_without_stream(**kw)
|
|
30
|
+
@stream_transport = stream_transport || method(:net_http_stream)
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
# One streamed request: yields the answer's bytes as they arrive. A
|
|
34
|
+
# refusal before the stream starts raises the usual typed error (a
|
|
35
|
+
# refusal made before anything ran, such as a 429, is retried as
|
|
36
|
+
# retry_policy allows); nothing is retried once bytes flow. A broken or
|
|
37
|
+
# stalled stream raises Kosa8::StreamError.
|
|
38
|
+
def stream(method, path, body)
|
|
39
|
+
headers = { "Authorization" => "Bearer #{@key}", "User-Agent" => "kosa8-ruby/#{VERSION}",
|
|
40
|
+
"Accept" => "application/x-ndjson, application/json", "Content-Type" => "application/json" }
|
|
41
|
+
payload = JSON.generate(body)
|
|
42
|
+
read_timeout = [@timeout.to_f, STREAM_MIN_READ_TIMEOUT_S].max
|
|
43
|
+
attempt = 1
|
|
44
|
+
loop do
|
|
45
|
+
started = false
|
|
46
|
+
begin
|
|
47
|
+
status, content, resp_headers = @stream_transport.call(method, @base_url + path, headers, payload,
|
|
48
|
+
read_timeout) do |chunk|
|
|
49
|
+
started = true
|
|
50
|
+
begin
|
|
51
|
+
yield chunk
|
|
52
|
+
rescue Exception => e # rubocop:disable Lint/RescueException
|
|
53
|
+
raise CallbackFailure.new(e)
|
|
54
|
+
end
|
|
55
|
+
end
|
|
56
|
+
rescue CallbackFailure => e
|
|
57
|
+
raise e.cause_error
|
|
58
|
+
rescue Net::OpenTimeout, Net::ReadTimeout, Timeout::Error => e
|
|
59
|
+
if started
|
|
60
|
+
raise StreamError.new("kosa8 Cloud stopped sending the exec stream (no data or heartbeat in #{read_timeout.round} s)",
|
|
61
|
+
method: method, path: path, code: "stream_stalled")
|
|
62
|
+
end
|
|
63
|
+
raise TimeoutError.new("kosa8 Cloud did not answer #{method} #{path} within #{read_timeout.round} s (#{e.message})",
|
|
64
|
+
method: method, path: path)
|
|
65
|
+
rescue SystemCallError, IOError, SocketError, OpenSSL::SSL::SSLError => e
|
|
66
|
+
raise StreamError.new("the exec stream broke: #{e.message}", method: method, path: path, code: "stream_broken") if started
|
|
67
|
+
|
|
68
|
+
raise ConnectionError.new("could not reach kosa8 Cloud at #{@base_url}: #{e.message}; " \
|
|
69
|
+
"check the network connection and KOSA8_CLOUD_URL (or base_url:), then try again",
|
|
70
|
+
method: method, path: path)
|
|
71
|
+
end
|
|
72
|
+
return nil if status.to_i < 400
|
|
73
|
+
|
|
74
|
+
text = content.to_s.dup.force_encoding(Encoding::UTF_8).scrub
|
|
75
|
+
parsed = begin
|
|
76
|
+
text.strip.empty? ? nil : JSON.parse(text)
|
|
77
|
+
rescue JSON::ParserError
|
|
78
|
+
text
|
|
79
|
+
end
|
|
80
|
+
e = Cloud.error(status.to_i, parsed, method, path, resp_headers)
|
|
81
|
+
raise e unless !started && Cloud.pre_execution?(e) && @retry_policy.retry?(e, attempt)
|
|
82
|
+
|
|
83
|
+
@sleeper.call(@retry_policy.delay(e, attempt))
|
|
84
|
+
attempt += 1
|
|
85
|
+
end
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
def self.check_stream_timeout(timeout_s)
|
|
89
|
+
return if timeout_s.nil? || (timeout_s.is_a?(Integer) && timeout_s.between?(1, STREAM_MAX_TIMEOUT_S))
|
|
90
|
+
|
|
91
|
+
raise ArgumentError, "timeout_s must be a whole number of seconds from 1 to #{STREAM_MAX_TIMEOUT_S}"
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
private
|
|
95
|
+
|
|
96
|
+
def net_http_stream(method, url, headers, body, timeout)
|
|
97
|
+
u = URI.parse(url)
|
|
98
|
+
http = Net::HTTP.new(u.hostname, u.port)
|
|
99
|
+
http.use_ssl = u.scheme == "https"
|
|
100
|
+
http.open_timeout = [timeout, 30].min
|
|
101
|
+
http.read_timeout = timeout
|
|
102
|
+
http.write_timeout = timeout if http.respond_to?(:write_timeout=)
|
|
103
|
+
req = Net::HTTPGenericRequest.new(method, !body.nil?, true, u.request_uri)
|
|
104
|
+
headers.each { |k, v| req[k] = v }
|
|
105
|
+
req.body = body unless body.nil?
|
|
106
|
+
http.start do |h|
|
|
107
|
+
h.request(req) do |resp|
|
|
108
|
+
code = resp.code.to_i
|
|
109
|
+
return [code, resp.read_body.to_s, resp.to_hash] if code >= 400
|
|
110
|
+
|
|
111
|
+
resp.read_body { |chunk| yield chunk }
|
|
112
|
+
return [code, nil, resp.to_hash]
|
|
113
|
+
end
|
|
114
|
+
end
|
|
115
|
+
end
|
|
116
|
+
end
|
|
117
|
+
|
|
118
|
+
# Reads a streamed exec's NDJSON frames from chunks that split lines and
|
|
119
|
+
# UTF-8 characters anywhere.
|
|
120
|
+
class CloudExecStream # :nodoc:
|
|
121
|
+
STREAMS = %w[stdout stderr].freeze
|
|
122
|
+
attr_reader :exit_code, :done
|
|
123
|
+
|
|
124
|
+
def initialize(path, on_text)
|
|
125
|
+
@path = path
|
|
126
|
+
@on_text = on_text
|
|
127
|
+
@line = +"".b
|
|
128
|
+
@pending = { "stdout" => +"".b, "stderr" => +"".b }
|
|
129
|
+
@out = { "stdout" => +"", "stderr" => +"" }
|
|
130
|
+
@exit_code = nil
|
|
131
|
+
@done = false
|
|
132
|
+
@whole = nil
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
def stdout
|
|
136
|
+
@out["stdout"]
|
|
137
|
+
end
|
|
138
|
+
|
|
139
|
+
def stderr
|
|
140
|
+
@out["stderr"]
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
# A buffered answer (an ExecResult) when the server sent one instead of frames.
|
|
144
|
+
attr_reader :whole
|
|
145
|
+
|
|
146
|
+
def feed(chunk)
|
|
147
|
+
return if @done
|
|
148
|
+
|
|
149
|
+
@line << chunk.to_s.b
|
|
150
|
+
while (i = @line.index("\n".b))
|
|
151
|
+
line = @line.slice!(0..i)
|
|
152
|
+
frame(line)
|
|
153
|
+
return if @done
|
|
154
|
+
end
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
# The stream ended: the last line, then any bytes held for a split character.
|
|
158
|
+
def finish
|
|
159
|
+
frame(@line) unless @done || @line.strip.empty?
|
|
160
|
+
flush
|
|
161
|
+
return if @done || @whole
|
|
162
|
+
|
|
163
|
+
raise StreamError.new("the exec stream ended before the command finished (no final frame)",
|
|
164
|
+
stdout: stdout, stderr: stderr, method: "POST", path: @path, code: "stream_broken")
|
|
165
|
+
end
|
|
166
|
+
|
|
167
|
+
private
|
|
168
|
+
|
|
169
|
+
def frame(line)
|
|
170
|
+
text = line.strip
|
|
171
|
+
return if text.empty?
|
|
172
|
+
|
|
173
|
+
f = begin
|
|
174
|
+
JSON.parse(text.force_encoding(Encoding::UTF_8))
|
|
175
|
+
rescue JSON::ParserError
|
|
176
|
+
raise StreamError.new("kosa8 Cloud sent a stream line that is not JSON: #{text[0, 200].inspect}",
|
|
177
|
+
stdout: stdout, stderr: stderr, method: "POST", path: @path, code: "stream_broken")
|
|
178
|
+
end
|
|
179
|
+
return unless f.is_a?(Hash)
|
|
180
|
+
|
|
181
|
+
if f["done"]
|
|
182
|
+
flush
|
|
183
|
+
@done = true
|
|
184
|
+
fail_with(f) unless f["error"].nil?
|
|
185
|
+
@exit_code = f["exit"].is_a?(Integer) ? f["exit"] : nil
|
|
186
|
+
return
|
|
187
|
+
end
|
|
188
|
+
if f.key?("exit") && f.key?("stdout") && !f.key?("stream")
|
|
189
|
+
@whole = f # a server that ignored stream: true answered the whole result
|
|
190
|
+
@done = true
|
|
191
|
+
return
|
|
192
|
+
end
|
|
193
|
+
name = f["stream"]
|
|
194
|
+
data = f["data"]
|
|
195
|
+
return unless STREAMS.include?(name) && data.is_a?(String) && !data.empty? # a heartbeat, or unknown
|
|
196
|
+
|
|
197
|
+
bytes = begin
|
|
198
|
+
data.unpack1("m0")
|
|
199
|
+
rescue ArgumentError
|
|
200
|
+
data.b
|
|
201
|
+
end
|
|
202
|
+
emit(name, decode(name, bytes))
|
|
203
|
+
end
|
|
204
|
+
|
|
205
|
+
def emit(name, text)
|
|
206
|
+
return if text.empty?
|
|
207
|
+
|
|
208
|
+
@out[name] << text
|
|
209
|
+
@on_text&.call(name, text)
|
|
210
|
+
end
|
|
211
|
+
|
|
212
|
+
def flush
|
|
213
|
+
STREAMS.each do |name|
|
|
214
|
+
rest = @pending[name]
|
|
215
|
+
@pending[name] = +"".b
|
|
216
|
+
emit(name, rest.force_encoding(Encoding::UTF_8).scrub) unless rest.empty?
|
|
217
|
+
end
|
|
218
|
+
end
|
|
219
|
+
|
|
220
|
+
# The text of +bytes+ after what was held back, holding back a
|
|
221
|
+
# trailing incomplete UTF-8 character for the next chunk.
|
|
222
|
+
def decode(name, bytes)
|
|
223
|
+
buf = @pending[name] + bytes.b
|
|
224
|
+
cut = buf.bytesize
|
|
225
|
+
1.upto([3, buf.bytesize].min) do |k|
|
|
226
|
+
b = buf.getbyte(buf.bytesize - k)
|
|
227
|
+
break if b < 0x80 # ASCII: nothing is split
|
|
228
|
+
next unless b >= 0xC0 # a lead byte
|
|
229
|
+
|
|
230
|
+
need = if b >= 0xF0 then 4
|
|
231
|
+
elsif b >= 0xE0 then 3
|
|
232
|
+
else 2
|
|
233
|
+
end
|
|
234
|
+
cut = buf.bytesize - k if need > k
|
|
235
|
+
break
|
|
236
|
+
end
|
|
237
|
+
@pending[name] = buf.byteslice(cut..-1) || +"".b
|
|
238
|
+
buf.byteslice(0, cut).force_encoding(Encoding::UTF_8).scrub
|
|
239
|
+
end
|
|
240
|
+
|
|
241
|
+
def fail_with(f)
|
|
242
|
+
msg = f["error"].to_s
|
|
243
|
+
msg = "the command failed" if msg.empty?
|
|
244
|
+
code = f["code"].is_a?(String) ? f["code"] : nil
|
|
245
|
+
if code == "exec_timeout" || msg.include?("timeout_s")
|
|
246
|
+
e = ExecTimeoutError.new(msg, status: 504, daemon_message: msg, method: "POST", path: @path,
|
|
247
|
+
code: "exec_timeout")
|
|
248
|
+
e.stdout = stdout
|
|
249
|
+
e.stderr = stderr
|
|
250
|
+
raise e
|
|
251
|
+
end
|
|
252
|
+
raise StreamError.new(msg, stdout: stdout, stderr: stderr, method: "POST", path: @path, code: code)
|
|
253
|
+
end
|
|
254
|
+
end
|
|
255
|
+
|
|
256
|
+
class CloudSandbox
|
|
257
|
+
alias exec_buffered exec
|
|
258
|
+
|
|
259
|
+
# Run a command and wait for it. A String runs through sh -c, an Array is
|
|
260
|
+
# the argv. A sleeping sandbox wakes for it.
|
|
261
|
+
#
|
|
262
|
+
# With +on_stdout+ / +on_stderr+ (callables taking the text), +stream:
|
|
263
|
+
# true+ or a +timeout_s+ over 90, it runs as a streamed exec
|
|
264
|
+
# (#exec_stream): the callbacks get the output as the command prints it
|
|
265
|
+
# and the command is not held to the 90 s of a buffered exec. The result
|
|
266
|
+
# is a CloudExecResult either way. +stream: false+ always buffers.
|
|
267
|
+
def exec(cmd, image: nil, env: nil, timeout_s: nil, stream: nil, on_stdout: nil, on_stderr: nil)
|
|
268
|
+
long = timeout_s.is_a?(Numeric) && timeout_s > Cloud::EXEC_LIMIT_S
|
|
269
|
+
if stream == true || (stream.nil? && (on_stdout || on_stderr || long))
|
|
270
|
+
return exec_stream(cmd, image: image, env: env, timeout_s: timeout_s, on_stdout: on_stdout,
|
|
271
|
+
on_stderr: on_stderr)
|
|
272
|
+
end
|
|
273
|
+
|
|
274
|
+
r = exec_buffered(cmd, image: image, env: env, timeout_s: timeout_s)
|
|
275
|
+
on_stdout&.call(r.stdout) unless r.stdout.empty?
|
|
276
|
+
on_stderr&.call(r.stderr) unless r.stderr.empty?
|
|
277
|
+
r
|
|
278
|
+
end
|
|
279
|
+
|
|
280
|
+
# Run a command and read its output as it prints (a streamed exec); not
|
|
281
|
+
# held to the 90 s of a buffered exec. +timeout_s+ (1 s to a day) stops
|
|
282
|
+
# it in the sandbox. Yields (stream, text) with stream "stdout" or
|
|
283
|
+
# "stderr" (UTF-8, decoded across chunk edges; heartbeats skipped), and
|
|
284
|
+
# calls +on_stdout+ / +on_stderr+ likewise; returns a CloudExecResult
|
|
285
|
+
# with everything it printed.
|
|
286
|
+
#
|
|
287
|
+
# box.exec_stream("make test") { |_stream, text| print text }
|
|
288
|
+
#
|
|
289
|
+
# A refusal (bad request, sandbox not running) raises before any output.
|
|
290
|
+
# A command stopped at +timeout_s+ raises Kosa8::ExecTimeoutError (its
|
|
291
|
+
# #stdout / #stderr hold the output so far); a stream that breaks or
|
|
292
|
+
# ends early raises Kosa8::StreamError, with the output so far.
|
|
293
|
+
def exec_stream(cmd, image: nil, env: nil, timeout_s: nil, on_stdout: nil, on_stderr: nil, &block)
|
|
294
|
+
argv = cmd.is_a?(String) ? ["sh", "-c", cmd] : cmd.to_a
|
|
295
|
+
raise ArgumentError, "exec_stream needs a command" if argv.empty?
|
|
296
|
+
|
|
297
|
+
Cloud.check_stream_timeout(timeout_s)
|
|
298
|
+
body = { "cmd" => argv, "stream" => true }
|
|
299
|
+
body["image"] = image unless image.nil?
|
|
300
|
+
body["env"] = Cloud.env_list(env) if env && !env.empty?
|
|
301
|
+
body["timeout_s"] = timeout_s unless timeout_s.nil?
|
|
302
|
+
cbs = { "stdout" => on_stdout, "stderr" => on_stderr }
|
|
303
|
+
reader = CloudExecStream.new(path("/exec"), lambda { |name, text|
|
|
304
|
+
cbs[name]&.call(text)
|
|
305
|
+
block&.call(name, text)
|
|
306
|
+
})
|
|
307
|
+
@cloud.stream("POST", path("/exec"), body) { |chunk| reader.feed(chunk) }
|
|
308
|
+
reader.finish
|
|
309
|
+
if (w = reader.whole)
|
|
310
|
+
res = CloudExecResult.new(exit_code: w["exit"], stdout: w["stdout"].to_s, stderr: w["stderr"].to_s,
|
|
311
|
+
woke_ms: w["woke_ms"], failure_class: nil, retryable: nil)
|
|
312
|
+
fc, rt = Kosa8.exec_failure(w["exit"])
|
|
313
|
+
res.failure_class = w["failure_class"].is_a?(String) ? w["failure_class"] : fc
|
|
314
|
+
res.retryable = [true, false].include?(w["retryable"]) ? w["retryable"] : rt
|
|
315
|
+
{ "stdout" => res.stdout, "stderr" => res.stderr }.each do |n, t|
|
|
316
|
+
next if t.empty?
|
|
317
|
+
|
|
318
|
+
cbs[n]&.call(t)
|
|
319
|
+
block&.call(n, t)
|
|
320
|
+
end
|
|
321
|
+
return res
|
|
322
|
+
end
|
|
323
|
+
fc, rt = Kosa8.exec_failure(reader.exit_code)
|
|
324
|
+
CloudExecResult.new(exit_code: reader.exit_code, stdout: reader.stdout, stderr: reader.stderr, woke_ms: nil,
|
|
325
|
+
failure_class: fc, retryable: rt, stdout_truncated: false, stderr_truncated: false,
|
|
326
|
+
stdout_bytes: reader.stdout.bytesize, stderr_bytes: reader.stderr.bytesize)
|
|
327
|
+
end
|
|
328
|
+
end
|
|
329
|
+
end
|
data/lib/kosa8/errors.rb
CHANGED
|
@@ -63,30 +63,86 @@ module Kosa8
|
|
|
63
63
|
end
|
|
64
64
|
|
|
65
65
|
class ConnectionError < Error; end # daemon unreachable
|
|
66
|
-
class ApiError < Error; end # any HTTP error answer
|
|
67
|
-
class BadRequestError < ApiError; end # 400
|
|
68
|
-
class AuthError < ApiError; end # 401
|
|
69
|
-
class PolicyError < ApiError; end # 403
|
|
70
|
-
class NotFoundError < ApiError; end # 404
|
|
71
|
-
class ConflictError < ApiError; end # 409
|
|
72
|
-
class UnsupportedError < ApiError; end # 501
|
|
73
66
|
|
|
74
|
-
#
|
|
75
|
-
#
|
|
76
|
-
|
|
77
|
-
|
|
67
|
+
# Any HTTP error answer. A kosa8 Cloud answer's contract fields (see the
|
|
68
|
+
# API's Error schema) are read from +body+; each is nil when the answer
|
|
69
|
+
# did not carry it.
|
|
70
|
+
class ApiError < Error
|
|
71
|
+
# 402: where the person adds a payment method or credit, or raises the cap.
|
|
78
72
|
def upgrade_url
|
|
79
73
|
Kosa8.body_str(body, "upgrade_url")
|
|
80
74
|
end
|
|
81
75
|
|
|
82
|
-
#
|
|
76
|
+
# 402 and 429 quota_exceeded: a sentence an AI agent should relay to its
|
|
77
|
+
# person word for word.
|
|
83
78
|
def agent_message
|
|
84
79
|
Kosa8.body_str(body, "agent_message")
|
|
85
80
|
end
|
|
81
|
+
|
|
82
|
+
# 429 quota_exceeded: where to ask for a higher limit.
|
|
83
|
+
def request_url
|
|
84
|
+
Kosa8.body_str(body, "request_url")
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
# 402 plan_limit: which limit (sandbox_hours, running, size, persistent or snapshots).
|
|
88
|
+
def limit_name
|
|
89
|
+
Kosa8.body_str(body, "limit_name")
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
# 402 plan_limit: the plan's limit (a Number).
|
|
93
|
+
def limit
|
|
94
|
+
Kosa8.body_num(body, "limit")
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
# 402 plan_limit: what the organization has used.
|
|
98
|
+
def used
|
|
99
|
+
Kosa8.body_num(body, "used")
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
# 402 plan_limit and plan_feature: the organization's plan.
|
|
103
|
+
def plan
|
|
104
|
+
Kosa8.body_str(body, "plan")
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
# 402 plan_limit and plan_feature: the first plan that includes more (nil: contact sales).
|
|
108
|
+
def next_plan
|
|
109
|
+
Kosa8.body_str(body, "next_plan")
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
# 402 plan_feature: the feature the plan lacks.
|
|
113
|
+
def feature
|
|
114
|
+
Kosa8.body_str(body, "feature")
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
# 402 plan_limit: the ways past the limit, cheaper first (Hashes: "kind"
|
|
118
|
+
# pack or upgrade, "addon", "plan", "label", "monthly_usd", "url").
|
|
119
|
+
def options
|
|
120
|
+
v = body.is_a?(Hash) ? body["options"] : nil
|
|
121
|
+
v.is_a?(Array) ? v.select { |o| o.is_a?(Hash) } : []
|
|
122
|
+
end
|
|
123
|
+
|
|
124
|
+
# 402 plan_limit: where to add the pack for this limit, when one is sold.
|
|
125
|
+
def pack_url
|
|
126
|
+
Kosa8.body_str(body, "pack_url")
|
|
127
|
+
end
|
|
86
128
|
end
|
|
87
129
|
|
|
88
|
-
|
|
89
|
-
|
|
130
|
+
class BadRequestError < ApiError; end # 400
|
|
131
|
+
class AuthError < ApiError; end # 401
|
|
132
|
+
class PolicyError < ApiError; end # 403
|
|
133
|
+
class NotFoundError < ApiError; end # 404
|
|
134
|
+
class ConflictError < ApiError; end # 409
|
|
135
|
+
class UnsupportedError < ApiError; end # 501
|
|
136
|
+
|
|
137
|
+
# 402: kosa8 Cloud wants a payment method, credit or an accepted price first
|
|
138
|
+
# (+code+ payment_required, spending_cap_reached, price_not_accepted, ...).
|
|
139
|
+
# #upgrade_url, #agent_message and the plan_limit fields (#limit_name,
|
|
140
|
+
# #limit, #used, #plan, #next_plan, #options, #pack_url) are on ApiError.
|
|
141
|
+
class PaymentRequiredError < ApiError; end
|
|
142
|
+
|
|
143
|
+
# 429: too many requests, or a quota reached (+code+ quota_exceeded, with
|
|
144
|
+
# #agent_message and #request_url). +retry_after+ is the server's
|
|
145
|
+
# Retry-After in seconds, when it sent one.
|
|
90
146
|
class RateLimitError < ApiError; end
|
|
91
147
|
|
|
92
148
|
# 423 (+code+ org_frozen): the org is frozen in the Security Center. New
|
|
@@ -100,7 +156,24 @@ module Kosa8
|
|
|
100
156
|
# writing to /workspace, and poll it:
|
|
101
157
|
#
|
|
102
158
|
# box.exec("nohup sh -c 'make test > /workspace/test.log 2>&1' &")
|
|
103
|
-
class ExecTimeoutError < ApiError
|
|
159
|
+
class ExecTimeoutError < ApiError
|
|
160
|
+
attr_writer :stdout, :stderr
|
|
161
|
+
|
|
162
|
+
# The output so far: a streamed exec's, or what a buffered exec stopped
|
|
163
|
+
# at its own timeout_s sent back ("" when the answer had none).
|
|
164
|
+
def stdout
|
|
165
|
+
@stdout || Kosa8.body_str(body, "stdout") || ""
|
|
166
|
+
end
|
|
167
|
+
|
|
168
|
+
def stderr
|
|
169
|
+
@stderr || Kosa8.body_str(body, "stderr") || ""
|
|
170
|
+
end
|
|
171
|
+
|
|
172
|
+
# The limit the command ran past, in seconds, when the answer said.
|
|
173
|
+
def limit_s
|
|
174
|
+
Kosa8.body_num(body, "limit_s")
|
|
175
|
+
end
|
|
176
|
+
end
|
|
104
177
|
|
|
105
178
|
# 403 that a signed approval would lift; +approval+ is the daemon's refusal.
|
|
106
179
|
class ApprovalRequiredError < PolicyError
|
|
@@ -141,6 +214,12 @@ module Kosa8
|
|
|
141
214
|
v.is_a?(String) && !v.empty? ? v : nil
|
|
142
215
|
end
|
|
143
216
|
|
|
217
|
+
# body[key] when it is a Number, else nil.
|
|
218
|
+
def self.body_num(body, key)
|
|
219
|
+
v = body.is_a?(Hash) ? body[key] : nil
|
|
220
|
+
v.is_a?(Numeric) ? v : nil
|
|
221
|
+
end
|
|
222
|
+
|
|
144
223
|
# The typed error for an HTTP error answer: the daemon's message with its
|
|
145
224
|
# remediation in parentheses, as the CLI and MCP server print it.
|
|
146
225
|
def self.error_from_response(status, body, method:, path:, code: nil)
|