cocoonstack-sandbox 0.1.36__tar.gz → 0.1.38__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 (36) hide show
  1. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.38}/PKG-INFO +2 -2
  2. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.38}/cocoonsandbox/client.py +23 -17
  3. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.38}/cocoonsandbox/conn.py +19 -8
  4. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.38}/cocoonsandbox/errors.py +2 -4
  5. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.38}/cocoonsandbox/frames.py +1 -3
  6. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.38}/cocoonsandbox/sandbox.py +49 -36
  7. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.38}/cocoonstack_sandbox.egg-info/PKG-INFO +2 -2
  8. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.38}/pyproject.toml +2 -2
  9. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.38}/tests/test_fault_matrix.py +76 -3
  10. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.38}/tests/test_hardening.py +107 -0
  11. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.38}/tests/test_stream.py +59 -5
  12. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.38}/LICENSE +0 -0
  13. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.38}/README.md +0 -0
  14. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.38}/cocoonsandbox/__init__.py +0 -0
  15. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.38}/cocoonsandbox/checkpoint.py +0 -0
  16. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.38}/cocoonsandbox/endpoint.py +0 -0
  17. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.38}/cocoonsandbox/py.typed +0 -0
  18. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.38}/cocoonsandbox/template.py +0 -0
  19. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.38}/cocoonsandbox/volumes.py +0 -0
  20. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.38}/cocoonstack_sandbox.egg-info/SOURCES.txt +0 -0
  21. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.38}/cocoonstack_sandbox.egg-info/dependency_links.txt +0 -0
  22. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.38}/cocoonstack_sandbox.egg-info/top_level.txt +0 -0
  23. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.38}/setup.cfg +0 -0
  24. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.38}/tests/test_checkpoint.py +0 -0
  25. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.38}/tests/test_client.py +0 -0
  26. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.38}/tests/test_endpoint.py +0 -0
  27. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.38}/tests/test_fixtures.py +0 -0
  28. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.38}/tests/test_frames.py +0 -0
  29. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.38}/tests/test_keepalive.py +0 -0
  30. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.38}/tests/test_packaging.py +0 -0
  31. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.38}/tests/test_proc.py +0 -0
  32. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.38}/tests/test_proxy.py +0 -0
  33. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.38}/tests/test_upgrade.py +0 -0
  34. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.38}/tests/test_volume_controller.py +0 -0
  35. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.38}/tests/test_volumes.py +0 -0
  36. {cocoonstack_sandbox-0.1.36 → cocoonstack_sandbox-0.1.38}/tests/test_wire_binding.py +0 -0
@@ -1,9 +1,9 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cocoonstack-sandbox
3
- Version: 0.1.36
3
+ Version: 0.1.38
4
4
  Summary: Python SDK for the cocoon sandbox control plane
5
5
  License: Apache-2.0
6
- Requires-Python: >=3.10
6
+ Requires-Python: >=3.12
7
7
  Description-Content-Type: text/markdown
8
8
  License-File: LICENSE
9
9
  Dynamic: license-file
@@ -10,7 +10,7 @@ import threading
10
10
  import time
11
11
  import urllib.parse
12
12
  from collections.abc import Callable, Iterable, Sequence
13
- from typing import Any, TypeVar, cast
13
+ from typing import Any, cast
14
14
 
15
15
  from .checkpoint import Checkpoint
16
16
  from .conn import Conn, _Closeable, dial_agent, is_quiet, remaining_timeout
@@ -20,8 +20,6 @@ from .sandbox import Sandbox
20
20
  from .template import _claim_body, _template_query
21
21
  from .volumes import Volume
22
22
 
23
- _T = TypeVar("_T")
24
-
25
23
  _PEERS_TIMEOUT = 5.0
26
24
  _IDLE_CONNS = 8
27
25
 
@@ -38,10 +36,7 @@ class Client(_Closeable):
38
36
  ssl_context: ssl.SSLContext | None = None,
39
37
  keep_alive: float = 30.0,
40
38
  ) -> None:
41
- """keep_alive parks idle connections, 0 dials per call; a parked relay one holds the sandbox's idle clock.
42
-
43
- ssl_context is set to offer ALPN http/1.1, which the relay upgrade needs; pass a dedicated context.
44
- """
39
+ """keep_alive parks idle connections (0 dials per call); ssl_context is set to offer ALPN http/1.1."""
45
40
  endpoint = _endpoint_url(addr.strip())
46
41
  self.addr = endpoint.geturl().removeprefix("http://")
47
42
  self._scheme = endpoint.scheme
@@ -99,7 +94,11 @@ class Client(_Closeable):
99
94
  peers, peers_err = self._peers()
100
95
  try:
101
96
  return _scatter([self.addr, *peers], probe)
102
- except APIError:
97
+ except APIError as exc:
98
+ if exc.status >= 500 or exc.status == 0:
99
+ raise
100
+ if peers_err is not None and (peers_err.status >= 500 or peers_err.status == 0):
101
+ raise peers_err from None
103
102
  reason = f"no owner found for {id}" if peers_err is None else f"no owner found for {id}; {peers_err}"
104
103
  raise APIError("lookup", 404, reason) from None
105
104
 
@@ -300,9 +299,9 @@ def _retry_miss(exc: APIError) -> bool:
300
299
  return exc.status in (404, 0)
301
300
 
302
301
 
