cocoonstack-sandbox 0.1.0__tar.gz → 0.1.2__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.
Files changed (26) hide show
  1. cocoonstack_sandbox-0.1.2/LICENSE +202 -0
  2. {cocoonstack_sandbox-0.1.0 → cocoonstack_sandbox-0.1.2}/PKG-INFO +7 -4
  3. {cocoonstack_sandbox-0.1.0 → cocoonstack_sandbox-0.1.2}/README.md +4 -3
  4. {cocoonstack_sandbox-0.1.0 → cocoonstack_sandbox-0.1.2}/cocoonsandbox/checkpoint.py +6 -2
  5. cocoonstack_sandbox-0.1.2/cocoonsandbox/client.py +215 -0
  6. {cocoonstack_sandbox-0.1.0 → cocoonstack_sandbox-0.1.2}/cocoonsandbox/conn.py +21 -5
  7. {cocoonstack_sandbox-0.1.0 → cocoonstack_sandbox-0.1.2}/cocoonsandbox/frames.py +17 -1
  8. {cocoonstack_sandbox-0.1.0 → cocoonstack_sandbox-0.1.2}/cocoonsandbox/sandbox.py +45 -29
  9. {cocoonstack_sandbox-0.1.0 → cocoonstack_sandbox-0.1.2}/cocoonsandbox/template.py +9 -6
  10. {cocoonstack_sandbox-0.1.0 → cocoonstack_sandbox-0.1.2}/cocoonstack_sandbox.egg-info/PKG-INFO +7 -4
  11. {cocoonstack_sandbox-0.1.0 → cocoonstack_sandbox-0.1.2}/cocoonstack_sandbox.egg-info/SOURCES.txt +4 -0
  12. {cocoonstack_sandbox-0.1.0 → cocoonstack_sandbox-0.1.2}/pyproject.toml +1 -1
  13. cocoonstack_sandbox-0.1.2/tests/test_fault_matrix.py +148 -0
  14. {cocoonstack_sandbox-0.1.0 → cocoonstack_sandbox-0.1.2}/tests/test_fixtures.py +1 -1
  15. cocoonstack_sandbox-0.1.2/tests/test_frames.py +36 -0
  16. cocoonstack_sandbox-0.1.2/tests/test_hardening.py +115 -0
  17. {cocoonstack_sandbox-0.1.0 → cocoonstack_sandbox-0.1.2}/tests/test_wire_binding.py +39 -1
  18. cocoonstack_sandbox-0.1.0/cocoonsandbox/client.py +0 -141
  19. {cocoonstack_sandbox-0.1.0 → cocoonstack_sandbox-0.1.2}/cocoonsandbox/__init__.py +0 -0
  20. {cocoonstack_sandbox-0.1.0 → cocoonstack_sandbox-0.1.2}/cocoonsandbox/errors.py +0 -0
  21. {cocoonstack_sandbox-0.1.0 → cocoonstack_sandbox-0.1.2}/cocoonstack_sandbox.egg-info/dependency_links.txt +0 -0
  22. {cocoonstack_sandbox-0.1.0 → cocoonstack_sandbox-0.1.2}/cocoonstack_sandbox.egg-info/top_level.txt +0 -0
  23. {cocoonstack_sandbox-0.1.0 → cocoonstack_sandbox-0.1.2}/setup.cfg +0 -0
  24. {cocoonstack_sandbox-0.1.0 → cocoonstack_sandbox-0.1.2}/tests/test_client.py +0 -0
  25. {cocoonstack_sandbox-0.1.0 → cocoonstack_sandbox-0.1.2}/tests/test_proc.py +0 -0
  26. {cocoonstack_sandbox-0.1.0 → cocoonstack_sandbox-0.1.2}/tests/test_proxy.py +0 -0
@@ -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.
@@ -1,10 +1,12 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cocoonstack-sandbox
3
- Version: 0.1.0
3
+ Version: 0.1.2
4
4
  Summary: Python SDK for the cocoon sandbox control plane
5
5
  License: Apache-2.0
6
6
  Requires-Python: >=3.9
7
7
  Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Dynamic: license-file
8
10
 
9
11
  # cocoonstack-sandbox
10
12
 
@@ -25,8 +27,9 @@ with client.new("ghcr.io/cocoonstack/sandbox/rt:24.04") as sb:
25
27
  stdlib-only and synchronous — `pip install cocoonstack-sandbox` brings no
26
28
  dependencies. The surface mirrors the Go SDK: exec/run, streaming files,
27
29
  tar push/pull, find/replace, watch, persistent sessions, git verbs, pty,
