withruntime 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 +7 -0
- data/GUIDE.md +406 -0
- data/LICENSE +55 -0
- data/lib/withruntime/client.rb +79 -0
- data/lib/withruntime/credentials.rb +85 -0
- data/lib/withruntime/errors.rb +114 -0
- data/lib/withruntime/fields.rb +40 -0
- data/lib/withruntime/file_watch.rb +73 -0
- data/lib/withruntime/images.rb +258 -0
- data/lib/withruntime/network_products.rb +49 -0
- data/lib/withruntime/parity_products.rb +51 -0
- data/lib/withruntime/products.rb +373 -0
- data/lib/withruntime/record.rb +85 -0
- data/lib/withruntime/sandbox.rb +618 -0
- data/lib/withruntime/tar.rb +107 -0
- data/lib/withruntime/transport.rb +362 -0
- data/lib/withruntime/tunnel.rb +275 -0
- data/lib/withruntime/version.rb +5 -0
- data/lib/withruntime/websocket.rb +249 -0
- data/lib/withruntime.rb +32 -0
- metadata +64 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: 8912abd064916dd450a7fb5b9f0c1610c79b65918cf63a3a599b5906d46e3577
|
|
4
|
+
data.tar.gz: c7e663ef88244b43c2c761bb6f55e43ea147631e7c22b9c19b7d68789510c0e0
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: 041d53fd9761a1f1e0c9f94cfb70a77c6f0805329dbfbc3523f08cb7024ad4c3bcd06373e08fa6a391823ca48688d786be6643a2b2f460ad1c14c43ee8750c2b
|
|
7
|
+
data.tar.gz: 4ad9e1df60b31416e7d35abb1499a2fd5e1c329e314a91d9f440f6b56ec2bde9975ae7765a030187f8c6dff540ad8268468188d301de716ae83fd3758117493c
|
data/GUIDE.md
ADDED
|
@@ -0,0 +1,406 @@
|
|
|
1
|
+
# Ruby SDK
|
|
2
|
+
|
|
3
|
+
One Ruby client for every Runtime Cloud product.
|
|
4
|
+
|
|
5
|
+
The `withruntime` gem needs Ruby 3.2 or later and uses only the standard
|
|
6
|
+
library. It is safe to share between threads and keeps its connections open.
|
|
7
|
+
|
|
8
|
+
```bash no-run
|
|
9
|
+
gem install withruntime
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
**The client finds its key by itself.** It uses `RUNTIME_API_KEY` when that is
|
|
13
|
+
set, and otherwise the connection this machine saved (any `npx withruntime`
|
|
14
|
+
command connects it, with one browser approval).
|
|
15
|
+
|
|
16
|
+
On a server, put a key from https://withruntime.com/account/keys in
|
|
17
|
+
`RUNTIME_API_KEY` from your secret manager. Never put it in source code, a URL
|
|
18
|
+
or a command-line argument. With no key anywhere, `WithRuntime::Client.new`
|
|
19
|
+
raises `WithRuntime::AuthenticationError` whose `code` is `missing_api_key`
|
|
20
|
+
and whose `hint` says how to get one.
|
|
21
|
+
|
|
22
|
+
## Hello, sandbox
|
|
23
|
+
|
|
24
|
+
```ruby
|
|
25
|
+
require "withruntime"
|
|
26
|
+
|
|
27
|
+
runtime = WithRuntime::Client.new
|
|
28
|
+
sbx = runtime.sandboxes.create(funding: "trial")
|
|
29
|
+
begin
|
|
30
|
+
puts sbx.exec("python3 -c 'print(6 * 7)'", check: true).stdout
|
|
31
|
+
ensure
|
|
32
|
+
sbx.stop
|
|
33
|
+
end
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
`create` returns once the sandbox is running. With no arguments you get the
|
|
37
|
+
free trial while it lasts, the default region, and 2 vCPU, 4 GiB of memory and
|
|
38
|
+
a 4 GiB disk for up to 30 minutes. `funding: "trial"` never falls back to paid
|
|
39
|
+
credit. Every field is optional, in snake_case:
|
|
40
|
+
|
|
41
|
+
```ruby
|
|
42
|
+
require "withruntime"
|
|
43
|
+
|
|
44
|
+
runtime = WithRuntime::Client.new
|
|
45
|
+
sbx = runtime.sandboxes.create(
|
|
46
|
+
name: "tests-42",
|
|
47
|
+
labels: { team: "search", job: "42" },
|
|
48
|
+
vcpu: 2,
|
|
49
|
+
memory_mib: 4096,
|
|
50
|
+
disk_mib: 8192,
|
|
51
|
+
timeout_seconds: 900,
|
|
52
|
+
on_lease_end: "stop",
|
|
53
|
+
network: { internet: true, allow: ["rubygems.org", "*.githubusercontent.com"] }
|
|
54
|
+
)
|
|
55
|
+
puts sbx.id, sbx.info.funding, sbx.info.expires_at
|
|
56
|
+
sbx.stop
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
An answer reads by snake_case name (`sbx.info.memory_mib`) or by the API's own
|
|
60
|
+
key (`sbx.info["memoryMiB"]`), so a field newer than the SDK is always there. A
|
|
61
|
+
string key in a request (`"newField" => 1`) is sent as it is.
|
|
62
|
+
|
|
63
|
+
## Run commands
|
|
64
|
+
|
|
65
|
+
A string runs under `bash -c`; an array runs the program directly, with no
|
|
66
|
+
shell, which is what you want for untrusted arguments.
|
|
67
|
+
|
|
68
|
+
```ruby
|
|
69
|
+
require "withruntime"
|
|
70
|
+
|
|
71
|
+
runtime = WithRuntime::Client.new
|
|
72
|
+
sbx = runtime.sandboxes.create
|
|
73
|
+
sbx.exec("mkdir -p app && echo 'print(1 + 1)' > app/main.py")
|
|
74
|
+
run = sbx.exec(["python3", "main.py"], cwd: "/workspace/app", env: { API_TOKEN: ENV.fetch("API_TOKEN", "") }, timeout: 120)
|
|
75
|
+
warn run.stderr unless run.exit_code.zero?
|
|
76
|
+
print run.stdout
|
|
77
|
+
|
|
78
|
+
sbx.exec("for i in 1 2 3; do echo line $i; sleep 1; done", on_stdout: ->(text) { print text })
|
|
79
|
+
sbx.exec_stream("node --version") do |event|
|
|
80
|
+
print event["data"] if event["type"] == "stdout"
|
|
81
|
+
end
|
|
82
|
+
sbx.stop
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
- `env:` is how secrets reach a command. It is never echoed back. Never put a
|
|
86
|
+
secret in the command line itself.
|
|
87
|
+
- `stdin:` gives the command input, then closes it.
|
|
88
|
+
- The default timeout is 60 seconds; the maximum is a day. A timeout is a
|
|
89
|
+
result (`timed_out` is true, with the output so far), not an exception.
|
|
90
|
+
- `check: true` raises `WithRuntime::CommandError`, with the exit code and
|
|
91
|
+
output, on a non-zero exit or a timeout.
|
|
92
|
+
- With `on_stdout:`, `on_stderr:` or a timeout over a minute, the command
|
|
93
|
+
streams and the result keeps everything it printed. A long stream resumes by
|
|
94
|
+
itself when the server ends it, so no output is dropped.
|
|
95
|
+
|
|
96
|
+
## Background processes
|
|
97
|
+
|
|
98
|
+
```ruby
|
|
99
|
+
require "withruntime"
|
|
100
|
+
|
|
101
|
+
runtime = WithRuntime::Client.new
|
|
102
|
+
sbx = runtime.sandboxes.create
|
|
103
|
+
server = sbx.spawn("python3 -m http.server 8000", cwd: "/workspace")
|
|
104
|
+
repl = sbx.spawn(["python3", "-i", "-q"], pipe_stdin: true)
|
|
105
|
+
repl.write("print(21 * 2)\n", eof: true)
|
|
106
|
+
print repl.wait.stdout
|
|
107
|
+
sbx.processes.each { |process| puts "#{process.id} #{process.state} #{process.command}" }
|
|
108
|
+
server.kill("SIGTERM")
|
|
109
|
+
sbx.stop
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
A process outlives your connection; get it back with `sbx.process(id)`.
|
|
113
|
+
`write` tracks input offsets, so a retried write is never typed twice.
|
|
114
|
+
|
|
115
|
+
## Files
|
|
116
|
+
|
|
117
|
+
```ruby
|
|
118
|
+
require "withruntime"
|
|
119
|
+
|
|
120
|
+
runtime = WithRuntime::Client.new
|
|
121
|
+
sbx = runtime.sandboxes.create
|
|
122
|
+
sbx.files.write("/workspace/data/input.csv", "a,b\n1,2\n")
|
|
123
|
+
print sbx.files.read_text("/workspace/data/input.csv")
|
|
124
|
+
sbx.files.list("/workspace", depth: 2).each { |entry| puts "#{entry.type} #{entry.size} #{entry.path}" }
|
|
125
|
+
sbx.files.mkdir("/workspace/out")
|
|
126
|
+
sbx.files.rename("/workspace/data/input.csv", "/workspace/out/input.csv")
|
|
127
|
+
sbx.files.upload("./lib", "/workspace/project/lib")
|
|
128
|
+
sbx.files.download("/workspace/out", "./out")
|
|
129
|
+
sbx.stop
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
`write` makes parent directories and replaces the file atomically; a file over
|
|
133
|
+
1 MiB goes in parallel chunks checked by SHA-256. `stat` returns `nil` for a
|
|
134
|
+
path that does not exist. `upload` and `download` move a whole directory as
|
|
135
|
+
one gzipped archive. Pass `mode: 0o755` to write an executable, or
|
|
136
|
+
`mode: 0` for no permission bits. `chmod(path, mode)` changes an existing
|
|
137
|
+
file. A caller-supplied `idempotency_key:` also makes a complete large-file
|
|
138
|
+
write safe to repeat; each upload phase keeps its own stable key. On an
|
|
139
|
+
older guest, setting a mode also needs the exec grant for its chmod fallback.
|
|
140
|
+
|
|
141
|
+
## Pause, wake, fork and snapshot
|
|
142
|
+
|
|
143
|
+
```ruby
|
|
144
|
+
require "withruntime"
|
|
145
|
+
|
|
146
|
+
runtime = WithRuntime::Client.new
|
|
147
|
+
sbx = runtime.sandboxes.create(funding: "trial")
|
|
148
|
+
sbx.pause # memory and files are kept; compute billing stops
|
|
149
|
+
again = runtime.sandboxes.get(sbx.id)
|
|
150
|
+
again.wake(timeout_seconds: 1200)
|
|
151
|
+
again.extend_lease(600)
|
|
152
|
+
|
|
153
|
+
copies = again.fork(count: 2, funding: "trial")
|
|
154
|
+
copies.each(&:stop)
|
|
155
|
+
snapshot = again.snapshot(name: "ready", retention_days: 7)
|
|
156
|
+
runtime.sandboxes.create(snapshot: snapshot.id, funding: "trial").stop
|
|
157
|
+
runtime.snapshots.delete(snapshot.id)
|
|
158
|
+
again.stop
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
A fork copies a sandbox as it is now, with its files, memory and running
|
|
162
|
+
processes, on the same server; see [JavaScript](./javascript) for what forks
|
|
163
|
+
and snapshots keep and how they are billed. If a copy fails, the error's
|
|
164
|
+
`details["startedSandboxIds"]` names the copies that did start. Because
|
|
165
|
+
`extend` is Ruby's own, the lease is extended with `extend_lease(seconds)`.
|
|
166
|
+
`sbx.keep_alive` extends it from your process until `stop`, and
|
|
167
|
+
`runtime.sandboxes.get_or_create(name, **fields)` answers the sandbox with
|
|
168
|
+
that name, woken or restarted, or creates it.
|
|
169
|
+
|
|
170
|
+
## Share a port
|
|
171
|
+
|
|
172
|
+
```ruby
|
|
173
|
+
require "withruntime"
|
|
174
|
+
|
|
175
|
+
runtime = WithRuntime::Client.new
|
|
176
|
+
sbx = runtime.sandboxes.create
|
|
177
|
+
sbx.spawn("python3 -m http.server 3000")
|
|
178
|
+
preview = sbx.previews.create(3000)
|
|
179
|
+
puts preview.url, preview.token # send the token as x-runtime-preview-token
|
|
180
|
+
sbx.stop
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
A preview is private by default; `visibility: "public"` shares it with anyone
|
|
184
|
+
who has the address. Addresses are under `runtimehost.com`.
|
|
185
|
+
|
|
186
|
+
## Images, volumes, network rules and secrets
|
|
187
|
+
|
|
188
|
+
```ruby
|
|
189
|
+
require "withruntime"
|
|
190
|
+
|
|
191
|
+
runtime = WithRuntime::Client.new
|
|
192
|
+
image = runtime.images.build(name: "data", recipe: { pip: ["pandas"], apt: ["jq"] }) { |line| puts line.text }
|
|
193
|
+
volume = runtime.volumes.create(size_mib: 10_240, name: "cache")
|
|
194
|
+
sbx = runtime.sandboxes.create(image: image.id, volumes: [{ volume_id: volume.id, path: "/data" }])
|
|
195
|
+
print sbx.exec("python3 -c 'import pandas; print(pandas.__version__)'").stdout
|
|
196
|
+
cell = sbx.interpreter.run("import math\nround(math.pi * 2, 3)")
|
|
197
|
+
puts cell.results.first.data["text/plain"]
|
|
198
|
+
sbx.network.set(internet: true, allow: ["pypi.org", "*.pythonhosted.org"])
|
|
199
|
+
sbx.stop
|
|
200
|
+
|
|
201
|
+
secret = runtime.secrets.set("OPENAI_API_KEY", value: "sk-...", hosts: ["api.openai.com"])
|
|
202
|
+
puts secret.placeholder # what sandboxes see in $OPENAI_API_KEY
|
|
203
|
+
```
|
|
204
|
+
|
|
205
|
+
`images.build` waits until the image is ready and raises with code
|
|
206
|
+
`image_failed` when the build fails; `images.create` queues it and returns. A
|
|
207
|
+
Dockerfile build takes `dockerfile:` and `context_dir:`, the folder
|
|
208
|
+
`docker build` would read, with its `.dockerignore`; only the parts the server
|
|
209
|
+
does not have yet are uploaded. See [custom images](./images). A volume lives
|
|
210
|
+
on one server; volume backups can restore its data onto another host.
|
|
211
|
+
`sbx.desktop` drives a Linux desktop in the sandbox.
|
|
212
|
+
|
|
213
|
+
## Domains, TCP ports and private networking
|
|
214
|
+
|
|
215
|
+
```ruby
|
|
216
|
+
require "withruntime"
|
|
217
|
+
|
|
218
|
+
runtime = WithRuntime::Client.new
|
|
219
|
+
sbx = runtime.sandboxes.create
|
|
220
|
+
runtime.domains.add(hostname: "app.example.org", sandbox_id: sbx.id, port: 8080)
|
|
221
|
+
p runtime.domains.get("app.example.org") # DNS records to install, then verify
|
|
222
|
+
runtime.domains.verify("app.example.org")
|
|
223
|
+
port = runtime.ports.open(sandbox_id: sbx.id, port: 5432)
|
|
224
|
+
p port
|
|
225
|
+
runtime.ports.close(port.id)
|
|
226
|
+
runtime.domains.remove("app.example.org")
|
|
227
|
+
sbx.stop
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
`runtime.addresses.reserve(family: 4)` reserves a dedicated address;
|
|
231
|
+
`list` and `release(id)` manage it. Returned funding fields and integer money
|
|
232
|
+
are preserved. `runtime.tunnel` manages the account's WireGuard network with
|
|
233
|
+
`create`, `get`, `delete`, `add_peer`, `rotate_peer` and `remove_peer`.
|
|
234
|
+
Save a generated peer's `config` securely even when `config_ready` is false:
|
|
235
|
+
its private key is returned once. Calls generating a private key are not
|
|
236
|
+
retried automatically. `runtime.sso.get` reads the organization's SSO state.
|
|
237
|
+
|
|
238
|
+
## Backups, mounts, MCP and recordings
|
|
239
|
+
|
|
240
|
+
```ruby
|
|
241
|
+
require "withruntime"
|
|
242
|
+
|
|
243
|
+
runtime = WithRuntime::Client.new
|
|
244
|
+
volume = runtime.volumes.create(size_mib: 1024)
|
|
245
|
+
backup = runtime.volumes.backup(volume.id, name: "before-import", retention_days: 7)
|
|
246
|
+
runtime.volumes.set_backup_policy(volume.id, daily: true, retention_days: 7)
|
|
247
|
+
restored = runtime.volumes.restore(backup.id, name: "restored")
|
|
248
|
+
p runtime.volumes.backups(volume_id: volume.id).data
|
|
249
|
+
runtime.volumes.delete_backup(backup.id)
|
|
250
|
+
runtime.volumes.delete(restored.id)
|
|
251
|
+
runtime.volumes.delete(volume.id)
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
`sbx.mounts.add(provider: "s3", bucket: "data", path: "/data", secret: "S3_KEY")`
|
|
255
|
+
mounts an object store; `list` and `remove(path)` manage mounts. The named
|
|
256
|
+
secret stays on Runtime. `runtime.mcp.catalog` lists supported servers;
|
|
257
|
+
`sbx.mcp.start(servers: [{ id: "fetch" }])`, `ready`, `get` and `stop` manage
|
|
258
|
+
servers in a sandbox. Server `secrets`, `env` and `options` keep their
|
|
259
|
+
original dictionary keys.
|
|
260
|
+
|
|
261
|
+
`sbx.desktop.recordings.start(fps: 10)` returns a recording. Use `get(id)`,
|
|
262
|
+
`list`, `stop(id)`, `download(id)` for MP4 bytes, and `delete(id)` to manage it.
|
|
263
|
+
|
|
264
|
+
## Watch files
|
|
265
|
+
|
|
266
|
+
```ruby
|
|
267
|
+
require "withruntime"
|
|
268
|
+
|
|
269
|
+
runtime = WithRuntime::Client.new
|
|
270
|
+
sbx = runtime.sandboxes.create
|
|
271
|
+
watch = sbx.files.watch("/workspace", recursive: true)
|
|
272
|
+
begin
|
|
273
|
+
watch.events.each { |event| puts "#{event.k}: #{event.path}" }
|
|
274
|
+
ensure
|
|
275
|
+
watch.stop
|
|
276
|
+
sbx.stop
|
|
277
|
+
end
|
|
278
|
+
```
|
|
279
|
+
|
|
280
|
+
The reader follows continuation messages and keeps `watch.cursor`. Overflow
|
|
281
|
+
and lost-event notices reach your block. `watch.close` cancels only the active
|
|
282
|
+
reader; another thread can call it while HTTP headers, a body or a retry delay
|
|
283
|
+
is pending. `watch.stop` also removes the watch in the guest and prevents new
|
|
284
|
+
readers. A paused sandbox ends the current stream.
|
|
285
|
+
|
|
286
|
+
## Terminal and local port forwarding
|
|
287
|
+
|
|
288
|
+
```ruby
|
|
289
|
+
require "withruntime"
|
|
290
|
+
|
|
291
|
+
runtime = WithRuntime::Client.new
|
|
292
|
+
sbx = runtime.sandboxes.get("your-sandbox-id")
|
|
293
|
+
terminal = sbx.terminal(cols: 100, rows: 30)
|
|
294
|
+
begin
|
|
295
|
+
terminal.write("printf 'hello\n'\n")
|
|
296
|
+
print terminal.read
|
|
297
|
+
terminal.resize(cols: 120, rows: 40)
|
|
298
|
+
ensure
|
|
299
|
+
terminal.close
|
|
300
|
+
end
|
|
301
|
+
forward = sbx.port_forward(8080)
|
|
302
|
+
begin
|
|
303
|
+
puts "Local server: http://#{forward.host}:#{forward.port}"
|
|
304
|
+
ensure
|
|
305
|
+
forward.close
|
|
306
|
+
end
|
|
307
|
+
```
|
|
308
|
+
|
|
309
|
+
A terminal exposes `read`, `write`, `resize`, `process_id`, `exit_code` and
|
|
310
|
+
`close`. `sbx.open_tunnel` shares one authenticated connection across
|
|
311
|
+
`connect(port)` and `ssh(public_key)` streams. Each stream supports `read`,
|
|
312
|
+
`write`, `close_write` and `close`; half-closing input still permits a response.
|
|
313
|
+
`port_forward` binds to `127.0.0.1` and a free port by default; pass `host:`
|
|
314
|
+
and `local_port:` to choose them. Closing it releases its listener and active
|
|
315
|
+
connections.
|
|
316
|
+
|
|
317
|
+
Read responses while writing large requests. An individual unread stream has
|
|
318
|
+
at most 1 MiB buffered; overflow closes that stream with
|
|
319
|
+
`tunnel_receive_overflow` and leaves other streams usable. Closing a terminal
|
|
320
|
+
or tunnel wakes blocked readers and writers. WebSockets use the same API key
|
|
321
|
+
and origin, support an HTTP CONNECT proxy, and verify TLS certificates.
|
|
322
|
+
|
|
323
|
+
## Metrics, events and webhooks
|
|
324
|
+
|
|
325
|
+
```ruby
|
|
326
|
+
require "withruntime"
|
|
327
|
+
|
|
328
|
+
runtime = WithRuntime::Client.new
|
|
329
|
+
hook = runtime.webhooks.create(url: "https://example.com/hooks/runtime")
|
|
330
|
+
secret = hook.secret # shown once; keep it
|
|
331
|
+
|
|
332
|
+
# In your endpoint, with the raw body and the Runtime-Signature header:
|
|
333
|
+
begin
|
|
334
|
+
event = WithRuntime::Webhooks.verify("{}", "t=0,v1=0", secret)
|
|
335
|
+
puts event.type
|
|
336
|
+
rescue WithRuntime::WebhookVerificationError => e
|
|
337
|
+
puts "refused: #{e.message}"
|
|
338
|
+
end
|
|
339
|
+
runtime.events.list(type: "sandbox.stopped").each { |event| puts "#{event.created_at} #{event.type}" }
|
|
340
|
+
```
|
|
341
|
+
|
|
342
|
+
`sbx.metrics(range: "15m")` returns the sandbox's measured CPU and memory, and
|
|
343
|
+
`runtime.otel.create(endpoint: ...)` pushes events and metrics to an
|
|
344
|
+
OpenTelemetry endpoint. See [metrics and webhooks](./observability).
|
|
345
|
+
|
|
346
|
+
## Errors and retries
|
|
347
|
+
|
|
348
|
+
```ruby
|
|
349
|
+
require "withruntime"
|
|
350
|
+
|
|
351
|
+
runtime = WithRuntime::Client.new
|
|
352
|
+
begin
|
|
353
|
+
runtime.sandboxes.get("00000000-0000-4000-8000-000000000000")
|
|
354
|
+
rescue WithRuntime::NotFoundError
|
|
355
|
+
puts "no such sandbox"
|
|
356
|
+
rescue WithRuntime::Error => e
|
|
357
|
+
puts e.code, e.hint, e.request_id
|
|
358
|
+
end
|
|
359
|
+
```
|
|
360
|
+
|
|
361
|
+
Every error is a `WithRuntime::Error` with `code`, `message`, `hint`,
|
|
362
|
+
`request_id`, `status` and `details`. Its subclasses are
|
|
363
|
+
`AuthenticationError`, `PermissionDeniedError`, `NotFoundError`,
|
|
364
|
+
`ConflictError`, `InvalidRequestError`, `RateLimitError`,
|
|
365
|
+
`ServiceUnavailableError`, `ConnectionError` and `CommandError`, the same
|
|
366
|
+
classes as the JavaScript, Python, Go and Java SDKs.
|
|
367
|
+
|
|
368
|
+
Every write carries an idempotency key, made for you and kept across the
|
|
369
|
+
client's own retries. Transport failures, 429, 502, 503 and 504 are retried
|
|
370
|
+
with the same key, so a retry never makes two sandboxes or runs a command
|
|
371
|
+
twice. `retryable?` says whether trying the same call again may work.
|
|
372
|
+
|
|
373
|
+
**A create waits for room.** When every trial slot is taken (`trial_busy`), the
|
|
374
|
+
account is at its limit (`quota_exceeded`) or the region is full
|
|
375
|
+
(`no_capacity`), `sandboxes.create` waits and sends the same request again, for
|
|
376
|
+
up to two minutes. Pass `wait_for_capacity:` (seconds) to the client or to one
|
|
377
|
+
create; zero fails at once.
|
|
378
|
+
|
|
379
|
+
An owner, admin or developer can make a read-only key and set a daily spending
|
|
380
|
+
limit on a key at [API keys](https://withruntime.com/account/keys).
|
|
381
|
+
`runtime.limits.get` reads both; past the limit, a create, wake or extension
|
|
382
|
+
raises with code `spending_limit_reached`, and it is not retried.
|
|
383
|
+
|
|
384
|
+
## Configuration
|
|
385
|
+
|
|
386
|
+
```ruby
|
|
387
|
+
require "withruntime"
|
|
388
|
+
|
|
389
|
+
runtime = WithRuntime::Client.new(
|
|
390
|
+
api_key: ENV.fetch("MY_RUNTIME_KEY"),
|
|
391
|
+
timeout: 120,
|
|
392
|
+
max_retries: 4,
|
|
393
|
+
wait_for_capacity: 600
|
|
394
|
+
)
|
|
395
|
+
puts runtime.me.org_id
|
|
396
|
+
p runtime.request("GET", "/v1/volumes") # any endpoint, same rules
|
|
397
|
+
```
|
|
398
|
+
|
|
399
|
+
- `RUNTIME_API_URL` points the client at another API origin, as `base_url:`
|
|
400
|
+
does.
|
|
401
|
+
- The client is safe to share between threads. It keeps its connections open
|
|
402
|
+
and holds at most 32 calls in flight (`max_connections:`).
|
|
403
|
+
- It honours `HTTPS_PROXY` and `NO_PROXY`.
|
|
404
|
+
- Money is integer microdollars: 1,000,000 is one US dollar.
|
|
405
|
+
`runtime.usage.available` is the account's balance as an exact decimal
|
|
406
|
+
string.
|
data/LICENSE
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
|
|
5
|
+
http://www.apache.org/licenses/
|
|
6
|
+
|
|
7
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
8
|
+
|
|
9
|
+
1. Definitions.
|
|
10
|
+
|
|
11
|
+
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
|
16
|
+
|
|
17
|
+
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
|
|
18
|
+
|
|
19
|
+
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
|
20
|
+
|
|
21
|
+
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
|
22
|
+
|
|
23
|
+
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
|
|
24
|
+
|
|
25
|
+
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
|
26
|
+
|
|
27
|
+
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
|
28
|
+
|
|
29
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
|
|
30
|
+
|
|
31
|
+
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
|
|
32
|
+
|
|
33
|
+
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
|
|
34
|
+
|
|
35
|
+
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
|
36
|
+
|
|
37
|
+
You must give any other recipients of the Work or Derivative Works a copy of this License; and
|
|
38
|
+
|
|
39
|
+
You must cause any modified files to carry prominent notices stating that You changed the files; and
|
|
40
|
+
|
|
41
|
+
You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
|
|
42
|
+
|
|
43
|
+
If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
|
|
44
|
+
|
|
45
|
+
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
|
46
|
+
|
|
47
|
+
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
|
|
48
|
+
|
|
49
|
+
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
|
|
50
|
+
|
|
51
|
+
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
|
52
|
+
|
|
53
|
+
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
|
54
|
+
|
|
55
|
+
END OF TERMS AND CONDITIONS
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module WithRuntime
|
|
4
|
+
DEFAULT_BASE_URL = "https://api.withruntime.com"
|
|
5
|
+
|
|
6
|
+
# One client for every Runtime Cloud product. Make it once and share it: it
|
|
7
|
+
# is safe for use from many threads and keeps its connections open.
|
|
8
|
+
#
|
|
9
|
+
# runtime = WithRuntime::Client.new # RUNTIME_API_KEY, or this machine's saved connection
|
|
10
|
+
# sbx = runtime.sandboxes.create(funding: "trial")
|
|
11
|
+
# puts sbx.exec("python3 -c 'print(6 * 7)'", check: true).stdout
|
|
12
|
+
# sbx.stop
|
|
13
|
+
#
|
|
14
|
+
# Every product is +runtime.<product>.<verb>+. Money is integer microdollars
|
|
15
|
+
# (1,000,000 is one US dollar).
|
|
16
|
+
class Client
|
|
17
|
+
attr_reader :transport, :sandboxes, :snapshots, :images, :volumes, :secrets, :limits, :referrals,
|
|
18
|
+
:switching, :events, :webhooks, :otel, :audit, :feedback, :support, :domains, :ports, :addresses, :tunnel, :sso, :mcp
|
|
19
|
+
|
|
20
|
+
# +api_key+: default RUNTIME_API_KEY, then this machine's saved connection.
|
|
21
|
+
# +base_url+: default RUNTIME_API_URL, then https://api.withruntime.com.
|
|
22
|
+
# +timeout+: seconds for each call, retries included (300).
|
|
23
|
+
# +max_retries+: of transport failures, 429, 502, 503 and 504 (4).
|
|
24
|
+
# +max_connections+: calls in flight at once; streams do not count (32).
|
|
25
|
+
# +wait_for_capacity+: seconds a sandbox create keeps retrying, with the
|
|
26
|
+
# same key and input, when the trial, quota or region is full (120; 0 fails at once).
|
|
27
|
+
def initialize(api_key: nil, base_url: nil, timeout: 300, max_retries: 4, max_connections: 32,
|
|
28
|
+
wait_for_capacity: 120, env: ENV)
|
|
29
|
+
origin = Credentials.origin(base_url || env["RUNTIME_API_URL"].then { |url| url.nil? || url.empty? ? DEFAULT_BASE_URL : url })
|
|
30
|
+
key = api_key
|
|
31
|
+
key ||= env["RUNTIME_API_KEY"] unless env["RUNTIME_API_KEY"].to_s.empty?
|
|
32
|
+
key ||= Credentials.saved_key(env, origin)
|
|
33
|
+
raise Error.missing_key if key.nil? || key.empty?
|
|
34
|
+
raise ArgumentError, "The Runtime API key contains whitespace." if key.match?(/\s/)
|
|
35
|
+
raise ArgumentError, "max_retries cannot be negative." if max_retries.negative?
|
|
36
|
+
|
|
37
|
+
@transport = Transport.new(api_key: key, base_url: origin, timeout: timeout, max_retries: max_retries,
|
|
38
|
+
max_connections: max_connections, wait_for_capacity: [0, wait_for_capacity].max)
|
|
39
|
+
@sandboxes = Sandboxes.new(@transport)
|
|
40
|
+
@snapshots = Snapshots.new(@transport)
|
|
41
|
+
@images = Images.new(@transport)
|
|
42
|
+
@volumes = Volumes.new(@transport)
|
|
43
|
+
@secrets = Secrets.new(@transport)
|
|
44
|
+
@limits = Limits.new(@transport)
|
|
45
|
+
@referrals = Referrals.new(@transport)
|
|
46
|
+
@switching = Switching.new(@transport)
|
|
47
|
+
@events = Events.new(@transport)
|
|
48
|
+
@webhooks = Webhooks.new(@transport)
|
|
49
|
+
@otel = Otel.new(@transport)
|
|
50
|
+
@audit = Audit.new(@transport)
|
|
51
|
+
@feedback = Feedback.new(@transport)
|
|
52
|
+
@support = Support.new(@transport)
|
|
53
|
+
@domains = Domains.new(@transport)
|
|
54
|
+
@ports = Ports.new(@transport)
|
|
55
|
+
@addresses = Addresses.new(@transport)
|
|
56
|
+
@tunnel = PrivateTunnel.new(@transport)
|
|
57
|
+
@sso = SSO.new(@transport)
|
|
58
|
+
@mcp = MCP.new(@transport)
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
def base_url = @transport.base_url
|
|
62
|
+
|
|
63
|
+
# Who this key is: organization, agent and credential.
|
|
64
|
+
def me = Record.new(@transport.json("GET", "/v1/me"))
|
|
65
|
+
|
|
66
|
+
# The account's credit, holds, trial time and per-resource charges.
|
|
67
|
+
def usage = Record.new(@transport.json("GET", "/v1/usage"))
|
|
68
|
+
|
|
69
|
+
# Calls any API path with this client's key, retries, idempotency keys and
|
|
70
|
+
# errors, and returns the parsed JSON answer. For an endpoint newer than this SDK.
|
|
71
|
+
def request(method, path, query: nil, body: nil)
|
|
72
|
+
raise ArgumentError, "The path must start with /." unless path.start_with?("/")
|
|
73
|
+
|
|
74
|
+
method = method.to_s.upcase
|
|
75
|
+
body = {} if body.nil? && !%w[GET DELETE].include?(method)
|
|
76
|
+
@transport.json(method, path, query: query, body: body)
|
|
77
|
+
end
|
|
78
|
+
end
|
|
79
|
+
end
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "digest"
|
|
4
|
+
require "json"
|
|
5
|
+
require "uri"
|
|
6
|
+
|
|
7
|
+
module WithRuntime
|
|
8
|
+
# The key `runtime login` saved for this machine. Its file is the CLI's
|
|
9
|
+
# (packages/cloud-sdk/src/credentials.ts) and is read exactly as the CLI
|
|
10
|
+
# reads it: only from a private file in a private directory, bound to both
|
|
11
|
+
# origins.
|
|
12
|
+
module Credentials
|
|
13
|
+
KEY = /\Artcloud_[a-f0-9-]{36}_[A-Za-z0-9_-]{43}\z/
|
|
14
|
+
|
|
15
|
+
module_function
|
|
16
|
+
|
|
17
|
+
# An HTTPS origin, or plain HTTP to localhost for tests, with nothing after the host.
|
|
18
|
+
def origin(value)
|
|
19
|
+
uri = URI(value)
|
|
20
|
+
local = %w[localhost 127.0.0.1 [::1] ::1].include?(uri.host)
|
|
21
|
+
unless uri.host && (uri.scheme == "https" || (local && uri.scheme == "http")) && uri.userinfo.nil? &&
|
|
22
|
+
uri.query.nil? && uri.fragment.nil? && ["", "/"].include?(uri.path.to_s)
|
|
23
|
+
raise ArgumentError, "Use an HTTPS API origin (or http://localhost for tests)."
|
|
24
|
+
end
|
|
25
|
+
|
|
26
|
+
default_port = uri.scheme == "https" ? 443 : 80
|
|
27
|
+
host = uri.host.include?(":") && !uri.host.start_with?("[") ? "[#{uri.host}]" : uri.host
|
|
28
|
+
"#{uri.scheme}://#{host}#{uri.port == default_port ? "" : ":#{uri.port}"}"
|
|
29
|
+
rescue URI::InvalidURIError
|
|
30
|
+
raise ArgumentError, "Use an HTTPS API origin (or http://localhost for tests)."
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
# Where the CLI keeps this machine's connection for the two origins.
|
|
34
|
+
def file(env, api_origin, auth_origin)
|
|
35
|
+
root = env["XDG_CONFIG_HOME"]
|
|
36
|
+
root = File.join(Dir.home, ".config") if root.nil? || root.empty?
|
|
37
|
+
raise ArgumentError, "XDG_CONFIG_HOME must be an absolute path." unless root.start_with?("/")
|
|
38
|
+
|
|
39
|
+
File.join(root, "runtime-cloud", "#{Digest::SHA256.hexdigest("#{auth_origin}\n#{api_origin}")}.json")
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
# The saved key, or nil when there is none.
|
|
43
|
+
def saved_key(env, api_origin)
|
|
44
|
+
auth = env["RUNTIME_AUTH_URL"]
|
|
45
|
+
auth_origin = origin(auth.nil? || auth.empty? ? "https://withruntime.com" : auth)
|
|
46
|
+
path = file(env, api_origin, auth_origin)
|
|
47
|
+
directory = File.dirname(path)
|
|
48
|
+
begin
|
|
49
|
+
info = File.lstat(directory)
|
|
50
|
+
rescue Errno::ENOENT
|
|
51
|
+
return nil
|
|
52
|
+
end
|
|
53
|
+
raise SecurityError, "Runtime's credential directory must be private to your user." unless info.directory? && private?(info)
|
|
54
|
+
|
|
55
|
+
text = begin
|
|
56
|
+
File.open(path, File::RDONLY | File::NOFOLLOW) do |handle|
|
|
57
|
+
stat = handle.stat
|
|
58
|
+
raise SecurityError, "Runtime's saved connection must be private to your user." unless stat.file? && stat.size <= 4096 && private?(stat)
|
|
59
|
+
|
|
60
|
+
handle.read(4097)
|
|
61
|
+
end
|
|
62
|
+
rescue Errno::ENOENT
|
|
63
|
+
return nil
|
|
64
|
+
rescue Errno::ELOOP
|
|
65
|
+
raise SecurityError, "Could not safely open Runtime's saved connection."
|
|
66
|
+
end
|
|
67
|
+
saved = JSON.parse(text)
|
|
68
|
+
unless saved.is_a?(Hash) && saved["version"] == 1 && saved["apiOrigin"] == api_origin &&
|
|
69
|
+
saved["authOrigin"] == auth_origin && saved["key"].is_a?(String) && KEY.match?(saved["key"]) &&
|
|
70
|
+
%w[connectionId orgId agentName].all? { |name| saved[name].is_a?(String) }
|
|
71
|
+
raise ArgumentError, "Runtime's saved connection is invalid. Connect again with `npx withruntime login`."
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
saved["key"]
|
|
75
|
+
rescue JSON::ParserError
|
|
76
|
+
raise ArgumentError, "Runtime's saved connection is invalid. Connect again with `npx withruntime login`."
|
|
77
|
+
end
|
|
78
|
+
|
|
79
|
+
def private?(stat)
|
|
80
|
+
return true if Gem.win_platform?
|
|
81
|
+
|
|
82
|
+
(stat.mode & 0o077).zero? && stat.uid == Process.uid
|
|
83
|
+
end
|
|
84
|
+
end
|
|
85
|
+
end
|