kosa8 0.4.0 → 0.5.1

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,526 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "uri"
5
+
6
+ # Fan-out on kosa8 Cloud, for RL rollouts and evals: many sandboxes at once
7
+ # (create_many, fork up to 1000), leases so a crashed trainer leaks none
8
+ # (lease_s, heartbeat), a drain to clean up a run, the sealed grader, retries
9
+ # with backoff, fork_map, org templates and capability tokens.
10
+ module Kosa8
11
+ # How often and how long to retry.
12
+ #
13
+ # +attempts+ counts the first try (1 turns retries off). The n-th retry
14
+ # waits a random time up to min(max_s, base_s * 2**(n-1)) ("full jitter",
15
+ # so a thousand rollouts that failed together do not come back together),
16
+ # and never less than the server's Retry-After (capped at
17
+ # max_retry_after_s). Only what can pass is retried: infra failures and
18
+ # rate limits (Kosa8.classify_failure).
19
+ class RetryPolicy
20
+ attr_reader :attempts, :base_s, :max_s, :max_retry_after_s
21
+
22
+ def initialize(attempts: 3, base_s: 0.5, max_s: 8.0, max_retry_after_s: 60.0, rng: nil)
23
+ raise ArgumentError, "attempts must be a whole number of at least 1" unless attempts.is_a?(Integer) && attempts >= 1
24
+ raise ArgumentError, "base_s and max_s must not be negative" if base_s.negative? || max_s.negative?
25
+
26
+ @attempts = attempts
27
+ @base_s = base_s.to_f
28
+ @max_s = max_s.to_f
29
+ @max_retry_after_s = max_retry_after_s.to_f
30
+ @rng = rng || Random.new
31
+ end
32
+
33
+ def inspect
34
+ "#<Kosa8::RetryPolicy attempts=#{@attempts} base_s=#{@base_s} max_s=#{@max_s}>"
35
+ end
36
+
37
+ # Whether to try again after +exc+ on attempt +attempt+ (1-based).
38
+ def retry?(exc, attempt)
39
+ attempt < @attempts && Kosa8.classify_failure(exc)[1]
40
+ end
41
+
42
+ # Seconds to wait before attempt +attempt+ + 1.
43
+ def delay(exc, attempt)
44
+ cap = [@max_s, @base_s * (2**[0, attempt - 1].max)].min
45
+ wait = cap.positive? ? @rng.rand * cap : 0.0
46
+ ra = exc.respond_to?(:retry_after) ? exc.retry_after : nil
47
+ wait = [wait, [ra.to_f, @max_retry_after_s].min].max if ra.is_a?(Numeric) && ra.positive?
48
+ wait
49
+ end
50
+
51
+ # No retries.
52
+ NONE = new(attempts: 1)
53
+ end
54
+
55
+ # Call the block until it returns, retrying what +policy+ allows; waits
56
+ # with +sleeper+ (default Kernel#sleep). The block gets the attempt number.
57
+ def self.with_retry(policy, sleeper: nil, on_retry: nil)
58
+ attempt = 1
59
+ loop do
60
+ begin
61
+ return yield(attempt)
62
+ rescue StandardError => e
63
+ raise unless policy.retry?(e, attempt)
64
+
65
+ wait = policy.delay(e, attempt)
66
+ on_retry&.call(e, attempt, wait)
67
+ (sleeper || Kernel.method(:sleep)).call(wait)
68
+ attempt += 1
69
+ end
70
+ end
71
+ end
72
+
73
+ # The sandboxes a batch or a fork made: an Array of CloudSandbox, with
74
+ # +failed+ (Hashes: "index", "code", "message", "failure_class",
75
+ # "retryable") for those it could not make, +requested+ and +run_id+.
76
+ class SandboxBatch < Array
77
+ attr_accessor :failed, :requested, :run_id
78
+
79
+ def initialize(sandboxes = [], failed: [], requested: nil, run_id: nil)
80
+ super(sandboxes)
81
+ @failed = failed
82
+ @requested = requested.nil? ? sandboxes.size : requested
83
+ @run_id = run_id
84
+ end
85
+
86
+ # How many were made.
87
+ def created
88
+ size
89
+ end
90
+
91
+ # Whether all that were asked for were made.
92
+ def complete?
93
+ @failed.empty? && size >= @requested.to_i
94
+ end
95
+
96
+ def self.from(cloud, answer, requested)
97
+ r = answer.is_a?(Hash) ? answer : {}
98
+ new((r["sandboxes"] || []).map { |s| CloudSandbox.new(cloud, s) }, failed: Array(r["failed"]),
99
+ requested: r["requested"] || requested,
100
+ run_id: r["run_id"])
101
+ end
102
+ end
103
+
104
+ # What a sealed grade answered. +reward+ is nil when the grader did not
105
+ # finish (+failure_class+ "timeout" or "infra"): mask it, never score it 0.
106
+ # +recorded+ is true when kosa8 Cloud recorded it as a rollout of +run_id+.
107
+ GradeResult = Struct.new(:reward, :metrics, :reward_from, :exit_code, :stdout, :stderr, :failure_class,
108
+ :retryable, :ms, :grader_id, :kept, :sandbox_id, :run_id, :recorded, :error, :message,
109
+ keyword_init: true) do
110
+ def ok?
111
+ failure_class == "ok"
112
+ end
113
+
114
+ def self.from(r)
115
+ r = {} unless r.is_a?(Hash)
116
+ new(reward: r["reward"], metrics: r["metrics"].is_a?(Hash) ? r["metrics"] : {}, reward_from: r["reward_from"],
117
+ exit_code: r["exit"], stdout: r["stdout"].to_s, stderr: r["stderr"].to_s,
118
+ failure_class: (r["failure_class"] || "ok").to_s, retryable: r["retryable"] == true, ms: r["ms"],
119
+ grader_id: r["grader_id"], kept: r["kept"] == true, sandbox_id: r["sandbox_id"], run_id: r["run_id"],
120
+ recorded: r["recorded"], error: r["error"], message: r["message"])
121
+ end
122
+ end
123
+
124
+ class Cloud
125
+ RUN_LABEL = "kosa8.run"
126
+ MAX_BATCH = 1000
127
+ MIN_LEASE_S = 60
128
+ MAX_LEASE_S = 86_400
129
+ DRAIN_MAX = 1000
130
+ DRAIN_ROUNDS = 100
131
+ GRADE_MAX_FILES = 64
132
+ GRADE_MAX_BYTES = 8 * 1024 * 1024
133
+ RUN_ID = /\A[A-Za-z0-9][A-Za-z0-9_.:-]{0,127}\z/.freeze
134
+ PREFIX = /\A[A-Za-z0-9][A-Za-z0-9._-]{0,58}\z/.freeze
135
+ ORG_TEMPLATE_NAME = /\A[a-z0-9][a-z0-9._-]{0,62}\z/.freeze
136
+ TOKEN_SCOPES = %w[sandboxes:read sandboxes:write functions:invoke].freeze
137
+
138
+ alias initialize_without_rl initialize
139
+ def initialize(**kw)
140
+ initialize_without_rl(**kw)
141
+ @org_templates = CloudOrgTemplates.new(self)
142
+ @tokens = CloudTokens.new(self)
143
+ end
144
+
145
+ # The org's own templates (built from an image or a Dockerfile, kept as a snapshot).
146
+ attr_reader :org_templates
147
+ # Short-lived capability tokens.
148
+ attr_reader :tokens
149
+
150
+ def self.check_lease(lease_s)
151
+ return lease_s if lease_s.is_a?(Integer) && lease_s.between?(MIN_LEASE_S, MAX_LEASE_S)
152
+
153
+ raise ArgumentError, "lease_s must be a whole number of seconds from #{MIN_LEASE_S} to #{MAX_LEASE_S}"
154
+ end
155
+
156
+ def self.check_run_id(run_id)
157
+ return run_id.to_s if RUN_ID.match?(run_id.to_s)
158
+
159
+ raise ArgumentError, "run_id must be 1-128 letters, digits, '_', '.', ':' or '-', starting with a letter or digit"
160
+ end
161
+
162
+ # The fan-out fields a batch and a fork share, with the open Run's
163
+ # run_id and lease_s when not given.
164
+ def self.fanout_body(cloud, labels: nil, run_id: nil, lease_s: nil, prefix: nil, partial_ok: nil)
165
+ amb = cloud.run_defaults || {}
166
+ run_id = amb["run_id"] if run_id.nil?
167
+ lease_s = amb["lease_s"] if lease_s.nil?
168
+ body = {}
169
+ body["labels"] = check_labels(labels) unless labels.nil?
170
+ unless run_id.nil?
171
+ body["run_id"] = check_run_id(run_id)
172
+ if (body["labels"] || {}).merge(RUN_LABEL => run_id).size > MAX_LABELS
173
+ raise ArgumentError, "at most #{MAX_LABELS} labels, kosa8.run included"
174
+ end
175
+ end
176
+ body["lease_s"] = check_lease(lease_s) unless lease_s.nil?
177
+ unless prefix.nil?
178
+ unless PREFIX.match?(prefix.to_s)
179
+ raise ArgumentError, "prefix must be 1-59 letters, digits, '.', '_' or '-', starting with a letter or digit"
180
+ end
181
+
182
+ body["prefix"] = prefix.to_s
183
+ end
184
+ unless partial_ok.nil?
185
+ raise ArgumentError, "partial_ok must be true or false" unless [true, false].include?(partial_ok)
186
+
187
+ body["partial_ok"] = partial_ok
188
+ end
189
+ body
190
+ end
191
+
192
+ # run_id, labels and ids (at least one) for heartbeat and drain.
193
+ def self.selector(run_id, labels, ids)
194
+ body = {}
195
+ body["run_id"] = check_run_id(run_id) unless run_id.nil?
196
+ body["labels"] = check_labels(labels) unless labels.nil?
197
+ unless ids.nil?
198
+ list = Array(ids).map { |x| x.is_a?(CloudSandbox) ? x.id : x.to_s }
199
+ raise ArgumentError, "ids must be 1 to #{DRAIN_MAX} sandbox ids" if list.empty? || list.size > DRAIN_MAX
200
+
201
+ body["ids"] = list
202
+ end
203
+ raise ArgumentError, "give run_id:, labels: or ids: (which sandboxes)" if body.empty?
204
+
205
+ body
206
+ end
207
+
208
+ # The body of POST /v1/sandboxes/{id}/grade.
209
+ def self.grade_body(cmd, files: nil, timeout_s: nil, env: nil, keep: false, run_id: nil, rollout: nil)
210
+ argv = cmd.is_a?(String) ? ["sh", "-c", cmd] : Array(cmd).map(&:to_s)
211
+ raise ArgumentError, "cmd must be a command: a String or a non-empty Array" if argv.empty?
212
+
213
+ body = { "cmd" => argv }
214
+ unless files.nil?
215
+ raise ArgumentError, "files is a Hash of {\"/absolute/path\" => content}" unless files.is_a?(Hash)
216
+ raise ArgumentError, "at most #{GRADE_MAX_FILES} files" if files.size > GRADE_MAX_FILES
217
+
218
+ total = 0
219
+ body["files"] = files.map do |p, v|
220
+ p = p.to_s
221
+ raise ArgumentError, "file path #{p.inspect} must be absolute, without .." if !p.start_with?("/") || p.split("/").include?("..")
222
+
223
+ bytes = v.to_s.b
224
+ total += bytes.bytesize
225
+ raise ArgumentError, "files add up to more than 8 MiB" if total > GRADE_MAX_BYTES
226
+
227
+ [p, [bytes].pack("m0")]
228
+ end.to_h
229
+ end
230
+ unless timeout_s.nil?
231
+ t = timeout_s.is_a?(Float) && timeout_s == timeout_s.floor ? timeout_s.to_i : timeout_s
232
+ raise ArgumentError, "timeout_s must be a whole number of seconds from 1 to 90" unless t.is_a?(Integer) && t.between?(1, 90)
233
+
234
+ body["timeout_s"] = t
235
+ end
236
+ unless env.nil?
237
+ body["env"] = env.is_a?(Hash) ? Cloud.env_list(Cloud.check_env(env)) : Array(env).map(&:to_s)
238
+ end
239
+ body["keep"] = true if keep
240
+ body["run_id"] = check_run_id(run_id) unless run_id.nil?
241
+ unless rollout.nil?
242
+ raise ArgumentError, "rollout is a Hash of step, group, index, meta" unless rollout.is_a?(Hash)
243
+
244
+ ro = rollout.map { |k, v| [k.to_s, v] }.to_h
245
+ ro["group"] = ro["group"].to_s if ro.key?("group") && !ro["group"].nil?
246
+ body["rollout"] = ro.reject { |_, v| v.nil? }
247
+ end
248
+ body
249
+ end
250
+
251
+ # Run +block+ (sandbox, item) in a fork of +base+ for every item; see
252
+ # CloudSandbox#fork_map.
253
+ def fork_map(base, items, **opts, &block)
254
+ ForkMap.run(self, base, items, **opts, &block)
255
+ end
256
+ end
257
+
258
+ class CloudSandboxes
259
+ # Make +count+ (1 to 1000) sandboxes in one call, paced by kosa8 (16 at a
260
+ # time), as a SandboxBatch. Takes the options of #create (template:,
261
+ # size:, image:, env:, egress:, ttl_s:, ...) for every one, plus labels:,
262
+ # run_id: (labels them kosa8.run), lease_s:, prefix: (names them
263
+ # <prefix>-0001, ...) and partial_ok: (default true: make what fits and
264
+ # list the rest in +failed+; false: all or nothing). Nothing made raises
265
+ # the first refusal. Carries an Idempotency-Key (+idempotency_key+,
266
+ # default a new UUID) reused on every retry, so a retried batch never
267
+ # doubles the fleet.
268
+ def create_many(count, labels: nil, run_id: nil, lease_s: nil, prefix: nil, partial_ok: nil,
269
+ idempotency_key: nil, **create_opts)
270
+ unless count.is_a?(Integer) && count.between?(1, Cloud::MAX_BATCH)
271
+ raise ArgumentError, "count must be a whole number from 1 to #{Cloud::MAX_BATCH}"
272
+ end
273
+ raise ArgumentError, "a batch names its sandboxes with prefix:, not name:" if create_opts.key?(:name)
274
+
275
+ unknown = create_opts.keys - %i[template region sleep_after_s ttl_s delete_after accept_price size cpus mem_mb
276
+ image disk_gb persistent docker cpu env secrets egress snapshot]
277
+ raise ArgumentError, "unknown option #{unknown.first}: for create_many" unless unknown.empty?
278
+ if !lease_s.nil? && (create_opts[:ttl_s] || create_opts[:delete_after])
279
+ raise ArgumentError, "give lease_s or ttl_s/delete_after, not both"
280
+ end
281
+
282
+ body = create_body(**create_opts)
283
+ fan_lease = lease_s
284
+ fan_lease = (@cloud.run_defaults || {})["lease_s"] if fan_lease.nil? && !body.key?("ttl_s") && !body.key?("delete_after")
285
+ fan = Cloud.fanout_body(@cloud, labels: labels, run_id: run_id, lease_s: fan_lease, prefix: prefix,
286
+ partial_ok: partial_ok)
287
+ fan.delete("lease_s") if fan_lease.nil?
288
+ body = { "count" => count }.merge(body).merge(fan)
289
+ Cloud.check_idempotency_key(idempotency_key)
290
+ r = @cloud.request("POST", "/v1/sandboxes/batch", body, idempotency_key: idempotency_key)
291
+ SandboxBatch.from(@cloud, r, count)
292
+ end
293
+
294
+ # Push back the lease of the matching leased sandboxes to now + extend_s
295
+ # (default each one's own lease_s). Returns how many were extended.
296
+ def heartbeat(run_id: nil, labels: nil, ids: nil, extend_s: nil)
297
+ body = Cloud.selector(run_id, labels, ids)
298
+ body["extend_s"] = Cloud.check_lease(extend_s) unless extend_s.nil?
299
+ r = @cloud.request("POST", "/v1/sandboxes/heartbeat", body)
300
+ r.is_a?(Hash) ? r["extended"].to_i : 0
301
+ end
302
+
303
+ # Delete every matching sandbox of the org: {"deleted" => n, "ids" =>
304
+ # [...], "failed" => [...]}. kosa8 Cloud deletes up to 1000 a call; this
305
+ # calls again while it says there are more (and stops if a call deleted none).
306
+ def drain(run_id: nil, labels: nil, ids: nil)
307
+ sel = Cloud.selector(run_id, labels, ids)
308
+ out = { "deleted" => 0, "ids" => [], "failed" => [] }
309
+ Cloud::DRAIN_ROUNDS.times do
310
+ r = @cloud.request("POST", "/v1/sandboxes/drain", sel)
311
+ r = {} unless r.is_a?(Hash)
312
+ n = r["deleted"].to_i
313
+ out["deleted"] += n
314
+ out["ids"].concat(Array(r["ids"]))
315
+ out["failed"].concat(Array(r["failed"]))
316
+ break unless r["more"] == true && n.positive?
317
+ end
318
+ out
319
+ end
320
+
321
+ # Grade a solved sandbox (an id or a CloudSandbox) in a sealed fork; see CloudSandbox#grade.
322
+ def grade(sandbox, cmd, **opts)
323
+ box = sandbox.is_a?(CloudSandbox) ? sandbox : CloudSandbox.new(@cloud, { "id" => sandbox.to_s })
324
+ box.grade(cmd, **opts)
325
+ end
326
+ end
327
+
328
+ class CloudSandbox
329
+ # Push back this sandbox's lease; see CloudSandboxes#heartbeat.
330
+ def heartbeat(extend_s: nil)
331
+ @cloud.sandboxes.heartbeat(ids: [id], extend_s: extend_s)
332
+ end
333
+
334
+ # Grade this sandbox's state with hidden tests, in a sealed fork.
335
+ #
336
+ # kosa8 Cloud forks one copy, takes all network away from it, writes
337
+ # +files+ ({"/grader/test.py" => "..."}; this sandbox never sees them),
338
+ # runs +cmd+ and deletes the copy (unless keep: true). The reward is the
339
+ # last stdout line that is JSON with a numeric "reward", else 1.0 for exit
340
+ # 0 and 0.0 otherwise; nil when the command did not finish. With run_id:
341
+ # it is recorded as a rollout of that run (rollout: step, group, index,
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 on every
344
+ # retry: a retry gets the first grade's answer and records nothing twice.
345
+ def grade(cmd, files: nil, timeout_s: nil, env: nil, keep: false, run_id: nil, rollout: nil, idempotency_key: nil)
346
+ run_id = (@cloud.run_defaults || {})["run_id"] if run_id.nil?
347
+ body = Cloud.grade_body(cmd, files: files, timeout_s: timeout_s, env: env, keep: keep, run_id: run_id,
348
+ rollout: rollout)
349
+ Cloud.check_idempotency_key(idempotency_key)
350
+ GradeResult.from(@cloud.request("POST", path("/grade"), body, idempotency_key: idempotency_key))
351
+ end
352
+
353
+ # Run the block (child, item) for every item, each in its own fork of
354
+ # this sandbox, +concurrency+ at a time; results (ForkResult) in item
355
+ # order. A failure is the item's result, never raised; infra failures and
356
+ # rate limits are retried +retries+ times on a fresh fork with backoff.
357
+ # Every fork is deleted when its item is done, and all that are left when
358
+ # the map ends for any reason (an exception, Ctrl-C). timeout_s: caps
359
+ # each item (its fork is deleted). labels:, run_id:, lease_s: go on each fork.
360
+ def fork_map(items, **opts, &block)
361
+ ForkMap.run(@cloud, self, items, **opts, &block)
362
+ end
363
+ end
364
+
365
+ # cloud.org_templates: the org's own templates, built on a kosa8 Cloud host
366
+ # and kept as a snapshot, so a sandbox created from one
367
+ # (sandboxes.create(template: name)) is a restore, not a cold pull.
368
+ class CloudOrgTemplates
369
+ def initialize(cloud)
370
+ @cloud = cloud
371
+ end
372
+
373
+ def inspect
374
+ "#<Kosa8::CloudOrgTemplates>"
375
+ end
376
+
377
+ # Build a template from +image+ (a tag or @sha256 digest) or a
378
+ # +dockerfile+ (its text). Answers the template, queued or building; poll
379
+ # #wait_ready. setup_cmd: runs once in the booted template before it is saved.
380
+ def build(name, image: nil, dockerfile: nil, build_args: nil, setup_cmd: nil, size: nil, cpus: nil, mem_mb: nil,
381
+ region: nil)
382
+ raise ArgumentError, "give image: or dockerfile:, not both" if !image.nil? && !dockerfile.nil?
383
+ raise ArgumentError, "give image: or dockerfile:" if image.nil? && dockerfile.nil?
384
+
385
+ body = { "name" => check_name(name) }
386
+ body["image"] = image.to_s unless image.nil?
387
+ body["dockerfile"] = dockerfile.to_s unless dockerfile.nil?
388
+ body["build_args"] = build_args.map { |k, v| [k.to_s, v.to_s] }.to_h unless build_args.nil?
389
+ sizing(body, setup_cmd, size, cpus, mem_mb, region)
390
+ r = @cloud.request("POST", "/v1/templates", body)
391
+ r.is_a?(Hash) ? r["template"] : nil
392
+ end
393
+
394
+ # Queue many image templates at once (such as RL task images by
395
+ # digest): +images+ is an Array of {name:, image:}. Answers "queued",
396
+ # "templates" and "failed" (with partial_ok: true).
397
+ def import(images, setup_cmd: nil, size: nil, cpus: nil, mem_mb: nil, region: nil, partial_ok: nil)
398
+ list = Array(images).map do |i|
399
+ h = i.to_h.map { |k, v| [k.to_s, v] }.to_h
400
+ raise ArgumentError, "each image is {name:, image:}" if h["name"].nil? || h["image"].nil?
401
+
402
+ { "name" => check_name(h["name"]), "image" => h["image"].to_s }
403
+ end
404
+ raise ArgumentError, "images must be 1 to 1000 {name:, image:}" if list.empty? || list.size > 1000
405
+
406
+ body = { "images" => list }
407
+ sizing(body, setup_cmd, size, cpus, mem_mb, region)
408
+ body["partial_ok"] = partial_ok == true unless partial_ok.nil?
409
+ @cloud.request("POST", "/v1/templates/import", body)
410
+ end
411
+
412
+ # The org's templates (Cloud#templates lists kosa8's).
413
+ def list
414
+ r = @cloud.request("GET", "/v1/templates")
415
+ r.is_a?(Hash) ? (r["org_templates"] || []) : []
416
+ end
417
+
418
+ # One template (by id tpl_... or name), with its build log.
419
+ def get(id_or_name)
420
+ r = @cloud.request("GET", "/v1/templates/#{Kosa8.enc(id_or_name)}")
421
+ r.is_a?(Hash) ? r["template"] : nil
422
+ end
423
+
424
+ # Delete it: a build in flight stops and its snapshot is deleted.
425
+ def delete(id_or_name)
426
+ @cloud.request("DELETE", "/v1/templates/#{Kosa8.enc(id_or_name)}")
427
+ nil
428
+ end
429
+
430
+ # Poll until it is ready (returns it); raises Kosa8::Error if it failed
431
+ # or is gone, Kosa8::TimeoutError past +timeout+ seconds.
432
+ def wait_ready(id_or_name, timeout: 3600, poll_interval: 5)
433
+ deadline = Time.now + timeout
434
+ loop do
435
+ t = get(id_or_name) || {}
436
+ case t["state"]
437
+ when "ready" then return t
438
+ when "failed", "deleted"
439
+ raise Error.new("template #{id_or_name} #{t['state']}: #{t['last_error'] || 'no reason given'}",
440
+ body: t, code: "template_#{t['state']}")
441
+ end
442
+ raise TimeoutError, "template #{id_or_name} still #{t['state']} after #{timeout} s" if Time.now >= deadline
443
+
444
+ @cloud.sleeper.call(poll_interval)
445
+ end
446
+ end
447
+
448
+ private
449
+
450
+ def check_name(name)
451
+ return name.to_s if Cloud::ORG_TEMPLATE_NAME.match?(name.to_s)
452
+
453
+ raise ArgumentError, "a template name is 1-63 lowercase letters, digits, '.', '_' or '-'"
454
+ end
455
+
456
+ def sizing(body, setup_cmd, size, cpus, mem_mb, region)
457
+ body["setup_cmd"] = setup_cmd.is_a?(String) ? setup_cmd : Array(setup_cmd).map(&:to_s) unless setup_cmd.nil?
458
+ unless size.nil?
459
+ raise ArgumentError, "size must be one of #{Cloud::SIZES.join(', ')}" unless Cloud::SIZES.include?(size.to_s)
460
+
461
+ body["size"] = size.to_s
462
+ end
463
+ raise ArgumentError, "give cpus: and mem_mb: together" if cpus.nil? != mem_mb.nil?
464
+
465
+ unless cpus.nil?
466
+ body["cpus"] = Integer(cpus)
467
+ body["mem_mb"] = Integer(mem_mb)
468
+ end
469
+ body["region"] = region.to_s unless region.nil?
470
+ end
471
+ end
472
+
473
+ # cloud.tokens: short-lived bearer tokens (k8c_tok_...) limited to some
474
+ # scopes and, optionally, some sandboxes, to hand a sandbox to your own end
475
+ # user without handing over the API key. Kosa8::Cloud.new(api_key: secret)
476
+ # works with one.
477
+ class CloudTokens
478
+ def initialize(cloud)
479
+ @cloud = cloud
480
+ end
481
+
482
+ def inspect
483
+ "#<Kosa8::CloudTokens>"
484
+ end
485
+
486
+ # Make a token; its "secret" is in the answer once and never again.
487
+ # +scopes+ from sandboxes:read, sandboxes:write, functions:invoke;
488
+ # sandbox_ids: (up to 100) or labels: limit what it reaches; ttl_s: 60 to
489
+ # 86400 (default 3600).
490
+ def create(scopes, sandbox_ids: nil, labels: nil, ttl_s: nil, name: nil)
491
+ list = Array(scopes).map(&:to_s)
492
+ if list.empty? || list.uniq.size != list.size || !(list - Cloud::TOKEN_SCOPES).empty?
493
+ raise ArgumentError, "scopes must be a non-empty list from #{Cloud::TOKEN_SCOPES.join(', ')}"
494
+ end
495
+
496
+ body = { "scopes" => list }
497
+ unless sandbox_ids.nil?
498
+ ids = Array(sandbox_ids).map { |x| x.is_a?(CloudSandbox) ? x.id : x.to_s }
499
+ raise ArgumentError, "sandbox_ids must be 1 to 100 sandbox ids" if ids.empty? || ids.size > 100
500
+
501
+ body["sandbox_ids"] = ids
502
+ end
503
+ body["labels"] = Cloud.check_labels(labels) unless labels.nil?
504
+ unless ttl_s.nil?
505
+ raise ArgumentError, "ttl_s must be a whole number of seconds from 60 to 86400" unless ttl_s.is_a?(Integer) && ttl_s.between?(60, 86_400)
506
+
507
+ body["ttl_s"] = ttl_s
508
+ end
509
+ body["name"] = name.to_s unless name.nil?
510
+ r = @cloud.request("POST", "/v1/tokens", body)
511
+ r.is_a?(Hash) ? r["token"] : nil
512
+ end
513
+
514
+ # The tokens (never their secrets); all: true adds the last day's revoked and expired ones.
515
+ def list(all: false)
516
+ r = @cloud.request("GET", "/v1/tokens#{all ? '?all=1' : ''}")
517
+ r.is_a?(Hash) ? (r["tokens"] || []) : []
518
+ end
519
+
520
+ # Revoke a token; it stops at once. Answers the token.
521
+ def revoke(id)
522
+ r = @cloud.request("DELETE", "/v1/tokens/#{Kosa8.enc(id)}")
523
+ r.is_a?(Hash) ? r["token"] : nil
524
+ end
525
+ end
526
+ end
data/lib/kosa8/errors.rb CHANGED
@@ -1,11 +1,16 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require "timeout"
4
+
3
5
  module Kosa8