28
- port dial/proxy/preview URLs, fork, hibernate, promote, checkpoints, and
29
- the LSP broker. Wire fidelity is pinned by the shared protocol fixture
30
- corpus (Rust + Go + Python all round-trip it in CI).
30
+ port dial/proxy/preview URLs, background processes (spawn/ps/kill/
31
+ logs/attach), fork, hibernate, promote, checkpoints, and the LSP broker.
32
+ Wire fidelity is pinned by the shared protocol fixture corpus (Rust + Go +
33
+ Python all round-trip it in CI).
31
34
 
32
35
  Full reference: https://cocoonstack.github.io/sandbox/sdk-python
@@ -17,8 +17,9 @@ with client.new("ghcr.io/cocoonstack/sandbox/rt:24.04") as sb:
17
17
  stdlib-only and synchronous — `pip install cocoonstack-sandbox` brings no
18
18
  dependencies. The surface mirrors the Go SDK: exec/run, streaming files,
19
19
  tar push/pull, find/replace, watch, persistent sessions, git verbs, pty,
20
- port dial/proxy/preview URLs, fork, hibernate, promote, checkpoints, and
21
- the LSP broker. Wire fidelity is pinned by the shared protocol fixture
22
- corpus (Rust + Go + Python all round-trip it in CI).
20
+ port dial/proxy/preview URLs, background processes (spawn/ps/kill/
21
+ logs/attach), fork, hibernate, promote, checkpoints, and the LSP broker.
22
+ Wire fidelity is pinned by the shared protocol fixture corpus (Rust + Go +
23
+ Python all round-trip it in CI).
23
24
 
24
25
  Full reference: https://cocoonstack.github.io/sandbox/sdk-python
