heaven-sdk 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,574 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "ipaddr"
4
+ require "json"
5
+ require "net/http"
6
+ require "securerandom"
7
+ require "uri"
8
+
9
+ module Heaven
10
+ # A client for one Heaven deployment's /v1 API (docs/API.md).
11
+ #
12
+ # Its typed methods cover Computers (#computers), operations
13
+ # (#operations) and #exec; #command sends any command in the catalog by
14
+ # its name, routed by the catalog GET /v1/command/ answers, so a command
15
+ # added to Heaven works without a new SDK release.
16
+ #
17
+ # Retries follow docs/API.md, "Retries":
18
+ #
19
+ # - A read, or a change sent with a request ID, is sent again after a
20
+ # lost connection, a timeout, an answer that isn't Heaven's (a proxy's
21
+ # 429 or 5xx, or one cut short), or Heaven's busy, rate_limited,
22
+ # unavailable or unknown. A change carries the same Idempotency-Key
23
+ # every time, so a repeat answers the first attempt and never makes a
24
+ # second Computer, operation or purchase.
25
+ # - Any other change, exec included, is sent again only when the
26
+ # connection was never made, or after Heaven's own busy, rate_limited
27
+ # or unavailable, which say nothing changed. A lost answer raises
28
+ # UnknownOutcomeError: check before repeating it.
29
+ class Client
30
+ DEFAULT_DOMAIN = "heaven.dev"
31
+
32
+ # exec's stdin in JSON is at most 1 MiB; more is sent as the body.
33
+ EXEC_JSON_STDIN_LIMIT = 1 << 20
34
+
35
+ # The longest wait one operation view takes.
36
+ OPERATION_WAIT_LIMIT = 600
37
+
38
+ # Retry modes: :idempotent for reads and changes sent with a request
39
+ # ID, :once for everything else.
40
+ RETRY_MODES = %i[idempotent once].freeze
41
+
42
+ # Kinds that say nothing changed, so any request may be sent again.
43
+ NOTHING_CHANGED = %w[busy rate_limited unavailable].freeze
44
+
45
+ # A request ID: 1 to 128 visible ASCII characters (the lobby takes 1 to
46
+ # 128 bytes; a header value cannot carry the rest unchanged).
47
+ REQUEST_ID = /\A[\x21-\x7e]{1,128}\z/
48
+
49
+ # HTTP status to kind, for an answer that is not Heaven's JSON.
50
+ STATUS_KINDS = {
51
+ 400 => "invalid", 401 => "unauthenticated", 402 => "payment_required", 403 => "denied",
52
+ 404 => "not_found", 409 => "conflict", 429 => "busy", 502 => "unavailable",
53
+ 503 => "unavailable", 504 => "unavailable"
54
+ }.freeze
55
+
56
+ attr_reader :base_url, :timeout, :open_timeout, :max_retries, :max_retry_wait, :computers, :operations
57
+
58
+ # [api_key] the bearer credential: an API key (heaven1...), a CLI
59
+ # sign-in's key or a signed heaven0 token. Defaults to
60
+ # HEAVEN_API_KEY.
61
+ # [domain] the deployment, as the heaven program's HEAVEN_DOMAIN:
62
+ # heaven.dev by default.
63
+ # [base_url] the origin to send to, overriding +domain+. http:// is
64
+ # accepted only for a loopback address (tests).
65
+ # [timeout] seconds to wait for each answer. exec answers within 30.
66
+ # [open_timeout] seconds to connect, TLS included.
67
+ # [max_retries] how many more times a request may be sent (see above);
68
+ # 0 sends each once.
69
+ # [max_retry_wait] the longest retry_after to wait out; a longer one
70
+ # is raised at once.
71
+ def initialize(api_key: nil, domain: nil, base_url: nil, timeout: 60, open_timeout: 10,
72
+ max_retries: 2, max_retry_wait: 30)
73
+ key = api_key || ENV.fetch("HEAVEN_API_KEY", "")
74
+ raise ArgumentError, "No credential: pass api_key: or set HEAVEN_API_KEY." if key.empty?
75
+
76
+ base_url ||= "https://#{domain || ENV.fetch('HEAVEN_DOMAIN', nil) || DEFAULT_DOMAIN}"
77
+ @origin = checked_origin(base_url)
78
+ @base_url = @origin.to_s.chomp("/")
79
+ @api_key = key
80
+ @timeout = timeout
81
+ @open_timeout = open_timeout
82
+ @max_retries = max_retries
83
+ @max_retry_wait = max_retry_wait
84
+ @sleeper = ->(seconds) { sleep(seconds) }
85
+ @catalog = nil
86
+ @catalog_lock = Mutex.new
87
+ @computers = Computers.new(self)
88
+ @operations = Operations.new(self)
89
+ end
90
+
91
+ # The key never appears.
92
+ def inspect = "#<#{self.class.name} base_url=#{@base_url.inspect}>"
93
+ alias to_s inspect
94
+
95
+ # A fresh request ID. Choose one before the first attempt of a change
96
+ # and pass it to every attempt of that change.
97
+ def self.new_request_id = SecureRandom.uuid
98
+
99
+ # Runs one shell command in a Computer, as `ssh NAME CMD` does, and
100
+ # answers its combined output and exit status as an ExecResult.
101
+ #
102
+ # The command has 30 seconds and 1 MiB of output. +stdin+ (a String
103
+ # of bytes) up to 1 MiB goes in the JSON body; more is the request
104
+ # body. A command that exits non-zero is its answer, not an error. A
105
+ # command is never sent again once it may have started: a lost answer
106
+ # raises UnknownOutcomeError, and whether it ran is checked inside the
107
+ # Computer.
108
+ def exec(computer, command, stdin: nil, timeout: nil)
109
+ raise ArgumentError, "command is one shell command line, a String." unless command.is_a?(String)
110
+
111
+ r = if stdin && stdin.bytesize > EXEC_JSON_STDIN_LIMIT
112
+ request(:post, "/v1/computer/exec", query: { computer: computer, command: command },
113
+ content: stdin.b, retry_mode: :once, timeout: timeout)
114
+ else
115
+ body = { computer: computer, command: command }
116
+ body[:stdin] = [stdin.b].pack("m0") if stdin
117
+ request(:post, "/v1/computer/exec", body: body, retry_mode: :once, timeout: timeout)
118
+ end
119
+ ExecResult.from_json(r.data || {})
120
+ end
121
+
122
+ # Sends any command in the catalog by its name or alias ("pool
123
+ # rename"), with its fields as the command reference names them
124
+ # (<tt>{pool: "web", name: "www"}</tt>), and answers a Response.
125
+ #
126
+ # A command that takes a request ID (a request-id flag in the catalog)
127
+ # always carries one as its Idempotency-Key: +request_id+, or a new one,
128
+ # which the answer and any error carry. +request_id+ for a command
129
+ # that takes none raises ArgumentError before anything is sent.
130
+ def command(name, fields = {}, request_id: nil, timeout: nil)
131
+ entry = catalog[name.to_s]
132
+ raise ArgumentError, "No command #{name.inspect} in the catalog: see GET /v1/command/." unless entry
133
+
134
+ route = entry["route"]
135
+ raise ArgumentError, "`#{entry['name']}` has no HTTPS endpoint; it runs over SSH only." unless route
136
+
137
+ takes_id = Client.takes_request_id?(entry)
138
+ raise ArgumentError, "`#{entry['name']}` takes no request ID (docs/API.md, Retries)." if request_id && !takes_id
139
+
140
+ sent = fields.to_h.transform_keys(&:to_s)
141
+ raise ArgumentError, "Pass request_id: as a keyword, not a field." if sent.key?("request_id")
142
+
143
+ sent["view"] = route["view"] if route["view"]
144
+ sent["action"] = route["action"] if route["action"]
145
+ if route["method"] == "GET"
146
+ request(:get, route["path"], query: sent, timeout: timeout)
147
+ else
148
+ request(:post, route["path"], body: sent, request_id: takes_id ? request_id || Client.new_request_id : nil,
149
+ timeout: timeout)
150
+ end
151
+ end
152
+
153
+ # The catalog by command name and alias, read once from GET
154
+ # /v1/command/, as the heaven program reads it.
155
+ def catalog
156
+ @catalog_lock.synchronize do
157
+ @catalog ||= begin
158
+ commands = (request(:get, "/v1/command/").data || {})["commands"] || []
159
+ raise UnavailableError, "Heaven listed no commands." if commands.empty?
160
+
161
+ by_name = {}
162
+ commands.each { |c| (c["aliases"] || []).each { by_name[_1] ||= c } }
163
+ commands.each { |c| by_name[c["name"]] = c }
164
+ by_name.freeze
165
+ end
166
+ end
167
+ end
168
+
169
+ # Whether a catalog entry takes a request ID, as the heaven program
170
+ # decides it: a request-id flag.
171
+ def self.takes_request_id?(entry)
172
+ (entry["flags"] || []).any? { _1["name"] == "request-id" }
173
+ end
174
+
175
+ # Sends one request to this client's origin and answers a Response,
176
+ # raising a Heaven::Error for a refusal. Every method above goes
177
+ # through it.
178
+ #
179
+ # +path+ is an absolute path on the origin (/v1/...). +query+ is
180
+ # encoded as the API reads it (an Array repeats its field, true and
181
+ # false are switches); +body+ is sent as JSON, or +content+ as
182
+ # application/octet-stream. +request_id+ is the Idempotency-Key.
183
+ #
184
+ # +retry_mode+ is :idempotent for a GET or a request with a +request_id+,
185
+ # and :once for any other. :idempotent for a change without a
186
+ # +request_id+ raises ArgumentError. +retry_unknown+ false raises
187
+ # Heaven's +unknown+ at once instead of sending it again, for a caller
188
+ # that reconciles it itself (Operations#wait). Redirects are never
189
+ # followed.
190
+ def request(method, path, query: nil, body: nil, content: nil, request_id: nil, retry_mode: nil, timeout: nil,
191
+ retry_unknown: true)
192
+ method = method.to_s.upcase
193
+ raise ArgumentError, "method is GET or POST, not #{method}." unless %w[GET POST].include?(method)
194
+ if request_id && !REQUEST_ID.match?(request_id.to_s)
195
+ raise ArgumentError, "A request ID is 1 to 128 visible ASCII characters, such as a UUID."
196
+ end
197
+
198
+ change = method != "GET"
199
+ mode = retry_mode || (!change || request_id ? :idempotent : :once)
200
+ raise ArgumentError, "retry_mode is :idempotent or :once, not #{mode.inspect}." unless RETRY_MODES.include?(mode)
201
+ if mode == :idempotent && change && request_id.nil?
202
+ raise ArgumentError, "Only a change sent with a request_id may be repeated after a lost answer."
203
+ end
204
+ raise ArgumentError, "Send body: or content:, not both." if body && content
205
+
206
+ target = "#{checked_path(path)}#{query && !query.empty? ? "?#{encode_query(query)}" : ''}"
207
+ headers = default_headers
208
+ payload = nil
209
+ if body
210
+ payload = JSON.generate(body)
211
+ headers["Content-Type"] = "application/json"
212
+ elsif content
213
+ payload = content
214
+ headers["Content-Type"] = "application/octet-stream"
215
+ end
216
+ headers["Idempotency-Key"] = request_id if request_id
217
+
218
+ attempt = 0
219
+ loop do
220
+ err = begin
221
+ return send_once(method, target, payload, headers, timeout || @timeout)
222
+ rescue NotSent => e
223
+ UnavailableError.new("Could not connect to #{@base_url}: #{e.message}. Nothing was sent.")
224
+ rescue Lost => e
225
+ if change
226
+ UnknownOutcomeError.new(lost_message(e.message, request_id), request_id: request_id,
227
+ retry_after: e.retry_after)
228
+ else
229
+ UnavailableError.new("#{e.message} A read changes nothing; send it again.", retry_after: e.retry_after)
230
+ end
231
+ rescue Error => e
232
+ e
233
+ end
234
+ err.request_id = request_id if change && err.request_id.nil? && request_id
235
+ retryable = if mode == :idempotent
236
+ NOTHING_CHANGED.include?(err.kind) || (retry_unknown && err.kind == "unknown")
237
+ else
238
+ # Only Heaven's own word that nothing changed: a
239
+ # proxy's 429 or 503 cannot say whether the lobby
240
+ # acted.
241
+ NOTHING_CHANGED.include?(err.kind) && !err.not_heavens
242
+ end
243
+ raise err if !retryable || attempt >= @max_retries
244
+
245
+ wait = err.retry_after || [0.5 * (2**attempt), 8.0].min
246
+ raise err if wait > @max_retry_wait
247
+
248
+ @sleeper.call(wait)
249
+ attempt += 1
250
+ end
251
+ end
252
+
253
+ # The connection never reached Heaven.
254
+ class NotSent < StandardError; end # :nodoc:
255
+
256
+ # The request may have reached Heaven, but its answer was lost or
257
+ # can't be read as Heaven's.
258
+ class Lost < StandardError # :nodoc:
259
+ attr_reader :retry_after
260
+
261
+ def initialize(message, retry_after: nil)
262
+ @retry_after = retry_after
263
+ super(message)
264
+ end
265
+ end
266
+
267
+ private
268
+
269
+ # What a connection that broke after it was made raises.
270
+ CONNECTION_ERRORS = [SystemCallError, IOError, EOFError, OpenSSL::SSL::SSLError, Net::HTTPBadResponse,
271
+ Zlib::Error].freeze
272
+ private_constant :CONNECTION_ERRORS
273
+
274
+ def default_headers
275
+ {
276
+ "Authorization" => "Bearer #{@api_key}",
277
+ "Accept" => "application/json",
278
+ "User-Agent" => "heaven-ruby/#{VERSION} ruby/#{RUBY_VERSION}"
279
+ }
280
+ end
281
+
282
+ # A connection to the origin, started. NotSent when it could not be
283
+ # made, so nothing reached Heaven.
284
+ def connect(read_timeout)
285
+ # No proxy for a loopback http:// origin, so a stray http_proxy
286
+ # never carries the key in the clear. https:// tunnels through one.
287
+ proxy = @origin.scheme == "http" ? nil : :ENV
288
+ http = Net::HTTP.new(@origin.hostname, @origin.port, proxy)
289
+ http.use_ssl = @origin.scheme == "https"
290
+ http.open_timeout = @open_timeout
291
+ http.ssl_timeout = @open_timeout if http.use_ssl?
292
+ http.read_timeout = read_timeout
293
+ http.write_timeout = read_timeout
294
+ http.max_retries = 0 # Net::HTTP would resend an idempotent request itself.
295
+ begin
296
+ http.start
297
+ rescue Net::OpenTimeout, SystemCallError, SocketError, OpenSSL::SSL::SSLError, IOError => e
298
+ raise NotSent, e.message
299
+ end
300
+ http
301
+ end
302
+
303
+ def send_once(method, target, payload, headers, read_timeout)
304
+ http = connect(read_timeout)
305
+ begin
306
+ req = method == "GET" ? Net::HTTP::Get.new(target, headers) : Net::HTTP::Post.new(target, headers)
307
+ req.body = payload if payload
308
+ res = http.request(req)
309
+ raw = res.body || ""
310
+ rescue Net::ReadTimeout, Net::WriteTimeout => e
311
+ raise Lost, "No answer within #{read_timeout} seconds (#{e.class.name})."
312
+ rescue *CONNECTION_ERRORS => e
313
+ raise Lost, "The connection failed: #{e.message}."
314
+ ensure
315
+ http.finish if http.started?
316
+ end
317
+ answer(method, target, res, raw)
318
+ end
319
+
320
+ def answer(method, target, res, raw)
321
+ status = res.code.to_i
322
+ heaven_id = res["Heaven-Request-Id"]
323
+ header_wait = res["Retry-After"]&.strip&.then { _1.match?(/\A\d+\z/) ? _1.to_i : nil }
324
+ where = "#{@base_url}#{target.split('?').first}"
325
+ if (300..399).cover?(status)
326
+ # Never followed: a redirect would carry the credential, or a
327
+ # change's body, somewhere this client was not pointed at.
328
+ raise RedirectError.new(
329
+ "HTTP #{status} from #{where}: a redirect to #{(res['Location'] || 'nowhere').inspect}, not followed. " \
330
+ "Point base_url at the deployment's own origin.", status: status, heaven_request_id: heaven_id
331
+ )
332
+ end
333
+ envelope = begin
334
+ raw.empty? ? nil : JSON.parse(raw)
335
+ rescue JSON::ParserError
336
+ nil
337
+ end
338
+ if envelope.is_a?(Hash) && envelope["error"].is_a?(Hash)
339
+ err = Error.from_body(envelope["error"], status: status, heaven_request_id: heaven_id)
340
+ err.retry_after = header_wait if err.retry_after.nil?
341
+ raise err
342
+ end
343
+ unless (200..299).cover?(status) && envelope.is_a?(Hash) && envelope["version"] == 1
344
+ # Not Heaven's answer: a proxy's page, or one garbled. A read may
345
+ # be sent again; a change's outcome is unknown unless the status
346
+ # says it was refused outright.
347
+ message = "HTTP #{status} from #{where} without Heaven's answer."
348
+ kind = STATUS_KINDS[status] || (method == "GET" ? "unavailable" : nil)
349
+ raise Lost.new(message, retry_after: header_wait) if method != "GET" && (kind.nil? || status == 429 || status >= 500)
350
+
351
+ err = (KINDS[kind] || Error).new(message, kind: kind, status: status, retry_after: header_wait,
352
+ heaven_request_id: heaven_id)
353
+ err.not_heavens = true
354
+ raise err
355
+ end
356
+ exit_status = res["Heaven-Exit-Status"]
357
+ Response.new(data: envelope["data"], status: status, headers: res.to_hash.transform_values { _1.join(", ") },
358
+ heaven_request_id: heaven_id,
359
+ exit_status: exit_status&.match?(/\A\d+\z/) ? exit_status.to_i : nil)
360
+ end
361
+
362
+ def checked_origin(base_url)
363
+ uri = URI.parse(base_url.to_s)
364
+ unless %w[https http].include?(uri.scheme) && uri.host && !uri.host.empty? && uri.userinfo.nil? &&
365
+ ["", "/"].include?(uri.path) && uri.query.nil? && uri.fragment.nil?
366
+ raise ArgumentError, "base_url must be an origin, https://HOST[:PORT], not #{base_url.inspect}."
367
+ end
368
+ if uri.scheme == "http" && !loopback?(uri.hostname)
369
+ raise ArgumentError, "http:// would send the credential in the clear; use https:// " \
370
+ "(http:// is for loopback tests)."
371
+ end
372
+ URI.parse("#{uri.scheme}://#{uri.host}:#{uri.port}")
373
+ rescue URI::InvalidURIError
374
+ raise ArgumentError, "base_url must be an origin, https://HOST[:PORT], not #{base_url.inspect}."
375
+ end
376
+
377
+ def loopback?(host)
378
+ host == "localhost" || IPAddr.new(host).loopback?
379
+ rescue IPAddr::Error
380
+ false
381
+ end
382
+
383
+ # A path on the client's own origin: absolute, with no host, query,
384
+ # fragment or dot segment of its own.
385
+ def checked_path(path)
386
+ path = path.to_s
387
+ if !path.start_with?("/") || path.start_with?("//") || path.match?(/[?#\\@\x00-\x20\x7f]/) ||
388
+ path.split("/").any? { %w[. ..].include?(_1) }
389
+ raise ArgumentError, "#{path.inspect} is not a path on the origin, such as /v1/computer/."
390
+ end
391
+ path
392
+ end
393
+
394
+ def encode_query(query)
395
+ pairs = query.flat_map do |name, value|
396
+ Array(value).map do |v|
397
+ case v
398
+ when true, false, String, Integer, Float, Symbol then [name.to_s, v.to_s]
399
+ else raise ArgumentError, "Query field #{name} cannot be #{v.class}; a GET takes strings, numbers, " \
400
+ "booleans and arrays of them."
401
+ end
402
+ end
403
+ end
404
+ URI.encode_www_form(pairs)
405
+ end
406
+
407
+ def lost_message(reason, request_id)
408
+ if request_id
409
+ "#{reason} The outcome is unknown: send the same request again with request_id: #{request_id.inspect}."
410
+ else
411
+ "#{reason} The outcome is unknown: check before repeating it (docs/API.md, Retries)."
412
+ end
413
+ end
414
+ end
415
+
416
+ # Computers: <tt>client.computers</tt>.
417
+ class Computers
418
+ def initialize(client)
419
+ @client = client
420
+ end
421
+
422
+ # The Computers you may see, narrowed by the filters. With +limit+,
423
+ # one page by name, whose +next+ is the next page's +after+; without
424
+ # it, every match.
425
+ def list(pool: nil, tag: nil, pattern: nil, states: nil, shared: nil, organization: nil, limit: nil, after: nil)
426
+ query = { pool: pool, tag: tag, pattern: pattern, states: states && Array(states), shared: shared,
427
+ organization: organization, limit: limit, after: after }.compact
428
+ ComputerPage.from_json(@client.request(:get, "/v1/computer/", query: query).data || {})
429
+ end
430
+
431
+ # Each matching Computer, read +page_size+ at a time. Without a block,
432
+ # an Enumerator.
433
+ def each(page_size: 100, **filters)
434
+ return enum_for(:each, page_size: page_size, **filters) unless block_given?
435
+
436
+ after = nil
437
+ loop do
438
+ page = list(limit: page_size, after: after, **filters)
439
+ page.computers.each { yield _1 }
440
+ break unless page.next
441
+
442
+ after = page.next
443
+ end
444
+ end
445
+
446
+ # One Computer by name or ID, with its latest operations, as
447
+ # ComputerDetails. Raises NotFoundError when there is none you may
448
+ # reach.
449
+ def get(computer, organization: nil)
450
+ query = { computer: computer, organization: organization }.compact
451
+ ComputerDetails.from_json(@client.request(:get, "/v1/computer/", query: query).data || {})
452
+ end
453
+
454
+ # Creates one Computer and answers Accepted: its operation, its
455
+ # request ID and where to reach it.
456
+ #
457
+ # +fields+ are the rest of create's fields as the command reference
458
+ # names them (template:, image:, disk:, tags:, setup_script:,
459
+ # copy: {computer: ...}, ...). Without a pool it uses your default
460
+ # pool. It always carries a request ID: +request_id+, or a new one
461
+ # (in the answer and any error), so sending it again after a lost
462
+ # answer never makes a second Computer. For count:, names: or
463
+ # dry_run:, whose answers list several, use client.command("create").
464
+ def create(name = nil, pool: nil, request_id: nil, **fields)
465
+ several = %i[count names dry_run] & fields.keys.map(&:to_sym)
466
+ unless several.empty?
467
+ raise ArgumentError, "create makes one Computer; send #{several.join(', ')} with client.command(\"create\", ...)."
468
+ end
469
+
470
+ body = fields.merge({ name: name, pool: pool }.compact)
471
+ r = @client.request(:post, "/v1/computer/create", body: body,
472
+ request_id: request_id || Client.new_request_id)
473
+ Accepted.from_json(r.data || {})
474
+ end
475
+
476
+ # Creates one Computer and waits up to +timeout+ seconds for it to be
477
+ # made. Answers the Accepted create and its finished Operation.
478
+ # Raises OperationFailedError when it failed or was superseded, and
479
+ # WaitTimeoutError when it is still being made at the deadline (it
480
+ # goes on; wait for the error's +operation+ again).
481
+ def create_and_wait(name = nil, timeout: Client::OPERATION_WAIT_LIMIT, **fields)
482
+ accepted = create(name, **fields)
483
+ op = @client.operations.wait(accepted.operation, timeout: timeout)
484
+ unless op.done?
485
+ raise WaitTimeoutError.new("#{accepted.name} was still being created after #{timeout} seconds.",
486
+ operation: op, request_id: accepted.request_id)
487
+ end
488
+ unless op.complete?
489
+ raise OperationFailedError.new("Creating #{accepted.name} #{op.state}: #{op.message || 'no reason given'}",
490
+ operation: op, request_id: accepted.request_id)
491
+ end
492
+ [accepted, op]
493
+ end
494
+
495
+ # Deletes Computers, by name or ID, with their disks and snapshots, at
496
+ # once and without confirmation. Answers a DeleteResult with one
497
+ # Removal per Computer; a refusal of some is in their +error+, not
498
+ # raised.
499
+ def delete(*computers, request_id: nil)
500
+ computers = computers.flatten
501
+ raise ArgumentError, "Name at least one Computer to delete." if computers.empty?
502
+
503
+ r = @client.request(:post, "/v1/computer/delete", body: { computers: computers },
504
+ request_id: request_id || Client.new_request_id)
505
+ DeleteResult.from_json(r.data || {})
506
+ end
507
+ end
508
+
509
+ # Operations: <tt>client.operations</tt>.
510
+ class Operations
511
+ def initialize(client)
512
+ @client = client
513
+ end
514
+
515
+ # An operation or operation group as it is now: an Operation or an
516
+ # OperationGroup.
517
+ def get(operation)
518
+ r = @client.request(:get, "/v1/operation/", query: { operation: id_of(operation) })
519
+ Heaven.operation_from_view(r.data || {})
520
+ end
521
+
522
+ # Waits up to +timeout+ seconds for an operation (its ID, or an
523
+ # Operation, Accepted or OperationGroup) to finish and answers it as it
524
+ # is then. One still accepted at the deadline is answered as it is, not
525
+ # raised: the work goes on, and waiting again picks it up. Each request
526
+ # waits at most 10 minutes on Heaven's side.
527
+ #
528
+ # When Heaven's wait ends before the operation does, it answers 503
529
+ # +unknown+ (naming the operation as +operation_id+, or for a group
530
+ # naming none): the wait ended, not the work. After that answer, from
531
+ # Heaven itself and naming no other operation, wait reads the operation
532
+ # once by ID, without waiting,
533
+ # and answers that, or waits again when +timeout+ is longer than the
534
+ # 10 minutes one request waits. Any other
535
+ # refusal, and an answer lost or not Heaven's, is raised as it is: it
536
+ # never guesses an outcome, and reading never repeats the change.
537
+ def wait(operation, timeout: Client::OPERATION_WAIT_LIMIT)
538
+ id = id_of(operation)
539
+ deadline = monotonic + timeout
540
+ loop do
541
+ remaining = deadline - monotonic
542
+ left = remaining.ceil.clamp(1, Client::OPERATION_WAIT_LIMIT)
543
+ op = begin
544
+ r = @client.request(:get, "/v1/operation/", query: { operation: id, wait: true, timeout: "#{left}s" },
545
+ timeout: left + 30, retry_unknown: false)
546
+ Heaven.operation_from_view(r.data || {})
547
+ rescue UnknownOutcomeError => e
548
+ raise unless e.status == 503 && [nil, id].include?(e.operation_id)
549
+
550
+ op = get(id)
551
+ # Heaven waited the time asked: answer what the read says, unless
552
+ # the caller's timeout is past one request's limit.
553
+ return op if op.done? || remaining <= Client::OPERATION_WAIT_LIMIT
554
+
555
+ op
556
+ end
557
+ return op if op.done? || monotonic >= deadline
558
+ end
559
+ end
560
+
561
+ private
562
+
563
+ def id_of(operation)
564
+ case operation
565
+ when String then operation
566
+ when Accepted then operation.operation.id
567
+ when Operation, OperationGroup then operation.id
568
+ else raise ArgumentError, "An operation is its ID, an Operation, an OperationGroup or an Accepted."
569
+ end
570
+ end
571
+
572
+ def monotonic = Process.clock_gettime(Process::CLOCK_MONOTONIC)
573
+ end
574
+ end