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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: b7655073d86b0dc15c071f81403b4f957b3be142558ae847d05b94a9fa47d9f1
4
+ data.tar.gz: 339f9a3bee9d7e300286d69c78fb0cef5dc8916c612a1390ada8288ab0295a25
5
+ SHA512:
6
+ metadata.gz: 36171ea5b05f6e472315f60594a259224d912d548ad40f0a6f70a55b828acee7625e7517df2584018d323cafaf99a0754bad1bbef339e409ad09195cf0daaf31
7
+ data.tar.gz: 6d9b23da773ffe702aaa17862b27d3975d9bf1bfcb39539e47a1a82e9763c664c8a23038acdec8e31da180599c1867869073e87408328d9b48c08b7e4843a8c6
data/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
data/NOTICE ADDED
@@ -0,0 +1,2 @@
1
+ Heaven Ruby SDK
2
+ Copyright 2026 Open Mesa Corporation
data/README.md ADDED
@@ -0,0 +1,280 @@
1
+ # Heaven's Ruby SDK
2
+
3
+ A client for Heaven's `/v1` HTTPS API ([HTTP API guide](https://heaven.dev/docs/http-api)):
4
+ list, read, create and delete Computers, wait for operations, run a
5
+ bounded command in a Computer, move files in and out of one, and send any
6
+ other command by its catalog name. It uses only Ruby's standard library and needs Ruby 3.2 or newer.
7
+
8
+ Install it with `gem install heaven-sdk`, or `gem "heaven-sdk"` in a Gemfile.
9
+
10
+ ## Use
11
+
12
+ ```ruby
13
+ require "heaven"
14
+
15
+ client = Heaven::Client.new # HEAVEN_API_KEY; HEAVEN_DOMAIN, or heaven.dev
16
+
17
+ created = client.computers.create("blog", pool: "web")
18
+ op = client.operations.wait(created, timeout: 600)
19
+ if op.complete?
20
+ run = client.exec("blog", "uname -a")
21
+ puts run.exit_code, run.text
22
+ end
23
+
24
+ client.computers.each(pool: "web", states: ["failed"]) { |c| puts "#{c.name}: #{c.state_message}" }
25
+
26
+ client.computers.delete("blog")
27
+ ```
28
+
29
+ [`examples/quickstart.rb`](examples/quickstart.rb) creates a Computer,
30
+ waits for it, runs two commands in it and deletes it. It deletes only the
31
+ Computer its own create made, by that Computer's ID, however the run ends,
32
+ and says so when that delete fails; a name already taken is refused and
33
+ left alone. The Computer uses your pool's capacity while
34
+ it exists.
35
+
36
+ ```sh
37
+ HEAVEN_API_KEY=heaven1... ruby examples/quickstart.rb my-scratch-box web
38
+ ```
39
+
40
+ | Method | Request | Answers |
41
+ | --- | --- | --- |
42
+ | `computers.list(pool:, tag:, pattern:, states:, shared:, organization:, limit:, after:)` | `GET /v1/computer/` | `ComputerPage`: `computers`, `total` and `next` |
43
+ | `computers.each(page_size: 100, **filters)` | the same, page by page | each `Computer` (an Enumerator without a block) |
44
+ | `computers.get(name_or_id)` | `GET /v1/computer/?computer=NAME` | `ComputerDetails`, with its latest `operations` |
45
+ | `computers.create(name, pool:, request_id:, **fields)` | `POST /v1/computer/create` | `Accepted`: `operation`, `request_id`, `name`, `ssh_dest`, `url` |
46
+ | `computers.create_and_wait(name, timeout: 600, **)` | create, then wait | `[accepted, operation]`, or raises (below) |
47
+ | `computers.delete(*names_or_ids, request_id:)` | `POST /v1/computer/delete` | `DeleteResult`: one `Removal` per Computer |
48
+ | `operations.get(id)`, `operations.wait(id, timeout: 600)` | `GET /v1/operation/` | `Operation` or `OperationGroup` |
49
+ | `exec(computer, command, stdin:, timeout:)` | `POST /v1/computer/exec` | `ExecResult`: `output` (bytes), `exit_code`, `text`, `success?` |
50
+ | `exec_stream(computer, command, stdin:, out:, err:, timeout:) { \|stream, data\| }` | the same, `Accept: application/x-ndjson` | the exit status, an Integer |
51
+ | `upload(computer, path, string_or_io, mode:)`, `upload_file(computer, local_path, path, mode:)` | `POST /v1/computer/exec?upload=PATH`, the file as the body | `Upload`: `path`, `bytes` |
52
+ | `download(computer, path, io)`, `download_file(computer, path, local_path)` | `GET /v1/computer/exec?download=PATH` | the bytes written |
53
+ | `command(name, fields, request_id:)` | the command's route in the catalog | `Response`: `data`, `status`, `heaven_request_id`, `exit_status` |
54
+ | `request(method, path, query:, body:, request_id:)` | the path given | `Response` |
55
+
56
+ Each typed answer keeps the whole decoded `data` in `raw`, so a field
57
+ Heaven adds is there before the SDK names it; every field is described
58
+ in [OpenAPI specification](https://heaven.dev/docs/openapi.json). `create` makes one
59
+ Computer. For `count`, `names` or `dry_run`, and every other command, use
60
+ `command` with the fields as the [command
61
+ reference](https://heaven.dev/docs/reference/commands) names them:
62
+
63
+ ```ruby
64
+ client.command("pool rename", { pool: "web", name: "www" })
65
+ client.command("restart", { computers: ["a", "b"] })
66
+ client.command("pool view", { pool: "web" }).data
67
+ ```
68
+
69
+ `command` reads the catalog (`GET /v1/command/`) once, as the `heaven`
70
+ program does, and sends each command, or its alias, to its route. A
71
+ command added to Heaven works without a new SDK release.
72
+
73
+ ### Waiting
74
+
75
+ `operations.wait` asks Heaven to wait (`wait=true`, at most 10 minutes
76
+ a request) and answers the operation when it finishes. When the time is
77
+ up, Heaven answers 503 `unknown` naming the operation, or, for a group,
78
+ naming none: the wait ended, not the work. `wait` then reads the
79
+ operation once by ID, without waiting, and answers it as it is, still
80
+ `accepted` (`done?` false); waiting again picks it up. It waits again by
81
+ itself only when `timeout` is longer than one request's 10 minutes. An
82
+ `unknown` naming another operation, an answer lost or not Heaven's, and
83
+ any other refusal are raised: it never guesses an outcome, and reading an
84
+ operation never repeats the change.
85
+
86
+ `create_and_wait` raises `Heaven::OperationFailedError` when the create
87
+ ended `failed` or `superseded`, and `Heaven::WaitTimeoutError` when it
88
+ was still `accepted` at the deadline. Both carry the `operation` and the
89
+ create's `request_id`.
90
+
91
+ ### Running commands
92
+
93
+ `exec` runs one command line, as `ssh NAME CMD` does, within 30 seconds
94
+ and 1 MiB of output. `output` is the combined output as bytes (`""` for a
95
+ silent command, whose `output` Heaven sends as null), and `exit_code` is
96
+ the command's status. A non-zero exit is the answer, not an error. `stdin`
97
+ up to 1 MiB goes in the JSON body; more is sent as the request body.
98
+ `exec_stream` runs one for up to an hour with its output as it is
99
+ written; a job that must outlast the connection starts itself in the
100
+ background (`nohup CMD >LOG 2>&1 &`) and is checked with another `exec`.
101
+
102
+ ### Streamed commands
103
+
104
+ ```ruby
105
+ status = client.exec_stream("blog", "make test") do |stream, data|
106
+ (stream == :stderr ? $stderr : $stdout).write(data) # stream is :stdout or :stderr
107
+ end
108
+ puts "exit #{status}"
109
+
110
+ status = client.exec_stream("blog", "make test") # without a block: to $stdout and $stderr, as system does
111
+ ```
112
+
113
+ - `data` is the bytes as written (a binary String), not whole lines.
114
+ Without a block, they go to `out:` and `err:` (anything with `write`;
115
+ `$stdout` and `$stderr` unless given, `nil` to drop them). The answer is
116
+ the exit status; a non-zero one is the answer, not an error.
117
+ - A refusal before the command starts (a missing or paused Computer, a key
118
+ without `exec`, a busy host) raises the usual `Heaven::Error` subclass.
119
+ - Once output has begun, a stream that ends without an exit status raises
120
+ `Heaven::ExecStreamError`, an `UnknownOutcomeError`. `from_heaven?` is
121
+ true for the lobby's own error line, whose message says what happened,
122
+ and false for a connection cut, a line that can't be read, or the
123
+ timeout. The command may have run: check inside the Computer before
124
+ running it again.
125
+ - It is sent once and never again, and output already given is not given
126
+ again.
127
+ - `break`, or an exception, in the block ends the request, which stops the
128
+ command; the exception comes through as it was raised.
129
+ - `timeout:` bounds the whole stream (`STREAM_TIMEOUT`, 61 minutes: the
130
+ lobby stops a streamed command after an hour, and the minute more lets
131
+ its last line arrive), apart from the client's `timeout`.
132
+
133
+ ### Files
134
+
135
+ ```ruby
136
+ client.upload_file("blog", "site.tar", "/srv/site.tar", mode: 0o644)
137
+ client.upload("blog", "/etc/app.conf", "port = 8080\n")
138
+ client.download_file("blog", "/var/log/app.log", "app.log")
139
+ client.download("blog", "/var/log/app.log", $stdout)
140
+ ```
141
+
142
+ Files move as `scp` moves them, as the user a command runs as, and need
143
+ what `exec` needs: the `exec` command and a running Computer. They
144
+ stream, so a file of any size takes the same memory.
145
+
146
+ - **Upload.** The source is a String of bytes or an IO (anything with
147
+ `read`) read to its end; `upload_file` reads a local file. Heaven writes
148
+ beside the old file and renames over it once the bytes are whole, so a
149
+ refused or broken upload leaves the old file as it was. `mode` (`0o644`
150
+ or `"0644"`) sets the permissions; without it a file already there
151
+ keeps its own. Heaven can refuse before a byte is sent (`Expect:
152
+ 100-continue`), which leaves a pipe unread.
153
+ - **Sending an upload again** is harmless, so one that broke is sent again
154
+ from the start of a source that has one: a String, a file, or an IO
155
+ that seeks back to where it stood. A pipe or socket is read once. Its
156
+ answer lost after it was sent whole is `UnknownOutcomeError` (read the
157
+ file to see whether it changed); broken before then, it is
158
+ `UnavailableError`, and the file is unchanged.
159
+ - **Download.** A missing or unreadable file is refused (`NotFoundError`,
160
+ `DeniedError`) before any byte. `download_file` writes beside the local
161
+ file and renames over it once whole, keeping a replaced file's
162
+ permissions, so a refusal or a download cut short leaves a file already
163
+ there as it was; one cut short starts over. `download` writes to the IO
164
+ as bytes arrive: one cut short raises `Heaven::DownloadCutError` (an
165
+ `UnavailableError`) whose `bytes` is how many the IO got, and the IO
166
+ keeps them. It is sent again by itself only while nothing was written.
167
+
168
+ ## Errors
169
+
170
+ A refusal raises one subclass of `Heaven::Error` per
171
+ [kind](https://heaven.dev/docs/reference/errors):
172
+ `InvalidError`, `UnauthenticatedError`, `DeniedError`,
173
+ `PaymentRequiredError`, `NotFoundError`, `ConflictError`,
174
+ `OverCapacityError`, `AccessListFullError`, `BusyError`,
175
+ `RateLimitedError`, `UnavailableError` and `UnknownOutcomeError`; a kind
176
+ this version doesn't know is a plain `Heaven::Error` with that `kind`.
177
+ Each keeps every field Heaven sent: `kind`, `message`, `status`,
178
+ `request_id`, `operation_id`, `url` (the page that pays, for
179
+ `payment_required`), `action` (`command` and `line`, the command the
180
+ message suggests), `retry_after`, `heaven_request_id` (quote it to
181
+ support) and `body`, the `error` object as sent.
182
+
183
+ ```ruby
184
+ begin
185
+ client.command("pool start", { pool: "web" })
186
+ rescue Heaven::PaymentRequiredError => e
187
+ puts "Pay at #{e.url}"
188
+ rescue Heaven::Error => e
189
+ puts "#{e.kind}: #{e.message}"
190
+ puts "Run: #{e.action.line}" if e.action
191
+ end
192
+ ```
193
+
194
+ A delete that some Computers refuse is not raised: each refused one's
195
+ `error` is in `result.failed`. A name or ID that matches none of your
196
+ Computers refuses the whole delete (`NotFoundError`), and none is deleted. A redirect raises `Heaven::RedirectError`.
197
+ Bad arguments (an unknown command, a malformed request ID, a path off the
198
+ origin) raise `ArgumentError` before anything is sent.
199
+
200
+ ## Request IDs and retries
201
+
202
+ A change that takes a request ID (`create`, `delete`, `restart`, the
203
+ snapshot changes and purchases: [HTTP API guide](https://heaven.dev/docs/reference/retries))
204
+ always carries one as its `Idempotency-Key`: yours, or one the SDK makes,
205
+ which the answer and any error carry. A request ID is 1 to 128 visible
206
+ ASCII characters. Sending the change again with the same ID answers the
207
+ first attempt and never makes a second Computer, operation or purchase.
208
+
209
+ ```ruby
210
+ rid = Heaven.new_request_id # before the first attempt
211
+ begin
212
+ created = client.computers.create("blog", pool: "web", request_id: rid)
213
+ rescue Heaven::UnknownOutcomeError
214
+ created = client.computers.create("blog", pool: "web", request_id: rid) # the same create
215
+ end
216
+ ```
217
+
218
+ The SDK sends a request again by itself up to `max_retries` (2) more
219
+ times, waiting `retry_after` (the body's, or `Retry-After`) or backing off
220
+ from half a second. A `retry_after` over `max_retry_wait` (30 s) is
221
+ raised at once.
222
+
223
+ | Request | Sent again after |
224
+ | --- | --- |
225
+ | A read, or a change with a request ID | a lost connection, a timeout, an answer that isn't Heaven's (a proxy's 429 or 5xx, or one cut short), or Heaven's `busy`, `rate_limited`, `unavailable` or `unknown` |
226
+ | Any other change, `exec` included | a connection never made, or Heaven's own `busy`, `rate_limited` or `unavailable`, which say nothing changed |
227
+
228
+ A change without a request ID whose answer is lost, cut short or not
229
+ Heaven's raises `UnknownOutcomeError` and is never sent again. A command
230
+ in `exec` may have run, so check inside the Computer before repeating it.
231
+
232
+ ## Timeouts
233
+
234
+ `Heaven::Client.new(timeout: 60, open_timeout: 10)`: 10 seconds to
235
+ connect (TLS included) and 60 to answer, which covers Heaven's 30 seconds
236
+ for a change or an `exec`. `exec(..., timeout:)` and `command(...,
237
+ timeout:)` change it for one call; `operations.wait` gives each request
238
+ its wait plus 30 seconds. A timeout before the answer is a lost answer
239
+ (above): a read is sent again, a change without a request ID is
240
+ `UnknownOutcomeError`.
241
+
242
+ ## The credential
243
+
244
+ - The key goes only to the client's origin, over HTTPS. `http://` is
245
+ refused except to a loopback address (tests), which never goes through
246
+ a proxy; HTTPS honors `https_proxy`, which carries it encrypted.
247
+ - Redirects are never followed, so neither the key nor a change's body
248
+ goes anywhere else.
249
+ - `request` takes only a path on that origin. A path with its own host,
250
+ query, fragment, `@` or `..` is refused.
251
+ - `inspect` and `to_s` show the origin, never the key.
252
+
253
+ ## Not in this version
254
+
255
+ - Resuming a streamed `exec` whose stream was cut.
256
+ - `export`, a Computer's whole disk.
257
+ - Live reads (`/v1/events`) and the operation stream.
258
+ - Typed methods beyond Computers, operations and `exec`; `command`
259
+ reaches the rest, answering the decoded `data`.
260
+ - Connection reuse: each request opens its own connection.
261
+
262
+ ## Tests
263
+
264
+ ```sh
265
+ sdk/ruby/script/check.sh # RUBY=/path/to/ruby to choose one
266
+ ```
267
+
268
+ It runs the tests against this checkout, builds the gem, installs it into
269
+ an empty gem directory, runs the tests again against the installed gem,
270
+ then runs a consumer program and the example from a directory outside
271
+ the repository with only the installed gem. Everything runs against a
272
+ stand-in lobby on a loopback port with a dummy key; nothing reaches
273
+ Heaven.
274
+
275
+ The stand-in answers what the lobby answered for the docs
276
+ (`web/apps/docs/generated/responses.json`), read from this repository,
277
+ not copied. A test fails when a typed method's route or request ID
278
+ differs from the catalog's (`tests/api_routes.json`,
279
+ `internal/commandinput/request_id_commands.json`), or when
280
+ `docs/COMMANDS.md` documents a kind with no class.
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Creates a Computer, waits for it, runs two commands in it and deletes it.
4
+ #
5
+ # HEAVEN_API_KEY=heaven1... ruby examples/quickstart.rb NAME [POOL]
6
+ #
7
+ # It deletes only the Computer its own create made, by that Computer's ID:
8
+ # a NAME already taken is refused (conflict) and left alone. Creating a
9
+ # Computer uses your pool's capacity while it exists.
10
+ # HEAVEN_BASE_URL points it at another origin (the tests' stand-in).
11
+ require "heaven"
12
+
13
+ $stdout.sync = true # its lines and the errors' stay in order
14
+ name, pool = ARGV
15
+ abort "usage: ruby examples/quickstart.rb NAME [POOL]" unless name
16
+
17
+ client = Heaven::Client.new(base_url: ENV.fetch("HEAVEN_BASE_URL", nil))
18
+ request_id = Heaven.new_request_id # one ID for every attempt of this create
19
+ created = nil
20
+ begin
21
+ begin
22
+ created = client.computers.create(name, pool: pool, request_id: request_id)
23
+ rescue Heaven::UnknownOutcomeError
24
+ # The SDK already sent it again; once more with the same ID answers
25
+ # the first create if it happened, and never makes a second.
26
+ created = client.computers.create(name, pool: pool, request_id: request_id)
27
+ end
28
+ puts "Creating #{created.name} (#{created.ssh_dest})"
29
+
30
+ op = client.operations.wait(created.operation, timeout: 600)
31
+ abort "#{created.name} was not ready within 10 minutes (operation #{op.id})." unless op.done?
32
+ abort "Creating #{created.name} #{op.state}: #{op.message}" unless op.complete?
33
+
34
+ run = client.exec(created.name, "uname -sr")
35
+ puts "uname: #{run.text.strip} (exit #{run.exit_code})"
36
+
37
+ run = client.exec(created.name, "test -e /no/such/file")
38
+ puts "test -e: exit #{run.exit_code}" # non-zero is an answer, not an error
39
+ rescue Heaven::Error => e
40
+ warn "#{e.kind}: #{e.message}"
41
+ warn "Run: #{e.action.line}" if e.action
42
+ warn "Request ID: #{e.heaven_request_id}" if e.heaven_request_id
43
+ warn "#{name} may have been created; it was not deleted." if created.nil? && e.is_a?(Heaven::UnknownOutcomeError)
44
+ exit 1
45
+ ensure
46
+ if created
47
+ begin
48
+ result = client.computers.delete(created.operation.computer_id)
49
+ result.failed.each { warn "Not deleted: #{_1.error.message}" }
50
+ puts "Deleted #{created.name}" if result.failed.empty?
51
+ rescue Heaven::Error => e
52
+ warn "#{created.name} was not deleted (#{e.kind}: #{e.message}). Delete it with `heaven delete #{created.name}`."
53
+ exit 1
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "lib/heaven/version"
4
+
5
+ Gem::Specification.new do |s|
6
+ s.name = "heaven-sdk"
7
+ s.version = Heaven::VERSION
8
+ s.summary = "A client for Heaven's /v1 HTTPS API: Computers, operations and exec."
9
+ s.description = "Lists, reads, creates and deletes Heaven Computers, waits for operations, runs bounded " \
10
+ "commands in a Computer and sends any command in Heaven's catalog. Standard library only."
11
+ s.authors = ["Heaven"]
12
+ s.email = "support@heaven.dev"
13
+ s.license = "Apache-2.0"
14
+ s.homepage = "https://heaven.dev/docs"
15
+ s.required_ruby_version = ">= 3.2"
16
+ s.files = Dir["lib/**/*.rb"] + %w[README.md LICENSE NOTICE heaven-sdk.gemspec examples/quickstart.rb]
17
+ s.require_paths = ["lib"]
18
+ s.metadata["allowed_push_host"] = "https://rubygems.org"
19
+ s.metadata["rubygems_mfa_required"] = "true"
20
+ end