@@ -4,6 +4,11 @@ keeps running and can be checkpointed again, so captures form a tree."""
4
4
 
5
5
  from __future__ import annotations
6
6
 
7
+ from typing import TYPE_CHECKING
8
+
9
+ if TYPE_CHECKING:
10
+ from .sandbox import Sandbox
11
+
7
12
 
8
13
  class Checkpoint:
9
14
  """A captured sandbox state on its owner node."""
@@ -16,7 +21,7 @@ class Checkpoint:
16
21
  self.sandbox_id = rec.get("sandbox_id", "")
17
22
  self.created_at = rec.get("created_at", "")
18
23
 
19
- def new(self, ttl_seconds: int = 0):
24
+ def new(self, ttl_seconds: int = 0) -> Sandbox:
20
25
  """Claims a fresh sandbox branched from the checkpoint."""
21
26
  body = {"ttl_seconds": ttl_seconds} if ttl_seconds else {}
22
27
  reply = self._client._post_json(self._addr, f"/v1/checkpoints/{self.id}/claim", body, "claim checkpoint")
@@ -25,4 +30,3 @@ class Checkpoint:
25
30
  def delete(self) -> None:
26
31
  """Removes the checkpoint from its node."""
27
32
  self._client._request(self._addr, "DELETE", f"/v1/checkpoints/{self.id}", None, "delete checkpoint")
28
-
@@ -0,0 +1,215 @@
1
+ """Client: the control-plane entry point. Dial any node of a cluster; a
2
+ claim either lands locally or follows one MOVED-style redirect to the node
3
+ that has capacity, and the returned Sandbox is bound to its owner."""
4
+
5
+ from __future__ import annotations
6
+
7
+ import http.client
8
+ import json
9
+ import queue
10
+ import threading
11
+ import urllib.error
12
+ import urllib.parse
13
+ import urllib.request
14
+
15
+ from .checkpoint import Checkpoint
16
+ from .errors import APIError
17
+ from .sandbox import Sandbox
18
+
19
+ _PEERS_TIMEOUT = 5.0
20
+
21
+
22
+ class Client:
23
+ """Talks to one sandboxd node (and, transparently, its cluster)."""
24
+
25
+ def __init__(self, addr: str, api_token: str = "", timeout: float = 120.0):
26
+ self.addr = addr.split(",")[0].strip()
27
+ self.api_token = api_token
28
+ self.timeout = timeout
29
+
30
+ def new(self, template: str, net: str = "", size: str = "", ttl_seconds: int = 0) -> Sandbox:
31
+ """Claims a sandbox; a warm hit is milliseconds. On a cluster a warm
32
+ miss may redirect to a peer, followed transparently."""
33
+ claim = _claim_body(template, net, size, ttl_seconds)
34
+ reply = self._post_json(self.addr, "/v1/claim", claim, "claim")
35
+ redirect = reply.get("redirect") or []
36
+ if redirect:
37
+ # Retry at a peer with no_redirect set: it warm-or-provisions and
38
+ # cannot bounce us again.
39
+ claim["no_redirect"] = True
40
+ # A candidate that is full (429) or erroring must not abort the
41
+ # follow — try every one until a node answers, matching the Go SDK.
42
+ return _try_each(redirect, lambda peer: self._handle_from(
43
+ peer, self._post_json(peer, "/v1/claim", claim, "claim")),
44
+ retry=lambda _: True)
45
+ return self._handle_from(self.addr, reply)
46
+
47
+ def delete_template(self, template: str, net: str = "", size: str = "") -> None:
48
+ """Removes a promoted template by name; on a cluster the delete
49
+ follows gossip to the owner node (one hop)."""
50
+ query = _template_query(template, net, size)
51
+ path = "/v1/templates?" + urllib.parse.urlencode(query)
52
+ reply = self._request(self.addr, "DELETE", path, None, "delete template")
53
+ candidates = (reply or {}).get("redirect") or []
54
+ if not candidates:
55
+ return
56
+ # The retry carries no_redirect, mirroring the claim protocol: the
57
+ # owner answers for itself, never a second hop.
58
+ query["no_redirect"] = "1"
59
+ path = "/v1/templates?" + urllib.parse.urlencode(query)
60
+ _try_each(candidates, lambda peer: self._request(peer, "DELETE", path, None, "delete template"))
61
+
62
+ def lookup(self, id: str, token: str) -> Sandbox:
63
+ """Relocates a handle from id + token: asks the entry node and every
64
+ mesh peer concurrently, binding to whichever confirms ownership
65
+ first — one dead peer must not cost its full timeout."""
66
+ def probe(addr: str) -> Sandbox:
67
+ reply = self._request(addr, "GET", f"/v1/sandboxes/{id}/owner", None, "owner", bearer=token)
68
+ return Sandbox(client=self, id=id, token=token,
69
+ owner=reply.get("owner_addr") or addr)
70
+
71
+ addrs = [self.addr, *self._peers()]
72
+ try:
73
+ return _scatter(addrs, probe)
74
+ except APIError:
75
+ raise APIError("lookup", 404, f"no owner found for {id}") from None
76
+
77
+ def checkpoint(self, id: str) -> Checkpoint:
78
+ """A handle for a known checkpoint id, bound to the entry node — no
79
+ listing round-trip; an unknown id surfaces as 404 at claim time."""
80
+ return Checkpoint(self, self.addr, {"id": id})
81
+
82
+ def checkpoints(self) -> list[Checkpoint]:
83
+ """Lists the connected node's checkpoints, newest first."""
84
+ reply = self._request(self.addr, "GET", "/v1/checkpoints", None, "list checkpoints")
85
+ return [Checkpoint(self, self.addr, rec) for rec in reply.get("checkpoints") or []]
86
+
87
+ def info(self) -> dict:
88
+ """The node's pool/claim counters, as served by GET /v1/info."""
89
+ return self._request(self.addr, "GET", "/v1/info", None, "info")
90
+
91
+ def _peers(self) -> list:
92
+ # /v1/peers is tenant-accessible (cluster topology); /v1/info is
93
+ # operator-only, so a tenant lookup cannot read peers from it. A
94
+ # single node has none — degrade to just the entry node. Bounded
95
+ # tighter than the client default (mirrors the Go SDK's peersTimeout)
96
+ # so one slow entry node cannot stall the scatter it feeds.
97
+ try:
98
+ return self._request(self.addr, "GET", "/v1/peers", None, "peers",
99
+ timeout=min(_PEERS_TIMEOUT, self.timeout)).get("peers") or []
100
+ except APIError:
101
+ return []
102
+
103
+ def _handle_from(self, dialed: str, reply: dict) -> Sandbox:
104
+ return Sandbox(
105
+ client=self,
106
+ id=reply["id"],
107
+ token=reply["token"],
108
+ owner=reply.get("owner_addr") or dialed,
109
+ deadline=reply.get("deadline", ""),
110
+ from_checkpoint=reply.get("from_checkpoint", ""),
111
+ )
112
+
113
+ def _post_json(self, addr: str, path: str, body: dict, verb: str) -> dict:
114
+ return self._request(addr, "POST", path, body, verb)
115
+
116
+ def _request(self, addr: str, method: str, path: str, body, verb: str, bearer: str = "",
117
+ timeout: float = 0.0) -> dict:
118
+ """Issues one control-plane request. bearer overrides the api token —
119
+ sandbox-scoped verbs (release, hibernate) authenticate with the
120
+ per-sandbox token instead; timeout overrides the client default (0 keeps it)."""
121
+ data = json.dumps(body).encode() if body is not None else None
122
+ req = urllib.request.Request(f"http://{addr}{path}", data=data, method=method)
123
+ if data is not None:
124
+ req.add_header("Content-Type", "application/json")
125
+ token = bearer or self.api_token
126
+ if token:
127
+ req.add_header("Authorization", f"Bearer {token}")
128
+ try:
129
+ with urllib.request.urlopen(req, timeout=timeout or self.timeout) as resp:
130
+ raw = resp.read()
131
+ except urllib.error.HTTPError as exc:
132
+ try:
133
+ detail = _error_message(exc.read())
134
+ except (OSError, http.client.HTTPException) as read_exc:
135
+ detail = str(read_exc)
136
+ raise APIError(verb, exc.code, detail) from None
137
+ except urllib.error.URLError as exc:
138
+ raise APIError(verb, 0, str(exc.reason)) from None
139
+ except (OSError, http.client.HTTPException) as exc:
140
+ # A reset or truncated body read is neither HTTPError nor URLError.
141
+ raise APIError(verb, 0, str(exc)) from None
142
+ if not raw:
143
+ return {}
144
+ try:
145
+ return json.loads(raw)
146
+ except json.JSONDecodeError as exc:
147
+ raise APIError(verb, 0, "malformed JSON in response") from exc
148
+
149
+
150
+ def _claim_body(template: str, net: str, size: str, ttl_seconds: int) -> dict:
151
+ claim = {"template": template}
152
+ if net:
153
+ claim["net"] = net
154
+ if size:
155
+ claim["size"] = size
156
+ if ttl_seconds:
157
+ claim["ttl_seconds"] = ttl_seconds
158
+ return claim
159
+
160
+
161
+ def _template_query(template: str, net: str, size: str) -> dict:
162
+ query = {"template": template}
163
+ if net:
164
+ query["net"] = net
165
+ if size:
166
+ query["size"] = size
167
+ return query
168
+
169
+
170
+ def _error_message(raw: bytes) -> str:
171
+ try:
172
+ return json.loads(raw)["error"]
173
+ except (ValueError, KeyError, TypeError):
174
+ return raw.decode(errors="replace").strip()
175
+
176
+
177
+ def _try_each(candidates, call, retry=lambda exc: exc.status in (404, 0)):
178
+ """Calls call against each candidate in turn, returning the first
179
+ success. An APIError for which retry(exc) is true moves on to the next
180
+ candidate and the last such error propagates; any other raises at once.
181
+ The default retries only a miss (404 or a dead peer, status 0);
182
+ candidates must be non-empty."""
183
+ last_error = None
184
+ for addr in candidates:
185
+ try:
186
+ return call(addr)
187
+ except APIError as exc:
188
+ if not retry(exc):
189
+ raise
190
+ last_error = exc
191
+ raise last_error
192
+
193
+
194
+ def _scatter(addrs, probe):
195
+ """Probes every addr concurrently and returns the first success; when
196
+ all probes fail the last error propagates. Loser threads are daemons
197
+ whose requests die with _request's own timeout; the queue is bounded by
198
+ len(addrs) so they never block. addrs must be non-empty."""
199
+ results = queue.Queue(maxsize=len(addrs))
200
+
201
+ def run(addr):
202
+ try:
203
+ results.put((probe(addr), None))
204
+ except Exception as exc: # any escape would hang the drain below
205
+ results.put((None, exc))
206
+
207
+ for addr in addrs:
208
+ threading.Thread(target=run, args=(addr,), daemon=True).start()
209
+ last_error = None
210
+ for _ in addrs:
211
+ value, error = results.get()
212
+ if error is None:
213
+ return value
214
+ last_error = error
215
+ raise last_error
@@ -5,6 +5,7 @@ from __future__ import annotations
5
5
 