303
- def _try_each(
304
- candidates: Iterable[str], call: Callable[[str], _T], retry: Callable[[APIError], bool] = _retry_miss
305
- ) -> _T:
302
+ def _try_each[T](
303
+ candidates: Iterable[str], call: Callable[[str], T], retry: Callable[[APIError], bool] = _retry_miss
304
+ ) -> T:
306
305
  last_error = None
307
306
  for addr in candidates:
308
307
  try:
@@ -345,8 +344,14 @@ def _redirect_fallback(
345
344
  raise APIError(verb, origin_exc.status, combined) from origin_exc
346
345
 
347
346
 
348
- def _scatter(addrs: Sequence[str], probe: Callable[[str], _T]) -> _T:
349
- results: queue.Queue[tuple[_T | None, Exception | None]] = queue.Queue(maxsize=len(addrs))
347
+ def _failure_rank(exc: Exception | None) -> int:
348
+ if not isinstance(exc, APIError):
349
+ return 0 if exc is None else 1
350
+ return 3 if exc.status >= 500 else 2 if exc.status == 0 else 1
351
+
352
+
353
+ def _scatter[T](addrs: Sequence[str], probe: Callable[[str], T]) -> T:
354
+ results: queue.Queue[tuple[T | None, Exception | None]] = queue.Queue(maxsize=len(addrs))
350
355
 
351
356
  def run(addr: str) -> None:
352
357
  try:
@@ -356,10 +361,11 @@ def _scatter(addrs: Sequence[str], probe: Callable[[str], _T]) -> _T:
356
361
 
357
362
  for addr in addrs:
358
363
  threading.Thread(target=run, args=(addr,), daemon=True).start()
359
- last_error = None
364
+ failure = None
360
365
  for _ in addrs:
361
366
  value, error = results.get()
362
367
  if error is None:
363
- return cast(_T, value)
364
- last_error = error
365
- raise cast(Exception, last_error)
368
+ return cast(T, value)
369
+ if _failure_rank(error) > _failure_rank(failure):
370
+ failure = error
371
+ raise cast(Exception, failure)
@@ -10,7 +10,7 @@ import threading
10
10
  import time
11
11
  import urllib.parse
12
12
  from collections.abc import Callable, Iterator
13
- from typing import Any, BinaryIO, Protocol, TypeVar, cast
13
+ from typing import Any, BinaryIO, Protocol, Self, cast
14
14
 
15
15
  from .errors import APIError, ProtocolError, SandboxError, SandboxTimeout, SilkdError, _error_message, _mark_gone
16
16
  from .frames import MAX_FRAME, decode_response, encode_request
@@ -18,13 +18,12 @@ from .frames import MAX_FRAME, decode_response, encode_request
18
18
  _KEEP_ALIVE_CONNS = 8
19
19
  _FD_SETSIZE = 1024
20
20
  _READ_BUFFER = 64 * 1024
21
+ _SEND_SLICE = 16 * 1024
21
22
  _TCP_KEEPALIVE = {"TCP_KEEPIDLE": 15, "TCP_KEEPALIVE": 15, "TCP_KEEPINTVL": 15, "TCP_KEEPCNT": 9}
22
23
 
23
- _CloseableT = TypeVar("_CloseableT", bound="_Closeable")
24
-
25
24
 
26
25
  class _Closeable(Protocol):
27
- def __enter__(self: _CloseableT) -> _CloseableT:
26
+ def __enter__(self) -> Self:
28
27
  return self
29
28
 
30
29
  def __exit__(self, *exc: object) -> None:
@@ -49,18 +48,24 @@ class Conn(_Closeable):
49
48
  self._request = request
50
49
  self._upgrade_timeout = upgrade_timeout
51
50
  self._tag = tag
51
+ self._bound: tuple[float, float] | None = None
52
52
 
53
53
  def send(self, op: str, **fields: object) -> None:
54
54
  frame = encode_request(op, **fields)
55
55
  if self._request:
56
56
  frame, self._request = self._request + frame, b""
57
+ view = memoryview(frame)
57
58
  try:
58
- self._sock.sendall(frame)
59
+ while view:
60
+ if self._bound is not None:
61
+ self._sock.settimeout(remaining_timeout(*self._bound, "agent request"))
62
+ view = view[self._sock.send(view[:_SEND_SLICE]) :]
59
63
  except OSError as exc:
60
- raise ProtocolError(f"write failed: {exc}") from exc
64
+ raise _io_error("write", exc) from exc
61
65
 
62
- def settimeout(self, timeout: float | None) -> None:
66
+ def settimeout(self, timeout: float | None, deadline: float | None = None) -> None:
63
67
  self._sock.settimeout(timeout)
68
+ self._bound = None if timeout is None or deadline is None else (timeout, deadline)
64
69
 
65
70
  def abort(self) -> None:
66
71
  """Unblocks a socket operation from another thread; close() still owns the socket."""
@@ -94,7 +99,7 @@ class Conn(_Closeable):
94
99
  try:
95
100
  line = self._reader.readline(MAX_FRAME + 1)
96
101
  except (OSError, ValueError) as exc:
97
- raise ProtocolError(f"read failed: {exc}") from exc
102
+ raise _io_error("read", exc) from exc
98
103
  if not line:
99
104
  raise ProtocolError("connection closed mid-stream")
100
105
  if len(line) > MAX_FRAME:
@@ -281,6 +286,12 @@ def _handshake_error(what: str, exc: OSError) -> SandboxError:
281
286
  return ProtocolError(f"{what}: {exc}")
282
287
 
283
288
 
289
+ def _io_error(what: str, exc: Exception) -> SandboxError:
290
+ if isinstance(exc, TimeoutError) and exc.errno is None:
291
+ return SandboxTimeout("agent request timed out")
292
+ return ProtocolError(f"{what} failed: {exc}")
293
+
294
+
284
295
  def _read_upgrade(reader: BinaryIO, arm: Callable[[], None], tag: tuple[str, str]) -> None:
285
296
  arm()
286
297
  status = reader.readline(1024).decode(errors="replace")
@@ -3,13 +3,11 @@
3
3
  from __future__ import annotations
4
4
 
5
5
  import json
6
- from typing import TYPE_CHECKING, Any, TypeVar, cast
6
+ from typing import TYPE_CHECKING, Any, cast
7
7
 
8
8
  if TYPE_CHECKING:
9
9
  from .volumes import SandboxVolumesResponse
10
10
 
11
- _E = TypeVar("_E", bound="SandboxError")
12
-
13
11
 
14
12
  class SandboxError(Exception):
15
13
  """Base class for all SDK errors."""
@@ -81,7 +79,7 @@ def _error_message(raw: bytes) -> str:
81
79
  return raw.decode(errors="replace").strip()
82
80
 
83
81
 
84
- def _mark_gone(exc: _E, tag: tuple[str, str]) -> _E:
82
+ def _mark_gone[E: SandboxError](exc: E, tag: tuple[str, str]) -> E:
85
83
  """Tags an owner's 404 or refused dial with its (sandbox id, owner address)."""
86
84
  exc._owner_gone = tag
87
85
  return exc
@@ -6,7 +6,6 @@ import base64
6
6
  import binascii
7
7
  import contextlib
8
8
  import json
9
- import sys
10
9
  from typing import Any
11
10
 
12
11
  PROTO_VERSION = 1
@@ -14,7 +13,6 @@ MAX_FRAME = 8 * 1024 * 1024
14
13
  BULK_CHUNK = 256 * 1024
15
14
  # tar and port streams chunk at 1 MiB, still under MAX_FRAME after base64
16
15
  STREAM_CHUNK = 1 << 20
17
- _FAST_DATA = sys.version_info >= (3, 11)
18
16
 
19
17
 
20
18
  def encode_request(op: str, **fields: object) -> bytes:
@@ -34,7 +32,7 @@ def encode_request(op: str, **fields: object) -> bytes:
34
32
 
35
33
  def decode_response(line: bytes) -> dict[str, Any]:
36
34
  """Decodes one response with binary payloads under data."""
37
- if _FAST_DATA and line.startswith(b'{"type":"'):
35
+ if line.startswith(b'{"type":"'):
38
36
  te = line.find(b'"', 9)
39
37
  if te > 0 and line[9:te] in (b"stdout", b"stderr", b"data") and line.startswith(b'","data":"', te):
40
38
  de = line.find(b'"', te + 10)
@@ -9,7 +9,7 @@ import threading
9
9
  import time
10
10
  from collections import deque
11
11
  from collections.abc import Callable, Iterator
12
- from typing import TYPE_CHECKING, Any, TypeVar, cast
12
+ from typing import TYPE_CHECKING, Any, cast
13
13
 
14
14
  from .checkpoint import Checkpoint
15
15
  from .conn import Conn, ConnPool, _Closeable, remaining_timeout
@@ -35,10 +35,8 @@ if TYPE_CHECKING:
35
35
  _ACCEPT_POLL_SECONDS = 1.0
36
36
  _KILL_WAIT_SECONDS = 5.0
37
37
 
38
- _F = TypeVar("_F", bound=Callable[..., Any])
39
38
 
40
-
41
- def _follows_move(method: _F) -> _F:
39
+ def _follows_move[F: Callable[..., Any]](method: F) -> F:
42
40
  """Runs a call once more on the owner a 404 points to; its arguments must be re-sendable."""
43
41
 
44
42
  @functools.wraps(method)
@@ -50,7 +48,7 @@ def _follows_move(method: _F) -> _F:
50
48
  raise
51
49
  return method(self, *args, **kwargs)
52
50
 
53
- return cast(_F, wrapper)
51
+ return cast(F, wrapper)
54
52
 
55
53
 
56
54
  class Sandbox:
@@ -187,7 +185,7 @@ class Sandbox:
187
185
  return cast(list[dict[str, Any]], _need(self._call("ps", "procs"), "procs"))
188
186
 
189
187
  def kill(self, pid: int, signal: int | None = None) -> None:
190
- """Signals a tracked process (default SIGKILL); killing one that already exited is a no-op success."""
188
+ """Signals the process group a tracked pid leads (default SIGKILL), even after the pid exited."""
191
189
  self._done_rpc("kill", pid=pid, signal=signal or None)
192
190
 
193
191
  def logs(
@@ -206,7 +204,7 @@ class Sandbox:
206
204
  on_stderr: Callable[[bytes], object] | None = None,
207
205
  ) -> int | None:
208
206
  """Replays then follows output until exit; a reader that falls behind misses live chunks."""
209
- return self._drain_proc("attach", pid, on_stdout, on_stderr)
207
+ return self._drain_proc("attach", pid, on_stdout, on_stderr, unbounded=True)
210
208
 
211
209
  @_follows_move
212
210
  def write_file(self, path: str, data: bytes, mode: int | None = None) -> None:
@@ -235,15 +233,16 @@ class Sandbox:
235
233
  self._done_rpc("fs_mkdir", path=path, parents=parents or None)
236
234
 
237
235
  def remove(self, path: str, recursive: bool = False) -> None:
238
- self._done_rpc("fs_rm", path=path, recursive=recursive or None)
236
+ self._done_rpc("fs_rm", unbounded=recursive, path=path, recursive=recursive or None)
239
237
 
240
238
  def rename(self, src: str, dst: str) -> None:
241
- self._done_rpc("fs_rename", **{"from": src, "to": dst})
239
+ paths: dict[str, Any] = {"from": src, "to": dst}
240
+ self._done_rpc("fs_rename", **paths)
242
241
 
243
242
  @_follows_move
244
243
  def push(self, dest: str, tar_stream: bytes) -> None:
245
244
  """Extracts a tar stream into dest; a truncated stream leaves dest untouched."""
246
- with self._lease(self._connect("fs_push", dest=dest)) as conn:
245
+ with self._lease(self._connect("fs_push", unbounded=True, dest=dest)) as conn:
247
246
  _upload(conn, tar_stream, STREAM_CHUNK)
248
247
 
249
248
  @_follows_move
@@ -271,41 +270,51 @@ class Sandbox:
271
270
 
272
271
  def git_clone(self, url: str, path: str, branch: str = "", depth: int = 0, auth: str = "") -> None:
273
272
  """Clones into path, shallow when depth is set; auth rides an in-memory header."""
274
- self._done_rpc("git_clone", url=url, path=path, branch=branch or None, depth=depth or None, auth=auth or None)
273
+ self._done_rpc(
274
+ "git_clone",
275
+ unbounded=True,
276
+ url=url,
277
+ path=path,
278
+ branch=branch or None,
279
+ depth=depth or None,
280
+ auth=auth or None,
281
+ )
275
282
 
276
283
  def git_status(self, path: str) -> dict[str, Any]:
277
- return self._call("git_status", "git_status_result", path=path)
284
+ return self._call("git_status", "git_status_result", unbounded=True, path=path)
278
285
 
279
286
  def git_add(self, path: str, files: list[str]) -> None:
280
- self._done_rpc("git_add", path=path, files=files)
287
+ self._done_rpc("git_add", unbounded=True, path=path, files=files)
281
288
 
282
289
  def git_commit(self, path: str, message: str, author: str) -> str:
283
290
  """Commits staged changes; returns the commit hash."""
284
291
  return cast(
285
292
  str,
286
- self._call("git_commit", "git_commit_result", path=path, message=message, author=author).get("hash", ""),
293
+ self._call(
294
+ "git_commit", "git_commit_result", unbounded=True, path=path, message=message, author=author
295
+ ).get("hash", ""),
287
296
  )
288
297
 
289
298
  def git_push(self, path: str, auth: str = "") -> None:
290
- self._done_rpc("git_push", path=path, auth=auth or None)
299
+ self._done_rpc("git_push", unbounded=True, path=path, auth=auth or None)
291
300
 
292
301
  def git_pull(self, path: str, auth: str = "") -> None:
293
- self._done_rpc("git_pull", path=path, auth=auth or None)
302
+ self._done_rpc("git_pull", unbounded=True, path=path, auth=auth or None)
294
303
 
295
304
  def git_branches(self, path: str) -> dict[str, Any]:
296
- return self._call("git_branch", "git_branches", path=path, action="list")
305
+ return self._call("git_branch", "git_branches", unbounded=True, path=path, action="list")
297
306
 
298
307
  def git_checkout(self, path: str, name: str) -> None:
299
- self._done_rpc("git_branch", path=path, action="checkout", name=name)
308
+ self._done_rpc("git_branch", unbounded=True, path=path, action="checkout", name=name)
300
309
 
301
310
  def git_create_branch(self, path: str, name: str) -> None:
302
- self._done_rpc("git_branch", path=path, action="create", name=name)
311
+ self._done_rpc("git_branch", unbounded=True, path=path, action="create", name=name)
303
312
 
304
313
  def git_delete_branch(self, path: str, name: str) -> None:
305
- self._done_rpc("git_branch", path=path, action="delete", name=name)
314
+ self._done_rpc("git_branch", unbounded=True, path=path, action="delete", name=name)
306
315
 
307
316
  def watch(self, path: str, recursive: bool = False) -> Watcher:
308
- """Streams filesystem events under path; events after the returned Watcher exists are guaranteed captured."""
317
+ """Returns an armed watcher that streams events under path, excluding directories whose own watch fails."""
309
318
  conn, _ = self._open_stream("fs_watch", path=path, recursive=recursive or None)
310
319
  return Watcher(conn)
311
320
 
@@ -326,7 +335,7 @@ class Sandbox:
326
335
  return [self._client._handle_from(addr, child, "fork") for child in reply.get("children") or []]
327
336
 
328
337
  def hibernate(self) -> None:
329
- """Snapshots and stops the VM; the next guest call restores its state."""
338
+ """Snapshots and stops the VM; the next guest call wakes it."""
330
339
  self._pool.drain()
331
340
  self._owner_request("hibernate", None, "hibernate", bearer=self.token)
332
341
 
@@ -407,9 +416,11 @@ class Sandbox:
407
416
  unreachable = exc if exc.status == 0 else None
408
417
  try:
409
418
  moved = self._client.lookup(self.id, self.token)
410
- except APIError:
419
+ except APIError as exc:
411
420
  if unreachable is not None:
412
421
  raise unreachable from None
422
+ if exc.status != 404:
423
+ raise
413
424
  return
414
425
  try:
415
426
  self._release_at(moved.owner)
@@ -462,7 +473,9 @@ class Sandbox:
462
473
  return True
463
474
  try:
464
475
  moved = self._client.lookup(self.id, self.token)
465
- except APIError:
476
+ except APIError as lookup_exc:
477
+ if lookup_exc.status >= 500:
478
+ raise
466
479
  return False
467
480
  if moved.owner == self.owner:
468
481
  return False
@@ -486,15 +499,14 @@ class Sandbox:
486
499
  def _dial(self, deadline: float | None = None) -> Conn:
487
500
  return self._client._dial(self.owner, self.id, self.token, deadline)
488
501
 
489
- def _connect(self, op: str, deadline: float | None = None, /, **fields: object) -> Conn:
502
+ def _connect(self, op: str, deadline: float | None = None, /, *, unbounded: bool = False, **fields: object) -> Conn:
490
503
  conn = self._pool.take()
491
504
  if conn is None:
492
505
  conn = self._dial(deadline)
493
506
  try:
494
- if deadline is not None:
495
- conn.settimeout(remaining_timeout(self._client.timeout, deadline, "agent request"))
507
+ conn.settimeout(remaining_timeout(self._client.timeout, deadline, "agent request"), deadline)
496
508
  conn.send(op, **fields)
497
- if deadline is not None:
509
+ if unbounded or deadline is not None:
498
510
  conn.settimeout(None)
499
511
  except BaseException:
500
512
  conn.close()
@@ -515,7 +527,7 @@ class Sandbox:
515
527
 
516
528
  @_follows_move
517
529
  def _open_stream(self, op: str, expect: str = "ready", **fields: object) -> tuple[Conn, dict[str, Any]]:
518
- conn = self._connect(op, **fields)
530
+ conn = self._connect(op, unbounded=True, **fields)
519
531
  try:
520
532
  frame = _expect(conn, expect) if expect else conn.recv()
521
533
  except SilkdError:
@@ -572,12 +584,12 @@ class Sandbox:
572
584
  local.close()
573
585
 
574
586
  @_follows_move
575
- def _call(self, op: str, expect: str, **fields: object) -> dict[str, Any]:
576
- with self._lease(self._connect(op, **fields)) as conn:
587
+ def _call(self, op: str, expect: str, /, *, unbounded: bool = False, **fields: object) -> dict[str, Any]:
588
+ with self._lease(self._connect(op, unbounded=unbounded, **fields)) as conn:
577
589
  return _expect(conn, expect)
578
590
 
579
- def _done_rpc(self, op: str, **fields: object) -> None:
580
- self._call(op, "done", **fields)
591
+ def _done_rpc(self, op: str, /, *, unbounded: bool = False, **fields: object) -> None:
592
+ self._call(op, "done", unbounded=unbounded, **fields)
581
593
 
582
594
  @_follows_move
583
595
  def _drain_proc(
@@ -587,8 +599,9 @@ class Sandbox:
587
599
  on_stdout: Callable[[bytes], object] | None,
588
600
  on_stderr: Callable[[bytes], object] | None,
589
601
  trailing_done: bool = False,
602
+ unbounded: bool = False,
590
603
  ) -> int | None:
591
- with self._lease(self._connect(op, pid=pid)) as conn:
604
+ with self._lease(self._connect(op, unbounded=unbounded, pid=pid)) as conn:
592
605
  code = _pump_stdio(conn, on_stdout, on_stderr)
593
606
  if trailing_done and code is not None:
594
607
  _expect(conn, "done")
@@ -607,7 +620,7 @@ class Sandbox:
607
620
  expired = threading.Event()
608
621
  started: deque[int] = deque(maxlen=1)
609
622
  try:
610
- conn = self._connect("exec", deadline, **fields)
623
+ conn = self._connect("exec", deadline, unbounded=True, **fields)
611
624
  except (ProtocolError, TimeoutError):
612
625
  if deadline is not None and time.monotonic() >= deadline:
613
626
  raise SandboxTimeout(f"command did not finish within {timeout}s") from None
@@ -853,7 +866,7 @@ def _need(frame: dict[str, Any], key: str) -> Any:
853
866
  return frame[key]
854
867
 
855
868
 
856
- def _rpc_ignoring_not_found(sandbox: Sandbox, op: str, **fields: object) -> None:
869
+ def _rpc_ignoring_not_found(sandbox: Sandbox, op: str, **fields: Any) -> None:
857
870
  try:
858
871
  sandbox._done_rpc(op, **fields)
859
872
  except SilkdError as exc:
@@ -1,9 +1,9 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cocoonstack-sandbox
3
- Version: 0.1.36
3
+ Version: 0.1.38
4
4
  Summary: Python SDK for the cocoon sandbox control plane
5
5
  License: Apache-2.0
6
- Requires-Python: >=3.10
6
+ Requires-Python: >=3.12
7
7
  Description-Content-Type: text/markdown
8
8
  License-File: LICENSE
9
9
  Dynamic: license-file
@@ -4,9 +4,9 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "cocoonstack-sandbox"
7
- version = "0.1.36"
7
+ version = "0.1.38"
8
8
  description = "Python SDK for the cocoon sandbox control plane"
9
- requires-python = ">=3.10"
9
+ requires-python = ">=3.12"
10
10
  license = { text = "Apache-2.0" }
11
11
  readme = "README.md"
12
12
 
@@ -7,7 +7,7 @@ import threading
7
7
 
8
8
  import cocoonsandbox.client
9
9
  import pytest
10
- from cocoonsandbox import APIError, Client
10
+ from cocoonsandbox import APIError, Client, Sandbox
11
11
  from conftest import bounded
12
12
 
13
13
  ENTRY_POINTS = pytest.mark.parametrize(
@@ -210,7 +210,7 @@ def test_lookup_returns_the_first_owner_without_waiting_for_a_slow_peer(spawn_no
210
210
  assert sb.owner == "10.0.0.9:7777"
211
211
 
212
212
 
213
- def test_lookup_all_miss(spawn_node, dead_addr):
213
+ def test_lookup_raises_a_peer_it_could_not_reach_instead_of_no_owner(spawn_node, dead_addr):
214
214
  entry = spawn_node(
215
215
  {
216
216
  ("GET", "/v1/sandboxes/sb_1/owner"): lambda body, path: (404, {"error": "not here"}),
@@ -219,7 +219,29 @@ def test_lookup_all_miss(spawn_node, dead_addr):
219
219
  )
220
220
  with pytest.raises(APIError) as exc:
221
221
  Client(entry).lookup("sb_1", "tok")
222
- assert exc.value.status == 404 and "no owner found" in exc.value.message
222
+ assert exc.value.status == 0, exc.value
223
+
224
+
225
+ def test_lookup_raises_a_node_error_instead_of_no_owner(spawn_node):
226
+ gate = threading.Event()
227
+
228
+ def late_miss(body, path):
229
+ gate.wait(60)
230
+ return 404, {"error": "not here"}
231
+
232
+ down = spawn_node(
233
+ {("GET", "/v1/sandboxes/sb_1/owner"): lambda body, path: (503, {"error": "archive registry down; retry"})}
234
+ )
235
+ entry = spawn_node(
236
+ {
237
+ ("GET", "/v1/sandboxes/sb_1/owner"): late_miss,
238
+ ("GET", "/v1/peers"): lambda body, path: (200, {"peers": [down]}),
239
+ }
240
+ )
241
+ threading.Timer(0.3, gate.set).start()
242
+ with pytest.raises(APIError) as exc:
243
+ Client(entry).lookup("sb_1", "tok")
244
+ assert exc.value.status == 503 and "retry" in exc.value.message, exc.value
223
245
 
224
246
 
225
247
  @pytest.mark.parametrize("retired", [False, True], ids=["old_node_404", "old_node_retired"])
@@ -299,6 +321,57 @@ def test_close_of_a_sandbox_no_node_holds_is_not_an_error(spawn_node):
299
321
  Client(gone).attach(gone, "sb_1", "tok").close()
300
322
 
301
323
 
324
+ def test_close_raises_a_peer_error_instead_of_already_gone(spawn_node):
325
+ with pytest.raises(APIError) as exc:
326
+ gone_sandbox(spawn_node, 503).close()
327
+ assert exc.value.status == 503, exc.value
328
+
329
+
330
+ def test_close_raises_when_a_peer_cannot_be_reached(spawn_node, dead_addr):
331
+ old = spawn_node({("GET", "/v1/peers"): lambda body, path: (200, {"peers": [dead_addr]})})
332
+ with pytest.raises(APIError) as info:
333
+ Client(old).attach(old, "sb_1", "tok").close()
334
+ assert info.value.status == 0, info.value
335
+
336
+
337
+ def test_close_raises_when_the_peer_listing_gets_no_answer(spawn_node):
338
+ def drop(body, path):
339
+ raise ConnectionResetError("peer listing dropped")
340
+
341
+ old = spawn_node({("GET", "/v1/peers"): drop})
342
+ with pytest.raises(APIError) as info:
343
+ Client(old).attach(old, "sb_1", "tok").close()
344
+ assert info.value.status == 0, info.value
345
+
346
+
347
+ def test_close_of_a_sandbox_no_peer_holds_is_not_an_error(spawn_node):
348
+ gone_sandbox(spawn_node, 404).close()
349
+
350
+
351
+ def test_lookup_raises_a_failed_peer_discovery_instead_of_no_owner(spawn_node):
352
+ entry = spawn_node(
353
+ {
354
+ ("GET", "/v1/sandboxes/sb_1/owner"): lambda body, path: (404, {"error": "not here"}),
355
+ ("GET", "/v1/peers"): lambda body, path: (503, {"error": "gossip not ready"}),
356
+ }
357
+ )
358
+ with pytest.raises(APIError) as exc:
359
+ Client(entry).lookup("sb_1", "tok")
360
+ assert exc.value.status == 503 and exc.value.verb == "peers", exc.value
361
+
362
+
363
+ def test_a_call_raises_a_peer_error_instead_of_the_old_owners_404(spawn_node):
364
+ with pytest.raises(APIError) as exc:
365
+ gone_sandbox(spawn_node, 503).stat("/")
366
+ assert exc.value.status == 503, exc.value
367
+
368
+
369
+ def gone_sandbox(spawn_node, peer_status: int) -> Sandbox:
370
+ peer = spawn_node({("GET", "/v1/sandboxes/sb_1/owner"): lambda body, path: (peer_status, {"error": "not ready"})})
371
+ old = spawn_node({("GET", "/v1/peers"): lambda body, path: (200, {"peers": [peer]})})
372
+ return Client(old).attach(old, "sb_1", "tok")
373
+
374
+
302
375
  def drop_reply(server: socket.socket) -> None:
303
376
  conn, _ = server.accept()
304
377
  conn.recv(65536)
@@ -1,8 +1,14 @@
1
1
  """Regression tests for the SDK error-surface hardening."""
2
2
 
3
3
  import base64
4
+ import contextlib
5
+ import errno
6
+ import io
4
7
  import json
8
+ import pathlib
9
+ import queue
5
10
  import socket
11
+ import ssl
6
12
  import threading
7
13
  import time
8
14
 
@@ -23,6 +29,8 @@ from cocoonsandbox.conn import Conn, dial_agent, remaining_timeout
23
29
  from cocoonsandbox.frames import BULK_CHUNK
24
30
  from conftest import sandbox_at, wait_until
25
31
 
32
+ TLS_PEM = pathlib.Path(__file__).with_name("tls.pem")
33
+
26
34
 
27
35
  def test_dial_agent_rejects_control_chars_in_identity():
28
36
  with pytest.raises(APIError):
@@ -221,6 +229,105 @@ def test_dial_timeout_bounds_the_whole_upgrade() -> None:
221
229
  conn.recv()
222
230
 
223
231
 
232
+ def test_a_watch_cut_by_tcp_keepalive_ends_with_a_protocol_error():
233
+ ours, theirs = socket.socketpair()
234
+ watcher = Watcher(Conn(ours, KeepaliveExpiredReader()))
235
+ assert list(watcher) == []
236
+ assert isinstance(watcher.error, ProtocolError), watcher.error
237
+ assert ours.fileno() == -1, "the ended watch kept its relay open"
238
+ theirs.close()
239
+
240
+
241
+ def test_a_send_stalled_past_the_socket_timeout_raises_sandbox_timeout():
242
+ ours, theirs = socket.socketpair()
243
+ ours.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 4096)
244
+ conn = Conn(ours, ours.makefile("rb"))
245
+ conn.settimeout(0.05)
246
+ try:
247
+ with pytest.raises(SandboxTimeout):
248
+ conn.send("data", data=bytes(4 << 20))
249
+ finally:
250
+ conn.close()
251
+ theirs.close()
252
+
253
+
254
+ @pytest.mark.parametrize("tls", [False, True], ids=["plain", "tls"])
255
+ def test_a_send_whose_bytes_keep_flowing_outlives_the_socket_timeout(tls):
256
+ ours, theirs = slow_pair()
257
+ if tls:
258
+ ours, theirs = tls_pair(ours, theirs)
259
+ conn = Conn(ours, ours.makefile("rb"))
260
+ conn.settimeout(0.2)
261
+ received = bytearray()
262
+ reader = threading.Thread(target=drain_slowly, args=(theirs, received), daemon=True)
263
+ reader.start()
264
+ try:
265
+ conn.send("data", data=bytes(2 << 20))
266
+ reader.join(10)
267
+ finally:
268
+ conn.close()
269
+ theirs.close()
270
+ assert len(base64.b64decode(json.loads(received)["data"])) == 2 << 20
271
+
272
+
273
+ def test_a_run_deadline_bounds_a_slowly_drained_request(monkeypatch):
274
+ ours, theirs = slow_pair()
275
+ sb = sandbox_at("127.0.0.1:1", keep_alive=0)
276
+ monkeypatch.setattr(sb, "_dial", lambda deadline=None: Conn(ours, ours.makefile("rb")))
277
+ threading.Thread(target=drain_slowly, args=(theirs, bytearray()), daemon=True).start()
278
+ started = time.monotonic()
279
+ try:
280
+ with pytest.raises(SandboxTimeout):
281
+ sb.run(["true"], env={"BIG": "x" * (8 << 20)}, timeout=0.3)
282
+ elapsed = time.monotonic() - started
283
+ finally:
284
+ theirs.close()
285
+ assert elapsed < 1.0, elapsed
286
+
287
+
288
+ def test_a_send_cut_by_tcp_keepalive_stays_a_protocol_error():
289
+ with pytest.raises(ProtocolError):
290
+ Conn(KeepaliveExpiredSocket(), io.BytesIO()).send("info")
291
+
292
+
293
+ class KeepaliveExpiredSocket:
294
+ def send(self, data: bytes) -> int:
295
+ raise OSError(errno.ETIMEDOUT, "connection timed out")
296
+
297
+
298
+ class KeepaliveExpiredReader:
299
+ def readline(self, limit: int) -> bytes:
300
+ raise OSError(errno.ETIMEDOUT, "connection timed out")
301
+
302
+ def close(self) -> None:
303
+ pass
304
+
305
+
306
+ def slow_pair() -> tuple[socket.socket, socket.socket]:
307
+ ours, theirs = socket.socketpair()
308
+ ours.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 64 * 1024)
309
+ theirs.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 64 * 1024)
310
+ return ours, theirs
311
+
312
+
313
+ def tls_pair(ours: socket.socket, theirs: socket.socket) -> tuple[ssl.SSLSocket, ssl.SSLSocket]:
314
+ server = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
315
+ server.load_cert_chain(TLS_PEM)
316
+ client = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
317
+ client.check_hostname = False
318
+ client.verify_mode = ssl.CERT_NONE
319
+ accepted: queue.Queue[ssl.SSLSocket] = queue.Queue()
320
+ threading.Thread(target=lambda: accepted.put(server.wrap_socket(theirs, server_side=True)), daemon=True).start()
321
+ return client.wrap_socket(ours), accepted.get(timeout=5)
322
+
323
+
324
+ def drain_slowly(sock: socket.socket, received: bytearray) -> None:
325
+ with contextlib.suppress(OSError):
326
+ while not received.endswith(b"\n") and (chunk := sock.recv(64 * 1024)):
327
+ received.extend(chunk)
328
+ time.sleep(0.01)
329
+
330
+
224
331
  @pytest.fixture
225
332
  def conn_pair():
226
333
  client_sock, guest_sock = socket.socketpair()
@@ -1,4 +1,4 @@
1
- """The client timeout bounds the dial and the upgrade, not the guest stream that follows."""
1
+ """The client timeout bounds the dial, the upgrade and each prompt call's wait, not a stream or a long verb."""
2
2
 
3
3
  import contextlib
4
4
  import json
@@ -14,13 +14,53 @@ from conftest import accept_upgrade, bounded, sandbox_at
14
14
  TIMEOUT = 0.2
15
15
 
16
16
 
17
- def test_port_stream_outlives_the_client_timeout(script_server):
17
+ @pytest.mark.parametrize(("keep_alive", "mkdirs"), [(0, 0), (30, 1)], ids=["fresh dial", "kept connection"])
18
+ def test_port_stream_outlives_the_client_timeout(script_server, keep_alive, mkdirs):
18
19
  ops: list[str] = []
19
- sb = short_timeout_sandbox(script_server(serve_port_forward, 3 * TIMEOUT, ops))
20
+ sb = sandbox_at(script_server(serve_port_forward, 3 * TIMEOUT, ops), timeout=TIMEOUT, keep_alive=keep_alive)
21
+ for _ in range(mkdirs):
22
+ sb.mkdir("/w")
20
23
  with sb.dial_port(5000) as port:
21
24
  assert port.recv() == b"late"
22
25
  assert port.recv() == b""
23
- assert ops == ["port_forward"]
26
+ assert ops == ["fs_mkdir"] * mkdirs + ["port_forward"]
27
+
28
+
29
+ @pytest.mark.parametrize(
30
+ "call",
31
+ [
32
+ lambda sb: sb.read_file("/f"),
33
+ lambda sb: sb.write_file("/f", b"x"),
34
+ lambda sb: sb.stat("/"),
35
+ lambda sb: sb.logs(7),
36
+ lambda sb: sb.remove("/f"),
37
+ ],
38
+ ids=["read_file", "write_file", "stat", "logs", "remove"],
39
+ )
40
+ def test_one_shot_call_to_a_silent_guest_times_out(script_server, call):
41
+ sb = short_timeout_sandbox(script_server(serve_silence, True))
42
+ with pytest.raises(SandboxTimeout):
43
+ bounded(lambda: call(sb))
44
+
45
+
46
+ @pytest.mark.parametrize(
47
+ ("op", "reply", "call"),
48
+ [
49
+ ("git_clone", "done", lambda sb: sb.git_clone("https://example.com/r.git", "/r")),
50
+ ("git_push", "done", lambda sb: sb.git_push("/r")),
51
+ ("git_pull", "done", lambda sb: sb.git_pull("/r")),
52
+ ("git_commit", "git_commit_result", lambda sb: sb.git_commit("/r", "m", "a <a@b>")),
53
+ ("git_status", "git_status_result", lambda sb: sb.git_status("/r")),
54
+ ("fs_push", "done", lambda sb: sb.push("/r", b"tar")),
55
+ ("fs_rm", "done", lambda sb: sb.remove("/r", recursive=True)),
56
+ ],
57
+ ids=["git_clone", "git_push", "git_pull", "git_commit", "git_status", "push", "recursive remove"],
58
+ )
59
+ def test_long_verb_outlives_the_client_timeout(script_server, op, reply, call):
60
+ ops: list[str] = []
61
+ sb = short_timeout_sandbox(script_server(serve_late_reply, 3 * TIMEOUT, reply, ops))
62
+ bounded(lambda: call(sb))
63
+ assert ops == [op]
24
64
 
25
65
 
26
66
  def test_run_timeout_cuts_a_silent_command_and_kills_it(script_server):
@@ -83,12 +123,24 @@ def serve_port_forward(server: socket.socket, quiet: float, ops: list[str]) -> N
83
123
  conn, _ = server.accept()
84
124
  reader = accept_upgrade(conn)
85
125
  ops.append(json.loads(reader.readline())["op"])
126
+ while ops[-1] != "port_forward":
127
+ conn.sendall(b'{"type":"done"}\n')
128
+ ops.append(json.loads(reader.readline())["op"])
86
129
  conn.sendall(b'{"type":"ready"}\n')
87
130
  time.sleep(quiet)
88
131
  conn.sendall(b'{"type":"data","data":"bGF0ZQ=="}\n{"type":"done"}\n')
89
132
  conn.close()
90
133
 
91
134
 
135
+ def serve_late_reply(server: socket.socket, quiet: float, reply: str, ops: list[str]) -> None:
136
+ conn, _ = server.accept()
137
+ reader = accept_upgrade(conn)
138
+ ops.append(json.loads(reader.readline())["op"])
139
+ time.sleep(quiet)
140
+ conn.sendall(json.dumps({"type": reply}).encode() + b"\n")
141
+ conn.close()
142
+
143
+
92
144
  def serve_started_then_hang(server: socket.socket, kills: list[dict]) -> None:
93
145
  conn, _ = server.accept()
94
146
  reader = accept_upgrade(conn)
@@ -117,8 +169,10 @@ def serve_started_then_trickle_the_kill_reply(server: socket.socket, kills: list
117
169
  conn.close()
118
170
 
119
171
 
120
- def serve_silence(server: socket.socket) -> None:
172
+ def serve_silence(server: socket.socket, upgrade: bool = False) -> None:
121
173
  conn, _ = server.accept()
174
+ if upgrade:
175
+ accept_upgrade(conn)
122
176
  with contextlib.suppress(OSError):
123
177
  while conn.recv(4096):
124
178
  pass