4
6
  # Every error this gem raises. The daemon's own words are kept in
5
7
  # +daemon_message+ and +remediation+, as @kosa8/sdk does.
6
8
  class Error < StandardError
7
9
  # +code+ is kosa8 Cloud's stable error code (payment_required, quota_exceeded, ...).
8
10
  attr_reader :status, :daemon_message, :remediation, :http_method, :path, :body, :code
11
+ # Seconds the server asked to wait before trying again (Retry-After, or
12
+ # the body's retry_after_s), when it said.
13
+ attr_accessor :retry_after
9
14
 
10
15
  def initialize(message = nil, status: nil, daemon_message: nil, remediation: nil, method: nil, path: nil, body: nil,
11
16
  code: nil)
@@ -18,6 +23,18 @@ module Kosa8
18
23
  @body = body
19
24
  @code = code
20
25
  end
26
+
27
+ # Whose fault it was: "ok", "exit_nonzero", "timeout", "infra", "quota",
28
+ # "client", or "error" (not an API answer). See Kosa8.classify_failure.
29
+ def failure_class
30
+ Kosa8.classify_failure(self)[0]
31
+ end
32
+
33
+ # Whether the same call may work if sent again.
34
+ def retryable?
35
+ Kosa8.classify_failure(self)[1]
36
+ end
37
+ alias retryable retryable?
21
38
  end