6
6
  import contextlib
7
7
  import socket
8
+ from collections.abc import Iterator
8
9
 
9
10
  from .errors import APIError, ProtocolError, SilkdError
10
11
  from .frames import MAX_FRAME, decode_response, encode_request
@@ -17,10 +18,10 @@ class Conn:
17
18
  self._sock = sock
18
19
  self._reader = reader
19
20
 
20
- def __enter__(self):
21
+ def __enter__(self) -> Conn:
21
22
  return self
22
23
 
23
- def __exit__(self, *exc):
24
+ def __exit__(self, *exc) -> None:
24
25
  self.close()
25
26
 
26
27
  def send(self, op: str, **fields) -> None:
@@ -39,7 +40,7 @@ class Conn:
39
40
  raise SilkdError(frame.get("kind", "internal"), frame.get("message", ""))
40
41
  return frame
41
42
 
42
- def recv_until(self, *terminal: str):
43
+ def recv_until(self, *terminal: str) -> Iterator[dict]:
43
44
  """Yields frames until one of the terminal types arrives; the
44
45
  terminal frame is yielded last."""
45
46
  while True:
@@ -58,11 +59,17 @@ class Conn:
58
59
  finally:
59
60
  self._sock.close()
60
61
 
62
+
61
63
  def dial_agent(addr: str, sandbox_id: str, token: str, timeout: float) -> Conn:
