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,159 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Heaven
4
+ # The command a refusal's message tells the caller to run: +command+ is
5
+ # the catalog's name ("pool start"), +line+ the command as the message
6
+ # quotes it ("pool start web").
7
+ ErrorAction = Data.define(:command, :line)
8
+
9
+ # A refusal from Heaven, or a change whose outcome is not known.
10
+ #
11
+ # Every refusal is <tt>{"version":1,"error":{kind, message, ...}}</tt>
12
+ # with an HTTP status per kind (docs/COMMANDS.md, "JSON contract and
13
+ # durable requests"). Each kind has its subclass; a kind this SDK does
14
+ # not know yet is a plain Heaven::Error carrying that kind. Branch on the
15
+ # class or on #kind, and show #message, whose wording can change.
16
+ class Error < StandardError
17
+ # The error's category: "not_found", "conflict", ...
18
+ attr_reader :kind
19
+ # The explanation for a person.
20
+ attr_reader :message
21
+ # The HTTP status, or nil when no answer arrived.
22
+ attr_reader :status
23
+ # The change's request ID, when it has one. Sending the same change
24
+ # again with it answers the first attempt and never does it twice.
25
+ attr_reader :request_id
26
+ # The operation to read before repeating the work.
27
+ attr_reader :operation_id
28
+ # The page that fixes it (Stripe's or Billing, for payment_required).
29
+ attr_reader :url
30
+ # The command the message suggests, as an ErrorAction, or nil.
31
+ attr_reader :action
32
+ # Seconds to wait before sending it again (busy, rate_limited), or nil.
33
+ attr_reader :retry_after
34
+ # The Heaven-Request-Id header, to quote to support. It is a request
35
+ # ID to retry with only when the command takes one.
36
+ attr_reader :heaven_request_id
37
+ # The decoded "error" object as sent, fields this SDK doesn't name
38
+ # included.
39
+ attr_reader :body
40
+
41
+ def self.kind = "unknown"
42
+
43
+ def initialize(message, kind: nil, status: nil, request_id: nil, operation_id: nil, url: nil,
44
+ action: nil, retry_after: nil, heaven_request_id: nil, body: nil)
45
+ @message = message
46
+ @kind = kind || self.class.kind
47
+ @status = status
48
+ @request_id = request_id
49
+ @operation_id = operation_id
50
+ @url = url
51
+ @action = action
52
+ @retry_after = retry_after
53
+ @heaven_request_id = heaven_request_id
54
+ @body = body || {}
55
+ super("#{@kind}: #{message}")
56
+ end
57
+
58
+ # Set by the client: the request ID it sent, the wait a header gave, or
59
+ # that the answer was a proxy's and not Heaven's own.
60
+ attr_writer :request_id, :retry_after # :nodoc:
61
+ attr_accessor :not_heavens # :nodoc:
62
+
63
+ # Uncaught, the error prints its kind before its message.
64
+ def detailed_message(highlight: false, **)
65
+ "#{kind}: #{message} (#{self.class.name})"
66
+ end
67
+
68
+ def inspect
69
+ "#<#{self.class.name} kind=#{kind.inspect} status=#{status.inspect} message=#{message.inspect}>"
70
+ end
71
+
72
+ # The exception for one "error" object, as an answer or a per-target
73
+ # result carries it.
74
+ def self.from_body(error, status: nil, heaven_request_id: nil)
75
+ kind = (error["kind"] || "unknown").to_s
76
+ action = error["action"]
77
+ retry_after = error["retry_after"]
78
+ (KINDS[kind] || Error).new(
79
+ (error["message"] || kind).to_s,
80
+ kind: kind,
81
+ status: status,
82
+ request_id: error["request_id"],
83
+ operation_id: error["operation_id"],
84
+ url: error["url"],
85
+ action: action.is_a?(Hash) ? ErrorAction.new(command: action["command"].to_s, line: action["line"].to_s) : nil,
86
+ retry_after: retry_after.is_a?(Numeric) ? retry_after.to_i : nil,
87
+ heaven_request_id: heaven_request_id,
88
+ body: error
89
+ )
90
+ end
91
+ end
92
+
93
+ # +invalid+ (400): a wrong field, value, size or syntax.
94
+ class InvalidError < Error; def self.kind = "invalid"; end
95
+ # +unauthenticated+ (401): no credential, or one expired or revoked.
96
+ class UnauthenticatedError < Error; def self.kind = "unauthenticated"; end
97
+ # +denied+ (403): the credential may not do this.
98
+ class DeniedError < Error; def self.kind = "denied"; end
99
+ # +payment_required+ (402): #url is the page that pays it.
100
+ class PaymentRequiredError < Error; def self.kind = "payment_required"; end
101
+ # +not_found+ (404): nothing by that name that you may reach.
102
+ class NotFoundError < Error; def self.kind = "not_found"; end
103
+ # +conflict+ (409): the state refuses it, the name is taken, or a request
104
+ # ID was reused for a different request.
105
+ class ConflictError < Error; def self.kind = "conflict"; end
106
+ # +over_capacity+ (409): the pool, its storage or its host is full.
107
+ class OverCapacityError < Error; def self.kind = "over_capacity"; end
108
+ # +access_list_full+ (409): a host's access list has no room.
109
+ class AccessListFullError < Error; def self.kind = "access_list_full"; end
110
+ # +busy+ (429): not accepted, nothing changed; send it again shortly.
111
+ class BusyError < Error; def self.kind = "busy"; end
112
+ # +rate_limited+ (429): not accepted; send it again after #retry_after.
113
+ class RateLimitedError < Error; def self.kind = "rate_limited"; end
114
+ # +unavailable+ (503): refused before anything changed, for a reason
115
+ # that passes. The SDK also raises it for a read whose answer was lost,
116
+ # and when it could not connect at all.
117
+ class UnavailableError < Error; def self.kind = "unavailable"; end
118
+ # +unknown+ (503): the outcome is not established, which never means
119
+ # failed. A change that takes a request ID is sent again with the same
120
+ # #request_id; any other is checked before it is repeated. The SDK also
121
+ # raises it, with a nil #status, when a change's answer never arrived.
122
+ class UnknownOutcomeError < Error; def self.kind = "unknown"; end
123
+
124
+ # A 3xx, which the SDK never follows: the credential and a change's body
125
+ # go only to the origin the client was given.
126
+ class RedirectError < Error; def self.kind = "redirect"; end
127
+
128
+ # Raised by Computers#create_and_wait when the create finished as
129
+ # +failed+ or +superseded+. #operation is the operation as it ended.
130
+ class OperationFailedError < Error
131
+ def self.kind = "operation_failed"
132
+ attr_reader :operation
133
+
134
+ def initialize(message, operation:, **kw)
135
+ @operation = operation
136
+ super(message, operation_id: operation.id, **kw)
137
+ end
138
+ end
139
+
140
+ # Raised by Computers#create_and_wait when the operation was still
141
+ # +accepted+ at the deadline. The work goes on: wait for #operation
142
+ # again to pick it up.
143
+ class WaitTimeoutError < Error
144
+ def self.kind = "wait_timeout"
145
+ attr_reader :operation
146
+
147
+ def initialize(message, operation:, **kw)
148
+ @operation = operation
149
+ super(message, operation_id: operation.id, **kw)
150
+ end
151
+ end
152
+
153
+ # Each API kind's class.
154
+ KINDS = [
155
+ InvalidError, UnauthenticatedError, DeniedError, PaymentRequiredError, NotFoundError,
156
+ ConflictError, OverCapacityError, AccessListFullError, BusyError, RateLimitedError,
157
+ UnavailableError, UnknownOutcomeError
158
+ ].to_h { |c| [c.kind, c] }.freeze
159
+ end
@@ -0,0 +1,300 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+ require "stringio"
5
+
6
+ module Heaven
7
+ # An upload's answer (UploadResult): the file's +path+ in the Computer
8
+ # and the +bytes+ it now holds.
9
+ Upload = Data.define(:path, :bytes, :raw) do
10
+ def self.from_json(d) = new(path: d["path"], bytes: d["bytes"], raw: d)
11
+ end
12
+
13
+ # A download cut short after +bytes+ arrived. Reading changes nothing in
14
+ # the Computer, so it can be sent again; a file download_file was
15
+ # writing is left as it was, and an IO passed to download has the
16
+ # +bytes+ that arrived.
17
+ class DownloadCutError < UnavailableError
18
+ attr_reader :bytes
19
+
20
+ def initialize(message, bytes:, **kw)
21
+ @bytes = bytes
22
+ super(message, **kw)
23
+ end
24
+ end
25
+
26
+ # Files in a Computer, through /v1/computer/exec as `scp` moves them
27
+ # (docs/API.md, "Running commands in a Computer"). Each streams, so a
28
+ # file of any size takes the same memory. They need the `exec` command
29
+ # and, like a command, a running Computer.
30
+ class Client
31
+ # Replaces the file at +path+ in +computer+ with +source+: a String of
32
+ # bytes, or an IO (or anything with +read+) read to its end. Answers an
33
+ # Upload. Heaven writes beside the old file and renames over it once
34
+ # the bytes are whole, so a refused or broken upload leaves the old
35
+ # file as it was. +mode+ (0o644 or "0644") sets its permissions; without
36
+ # it an existing file keeps its own.
37
+ #
38
+ # Repeating an upload is harmless, so one that broke is sent again when
39
+ # its source can be read again: a String, or an IO that can seek back
40
+ # to where it started (a File, a StringIO). A pipe or socket is read
41
+ # once: when the answer is lost after it was sent whole the outcome is
42
+ # unknown (UnknownOutcomeError: read the file to see), and when it broke
43
+ # before then the file is unchanged (UnavailableError).
44
+ def upload(computer, path, source, mode: nil)
45
+ unless source.is_a?(String) || source.respond_to?(:read)
46
+ raise ArgumentError, "An upload's source is a String of bytes or an IO; for a local file use upload_file."
47
+ end
48
+
49
+ send_upload(computer, path, mode, Source.new(source))
50
+ end
51
+
52
+ # Replaces the file at +path+ in +computer+ with the local file at
53
+ # +local_path+, read as it is sent. Answers an Upload, as #upload.
54
+ def upload_file(computer, local_path, path, mode: nil)
55
+ File.open(local_path, "rb") { |f| upload(computer, path, f, mode: mode) }
56
+ end
57
+
58
+ # Writes the file at +path+ in +computer+ to +to+ (an IO, or anything
59
+ # with +write+) as it arrives, and answers how many bytes it wrote. A
60
+ # missing or unreadable file is refused before any byte. A download cut
61
+ # short raises DownloadCutError: +to+ then holds the bytes that arrived
62
+ # (its +bytes+), and a whole copy needs a fresh destination. It is sent
63
+ # again by itself only while nothing has been written.
64
+ def download(computer, path, to)
65
+ raise ArgumentError, "A download's destination is an IO, or anything with write." unless to.respond_to?(:write)
66
+
67
+ receive_download(computer, path, restart: nil) { |chunk| to.write(chunk) }
68
+ end
69
+
70
+ # Writes the file at +path+ in +computer+ to +local_path+ and answers
71
+ # how many bytes it wrote. It writes beside +local_path+ and renames
72
+ # over it only once the file is whole, so a refusal or a download cut
73
+ # short (DownloadCutError) leaves a file already there as it was. A
74
+ # replaced file keeps its permissions; a new one gets the umask's.
75
+ def download_file(computer, path, local_path)
76
+ local_path = local_path.to_s
77
+ dir = File.dirname(local_path)
78
+ part = File.join(dir, ".#{File.basename(local_path)}.#{SecureRandom.hex(6)}.part")
79
+ placed = false
80
+ File.open(part, File::WRONLY | File::CREAT | File::EXCL | File::BINARY, 0o600) do |f|
81
+ bytes = receive_download(computer, path, restart: -> { f.truncate(0) && f.rewind }) { |chunk| f.write(chunk) }
82
+ f.flush
83
+ f.fsync
84
+ mode = File.exist?(local_path) ? File.stat(local_path).mode & 0o7777 : 0o666 & ~File.umask
85
+ f.chmod(mode)
86
+ File.rename(part, local_path)
87
+ placed = true
88
+ bytes
89
+ end
90
+ ensure
91
+ File.unlink(part) if part && !placed && File.exist?(part)
92
+ end
93
+
94
+ # An upload's source, read as the request is sent: it counts what it
95
+ # gave and whether it reached the end, and keeps a failure of its own
96
+ # apart from the connection's. It can be read again when it is a
97
+ # String or an IO that seeks back.
98
+ class Source # :nodoc:
99
+ attr_reader :sent, :failed
100
+
101
+ def initialize(source)
102
+ @io = source.is_a?(String) ? StringIO.new(source.b) : source
103
+ @start = begin
104
+ @io.pos if @io.respond_to?(:pos) && @io.respond_to?(:seek)
105
+ rescue SystemCallError, IOError
106
+ nil # a pipe or a socket
107
+ end
108
+ @sent = 0
109
+ @eof = false
110
+ @failed = nil
111
+ end
112
+
113
+ def replayable? = !@start.nil?
114
+
115
+ # Whether every byte was handed on.
116
+ def whole? = @eof
117
+
118
+ def rewind!
119
+ @io.seek(@start)
120
+ @sent = 0
121
+ @eof = false
122
+ end
123
+
124
+ # IO.copy_stream reads it so, a chunk at a time.
125
+ def read(length = nil, buffer = nil)
126
+ chunk = @io.read(length || 64 << 10)
127
+ if chunk.nil? || chunk.empty?
128
+ @eof = true
129
+ buffer&.clear
130
+ return nil
131
+ end
132
+ @sent += chunk.bytesize
133
+ buffer ? buffer.replace(chunk.b) : chunk.b
134
+ rescue StandardError => e
135
+ @failed = e
136
+ raise
137
+ end
138
+ end
139
+
140
+ private
141
+
142
+ # How long an upload waits for Heaven's 100 Continue before it sends
143
+ # its bytes anyway (a proxy may never send one).
144
+ CONTINUE_TIMEOUT = 2
145
+ private_constant :CONTINUE_TIMEOUT
146
+
147
+ def send_upload(computer, path, mode, source)
148
+ query = { computer: computer.to_s, upload: remote_path(path) }
149
+ query[:mode] = file_mode(mode) unless mode.nil?
150
+ target = "/v1/computer/exec?#{encode_query(query)}"
151
+ # Expect: 100-continue lets Heaven refuse (a wrong name, path or
152
+ # access) before any byte is sent, where it answers that.
153
+ headers = default_headers.merge("Content-Type" => "application/octet-stream",
154
+ "Transfer-Encoding" => "chunked", "Expect" => "100-continue")
155
+ attempt = 0
156
+ loop do
157
+ source.rewind! if attempt.positive? && source.replayable?
158
+ not_sent = false
159
+ err = begin
160
+ return Upload.from_json(post_stream(target, headers, source).data || {})
161
+ rescue NotSent => e
162
+ not_sent = true
163
+ UnavailableError.new("Could not connect to #{@base_url}: #{e.message}. Nothing was sent.")
164
+ rescue Lost => e
165
+ raise source.failed if source.failed
166
+ if source.whole?
167
+ UnknownOutcomeError.new("#{e.message} The upload to #{path} on #{computer} was sent whole, so whether " \
168
+ "the file was replaced is unknown: read it to see, or send it again.",
169
+ retry_after: e.retry_after)
170
+ else
171
+ UnavailableError.new("#{e.message} The upload to #{path} on #{computer} was cut short after " \
172
+ "#{source.sent} bytes, so the file is unchanged.", retry_after: e.retry_after)
173
+ end
174
+ rescue Error => e
175
+ e
176
+ end
177
+ raise source.failed if source.failed
178
+ # Sent again only from the start of a source that has one, after
179
+ # what leaves the old file or replaces it with the same bytes.
180
+ retryable = not_sent || source.sent.zero? && !source.whole? && NOTHING_CHANGED.include?(err.kind) ||
181
+ source.replayable? && (NOTHING_CHANGED.include?(err.kind) || err.kind == "unknown")
182
+ raise err if !retryable || attempt >= @max_retries
183
+
184
+ wait = err.retry_after || [0.5 * (2**attempt), 8.0].min
185
+ raise err if wait > @max_retry_wait
186
+
187
+ @sleeper.call(wait)
188
+ attempt += 1
189
+ end
190
+ end
191
+
192
+ def post_stream(target, headers, source)
193
+ http = connect(@timeout)
194
+ http.continue_timeout = CONTINUE_TIMEOUT
195
+ begin
196
+ req = Net::HTTP::Post.new(target, headers)
197
+ req.body_stream = source
198
+ res = http.request(req)
199
+ raw = res.body || ""
200
+ rescue Net::ReadTimeout, Net::WriteTimeout => e
201
+ raise Lost, "No answer within #{@timeout} seconds (#{e.class.name})."
202
+ rescue *CONNECTION_ERRORS => e
203
+ raise Lost, "The connection failed: #{e.message}."
204
+ ensure
205
+ http.finish if http.started?
206
+ end
207
+ answer("POST", target, res, raw)
208
+ end
209
+
210
+ # Streams a download to the block and answers its bytes. +restart+
211
+ # empties the destination, so a download cut short may start over; nil
212
+ # sends it again only while nothing was written.
213
+ def receive_download(computer, path, restart:, &sink)
214
+ target = "/v1/computer/exec?#{encode_query(computer: computer.to_s, download: remote_path(path))}"
215
+ attempt = 0
216
+ loop do
217
+ written = 0
218
+ err = begin
219
+ return get_stream(target) do |chunk|
220
+ sink.call(chunk)
221
+ written += chunk.bytesize
222
+ end
223
+ rescue NotSent => e
224
+ UnavailableError.new("Could not connect to #{@base_url}: #{e.message}. Nothing was sent.")
225
+ rescue Lost => e
226
+ if written.zero?
227
+ UnavailableError.new("#{e.message} A download changes nothing; send it again.", retry_after: e.retry_after)
228
+ else
229
+ DownloadCutError.new("#{e.message} The download of #{path} from #{computer} was cut short after " \
230
+ "#{written} bytes.", bytes: written, retry_after: e.retry_after)
231
+ end
232
+ rescue Error => e
233
+ e
234
+ end
235
+ retryable = NOTHING_CHANGED.include?(err.kind) && (written.zero? || restart)
236
+ raise err if !retryable || attempt >= @max_retries
237
+
238
+ wait = err.retry_after || [0.5 * (2**attempt), 8.0].min
239
+ raise err if wait > @max_retry_wait
240
+
241
+ @sleeper.call(wait)
242
+ restart&.call
243
+ attempt += 1
244
+ end
245
+ end
246
+
247
+ # One GET whose 200 answer streams to the block; any other answer is
248
+ # read whole and raised as Heaven's error (a redirect included).
249
+ def get_stream(target, &block)
250
+ http = connect(@timeout)
251
+ sink_failed = nil
252
+ bytes = 0
253
+ begin
254
+ http.request(Net::HTTP::Get.new(target, default_headers)) do |res|
255
+ unless res.code == "200"
256
+ raw = res.body || ""
257
+ answer("GET", target, res, raw)
258
+ raise Lost, "HTTP #{res.code} from #{@base_url} without Heaven's answer."
259
+ end
260
+ res.read_body do |chunk|
261
+ begin
262
+ block.call(chunk)
263
+ rescue Exception => e # rubocop:disable Lint/RescueException
264
+ sink_failed = e
265
+ raise
266
+ end
267
+ bytes += chunk.bytesize
268
+ end
269
+ end
270
+ rescue Net::ReadTimeout, Net::WriteTimeout => e
271
+ raise sink_failed if sink_failed
272
+
273
+ raise Lost, "No answer within #{@timeout} seconds (#{e.class.name})."
274
+ rescue *CONNECTION_ERRORS => e
275
+ raise sink_failed if sink_failed
276
+
277
+ raise Lost, "The connection failed: #{e.message}."
278
+ ensure
279
+ http.finish if http.started?
280
+ end
281
+ bytes
282
+ end
283
+
284
+ def remote_path(path)
285
+ path = path.to_s
286
+ raise ArgumentError, "A file's path in the Computer is needed, such as /srv/app.tar." if path.empty?
287
+
288
+ path
289
+ end
290
+
291
+ def file_mode(mode)
292
+ text = mode.is_a?(Integer) ? format("%04o", mode) : mode.to_s
293
+ unless text.match?(/\A[0-7]{1,4}\z/)
294
+ raise ArgumentError, "mode is the file's permissions in octal, such as 0o644 or \"0644\", not #{mode.inspect}."
295
+ end
296
+
297
+ text
298
+ end
299
+ end
300
+ end
@@ -0,0 +1,131 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Heaven
4
+ # The typed answers. Each keeps the whole decoded +data+ in +raw+, so a
5
+ # field Heaven adds is there before the SDK names it. Field meanings are
6
+ # in docs/openapi.json, under the schema each class names.
7
+
8
+ # One answer: its decoded +data+, HTTP status and headers.
9
+ # +heaven_request_id+ is Heaven-Request-Id (quote it to support);
10
+ # +exit_status+ is Heaven-Exit-Status, the status the command ends with
11
+ # over SSH: 1 when some targets of a change failed.
12
+ Response = Data.define(:data, :status, :headers, :heaven_request_id, :exit_status)
13
+
14
+ # A Computer as a list shows it (ComputerListEntry).
15
+ Computer = Data.define(:id, :name, :pool, :pool_id, :state, :state_message, :access,
16
+ :ssh_dest, :url, :tags, :created_at, :raw) do
17
+ def self.from_json(d)
18
+ new(id: d["id"], name: d["name"], pool: d["pool"], pool_id: d["pool_id"], state: d["state"],
19
+ state_message: d["state_message"], access: d["access"], ssh_dest: d["ssh_dest"], url: d["url"],
20
+ tags: d["tags"] || [], created_at: d["created_at"], raw: d)
21
+ end
22
+ end
23
+
24
+ # One page of Computers (ComputerList). +total+ counts every match;
25
+ # +next+ is the next page's +after+, nil on the last page.
26
+ ComputerPage = Data.define(:computers, :total, :next, :raw) do
27
+ def self.from_json(d)
28
+ new(computers: (d["computers"] || []).map { Computer.from_json(_1) }, total: d["total"],
29
+ next: d["next"], raw: d)
30
+ end
31
+ end
32
+
33
+ # One Computer with its latest operations (InspectResult). +withheld+
34
+ # names the parts the credential may not read.
35
+ ComputerDetails = Data.define(:id, :name, :pool, :state, :state_message, :ssh_dest, :url,
36
+ :operations, :withheld, :raw) do
37
+ def self.from_json(d)
38
+ view = d["computer"] || {}
39
+ saved = view["computer"] || {}
40
+ new(id: saved["id"], name: saved["name"], pool: view["pool_name"], state: view["state"],
41
+ state_message: view["state_message"], ssh_dest: view["ssh_dest"], url: view["url"],
42
+ operations: (d["operations"] || []).map { Operation.from_json(_1) },
43
+ withheld: d["withheld"] || [], raw: d)
44
+ end
45
+ end
46
+
47
+ # An accepted change to one Computer (Operation). +state+ is
48
+ # "accepted" (saved and unfinished), "complete", "failed" or
49
+ # "superseded" (a newer change replaced it); +message+ explains a
50
+ # failure.
51
+ Operation = Data.define(:id, :kind, :computer_id, :state, :message, :error_code, :created_at,
52
+ :completed_at, :raw) do
53
+ def self.from_json(d)
54
+ new(id: d["id"], kind: d["kind"], computer_id: d["computer_id"], state: d["state"],
55
+ message: d["message"], error_code: d["error_code"], created_at: d["created_at"],
56
+ completed_at: d["completed_at"], raw: d)
57
+ end
58
+
59
+ # Whether it has reached its final state.
60
+ def done? = state != "accepted"
61
+ def complete? = state == "complete"
62
+ end
63
+
64
+ # A change across several Computers or account steps (OperationGroup),
65
+ # with its member +operations+ as they are now.
66
+ OperationGroup = Data.define(:id, :kind, :state, :message, :operations, :steps, :raw) do
67
+ def self.from_json(d)
68
+ new(id: d["id"], kind: d["kind"], state: d["state"], message: d["message"],
69
+ operations: (d["operations"] || []).map { Operation.from_json(_1) }, steps: d["steps"] || [], raw: d)
70
+ end
71
+
72
+ def done? = state != "accepted"
73
+ def complete? = state == "complete"
74
+ end
75
+
76
+ # The answer to a create (OperationResult): its +operation+, the
77
+ # +request_id+ that sends it again safely, and where to reach it.
78
+ Accepted = Data.define(:operation, :request_id, :name, :ssh_dest, :url, :raw) do
79
+ def self.from_json(d)
80
+ new(operation: Operation.from_json(d["operation"] || {}), request_id: d["request_id"], name: d["name"],
81
+ ssh_dest: d["ssh_dest"], url: d["url"], raw: d)
82
+ end
83
+ end
84
+
85
+ # One Computer's part of a delete (RemovalResult): its +operation+ when
86
+ # accepted, otherwise its refusal as +error+ (a Heaven::Error).
87
+ Removal = Data.define(:computer_id, :computer, :operation, :error, :raw) do
88
+ def self.from_json(d)
89
+ target = d["computer"] || {}
90
+ new(computer_id: target["id"], computer: target["name"],
91
+ operation: d["operation"] && Operation.from_json(d["operation"]),
92
+ error: d["error"] && Error.from_body(d["error"]), raw: d)
93
+ end
94
+
95
+ def accepted? = !operation.nil? && error.nil?
96
+ end
97
+
98
+ # The answer to a delete (RemovalResults): one Removal per Computer.
99
+ # A refusal of some is in their +error+, not raised.
100
+ DeleteResult = Data.define(:results, :request_id, :recovery, :raw) do
101
+ def self.from_json(d)
102
+ new(results: (d["results"] || []).map { Removal.from_json(_1) }, request_id: d["request_id"],
103
+ recovery: d["recovery"], raw: d)
104
+ end
105
+
106
+ def accepted = results.select(&:accepted?)
107
+ def failed = results.reject(&:accepted?)
108
+ end
109
+
110
+ # A bounded command's combined output and exit status (GuestOutput).
111
+ # +output+ is binary; a silent command's null output is "". A nonzero
112
+ # +exit_code+ is the command's answer, not an error.
113
+ ExecResult = Data.define(:output, :exit_code, :raw) do
114
+ def self.from_json(d)
115
+ out = d["output"]
116
+ new(output: out.nil? ? "".b : out.unpack1("m0"), exit_code: d["exit_code"], raw: d)
117
+ end
118
+
119
+ def success? = exit_code == 0
120
+
121
+ # The output as UTF-8 text, invalid bytes replaced.
122
+ def text = output.dup.force_encoding(Encoding::UTF_8).scrub
123
+ end
124
+
125
+ # An operation view answer: an Operation, or an OperationGroup when the
126
+ # change spans several Computers.
127
+ def self.operation_from_view(data)
128
+ op = data["operation"] || {}
129
+ op.key?("operations") ? OperationGroup.from_json(op) : Operation.from_json(op)
130
+ end
131
+ end