orble-sdk 0.1.0__tar.gz

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,16 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Pocket Model, Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
6
+ documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
7
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
8
+ persons to whom the Software is furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
11
+ Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
14
+ WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
15
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
16
+ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,105 @@
1
+ Metadata-Version: 2.4
2
+ Name: orble-sdk
3
+ Version: 0.1.0
4
+ Summary: Orble: Linux boxes for agents
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://orble.tech
7
+ Project-URL: Documentation, https://orble.tech/docs
8
+ Requires-Python: >=3.9
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Dynamic: license-file
12
+
13
+ # Orble for Python
14
+
15
+ Make Linux boxes for agents, run commands in them, fork them and save them, from Python.
16
+
17
+ ```bash
18
+ pip install orble-sdk
19
+ ```
20
+
21
+ ```python
22
+ import orble
23
+
24
+ box = orble.create()
25
+ print(box.exec("echo hello").stdout)
26
+ box.delete()
27
+ ```
28
+
29
+ ## Run commands
30
+
31
+ ```python
32
+ r = box.exec("npm test", cwd="app", env={"CI": "1"}, timeout=300)
33
+ r.code, r.stdout, r.stderr
34
+ ```
35
+
36
+ Commands run with `/bin/sh -c` as the user `agent` (passwordless sudo), from `/home/agent`. `exec` waits for the
37
+ command to finish, up to `timeout` seconds (at most 600). Each stream comes back as its last 64 KiB.
38
+
39
+ ## Files
40
+
41
+ ```python
42
+ box.write("app/config.json", '{"port": 3000}')
43
+ box.read("app/config.json")
44
+ box.write("logo.png", data) # bytes too
45
+ box.read("logo.png", binary=True)
46
+ ```
47
+
48
+ Relative paths start at `/home/agent`. `write` makes any missing directories. A file can have up to 8 MiB.
49
+
50
+ ## Fork
51
+
52
+ ```python
53
+ a, b, c = box.fork(3)
54
+ ```
55
+
56
+ Each copy has the box's files, memory and running programs as they were when you forked it.
57
+
58
+ ## Snapshots
59
+
60
+ ```python
61
+ snap = box.snapshot("lab-start")
62
+ lab = orble.create(from_snapshot="lab-start")
63
+ orble.snapshots()
64
+ ```
65
+
66
+ ## Suspend and resume
67
+
68
+ ```python
69
+ box.suspend()
70
+ box.resume()
71
+ ```
72
+
73
+ Idle boxes suspend by themselves, and `exec`, `read` and `write` wake a suspended box.
74
+
75
+ ## Ports
76
+
77
+ ```python
78
+ box.exec("nohup python3 -m http.server 3000 > /dev/null 2>&1 &")
79
+ url = box.port(3000) # its https address, for your account only
80
+ url = box.port(3000, public=True) # for anyone with the address
81
+ ```
82
+
83
+ Public ports need an account that has added credit.
84
+
85
+ ## Boxes you have
86
+
87
+ ```python
88
+ orble.boxes()
89
+ box = orble.Box("k7f2")
90
+ ```
91
+
92
+ ## Auth
93
+
94
+ The SDK reads an API key from `ORBLE_API_KEY`. Make one in [Settings](https://orble.tech/settings?tab=api). Without
95
+ it, the SDK uses the sign-in of the [orble CLI](https://orble.tech/docs?tab=cli) (`orble login`). Errors are
96
+ `orble.Error`, with the HTTP `status` and Orble's `message`.
97
+
98
+ ## More
99
+
100
+ - [Docs](https://orble.tech/docs)
101
+ - [TypeScript](https://www.npmjs.com/package/@orble/sdk): `npm install @orble/sdk`
102
+
103
+ ## License
104
+
105
+ MIT
@@ -0,0 +1,93 @@
1
+ # Orble for Python
2
+
3
+ Make Linux boxes for agents, run commands in them, fork them and save them, from Python.
4
+
5
+ ```bash
6
+ pip install orble-sdk
7
+ ```
8
+
9
+ ```python
10
+ import orble
11
+
12
+ box = orble.create()
13
+ print(box.exec("echo hello").stdout)
14
+ box.delete()
15
+ ```
16
+
17
+ ## Run commands
18
+
19
+ ```python
20
+ r = box.exec("npm test", cwd="app", env={"CI": "1"}, timeout=300)
21
+ r.code, r.stdout, r.stderr
22
+ ```
23
+
24
+ Commands run with `/bin/sh -c` as the user `agent` (passwordless sudo), from `/home/agent`. `exec` waits for the
25
+ command to finish, up to `timeout` seconds (at most 600). Each stream comes back as its last 64 KiB.
26
+
27
+ ## Files
28
+
29
+ ```python
30
+ box.write("app/config.json", '{"port": 3000}')
31
+ box.read("app/config.json")
32
+ box.write("logo.png", data) # bytes too
33
+ box.read("logo.png", binary=True)
34
+ ```
35
+
36
+ Relative paths start at `/home/agent`. `write` makes any missing directories. A file can have up to 8 MiB.
37
+
38
+ ## Fork
39
+
40
+ ```python
41
+ a, b, c = box.fork(3)
42
+ ```
43
+
44
+ Each copy has the box's files, memory and running programs as they were when you forked it.
45
+
46
+ ## Snapshots
47
+
48
+ ```python
49
+ snap = box.snapshot("lab-start")
50
+ lab = orble.create(from_snapshot="lab-start")
51
+ orble.snapshots()
52
+ ```
53
+
54
+ ## Suspend and resume
55
+
56
+ ```python
57
+ box.suspend()
58
+ box.resume()
59
+ ```
60
+
61
+ Idle boxes suspend by themselves, and `exec`, `read` and `write` wake a suspended box.
62
+
63
+ ## Ports
64
+
65
+ ```python
66
+ box.exec("nohup python3 -m http.server 3000 > /dev/null 2>&1 &")
67
+ url = box.port(3000) # its https address, for your account only
68
+ url = box.port(3000, public=True) # for anyone with the address
69
+ ```
70
+
71
+ Public ports need an account that has added credit.
72
+
73
+ ## Boxes you have
74
+
75
+ ```python
76
+ orble.boxes()
77
+ box = orble.Box("k7f2")
78
+ ```
79
+
80
+ ## Auth
81
+
82
+ The SDK reads an API key from `ORBLE_API_KEY`. Make one in [Settings](https://orble.tech/settings?tab=api). Without
83
+ it, the SDK uses the sign-in of the [orble CLI](https://orble.tech/docs?tab=cli) (`orble login`). Errors are
84
+ `orble.Error`, with the HTTP `status` and Orble's `message`.
85
+
86
+ ## More
87
+
88
+ - [Docs](https://orble.tech/docs)
89
+ - [TypeScript](https://www.npmjs.com/package/@orble/sdk): `npm install @orble/sdk`
90
+
91
+ ## License
92
+
93
+ MIT
@@ -0,0 +1,194 @@
1
+ """Orble: Linux boxes for agents, from Python. https://orble.tech/docs"""
2
+ import base64
3
+ import json
4
+ import os
5
+ import sys
6
+ import time
7
+ import urllib.error
8
+ import urllib.parse
9
+ import urllib.request
10
+
11
+ __version__ = "0.1.0"
12
+ __all__ = ["Box", "Error", "Result", "Snapshot", "boxes", "create", "snapshots"]
13
+
14
+
15
+ class Error(Exception):
16
+ """A request Orble refused or couldn't answer: status is the HTTP status (0 when no answer came)."""
17
+
18
+ def __init__(self, status, message):
19
+ super().__init__(f"{status}: {message}" if status else message)
20
+ self.status, self.message = status, message
21
+
22
+
23
+ class Result:
24
+ """What a command did: its exit code and output (the last 64 KiB of each stream)."""
25
+
26
+ def __init__(self, code, stdout, stderr, timed_out=False):
27
+ self.code, self.stdout, self.stderr, self.timed_out = code, stdout, stderr, timed_out
28
+
29
+ def __repr__(self):
30
+ return f"Result(code={self.code}, stdout={self.stdout!r}, stderr={self.stderr!r})"
31
+
32
+
33
+ def _config_dir():
34
+ if sys.platform == "darwin":
35
+ return os.path.expanduser("~/Library/Application Support/orble")
36
+ if os.name == "nt":
37
+ return os.path.join(os.environ.get("APPDATA", ""), "orble")
38
+ return os.path.join(os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config"), "orble")
39
+
40
+
41
+ class Client:
42
+ """Talks to Orble's API. The key comes from ORBLE_API_KEY, or else from the orble CLI's sign-in."""
43
+
44
+ def __init__(self, key=None, url=None):
45
+ cli = {}
46
+ try:
47
+ with open(os.path.join(_config_dir(), "config.json")) as f:
48
+ cli = json.load(f)
49
+ except (OSError, ValueError):
50
+ pass
51
+ self.key = key or os.environ.get("ORBLE_API_KEY") or cli.get("token")
52
+ self.url = (url or os.environ.get("ORBLE_API_URL") or cli.get("api") or "https://orble.tech").rstrip("/")
53
+ if not self.key:
54
+ raise Error(0, "no API key: set ORBLE_API_KEY, or sign in with `orble login`")
55
+
56
+ def call(self, method, path, body=None, raw=None, timeout=660):
57
+ data, headers = None, {"Authorization": "Bearer " + self.key, "User-Agent": "orble-python/" + __version__}
58
+ if raw is not None:
59
+ data, headers["Content-Type"] = raw, "application/octet-stream"
60
+ elif body is not None:
61
+ data, headers["Content-Type"] = json.dumps(body).encode(), "application/json"
62
+ req = urllib.request.Request(self.url + path, data=data, method=method, headers=headers)
63
+ try:
64
+ with urllib.request.urlopen(req, timeout=timeout) as r:
65
+ text = r.read()
66
+ except urllib.error.HTTPError as e:
67
+ msg = e.read().decode(errors="replace")
68
+ try:
69
+ msg = json.loads(msg).get("error") or msg
70
+ except ValueError:
71
+ pass
72
+ raise Error(e.code, msg.strip() or e.reason) from None
73
+ except urllib.error.URLError as e:
74
+ raise Error(0, f"can't reach {self.url}: {e.reason}") from None
75
+ return json.loads(text) if text else {}
76
+
77
+
78
+ _default = None
79
+
80
+
81
+ def _client():
82
+ global _default
83
+ if _default is None:
84
+ _default = Client()
85
+ return _default
86
+
87
+
88
+ def _q(s):
89
+ return urllib.parse.quote(s, safe="")
90
+
91
+
92
+ class Box:
93
+ """A box, by name. Box("api") is an existing one; create() makes a new one."""
94
+
95
+ def __init__(self, name, client=None, info=None):
96
+ self.name, self._c, self.info = name, client or _client(), info or {}
97
+
98
+ def __repr__(self):
99
+ return f"Box({self.name!r})"
100
+
101
+ def _call(self, method, sub="", body=None, **kw):
102
+ return self._c.call(method, f"/v1/boxes/{_q(self.name)}{sub}", body, **kw)
103
+
104
+ def exec(self, command, timeout=None, env=None, cwd=None):
105
+ """Run a shell command as the user agent, from /home/agent unless cwd says otherwise, and wait for it."""
106
+ body = {"command": command}
107
+ if timeout:
108
+ body["timeout_s"] = int(timeout)
109
+ if env:
110
+ body["env"] = env
111
+ if cwd:
112
+ body["cwd"] = cwd
113
+ r = self._call("POST", "/exec", body)
114
+ while r.get("running"): # a command still running after 50 s: wait for it again
115
+ r = self._call("POST", "/exec", {"job": r["job"]})
116
+ return Result(r.get("exit_code"), r.get("stdout", ""), r.get("stderr", ""), r.get("timed_out", False))
117
+
118
+ def read(self, path, binary=False):
119
+ """A file's content: text, or bytes with binary=True. Relative paths start at /home/agent."""
120
+ out, offset = b"", 0
121
+ while True:
122
+ r = self._call("GET", f"/files?path={_q(path)}&offset={offset}")
123
+ part = r["content"].encode() if r["encoding"] == "utf-8" else base64.b64decode(r["content"])
124
+ out += part
125
+ offset += r["bytes"]
126
+ if not part or offset >= r["size"]:
127
+ return out if binary else out.decode()
128
+
129
+ def write(self, path, content):
130
+ """Write a file (text or bytes), replacing it, with any missing directories."""
131
+ data = content.encode() if isinstance(content, str) else bytes(content)
132
+ self._call("PUT", f"/files?path={_q(path)}", raw=data)
133
+
134
+ def port(self, port, public=False):
135
+ """Share a port at its own https address and return it. Private ports open for your account only."""
136
+ return self._call("PUT", f"/ports/{int(port)}", {"access": "public" if public else "private"})["url"]
137
+
138
+ def fork(self, count=1):
139
+ """Copies of the box as it is now, memory and running programs included."""
140
+ r = self._call("POST", "/fork", {"count": count})
141
+ if r.get("errors") and not r.get("boxes"):
142
+ raise Error(0, "; ".join(r["errors"]))
143
+ return [Box(b["name"], self._c, b) for b in r.get("boxes", [])]
144
+
145
+ def snapshot(self, name=None):
146
+ """Save the box as a snapshot, to make new boxes from later."""
147
+ r = self._call("POST", "/snapshot", {"name": name} if name else {})
148
+ return Snapshot(r["name"], self._c, r)
149
+
150
+ def suspend(self):
151
+ self.info = self._call("POST", "/suspend")
152
+
153
+ def resume(self):
154
+ self.info = self._call("POST", "/resume")
155
+
156
+ def delete(self):
157
+ self._call("DELETE")
158
+
159
+ def refresh(self):
160
+ self.info = self._call("GET")
161
+ return self.info
162
+
163
+ @property
164
+ def state(self):
165
+ return self.refresh()["state"]
166
+
167
+
168
+ class Snapshot:
169
+ def __init__(self, name, client=None, info=None):
170
+ self.name, self._c, self.info = name, client or _client(), info or {}
171
+
172
+ def __repr__(self):
173
+ return f"Snapshot({self.name!r})"
174
+
175
+ def delete(self):
176
+ self._c.call("DELETE", f"/v1/snapshots/{_q(self.name)}")
177
+
178
+
179
+ def create(size=None, name=None, from_snapshot=None, client=None):
180
+ """Make a box: size s (the default), m or l; from_snapshot names a snapshot to start from."""
181
+ c = client or _client()
182
+ body = {k: v for k, v in {"size": size, "name": name, "from": from_snapshot}.items() if v}
183
+ r = c.call("POST", "/v1/boxes", body)
184
+ return Box(r["name"], c, r)
185
+
186
+
187
+ def boxes(client=None):
188
+ c = client or _client()
189
+ return [Box(b["name"], c, b) for b in c.call("GET", "/v1/boxes")]
190
+
191
+
192
+ def snapshots(client=None):
193
+ c = client or _client()
194
+ return [Snapshot(s["name"], c, s) for s in c.call("GET", "/v1/snapshots")]
@@ -0,0 +1,105 @@
1
+ Metadata-Version: 2.4
2
+ Name: orble-sdk
3
+ Version: 0.1.0
4
+ Summary: Orble: Linux boxes for agents
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://orble.tech
7
+ Project-URL: Documentation, https://orble.tech/docs
8
+ Requires-Python: >=3.9
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Dynamic: license-file
12
+
13
+ # Orble for Python
14
+
15
+ Make Linux boxes for agents, run commands in them, fork them and save them, from Python.
16
+
17
+ ```bash
18
+ pip install orble-sdk
19
+ ```
20
+
21
+ ```python
22
+ import orble
23
+
24
+ box = orble.create()
25
+ print(box.exec("echo hello").stdout)
26
+ box.delete()
27
+ ```
28
+
29
+ ## Run commands
30
+
31
+ ```python
32
+ r = box.exec("npm test", cwd="app", env={"CI": "1"}, timeout=300)
33
+ r.code, r.stdout, r.stderr
34
+ ```
35
+
36
+ Commands run with `/bin/sh -c` as the user `agent` (passwordless sudo), from `/home/agent`. `exec` waits for the
37
+ command to finish, up to `timeout` seconds (at most 600). Each stream comes back as its last 64 KiB.
38
+
39
+ ## Files
40
+
41
+ ```python
42
+ box.write("app/config.json", '{"port": 3000}')
43
+ box.read("app/config.json")
44
+ box.write("logo.png", data) # bytes too
45
+ box.read("logo.png", binary=True)
46
+ ```
47
+
48
+ Relative paths start at `/home/agent`. `write` makes any missing directories. A file can have up to 8 MiB.
49
+
50
+ ## Fork
51
+
52
+ ```python
53
+ a, b, c = box.fork(3)
54
+ ```
55
+
56
+ Each copy has the box's files, memory and running programs as they were when you forked it.
57
+
58
+ ## Snapshots
59
+
60
+ ```python
61
+ snap = box.snapshot("lab-start")
62
+ lab = orble.create(from_snapshot="lab-start")
63
+ orble.snapshots()
64
+ ```
65
+
66
+ ## Suspend and resume
67
+
68
+ ```python
69
+ box.suspend()
70
+ box.resume()
71
+ ```
72
+
73
+ Idle boxes suspend by themselves, and `exec`, `read` and `write` wake a suspended box.
74
+
75
+ ## Ports
76
+
77
+ ```python
78
+ box.exec("nohup python3 -m http.server 3000 > /dev/null 2>&1 &")
79
+ url = box.port(3000) # its https address, for your account only
80
+ url = box.port(3000, public=True) # for anyone with the address
81
+ ```
82
+
83
+ Public ports need an account that has added credit.
84
+
85
+ ## Boxes you have
86
+
87
+ ```python
88
+ orble.boxes()
89
+ box = orble.Box("k7f2")
90
+ ```
91
+
92
+ ## Auth
93
+
94
+ The SDK reads an API key from `ORBLE_API_KEY`. Make one in [Settings](https://orble.tech/settings?tab=api). Without
95
+ it, the SDK uses the sign-in of the [orble CLI](https://orble.tech/docs?tab=cli) (`orble login`). Errors are
96
+ `orble.Error`, with the HTTP `status` and Orble's `message`.
97
+
98
+ ## More
99
+
100
+ - [Docs](https://orble.tech/docs)
101
+ - [TypeScript](https://www.npmjs.com/package/@orble/sdk): `npm install @orble/sdk`
102
+
103
+ ## License
104
+
105
+ MIT
@@ -0,0 +1,10 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ orble/__init__.py
5
+ orble_sdk.egg-info/PKG-INFO
6
+ orble_sdk.egg-info/SOURCES.txt
7
+ orble_sdk.egg-info/dependency_links.txt
8
+ orble_sdk.egg-info/top_level.txt
9
+ tests/test_live.py
10
+ tests/test_orble.py
@@ -0,0 +1 @@
1
+ orble
@@ -0,0 +1,19 @@
1
+ [project]
2
+ name = "orble-sdk"
3
+ version = "0.1.0"
4
+ description = "Orble: Linux boxes for agents"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ requires-python = ">=3.9"
8
+ dependencies = []
9
+
10
+ [project.urls]
11
+ Homepage = "https://orble.tech"
12
+ Documentation = "https://orble.tech/docs"
13
+
14
+ [build-system]
15
+ requires = ["setuptools>=77"]
16
+ build-backend = "setuptools.build_meta"
17
+
18
+ [tool.setuptools]
19
+ packages = ["orble"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,68 @@
1
+ """End to end against a real Orble, opt-in: ORBLE_LIVE=1 with ORBLE_API_KEY (and ORBLE_API_URL for staging).
2
+ It makes boxes and a snapshot under that key, and deletes them."""
3
+ import os
4
+ import time
5
+ import unittest
6
+
7
+ import orble
8
+
9
+
10
+ @unittest.skipUnless(os.environ.get("ORBLE_LIVE") == "1", "set ORBLE_LIVE=1 to run against a real Orble")
11
+ class Live(unittest.TestCase):
12
+ def test_everything(self):
13
+ made, snap = [], None
14
+ t0 = time.time()
15
+
16
+ def step(what):
17
+ print(f" {time.time() - t0:6.1f}s {what}", flush=True)
18
+
19
+ try:
20
+ box = orble.create(size="s")
21
+ made.append(box)
22
+ step(f"created {box.name}")
23
+ r = box.exec("echo hi; echo oops >&2; exit 3")
24
+ self.assertEqual((r.code, r.stdout, r.stderr), (3, "hi\n", "oops\n"))
25
+ r = box.exec('echo "$GREETING from $(pwd)"', env={"GREETING": "hello"}, cwd="/tmp")
26
+ self.assertEqual(r.stdout, "hello from /tmp\n")
27
+ step("exec")
28
+ box.write("app/config.json", '{"port": 3000}')
29
+ self.assertEqual(box.read("app/config.json"), '{"port": 3000}')
30
+ blob = bytes(range(256)) * 400 # 100 KiB of every byte value: more than one read
31
+ box.write("app/blob.bin", blob)
32
+ self.assertEqual(box.read("app/blob.bin", binary=True), blob)
33
+ step("write and read")
34
+ box.exec("echo forked > /home/agent/mark")
35
+ (copy,) = box.fork(1)
36
+ made.append(copy)
37
+ self.assertEqual(copy.exec("cat mark").stdout, "forked\n")
38
+ step(f"forked {copy.name}")
39
+ snap = box.snapshot(f"sdk-live-py-{int(t0)}")
40
+ step(f"snapshot {snap.name}")
41
+ again = orble.create(from_snapshot=snap.name)
42
+ made.append(again)
43
+ self.assertEqual(again.exec("cat mark").stdout, "forked\n")
44
+ step(f"created {again.name} from the snapshot")
45
+ box.suspend()
46
+ self.assertEqual(box.state, "suspended")
47
+ box.resume()
48
+ self.assertEqual(box.exec("cat app/config.json").stdout, '{"port": 3000}')
49
+ step("suspend and resume")
50
+ box.exec("nohup python3 -m http.server 3000 >/dev/null 2>&1 &")
51
+ url = box.port(3000)
52
+ self.assertTrue(url.startswith("https://"), url)
53
+ step(f"port 3000 at {url}")
54
+ self.assertIn(box.name, [b.name for b in orble.boxes()])
55
+ self.assertIn(snap.name, [s.name for s in orble.snapshots()])
56
+ with self.assertRaises(orble.Error) as e:
57
+ orble.Box("no-such-box").exec("true")
58
+ self.assertEqual(e.exception.status, 404)
59
+ finally:
60
+ for b in made:
61
+ b.delete()
62
+ if snap:
63
+ snap.delete()
64
+ step("deleted everything")
65
+
66
+
67
+ if __name__ == "__main__":
68
+ unittest.main()
@@ -0,0 +1,121 @@
1
+ """Unit tests against a fake Orble API: what each call sends, and what it makes of the answers."""
2
+ import base64
3
+ import json
4
+ import threading
5
+ import unittest
6
+ from http.server import BaseHTTPRequestHandler, HTTPServer
7
+
8
+ import orble
9
+
10
+
11
+ class Fake(BaseHTTPRequestHandler):
12
+ routes = {} # "METHOD path" -> list of (status, body) answers, used in turn
13
+ seen = []
14
+
15
+ def _serve(self):
16
+ n = int(self.headers.get("Content-Length") or 0)
17
+ body = self.rfile.read(n) if n else b""
18
+ Fake.seen.append((self.command, self.path, body, self.headers.get("Authorization")))
19
+ key = f"{self.command} {self.path.split('?')[0]}"
20
+ answers = Fake.routes.get(key) or [(404, {"error": "no such box"})]
21
+ status, out = answers.pop(0) if len(answers) > 1 else answers[0]
22
+ data = json.dumps(out).encode()
23
+ self.send_response(status)
24
+ self.send_header("Content-Type", "application/json")
25
+ self.send_header("Content-Length", str(len(data)))
26
+ self.end_headers()
27
+ self.wfile.write(data)
28
+
29
+ do_GET = do_POST = do_PUT = do_DELETE = _serve
30
+
31
+ def log_message(self, *a):
32
+ pass
33
+
34
+
35
+ class SDK(unittest.TestCase):
36
+ @classmethod
37
+ def setUpClass(cls):
38
+ cls.srv = HTTPServer(("127.0.0.1", 0), Fake)
39
+ threading.Thread(target=cls.srv.serve_forever, daemon=True).start()
40
+ cls.c = orble.Client(key="k1", url=f"http://127.0.0.1:{cls.srv.server_port}")
41
+
42
+ @classmethod
43
+ def tearDownClass(cls):
44
+ cls.srv.shutdown()
45
+
46
+ def setUp(self):
47
+ Fake.routes, Fake.seen = {}, []
48
+
49
+ def last(self):
50
+ m, p, b, auth = Fake.seen[-1]
51
+ return m, p, json.loads(b) if b and b[:1] in b"{[" else b, auth
52
+
53
+ def test_create_sends_only_what_was_given(self):
54
+ Fake.routes["POST /v1/boxes"] = [(200, {"name": "k7f2", "state": "running"})]
55
+ box = orble.create(size="m", from_snapshot="lab", client=self.c)
56
+ self.assertEqual(box.name, "k7f2")
57
+ self.assertEqual(self.last(), ("POST", "/v1/boxes", {"size": "m", "from": "lab"}, "Bearer k1"))
58
+
59
+ def test_exec_waits_for_a_long_command(self):
60
+ Fake.routes["POST /v1/boxes/k7f2/exec"] = [
61
+ (200, {"running": True, "job": "j1", "stdout": "a", "stderr": ""}),
62
+ (200, {"exit_code": 2, "stdout": "ab", "stderr": "e", "timed_out": False})]
63
+ r = orble.Box("k7f2", self.c).exec("make", timeout=90, env={"CI": "1"}, cwd="app")
64
+ self.assertEqual((r.code, r.stdout, r.stderr), (2, "ab", "e"))
65
+ self.assertEqual(json.loads(Fake.seen[0][2]), {"command": "make", "timeout_s": 90, "env": {"CI": "1"}, "cwd": "app"})
66
+ self.assertEqual(json.loads(Fake.seen[1][2]), {"job": "j1"})
67
+
68
+ def test_read_joins_parts_and_decodes(self):
69
+ Fake.routes["GET /v1/boxes/k7f2/files"] = [
70
+ (200, {"size": 6, "offset": 0, "bytes": 3, "encoding": "base64", "content": base64.b64encode(b"\x00\x01\x02").decode()}),
71
+ (200, {"size": 6, "offset": 3, "bytes": 3, "encoding": "utf-8", "content": "abc"})]
72
+ data = orble.Box("k7f2", self.c).read("a b/f", binary=True)
73
+ self.assertEqual(data, b"\x00\x01\x02abc")
74
+ self.assertEqual(Fake.seen[0][1], "/v1/boxes/k7f2/files?path=a%20b%2Ff&offset=0")
75
+ self.assertEqual(Fake.seen[1][1], "/v1/boxes/k7f2/files?path=a%20b%2Ff&offset=3")
76
+
77
+ def test_write_sends_the_bytes(self):
78
+ Fake.routes["PUT /v1/boxes/k7f2/files"] = [(200, {"path": "f", "bytes": 3})]
79
+ orble.Box("k7f2", self.c).write("f", b"\xff\x00x")
80
+ self.assertEqual(Fake.seen[-1][2], b"\xff\x00x")
81
+
82
+ def test_fork_snapshot_port(self):
83
+ Fake.routes["POST /v1/boxes/k7f2/fork"] = [(200, {"boxes": [{"name": "a1"}, {"name": "a2"}]})]
84
+ Fake.routes["POST /v1/boxes/k7f2/snapshot"] = [(200, {"name": "lab-start"})]
85
+ Fake.routes["PUT /v1/boxes/k7f2/ports/3000"] = [(200, {"port": 3000, "url": "https://3000-x.orble.tech"})]
86
+ box = orble.Box("k7f2", self.c)
87
+ self.assertEqual([b.name for b in box.fork(2)], ["a1", "a2"])
88
+ self.assertEqual(self.last()[2], {"count": 2})
89
+ self.assertEqual(box.snapshot("lab-start").name, "lab-start")
90
+ self.assertEqual(box.port(3000), "https://3000-x.orble.tech")
91
+ self.assertEqual(self.last()[2], {"access": "private"})
92
+
93
+ def test_errors_carry_status_and_message(self):
94
+ with self.assertRaises(orble.Error) as e:
95
+ orble.Box("nope", self.c).suspend()
96
+ self.assertEqual((e.exception.status, e.exception.message), (404, "no such box"))
97
+
98
+ def test_lists(self):
99
+ Fake.routes["GET /v1/boxes"] = [(200, [{"name": "a"}, {"name": "b"}])]
100
+ Fake.routes["GET /v1/snapshots"] = [(200, [{"name": "s"}])]
101
+ self.assertEqual([b.name for b in orble.boxes(self.c)], ["a", "b"])
102
+ self.assertEqual([s.name for s in orble.snapshots(self.c)], ["s"])
103
+
104
+ def test_no_key(self):
105
+ import os
106
+ old = os.environ.pop("ORBLE_API_KEY", None), os.environ.get("XDG_CONFIG_HOME")
107
+ os.environ["XDG_CONFIG_HOME"] = "/nonexistent"
108
+ try:
109
+ with self.assertRaises(orble.Error):
110
+ orble.Client()
111
+ finally:
112
+ if old[0]:
113
+ os.environ["ORBLE_API_KEY"] = old[0]
114
+ if old[1] is None:
115
+ os.environ.pop("XDG_CONFIG_HOME")
116
+ else:
117
+ os.environ["XDG_CONFIG_HOME"] = old[1]
118
+
119
+
120
+ if __name__ == "__main__":
121
+ unittest.main()