62
64
  """Opens the data-plane connection: TCP dial plus a hand-rolled HTTP
63
65
  Upgrade, so nothing pools or proxies underneath the byte stream."""
66
+ # id/token interpolate into the raw request line; CR/LF would inject headers.
67
+ for name, value in (("sandbox id", sandbox_id), ("token", token)):
68
+ if any(c in value for c in "\r\n\0"):
69
+ raise APIError("agent upgrade", 0, f"{name} contains a control character")
64
70
  host, port = addr.rsplit(":", 1)
65
71
  sock = socket.create_connection((host, int(port)), timeout=timeout)
72
+ reader = None
66
73
  try:
67
74
  request = (
68
75
  f"GET /v1/sandboxes/{sandbox_id}/agent HTTP/1.1\r\n"
@@ -84,11 +91,20 @@ def dial_agent(addr: str, sandbox_id: str, token: str, timeout: float) -> Conn:
84
91
  break
85
92
  name, _, value = header.decode(errors="replace").partition(":")
86
93
  if name.strip().lower() == "content-length":
87
- body_len = int(value.strip())
94
+ try:
95
+ body_len = int(value.strip())
96
+ if body_len < 0:
97
+ raise ValueError("negative content-length")
98
+ except ValueError as exc:
99
+ raise ProtocolError("invalid content-length in upgrade reply") from exc
88
100
  if code != 101:
89
- body = reader.read(body_len).decode(errors="replace") if body_len else ""
101
+ # A bogus content-length must not buffer unbounded bytes.
102
+ body = reader.read(min(body_len, MAX_FRAME)).decode(errors="replace") if body_len else ""
90
103
  raise APIError("agent upgrade", code, body.strip() or status.strip())
91
104
  return Conn(sock, reader)
92
105
  except Exception:
106
+ # makefile() holds a ref on the socket; close it too or the fd lingers.
107
+ if reader is not None:
108
+ reader.close()
93
109
  sock.close()
94
110
  raise
@@ -1,10 +1,11 @@
1
1
  """silkd wire frames: newline-delimited JSON, requests tagged by "op",
2
2
  responses by "type", binary payloads base64 in "data" fields. Mirrors the Go
3
- and Rust implementations; all three round-trip protocol/fixtures/v1."""
3
+ and Rust implementations; all three round-trip protocol/wire/fixtures/v1."""
4
4
 
5
5
  from __future__ import annotations
6
6
 
7
7
  import base64
8
+ import binascii
8
9
  import json
9
10
 
10
11
  PROTO_VERSION = 1
@@ -31,6 +32,21 @@ def encode_request(op: str, **fields) -> bytes:
31
32
  def decode_response(line: bytes) -> dict:
32
33
  """Parses one response frame; the returned dict carries its tag under
33
34
  "type" and any binary payload decoded under "data"."""
35
+ # Bulk frames (stdout/stderr/data) are the throughput path where json.loads
36
+ # of the big base64 string dominates. base64 is JSON-escape-free and these
37
+ # frames carry exactly {"type":...,"data":...}, so slice both out and skip
38
+ # json — but only for that exact shape; anything else (extra fields,
39
+ # trailing bytes, non-alphabet bytes in the segment) gets the full parse
40
+ # instead of a silently wrong slice.
41
+ if line.startswith(b'{"type":"'):
42
+ te = line.find(b'"', 9)
43
+ if te > 0 and line[9:te] in (b"stdout", b"stderr", b"data") and line.startswith(b'","data":"', te):
44
+ de = line.find(b'"', te + 10)
45
+ if de > 0 and line[de:] in (b'"}', b'"}\n'):
46
+ try:
47
+ return {"type": line[9:te].decode(), "data": base64.b64decode(line[te + 10 : de], validate=True)}
48
+ except binascii.Error:
49
+ pass
34
50
  frame = json.loads(line)
35
51
  if not isinstance(frame, dict) or "type" not in frame:
36
52
  raise ValueError(f"frame without a type tag: {line[:80]!r}")