22
39
 
23
40
  class ConnectionError < Error; end # daemon unreachable
@@ -45,18 +62,16 @@ module Kosa8
45
62
 
46
63
  # 429: too many requests, or a quota reached (+code+ quota_exceeded).
47
64
  # +retry_after+ is the server's Retry-After in seconds, when it sent one.
48
- class RateLimitError < ApiError
49
- attr_accessor :retry_after
50
- end
65
+ class RateLimitError < ApiError; end
51
66
 
52
67
  # 423 (+code+ org_frozen): the org is frozen in the Security Center. New
53
68
  # sandboxes, commands, wakes and function calls are refused until an owner or
54
69
  # admin unfreezes it; retrying does not help.
55
70
  class OrgFrozenError < ApiError; end
56
71
 
57
- # A kosa8 Cloud exec ran past the API's limit for a buffered command. Today a
58
- # buffered exec is cut off after about 30 s (HTTP 502 host_failed "timed out";
59
- # later servers answer 504 exec_timeout). Run long work in the background,
72
+ # A kosa8 Cloud exec ran past the API's limit for a buffered command. A
73
+ # buffered exec runs at most 90 s, then the API stops it and answers 504
74
+ # exec_timeout (older servers: HTTP 502 host_failed "timed out"). Run long work in the background,
60
75
  # writing to /workspace, and poll it:
61
76
  #
62
77
  # box.exec("nohup sh -c 'make test > /workspace/test.log 2>&1' &")
@@ -122,4 +137,67 @@ module Kosa8
122
137
 
123
138
  (BY_STATUS[status] || ApiError).new(text, **kw)
124
139
  end
140
+
141
+ # The failure classes kosa8 Cloud puts on every answer under /v1/sandboxes.
142
+ FAILURE_CLASSES = %w[ok exit_nonzero timeout oom infra quota client].freeze
143
+ INFRA_CODES = %w[host_failed not_ready no_capacity host_unreachable host_unavailable host_busy host_restarting
144
+ wake_failed try_again internal kernel_failed egress_failed dns_unreachable host_lost host_removed
145
+ insufficient_storage starting].freeze
146
+ RATE_CODES = %w[rate_limited slow_down too_soon].freeze
147
+ QUOTA_CODES = %w[quota_exceeded running_limit plan_required plan_limit plan_feature payment_required payment_declined
148
+ spending_cap_reached snapshot_limit org_frozen org_suspended too_many_runs].freeze
149
+ IDEMPOTENCY_IN_PROGRESS = "idempotency_in_progress"
150
+
151
+ # [failure_class, retryable] for an HTTP status and error code, by the
152
+ # server's own rules (workers/cloud-api failures.js), for answers that came
153
+ # without failure_class (an older server, a proxy).
154
+ def self.failure_of(status, code = nil)
155
+ c = code.is_a?(String) ? code : ""
156
+ return ["ok", false] if status < 400
157
+ return ["timeout", false] if c == "exec_timeout"
158
+ return ["timeout", true] if c.include?("timeout")
159
+ return ["quota", true] if RATE_CODES.include?(c)
160
+ return ["quota", false] if QUOTA_CODES.include?(c) || status == 402 || status == 423
161
+ return ["quota", c != "quota_exceeded"] if status == 429
162
+ return ["infra", false] if c == "not_available" || c == "not_supported" || status == 501
163
+ return ["infra", true] if INFRA_CODES.include?(c) || status >= 500
164
+
165
+ ["client", false]
166
+ end
167
+
168
+ # [failure_class, retryable] of an exec that ran: ok on exit 0,
169
+ # exit_nonzero on any other exit, infra when there was no exit code.
170
+ def self.exec_failure(exit_code)
171
+ return ["infra", true] unless exit_code.is_a?(Integer)
172
+
173
+ [exit_code.zero? ? "ok" : "exit_nonzero", false]
174
+ end
175
+
176
+ # [failure_class, retryable] for any exception. A kosa8 Cloud error body's
177
+ # failure_class and retryable are used as sent; 409 idempotency_in_progress
178
+ # is retryable (the first request with that key is still running); no
179
+ # answer at all is infra (retryable); an exec past its limit is timeout;
180
+ # else the server's rules (Kosa8.failure_of). An exception that is not a
181
+ # Kosa8::Error is "error" (not retryable): a bug in your code.
182
+ def self.classify_failure(exc)
183
+ return ["client", true] if exc.is_a?(Error) && exc.code == IDEMPOTENCY_IN_PROGRESS
184
+
185
+ body = exc.respond_to?(:body) ? exc.body : nil
186
+ if body.is_a?(Hash) && body["failure_class"].is_a?(String)
187
+ fc = body["failure_class"]
188
+ rt = body["retryable"]
189
+ return [fc, rt == true || rt == false ? rt : fc == "infra"]
190
+ end
191
+ unless exc.is_a?(Error)
192
+ return ["infra", true] if exc.is_a?(SystemCallError) || exc.is_a?(IOError) || exc.is_a?(SocketError) ||
193
+ exc.is_a?(::Timeout::Error)
194
+
195
+ return ["error", false]
196
+ end
197
+ return ["timeout", false] if exc.is_a?(ExecTimeoutError)
198
+ return ["infra", true] if exc.is_a?(ConnectionError) || exc.is_a?(TimeoutError)
199
+ return ["error", false] if exc.status.nil?
200
+
201
+ failure_of(exc.status, exc.code)
202
+ end
125
203
  end